repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
lilobase/ICONTO-EcoleNumerique
utils/copix/utils/CopixFilter.class.php
3688
<?php /** * @package copix * @subpackage core * @author Croës Gérald * @copyright CopixTeam * @link http://copix.org * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public Licence, see LICENCE file */ /** * Filtres pour récupérer des données sous une certaine forme * @package copix * @subpackage utils */ class CopixFilter { /** * Récupération d'un entier à partir de la variable * @param mixed $pInt la variable à récupérer sous la forme d'un entier * @return int */ public static function getInt ($pInt) { return intval (self::getNumeric ($pInt, true)); } /** * Récupération d'un numérique à partir de la variable * @param mixed $pNumeric la variable à récupérer sous la forme d'un numérique * @param boolean $pWithComma si l'on souhaite inclure les virgules et points dans l'élément * @return numeric */ public static function getNumeric ($pNumeric, $pWithComma = false) { if ($pWithComma){ return preg_replace('/[-+]?[^\d.]/', '', str_replace (',', '.', _toString($pNumeric))); }else{ return preg_replace('/[-+]?[^\d]/', '', _toString($pNumeric)); } } /** * Récupération des caractères d'une chaine * @param string $pAlpha chaine de caractère à traiter * @return string */ public static function getAlpha ($pAlpha, $pWithSpaces=true) { if ($pWithSpaces){ return preg_replace('/[^a-zA-ZàâäéèêëîïÿôöùüçñÀÂÄÉÈÊËÎÏŸÔÖÙÜÇÑ ]/', '', _toString($pAlpha)); }else{ return preg_replace('/[^a-zA-ZàâäéèêëîïÿôöùüçñÀÂÄÉÈÊËÎÏŸÔÖÙÜÇÑ]/', '', _toString($pAlpha)); } } /** * Récupération d'une chaine alphanumérique * @param string $pAlphaNum la chaine ou l'on va récupérer les éléments * @param boolean * @return string */ public static function getAlphaNum ($pAlphaNum, $pWithSpaces=true) { // \w <=> [a-zA-Z0-9_] et a-z contient les accent si système est en fr. // \W tout ce qui n'est pas \w if ($pWithSpaces){ return preg_replace('/[^a-zA-Z0-9àâäéèêëîïÿôöùüçñÀÂÄÉÈÊËÎÏŸÔÖÙÜÇÑ ]/', '', _toString($pAlphaNum)); }else{ return preg_replace('/[^a-zA-Z0-9àâäéèêëîïÿôöùüçñÀÂÄÉÈÊËÎÏŸÔÖÙÜÇÑ]/', '', _toString($pAlphaNum)); } } /** * Retourne une décimal à partir d'une entrée * @param mixed $pFloat l'élément à transformer * @return float */ public static function getFloat ($pFloat) { return floatval (str_replace (',', '.', self::getNumeric ($pFloat, true))); } /** * Retourne un booléen à partir d'une entrée. * * Evalue les chaînes suivantes comme vrai : yes, true, enable, enabled, 1. * Evalue les chaînes suivantes comme faux: no, false, disable, disabled, 0. * Si cela ne colle pas, transforme la chaîne en entier, 0 s'évalue comme faux et tout le reste comme vrai. * * @param mixed $pBoolean L'élément à transformer. * @return boolean */ public static function getBoolean ($pBoolean) { switch(strtolower(_toString ($pBoolean))) { case 'yes': case 'true': case 'enable': case 'enabled': case '1': return true; case 'no': case 'false': case 'disable': case 'disabled': case '0': case '': return false; default: return self::getInt($pBoolean) != 0; } } }
lgpl-2.1
sourcey/libsourcey
src/base/include/scy/logger.h
13132
/// // // LibSourcey // Copyright (c) 2005, Sourcey <https://sourcey.com> // // SPDX-License-Identifier: LGPL-2.1+ // /// @addtogroup base /// @{ #ifndef SCY_Logger_H #define SCY_Logger_H #include "scy/base.h" #include "scy/error.h" #include "scy/interface.h" #include "scy/singleton.h" #include "scy/thread.h" #include <ctime> #include <deque> #include <fstream> #include <iostream> #include <map> #include <sstream> #include <mutex> #include <string.h> namespace scy { enum class Level { Trace = 0, Debug = 1, Info = 2, Warn = 3, Error = 4, Fatal = 5, }; inline Level getLevelFromString(const char* level) { if (strcmp(level, "trace") == 0) return Level::Trace; if (strcmp(level, "debug") == 0) return Level::Debug; if (strcmp(level, "info") == 0) return Level::Info; if (strcmp(level, "warn") == 0) return Level::Warn; if (strcmp(level, "error") == 0) return Level::Error; if (strcmp(level, "fatal") == 0) return Level::Fatal; return Level::Trace; } inline const char* getStringFromLevel(Level level) { switch (level) { case Level::Trace: return "trace"; case Level::Debug: return "debug"; case Level::Info: return "info"; case Level::Warn: return "warn"; case Level::Error: return "error"; case Level::Fatal: return "fatal"; } return "debug"; } struct Base_API LogStream; class Base_API LogChannel; // // Default Log Writer // /// Log output stream writer. class Base_API LogWriter { public: LogWriter(); virtual ~LogWriter(); /// Writes the given log message stream. virtual void write(LogStream* stream); }; // // Asynchronous Log Writer // /// Thread based log output stream writer. class Base_API AsyncLogWriter : public LogWriter, public basic::Runnable { public: AsyncLogWriter(); virtual ~AsyncLogWriter(); /// Queues the given log message stream. virtual void write(LogStream* stream) override; /// Flushes queued messages. void flush(); /// Writes queued messages asynchronously. void run(); /// Clears all queued messages. void clear(); protected: bool writeNext(); Thread _thread; std::deque<LogStream*> _pending; mutable std::mutex _mutex; }; // // Logger // /// Logger class. class Base_API Logger { public: Logger(); ~Logger(); /// Returns the default logger singleton. /// Logger instances may be created separately as needed. static Logger& instance(); /// Sets the default logger singleton instance. static void setInstance(Logger* logger, bool freeExisting = true); /// Destroys the default logger singleton instance. static void destroy(); /// Adds the given log channel. void add(LogChannel* channel); /// Removes the given log channel by name, /// and optionally frees the pointer. void remove(const std::string& name, bool freePointer = true); /// Returns the specified log channel. /// Throws an exception if the channel doesn't exist. LogChannel* get(const std::string& name, bool whiny = true) const; /// Sets the default log to the specified log channel. void setDefault(const std::string& name); /// Sets the log writer instance. void setWriter(LogWriter* writer); /// Returns the default log channel, or the nullptr channel /// if no default channel has been set. LogChannel* getDefault() const; /// Writes the given message to the default log channel. /// The message will be copied. void write(const LogStream& stream); /// Writes the given message to the default log channel. /// The stream pointer will be deleted when appropriate. void write(LogStream* stream); /// Sends to the default log using the given class instance. /// Recommend using write(LogStream&) to avoid copying data. // LogStream& send(const char* level = "debug", const char* realm = "", // const void* ptr = nullptr, // const char* channel = nullptr) const; protected: /// NonCopyable and NonMovable Logger(const Logger&) = delete; Logger& operator=(const Logger&) = delete; typedef std::map<std::string, LogChannel*> LogChannelMap; friend class Singleton<Logger>; friend class Thread; mutable std::mutex _mutex; LogChannelMap _channels; LogChannel* _defaultChannel; LogWriter* _writer; }; // // Recursive logging for veradic arguments // template <typename T> void logArgs(std::ostream& o, T&& t) { o << t; // << ' '; // << std::endl; } template<typename T, typename... Args> void logArgs(std::ostream& o, T&& t, Args&&... args) // recursive variadic function { logArgs(o, std::forward<T>(t)); logArgs(o, std::forward<Args>(args)...); } // // Log Stream // #ifdef SCY_ENABLE_LOGGING struct LogStream { Level level; int line; std::string realm; std::ostringstream message; std::time_t ts; LogChannel* channel; bool flushed; LogStream(Level level, std::string realm, int line, const char* channel = nullptr); LogStream(const LogStream& that); ~LogStream(); /// Recursively log veradic arguments. template<typename... Args> void write(Args... args) { logArgs(message, args...); flush(); } /// Write data to the log message. template <typename T> LogStream& operator<<(const T& data) { message << data; return *this; } LogStream& operator<<(const Level data) { level = data; return *this; } LogStream& operator<<(LogChannel* data) { channel = data; return *this; } /// Handle std::endl manipulators. /// This method flushes the log message and queues it for write. LogStream& operator<<(std::ostream& (*f)(std::ostream&)) { flush(); return *this; } void flush() { if (!flushed) { flushed = true; message << std::endl; Logger::instance().write(new LogStream(*this)); } } }; #else struct LogStream { LogStream(Level level, std::string realm, int line, const char* channel = nullptr) {}; LogStream(const LogStream& that) {}; template<typename... Args> void write(Args... args) { } template <typename T> LogStream& operator<<(const T&) { return *this; } LogStream& operator<<(std::ostream& (*f)(std::ostream&)) { return *this; } }; #endif // // Log Channel // class Base_API LogChannel { public: LogChannel(std::string name, Level level = Level::Debug, std::string timeFormat = "%H:%M:%S"); virtual ~LogChannel() = default; virtual void write(const LogStream& stream); virtual void write(std::string message, Level level = Level::Debug, std::string realm = ""); virtual void format(const LogStream& stream, std::ostream& ost); std::string name() const { return _name; }; Level level() const { return _level; }; std::string timeFormat() const { return _timeFormat; }; void setLevel(Level level) { _level = level; }; void setTimeFormat(std::string format) { _timeFormat = std::move(format); }; void setFilter(std::string filter) { _filter = std::move(filter); } protected: std::string _name; Level _level; std::string _timeFormat; std::string _filter; }; /// Null log channel. /// /// Redifine the base `LogChannel` as `NullChannel` so it can be logically used /// as a disabled log channel. typedef LogChannel NullChannel; // // Console Channel // class Base_API ConsoleChannel : public LogChannel { public: ConsoleChannel(std::string name, Level level = Level::Debug, std::string timeFormat = "%H:%M:%S"); virtual ~ConsoleChannel() = default; virtual void write(const LogStream& stream) override; }; // // File Channel // class Base_API FileChannel : public LogChannel { public: FileChannel(std::string name, std::string path, Level level = Level::Debug, std::string timeFormat = "%H:%M:%S"); virtual ~FileChannel(); virtual void write(const LogStream& stream) override; void setPath(const std::string& path); std::string path() const; protected: virtual void open(); virtual void close(); protected: std::ofstream _fstream; std::string _path; }; // // Rotating File Channel // class Base_API RotatingFileChannel : public LogChannel { public: RotatingFileChannel(std::string name, std::string dir, Level level = Level::Debug, std::string extension = "log", int rotationInterval = 12 * 3600, // 12 hours std::string timeFormat = "%H:%M:%S"); virtual ~RotatingFileChannel(); virtual void write(const LogStream& stream) override; virtual void rotate(); std::string dir() const { return _dir; }; std::string filename() const { return _filename; }; int rotationInterval() const { return _rotationInterval; }; void setDir(std::string dir) { _dir = std::move(dir); }; void setExtension(std::string ext) { _extension = std::move(ext); }; void setRotationInterval(int interval) { _rotationInterval = interval; }; protected: std::ofstream* _fstream; std::string _dir; std::string _filename; std::string _extension; int _rotationInterval; ///< The log rotation interval in seconds time_t _rotatedAt; ///< The time the log was last rotated }; #if 0 class Base_API EventedFileChannel: public FileChannel { public: EventedFileChannel( std::string name, const std::string& dir, Level level = Level::Debug, const std::string& extension = "log", int rotationInterval = 12 * 3600, const char* timeFormat = "%H:%M:%S"); virtual ~EventedFileChannel(); virtual void write(const std::string& message, Level level = Level::Debug, const char* realm = "", const void* ptr = nullptr); virtual void write(const LogStream& stream); Signal<void(const std::string&, Level&, const Polymorphic*&)> OnLogStream; }; #endif // // Compile time helpers for replacing file paths with filenames // constexpr const char* str_end(const char *str) { return *str ? str_end(str + 1) : str; } constexpr bool str_slant(const char *str) { return *str == '/' || *str == '\\' ? true : (*str ? str_slant(str + 1) : false); } constexpr const char* r_slant(const char* str) { return *str == '/' || *str == '\\' ? (str + 1) : r_slant(str - 1); } constexpr const char* _fileName(const char* str) { return str_slant(str) ? r_slant(str_end(str)) : str; } // // Logging macros // // Macro for logging class functions #ifndef __CLASS_FUNCTION__ #if _MSC_VER #define __CLASS_FUNCTION__ __FUNCTION__ #else inline std::string _methodName(const std::string& fsig) { size_t colons = fsig.find("::"); size_t sbeg = fsig.substr(0, colons).rfind(" ") + 1; size_t send = fsig.rfind("(") - sbeg; return fsig.substr(sbeg, send) + "()"; } #define __CLASS_FUNCTION__ _methodName(__PRETTY_FUNCTION__) #endif #endif #define STrace LogStream(Level::Trace, _fileName(__FILE__), __LINE__) #define SDebug LogStream(Level::Debug, _fileName(__FILE__), __LINE__) #define SInfo LogStream(Level::Info, _fileName(__FILE__), __LINE__) #define SWarn LogStream(Level::Warn, _fileName(__FILE__), __LINE__) #define SError LogStream(Level::Error, _fileName(__FILE__), __LINE__) #define LTrace(...) { LogStream(Level::Trace, _fileName(__FILE__), __LINE__).write(__VA_ARGS__); } #define LDebug(...) { LogStream(Level::Debug, _fileName(__FILE__), __LINE__).write(__VA_ARGS__); } #define LInfo(...) { LogStream(Level::Info, _fileName(__FILE__), __LINE__).write(__VA_ARGS__); } #define LWarn(...) { LogStream(Level::Warn, _fileName(__FILE__), __LINE__).write(__VA_ARGS__); } #define LError(...) { LogStream(Level::Error, _fileName(__FILE__), __LINE__).write(__VA_ARGS__); } // #define TraceS(self) LogStream(Level::Trace, _fileName(__FILE__), __LINE__, self) // #define DebugS(self) LogStream(Level::Debug, _fileName(__FILE__), __LINE__, self) // #define InfoS(self) LogStream(Level::Info, _fileName(__FILE__), __LINE__, self) // #define WarnS(self) LogStream(Level::Warn, _fileName(__FILE__), __LINE__, self) // #define ErrorS(self) LogStream(Level::Error, _fileName(__FILE__), __LINE__, self) // #define TraceN(self) LogStream(Level::Trace, self->className(), __LINE__, self) // #define DebugN(self) LogStream(Level::Debug, self->className(), __LINE__, self) // #define InfoN(self) LogStream(Level::Info, self->className(), __LINE__, self) // #define WarnN(self) LogStream(Level::Warn, self->className(), __LINE__, self) // #define ErrorN(self) LogStream(Level::Error, self->className(), __LINE__, self) } // namespace scy #endif /// @\}
lgpl-2.1
sunblithe/qt-everywhere-opensource-src-4.7.1
doc/html/tools-plugandpaintplugins-basictools.html
23965
<?xml version="1.0" encoding="UTF-8"?> <!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_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- plugandpaint.qdoc --> <title>Qt 4.7: Plug &amp; Paint Basic Tools Example</title> <link rel="stylesheet" type="text/css" href="style/style.css" /> <script src="scripts/jquery.js" type="text/javascript"></script> <script src="scripts/functions.js" type="text/javascript"></script> </head> <body class="offline narrow creator"> <div class="header" id="qtdocheader"> <div class="content"> <div id="nav-logo"> <a href="index.html">Home</a></div> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> <div id="nav-topright"> <ul> <li class="nav-topright-home"><a href="http://qt.nokia.com/">Qt HOME</a></li> <li class="nav-topright-dev"><a href="http://developer.qt.nokia.com/">DEV</a></li> <li class="nav-topright-labs"><a href="http://labs.qt.nokia.com/blogs/">LABS</a></li> <li class="nav-topright-doc nav-topright-doc-active"><a href="http://doc.qt.nokia.com/"> DOC</a></li> <li class="nav-topright-blog"><a href="http://blog.qt.nokia.com/">BLOG</a></li> </ul> </div> <div id="shortCut"> <ul> <li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.7</a></span></li> <li class="shortCut-topleft-active"><a href="http://doc.qt.nokia.com">ALL VERSIONS </a></li> </ul> </div> <ul class="sf-menu sf-js-enabled sf-shadow" id="narrowmenu"> <li><a href="#">API Lookup</a> <ul id="topmenuLook"> <li><a href="classes.html">Class index</a></li> <li><a href="functions.html">Function index</a></li> <li><a href="modules.html">Modules</a></li> <li><a href="namespaces.html">Namespaces</a></li> <li><a href="qtglobal.html">Global Declarations</a></li> <li><a href="licensing.html">Licenses and Credits</a></li> </ul> </li> <li><a href="#">Qt Topics</a> <ul id="topmenuTopic"> <li><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li><a href="qtquick.html">Device UI's &amp; Qt Quick</a></li> <li><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li><a href="developing-with-qt.html">Cross-platform and Platform-specific</a></li> <li><a href="platform-specific.html">Platform-specific info</a></li> <li><a href="technology-apis.html">Qt and Key Technologies</a></li> <li><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </li> <li><a href="#">Examples</a> <ul id="topmenuexample"> <li><a href="all-examples.html">Examples</a></li> <li><a href="tutorials.html">Tutorials</a></li> <li><a href="demos.html">Demos</a></li> <li><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </li> </ul> </div> </div> <div class="wrapper"> <div class="hd"> <span></span> </div> <div class="bd group"> <div class="sidebar"> <div class="searchlabel"> Search index:</div> <div class="search"> <form id="qtdocsearch" action="" onsubmit="return false;"> <fieldset> <input type="text" name="searchstring" id="pageType" value="" /> </fieldset> </form> </div> <div class="box first bottombar" id="lookup"> <h2 title="API Lookup"><span></span> API Lookup</h2> <div id="list001" class="list"> <ul id="ul001" > <li class="defaultLink"><a href="classes.html">Class index</a></li> <li class="defaultLink"><a href="functions.html">Function index</a></li> <li class="defaultLink"><a href="modules.html">Modules</a></li> <li class="defaultLink"><a href="namespaces.html">Namespaces</a></li> <li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li> <li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </div> </div> <div class="box bottombar" id="topics"> <h2 title="Qt Topics"><span></span> Qt Topics</h2> <div id="list002" class="list"> <ul id="ul002" > <li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li class="defaultLink"><a href="qtquick.html">Device UI's &amp; Qt Quick</a></li> <li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li class="defaultLink"><a href="developing-with-qt.html">Cross-platform and Platform-specific</a></li> <li class="defaultLink"><a href="platform-specific.html">Platform-specific info</a></li> <li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li> <li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </div> </div> <div class="box" id="examples"> <h2 title="Examples"><span></span> Examples</h2> <div id="list003" class="list"> <ul id="ul003"> <li class="defaultLink"><a href="all-examples.html">Examples</a></li> <li class="defaultLink"><a href="tutorials.html">Tutorials</a></li> <li class="defaultLink"><a href="demos.html">Demos</a></li> <li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </div> </div> </div> <div class="wrap"> <div class="toolbar"> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Bread crumbs goes here --> <li><a href="all-examples.html">Examples</a></li> <li>Plug &amp; Paint Basic Tools Example</li> </ul> </div> <div class="toolbuttons toolblock"> <ul> <li id="smallA" class="t_button">A</li> <li id="medA" class="t_button active">A</li> <li id="bigA" class="t_button">A</li> <li id="print" class="t_button"><a href="javascript:this.print();"> <span>Print</span></a></li> </ul> </div> </div> <div class="content"> <div class="toc"> <h3><a name="toc">Contents</a></h3> <ul> <li class="level1"><a href="#declaration-of-the-plugin-class">Declaration of the Plugin Class</a></li> <li class="level1"><a href="#implementation-of-the-brush-interface">Implementation of the Brush Interface</a></li> <li class="level1"><a href="#implementation-of-the-shape-interface">Implementation of the Shape Interface</a></li> <li class="level1"><a href="#implementation-of-the-filter-interface">Implementation of the Filter Interface</a></li> <li class="level1"><a href="#exporting-the-plugin">Exporting the Plugin</a></li> <li class="level1"><a href="#the-pro-file">The .pro File</a></li> </ul> </div> <h1 class="title">Plug &amp; Paint Basic Tools Example</h1> <span class="subtitle"></span> <!-- $$$tools/plugandpaintplugins/basictools-description --> <div class="descr"> <a name="details"></a> <p>Files:</p> <ul> <li><a href="tools-plugandpaintplugins-basictools-basictoolsplugin-cpp.html">tools/plugandpaintplugins/basictools/basictoolsplugin.cpp</a></li> <li><a href="tools-plugandpaintplugins-basictools-basictoolsplugin-h.html">tools/plugandpaintplugins/basictools/basictoolsplugin.h</a></li> <li><a href="tools-plugandpaintplugins-basictools-basictools-pro.html">tools/plugandpaintplugins/basictools/basictools.pro</a></li> </ul> <p>The Basic Tools example is a static plugin for the <a href="tools-plugandpaint.html">Plug &amp; Paint</a> example. It provides a set of basic brushes, shapes, and filters. Through the Basic Tools example, we will review the four steps involved in writing a Qt plugin:</p> <ol class="1"> <li>Declare a plugin class.</li> <li>Implement the interfaces provided by the plugin.</li> <li>Export the plugin using the <a href="qtplugin.html#Q_EXPORT_PLUGIN2">Q_EXPORT_PLUGIN2</a>() macro.</li> <li>Build the plugin using an adequate <tt>.pro</tt> file.</li> </ol> <a name="declaration-of-the-plugin-class"></a> <h2>Declaration of the Plugin Class</h2> <pre class="highlightedCode brush: cpp"> #include &lt;plugandpaint/interfaces.h&gt; class BasicToolsPlugin : public QObject, public BrushInterface, public ShapeInterface, public FilterInterface { Q_OBJECT Q_INTERFACES(BrushInterface ShapeInterface FilterInterface)</pre> <p>We start by including <tt>interfaces.h</tt>, which defines the plugin interfaces for the <a href="tools-plugandpaint.html">Plug &amp; Paint</a> application. For the <tt>#include</tt> to work, we need to add an <tt>INCLUDEPATH</tt> entry to the <tt>.pro</tt> file with the path to Qt's <tt>examples/tools</tt> directory.</p> <p>The <tt>BasicToolsPlugin</tt> class is a <a href="qobject.html">QObject</a> subclass that implements the <tt>BrushInterface</tt>, the <tt>ShapeInterface</tt>, and the <tt>FilterInterface</tt>. This is done through multiple inheritance. The <tt>Q_INTERFACES()</tt> macro is necessary to tell <a href="moc.html#moc">moc</a>, Qt's meta-object compiler, that the base classes are plugin interfaces. Without the <tt>Q_INTERFACES()</tt> macro, we couldn't use <a href="qobject.html#qobject_cast">qobject_cast</a>() in the <a href="tools-plugandpaint.html">Plug &amp; Paint</a> application to detect interfaces.</p> <pre class="highlightedCode brush: cpp"> public: <span class="comment">// BrushInterface</span> QStringList brushes() const; QRect mousePress(const QString &amp;brush, QPainter &amp;painter, const QPoint &amp;pos); QRect mouseMove(const QString &amp;brush, QPainter &amp;painter, const QPoint &amp;oldPos, const QPoint &amp;newPos); QRect mouseRelease(const QString &amp;brush, QPainter &amp;painter, const QPoint &amp;pos); <span class="comment">// ShapeInterface</span> QStringList shapes() const; QPainterPath generateShape(const QString &amp;shape, QWidget *parent); <span class="comment">// FilterInterface</span> QStringList filters() const; QImage filterImage(const QString &amp;filter, const QImage &amp;image, QWidget *parent); };</pre> <p>In the <tt>public</tt> section of the class, we declare all the functions from the three interfaces.</p> <a name="implementation-of-the-brush-interface"></a> <h2>Implementation of the Brush Interface</h2> <p>Let's now review the implementation of the <tt>BasicToolsPlugin</tt> member functions inherited from <tt>BrushInterface</tt>.</p> <pre class="highlightedCode brush: cpp"> QStringList BasicToolsPlugin::brushes() const { return QStringList() &lt;&lt; tr(&quot;Pencil&quot;) &lt;&lt; tr(&quot;Air Brush&quot;) &lt;&lt; tr(&quot;Random Letters&quot;); }</pre> <p>The <tt>brushes()</tt> function returns a list of brushes provided by this plugin. We provide three brushes: <b>Pencil</b>, <b>Air Brush</b>, and <b>Random Letters</b>.</p> <pre class="highlightedCode brush: cpp"> QRect BasicToolsPlugin::mousePress(const QString &amp;brush, QPainter &amp;painter, const QPoint &amp;pos) { return mouseMove(brush, painter, pos, pos); }</pre> <p>On a mouse press event, we just call <tt>mouseMove()</tt> to draw the spot where the event occurred.</p> <pre class="highlightedCode brush: cpp"> QRect BasicToolsPlugin::mouseMove(const QString &amp;brush, QPainter &amp;painter, const QPoint &amp;oldPos, const QPoint &amp;newPos) { painter.save(); int rad = painter.pen().width() / 2; QRect boundingRect = QRect(oldPos, newPos).normalized() .adjusted(-rad, -rad, +rad, +rad); QColor color = painter.pen().color(); int thickness = painter.pen().width(); QColor transparentColor(color.red(), color.green(), color.blue(), 0);</pre> <p>In <tt>mouseMove()</tt>, we start by saving the state of the <a href="qpainter.html">QPainter</a> and we compute a few variables that we'll need later.</p> <pre class="highlightedCode brush: cpp"> if (brush == tr(&quot;Pencil&quot;)) { painter.drawLine(oldPos, newPos); } else if (brush == tr(&quot;Air Brush&quot;)) { int numSteps = 2 + (newPos - oldPos).manhattanLength() / 2; painter.setBrush(QBrush(color, Qt::Dense6Pattern)); painter.setPen(Qt::NoPen); for (int i = 0; i &lt; numSteps; ++i) { int x = oldPos.x() + i * (newPos.x() - oldPos.x()) / (numSteps - 1); int y = oldPos.y() + i * (newPos.y() - oldPos.y()) / (numSteps - 1); painter.drawEllipse(x - (thickness / 2), y - (thickness / 2), thickness, thickness); } } else if (brush == tr(&quot;Random Letters&quot;)) { QChar ch('A' + (qrand() % 26)); QFont biggerFont = painter.font(); biggerFont.setBold(true); biggerFont.setPointSize(biggerFont.pointSize() + thickness); painter.setFont(biggerFont); painter.drawText(newPos, QString(ch)); QFontMetrics metrics(painter.font()); boundingRect = metrics.boundingRect(ch); boundingRect.translate(newPos); boundingRect.adjust(-10, -10, +10, +10); } painter.restore(); return boundingRect; }</pre> <p>Then comes the brush-dependent part of the code:</p> <ul> <li>If the brush is <b>Pencil</b>, we just call <a href="qpainter.html#drawLine">QPainter::drawLine</a>() with the current <a href="qpen.html">QPen</a>.</li> <li>If the brush is <b>Air Brush</b>, we start by setting the painter's <a href="qbrush.html">QBrush</a> to <a href="qt.html#BrushStyle-enum">Qt::Dense6Pattern</a> to obtain a dotted pattern. Then we draw a circle filled with that <a href="qbrush.html">QBrush</a> several times, resulting in a thick line.</li> <li>If the brush is <b>Random Letters</b>, we draw a random letter at the new cursor position. Most of the code is for setting the font to be bold and larger than the default font and for computing an appropriate bounding rect.</li> </ul> <p>At the end, we restore the painter state to what it was upon entering the function and we return the bounding rectangle.</p> <pre class="highlightedCode brush: cpp"> QRect BasicToolsPlugin::mouseRelease(const QString &amp; <span class="comment">/* brush */</span>, QPainter &amp; <span class="comment">/* painter */</span>, const QPoint &amp; <span class="comment">/* pos */</span>) { return QRect(0, 0, 0, 0); }</pre> <p>When the user releases the mouse, we do nothing and return an empty <a href="qrect.html">QRect</a>.</p> <a name="implementation-of-the-shape-interface"></a> <h2>Implementation of the Shape Interface</h2> <pre class="highlightedCode brush: cpp"> QStringList BasicToolsPlugin::shapes() const { return QStringList() &lt;&lt; tr(&quot;Circle&quot;) &lt;&lt; tr(&quot;Star&quot;) &lt;&lt; tr(&quot;Text...&quot;); }</pre> <p>The plugin provides three shapes: <b>Circle</b>, <b>Star</b>, and <b>Text..&#x2e;</b>. The three dots after <b>Text</b> are there because the shape pops up a dialog asking for more information. We know that the shape names will end up in a menu, so we include the three dots in the shape name.</p> <p>A cleaner but more complicated design would have been to distinguish between the internal shape name and the name used in the user interface.</p> <pre class="highlightedCode brush: cpp"> QPainterPath BasicToolsPlugin::generateShape(const QString &amp;shape, QWidget *parent) { QPainterPath path; if (shape == tr(&quot;Circle&quot;)) { path.addEllipse(0, 0, 50, 50); } else if (shape == tr(&quot;Star&quot;)) { path.moveTo(90, 50); for (int i = 1; i &lt; 5; ++i) { path.lineTo(50 + 40 * cos(0.8 * i * Pi), 50 + 40 * sin(0.8 * i * Pi)); } path.closeSubpath(); } else if (shape == tr(&quot;Text...&quot;)) { QString text = QInputDialog::getText(parent, tr(&quot;Text Shape&quot;), tr(&quot;Enter text:&quot;), QLineEdit::Normal, tr(&quot;Qt&quot;)); if (!text.isEmpty()) { QFont timesFont(&quot;Times&quot;, 50); timesFont.setStyleStrategy(QFont::ForceOutline); path.addText(0, 0, timesFont, text); } } return path; }</pre> <p>The <tt>generateShape()</tt> creates a <a href="qpainterpath.html">QPainterPath</a> for the specified shape. If the shape is <b>Text</b>, we pop up a <a href="qinputdialog.html">QInputDialog</a> to let the user enter some text.</p> <a name="implementation-of-the-filter-interface"></a> <h2>Implementation of the Filter Interface</h2> <pre class="highlightedCode brush: cpp"> QStringList BasicToolsPlugin::filters() const { return QStringList() &lt;&lt; tr(&quot;Invert Pixels&quot;) &lt;&lt; tr(&quot;Swap RGB&quot;) &lt;&lt; tr(&quot;Grayscale&quot;); }</pre> <p>The plugin provides three filters: <b>Invert Pixels</b>, <b>Swap RGB</b>, and <b>Grayscale</b>.</p> <pre class="highlightedCode brush: cpp"> QImage BasicToolsPlugin::filterImage(const QString &amp;filter, const QImage &amp;image, QWidget * <span class="comment">/* parent */</span>) { QImage result = image.convertToFormat(QImage::Format_RGB32); if (filter == tr(&quot;Invert Pixels&quot;)) { result.invertPixels(); } else if (filter == tr(&quot;Swap RGB&quot;)) { result = result.rgbSwapped(); } else if (filter == tr(&quot;Grayscale&quot;)) { for (int y = 0; y &lt; result.height(); ++y) { for (int x = 0; x &lt; result.width(); ++x) { int pixel = result.pixel(x, y); int gray = qGray(pixel); int alpha = qAlpha(pixel); result.setPixel(x, y, qRgba(gray, gray, gray, alpha)); } } } return result; }</pre> <p>The <tt>filterImage()</tt> function takes a filter name and a <a href="qimage.html">QImage</a> as parameters and returns an altered <a href="qimage.html">QImage</a>. The first thing we do is to convert the image to a 32-bit RGB format, to ensure that the algorithms will work as expected. For example, <a href="qimage.html#invertPixels">QImage::invertPixels</a>(), which is used to implement the <b>Invert Pixels</b> filter, gives counterintuitive results for 8-bit images, because they invert the indices into the color table instead of inverting the color table's entries.</p> <a name="exporting-the-plugin"></a> <h2>Exporting the Plugin</h2> <p>Whereas applications have a <tt>main()</tt> function as their entry point, plugins need to contain exactly one occurrence of the <a href="qtplugin.html#Q_EXPORT_PLUGIN2">Q_EXPORT_PLUGIN2</a>() macro to specify which class provides the plugin:</p> <pre class="highlightedCode brush: cpp"> Q_EXPORT_PLUGIN2(pnp_basictools, BasicToolsPlugin)</pre> <p>This line may appear in any <tt>.cpp</tt> file that is part of the plugin's source code.</p> <a name="the-pro-file"></a> <h2>The .pro File</h2> <p>Here's the project file for building the Basic Tools plugin:</p> <pre class="highlightedCode brush: cpp"> TEMPLATE = lib CONFIG += plugin static INCLUDEPATH += ../.. HEADERS = basictoolsplugin.h SOURCES = basictoolsplugin.cpp TARGET = $$qtLibraryTarget(pnp_basictools) DESTDIR = ../../plugandpaint/plugins</pre> <p>The <tt>.pro</tt> file differs from typical <tt>.pro</tt> files in many respects. First, it starts with a <tt>TEMPLATE</tt> entry specifying <tt>lib</tt>. (The default template is <tt>app</tt>.) It also adds <tt>plugin</tt> to the <tt>CONFIG</tt> variable. This is necessary on some platforms to avoid generating symbolic links with version numbers in the file name, which is appropriate for most dynamic libraries but not for plugins.</p> <p>To make the plugin a static plugin, all that is required is to specify <tt>static</tt> in addition to <tt>plugin</tt>. The <a href="tools-plugandpaintplugins-extrafilters.html">Extra Filters</a> plugin, which is compiled as a dynamic plugin, doesn't specify <tt>static</tt> in its <tt>.pro</tt> file.</p> <p>The <tt>INCLUDEPATH</tt> variable sets the search paths for global headers (i.e&#x2e;, header files included using <tt>#include &lt;...&gt;</tt>). We add Qt's <tt>examples/tools</tt> directory (strictly speaking, <tt>examples/tools/plugandpaintplugins/basictools/../..</tt>) to the list, so that we can include <tt>&lt;plugandpaint/interfaces.h&gt;</tt>.</p> <p>The <tt>TARGET</tt> variable specifies which name we want to give the target library. We use <tt>pnp_</tt> as the prefix to show that the plugin is designed to work with Plug &amp; Paint. On Unix, <tt>lib</tt> is also prepended to that name. On all platforms, a platform-specific suffix is appended (e.g&#x2e;, <tt>.dll</tt> on Windows, <tt>.a</tt> on Linux).</p> <p>The <tt>CONFIG()</tt> code at the end is necessary for this example because the example is part of the Qt distribution and Qt can be configured to be built simultaneously in debug and in release modes. You don't need to for your own plugins.</p> </div> <!-- @@@tools/plugandpaintplugins/basictools --> <div class="feedback t_button"> [+] Documentation Feedback</div> </div> </div> </div> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2008-2010 Nokia Corporation and/or its subsidiaries. Nokia, Qt and their respective logos are trademarks of Nokia Corporation in Finland and/or other countries worldwide.</p> <p> All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://qt.nokia.com/about/privacy-policy">Privacy Policy</a></p> <br /> <p> Licensees holding valid Qt Commercial licenses may use this document in accordance with the Qt Commercial License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Nokia.</p> <p> Alternatively, this document may be used under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> </div> <div id="feedbackBox"> <div id="feedcloseX" class="feedclose t_button">X</div> <form id="feedform" action="http://doc.qt.nokia.com/docFeedbck/feedback.php" method="get"> <p id="noteHead">Thank you for giving your feedback.</p> <p class="note">Make sure it is related to this specific page. For more general bugs and requests, please use the <a href="http://bugreports.qt.nokia.com/secure/Dashboard.jspa">Qt Bug Tracker</a>.</p> <p><textarea id="feedbox" name="feedText" rows="5" cols="40"></textarea></p> <p><input id="feedsubmit" class="feedclose" type="submit" name="feedback" /></p> </form> </div> <div id="blurpage"> </div> </body> </html>
lgpl-2.1
zaps166/DSPBlocks
Blocks/General/FileReader.hpp
861
#ifndef FILEREADER_HPP #define FILEREADER_HPP #include "Block.hpp" #include <QFile> class FileReader : public Block { friend class FileReaderUI; public: FileReader(); bool start(); void exec( Array< Sample > &samples ); void stop(); Block *createInstance(); private: void serialize( QDataStream &ds ) const; void deSerialize( QDataStream &ds ); bool loop, textMode, pcm_s16; QFile f; }; #include "Settings.hpp" class QPushButton; class QLineEdit; class QCheckBox; class FileReaderUI : public AdditionalSettings { Q_OBJECT public: FileReaderUI( FileReader &block ); void prepare(); void setRunMode( bool b ); private slots: void setValue(); void setLoop(); void setFileName(); void browseFile(); private: FileReader &block; QLineEdit *fileE; QCheckBox *loopB, *textModeB, *pcmB; QPushButton *applyB; }; #endif // FILEREADER_HPP
lgpl-2.1
kkoksvik/FreeCAD
src/Mod/Sketcher/Gui/ViewProviderSketch.cpp
230010
/*************************************************************************** * Copyright (c) 2009 Juergen Riegel <juergen.riegel@web.de> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <Standard_math.hxx> # include <Poly_Polygon3D.hxx> # include <Geom_BSplineCurve.hxx> # include <Geom_Circle.hxx> # include <Geom_Ellipse.hxx> # include <Geom_TrimmedCurve.hxx> # include <Inventor/actions/SoGetBoundingBoxAction.h> # include <Inventor/SoPath.h> # include <Inventor/SbBox3f.h> # include <Inventor/SbImage.h> # include <Inventor/SoPickedPoint.h> # include <Inventor/details/SoLineDetail.h> # include <Inventor/details/SoPointDetail.h> # include <Inventor/nodes/SoBaseColor.h> # include <Inventor/nodes/SoCoordinate3.h> # include <Inventor/nodes/SoDrawStyle.h> # include <Inventor/nodes/SoImage.h> # include <Inventor/nodes/SoInfo.h> # include <Inventor/nodes/SoLineSet.h> # include <Inventor/nodes/SoPointSet.h> # include <Inventor/nodes/SoMarkerSet.h> # include <Inventor/nodes/SoMaterial.h> # include <Inventor/nodes/SoAsciiText.h> # include <Inventor/nodes/SoTransform.h> # include <Inventor/nodes/SoSeparator.h> # include <Inventor/nodes/SoAnnotation.h> # include <Inventor/nodes/SoVertexProperty.h> # include <Inventor/nodes/SoTranslation.h> # include <Inventor/nodes/SoText2.h> # include <Inventor/nodes/SoFont.h> # include <Inventor/nodes/SoPickStyle.h> # include <Inventor/nodes/SoCamera.h> /// Qt Include Files # include <QAction> # include <QApplication> # include <QColor> # include <QDialog> # include <QFont> # include <QImage> # include <QMenu> # include <QMessageBox> # include <QPainter> # include <QTextStream> #endif #ifndef _PreComp_ # include <boost/bind.hpp> #endif #include <Inventor/SbTime.h> #include <boost/scoped_ptr.hpp> /// Here the FreeCAD includes sorted by Base,App,Gui...... #include <Base/Tools.h> #include <Base/Parameter.h> #include <Base/Console.h> #include <Base/Vector3D.h> #include <Gui/Application.h> #include <Gui/BitmapFactory.h> #include <Gui/Document.h> #include <Gui/Command.h> #include <Gui/Control.h> #include <Gui/Selection.h> #include <Gui/Utilities.h> #include <Gui/MainWindow.h> #include <Gui/MenuManager.h> #include <Gui/View3DInventor.h> #include <Gui/View3DInventorViewer.h> #include <Gui/DlgEditFileIncludeProptertyExternal.h> #include <Gui/SoFCBoundingBox.h> #include <Gui/SoFCUnifiedSelection.h> #include <Gui/Inventor/MarkerBitmaps.h> #include <Mod/Part/App/Geometry.h> #include <Mod/Sketcher/App/SketchObject.h> #include <Mod/Sketcher/App/Sketch.h> #include "SoZoomTranslation.h" #include "SoDatumLabel.h" #include "EditDatumDialog.h" #include "ViewProviderSketch.h" #include "DrawSketchHandler.h" #include "TaskDlgEditSketch.h" #include "TaskSketcherValidation.h" // The first is used to point at a SoDatumLabel for some // constraints, and at a SoMaterial for others... #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 #define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1 #define CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON 2 #define CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID 3 #define CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION 4 #define CONSTRAINT_SEPARATOR_INDEX_SECOND_ICON 5 #define CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID 6 using namespace SketcherGui; using namespace Sketcher; SbColor ViewProviderSketch::VertexColor (1.0f,0.149f,0.0f); // #FF2600 -> (255, 38, 0) SbColor ViewProviderSketch::CurveColor (1.0f,1.0f,1.0f); // #FFFFFF -> (255,255,255) SbColor ViewProviderSketch::CurveDraftColor (0.0f,0.0f,0.86f); // #0000DC -> ( 0, 0,220) SbColor ViewProviderSketch::CurveExternalColor (0.8f,0.2f,0.6f); // #CC3399 -> (204, 51,153) SbColor ViewProviderSketch::CrossColorH (0.8f,0.4f,0.4f); // #CC6666 -> (204,102,102) SbColor ViewProviderSketch::CrossColorV (0.4f,0.8f,0.4f); // #66CC66 -> (102,204,102) SbColor ViewProviderSketch::FullyConstrainedColor (0.0f,1.0f,0.0f); // #00FF00 -> ( 0,255, 0) SbColor ViewProviderSketch::ConstrDimColor (1.0f,0.149f,0.0f); // #FF2600 -> (255, 38, 0) SbColor ViewProviderSketch::ConstrIcoColor (1.0f,0.149f,0.0f); // #FF2600 -> (255, 38, 0) SbColor ViewProviderSketch::NonDrivingConstrDimColor (0.0f,0.149f,1.0f); // #0026FF -> ( 0, 38,255) SbColor ViewProviderSketch::PreselectColor (0.88f,0.88f,0.0f); // #E1E100 -> (225,225, 0) SbColor ViewProviderSketch::SelectColor (0.11f,0.68f,0.11f); // #1CAD1C -> ( 28,173, 28) SbColor ViewProviderSketch::PreselectSelectedColor (0.36f,0.48f,0.11f); // #5D7B1C -> ( 93,123, 28) // Variables for holding previous click SbTime ViewProviderSketch::prvClickTime; SbVec3f ViewProviderSketch::prvClickPoint; SbVec2s ViewProviderSketch::prvCursorPos; SbVec2s ViewProviderSketch::newCursorPos; //************************************************************************** // Edit data structure /// Data structure while editing the sketch struct EditData { EditData(): sketchHandler(0), editDatumDialog(false), buttonPress(false), DragPoint(-1), DragCurve(-1), PreselectPoint(-1), PreselectCurve(-1), PreselectCross(-1), MarkerSize(7), blockedPreselection(false), FullyConstrained(false), //ActSketch(0), // if you are wondering, it went to SketchObject, accessible via getSketchObject()->getSolvedSketch() EditRoot(0), PointsMaterials(0), CurvesMaterials(0), PointsCoordinate(0), CurvesCoordinate(0), CurveSet(0), RootCrossSet(0), EditCurveSet(0), PointSet(0), pickStyleAxes(0) {} // pointer to the active handler for new sketch objects DrawSketchHandler *sketchHandler; bool editDatumDialog; bool buttonPress; // dragged point int DragPoint; // dragged curve int DragCurve; // dragged constraints std::set<int> DragConstraintSet; SbColor PreselectOldColor; int PreselectPoint; int PreselectCurve; int PreselectCross; int MarkerSize; std::set<int> PreselectConstraintSet; bool blockedPreselection; bool FullyConstrained; bool visibleBeforeEdit; // container to track our own selected parts std::set<int> SelPointSet; std::set<int> SelCurvSet; // also holds cross axes at -1 and -2 std::set<int> SelConstraintSet; std::vector<int> CurvIdToGeoId; // conversion of SoLineSet index to GeoId // helper data structures for the constraint rendering std::vector<ConstraintType> vConstrType; // For each of the combined constraint icons drawn, also create a vector // of bounding boxes and associated constraint IDs, to go from the icon's // pixel coordinates to the relevant constraint IDs. // // The outside map goes from a string representation of a set of constraint // icons (like the one used by the constraint IDs we insert into the Coin // rendering tree) to a vector of those bounding boxes paired with relevant // constraint IDs. std::map<QString, ViewProviderSketch::ConstrIconBBVec> combinedConstrBoxes; // nodes for the visuals SoSeparator *EditRoot; SoMaterial *PointsMaterials; SoMaterial *CurvesMaterials; SoMaterial *RootCrossMaterials; SoMaterial *EditCurvesMaterials; SoCoordinate3 *PointsCoordinate; SoCoordinate3 *CurvesCoordinate; SoCoordinate3 *RootCrossCoordinate; SoCoordinate3 *EditCurvesCoordinate; SoLineSet *CurveSet; SoLineSet *RootCrossSet; SoLineSet *EditCurveSet; SoMarkerSet *PointSet; SoText2 *textX; SoTranslation *textPos; SoGroup *constrGroup; SoPickStyle *pickStyleAxes; }; // this function is used to simulate cyclic periodic negative geometry indices (for external geometry) const Part::Geometry* GeoById(const std::vector<Part::Geometry*> GeoList, int Id) { if (Id >= 0) return GeoList[Id]; else return GeoList[GeoList.size()+Id]; } //************************************************************************** // Construction/Destruction /* TRANSLATOR SketcherGui::ViewProviderSketch */ PROPERTY_SOURCE(SketcherGui::ViewProviderSketch, PartGui::ViewProvider2DObject) ViewProviderSketch::ViewProviderSketch() : edit(0), Mode(STATUS_NONE) { // FIXME Should this be placed in here? ADD_PROPERTY_TYPE(Autoconstraints,(true),"Auto Constraints",(App::PropertyType)(App::Prop_None),"Create auto constraints"); sPixmap = "Sketcher_Sketch"; LineColor.setValue(1,1,1); PointColor.setValue(1,1,1); PointSize.setValue(4); zCross=0.001f; zLines=0.005f; zConstr=0.006f; // constraint not construction zHighLine=0.007f; zPoints=0.008f; zHighlight=0.009f; zText=0.011f; zEdit=0.001f; xInit=0; yInit=0; relative=false; unsigned long color; ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); // edge color App::Color edgeColor = LineColor.getValue(); color = (unsigned long)(edgeColor.getPackedValue()); color = hGrp->GetUnsigned("SketchEdgeColor", color); edgeColor.setPackedValue((uint32_t)color); LineColor.setValue(edgeColor); // vertex color App::Color vertexColor = PointColor.getValue(); color = (unsigned long)(vertexColor.getPackedValue()); color = hGrp->GetUnsigned("SketchVertexColor", color); vertexColor.setPackedValue((uint32_t)color); PointColor.setValue(vertexColor); //rubberband selection rubberband = new Gui::Rubberband(); } ViewProviderSketch::~ViewProviderSketch() { delete rubberband; } void ViewProviderSketch::slotUndoDocument(const Gui::Document& doc) { if(getSketchObject()->noRecomputes) getSketchObject()->solve(); // the sketch must be solved to update the DoF of the solver else getSketchObject()->getDocument()->recompute(); // or fully recomputed if applicable } void ViewProviderSketch::slotRedoDocument(const Gui::Document& doc) { if(getSketchObject()->noRecomputes) getSketchObject()->solve(); // the sketch must be solved to update the DoF of the solver else getSketchObject()->getDocument()->recompute(); // or fully recomputed if applicable } // handler management *************************************************************** void ViewProviderSketch::activateHandler(DrawSketchHandler *newHandler) { assert(edit); assert(edit->sketchHandler == 0); edit->sketchHandler = newHandler; Mode = STATUS_SKETCH_UseHandler; edit->sketchHandler->sketchgui = this; edit->sketchHandler->activated(this); } void ViewProviderSketch::deactivateHandler() { assert(edit); if(edit->sketchHandler != 0){ std::vector<Base::Vector2D> editCurve; editCurve.clear(); drawEdit(editCurve); // erase any line edit->sketchHandler->deactivated(this); edit->sketchHandler->unsetCursor(); delete(edit->sketchHandler); } edit->sketchHandler = 0; Mode = STATUS_NONE; } /// removes the active handler void ViewProviderSketch::purgeHandler(void) { deactivateHandler(); // ensure that we are in sketch only selection mode Gui::MDIView *mdi = Gui::Application::Instance->activeDocument()->getActiveView(); Gui::View3DInventorViewer *viewer; viewer = static_cast<Gui::View3DInventor *>(mdi)->getViewer(); SoNode* root = viewer->getSceneGraph(); static_cast<Gui::SoFCUnifiedSelection*>(root)->selectionRole.setValue(false); } void ViewProviderSketch::setAxisPickStyle(bool on) { assert(edit); if (on) edit->pickStyleAxes->style = SoPickStyle::SHAPE; else edit->pickStyleAxes->style = SoPickStyle::UNPICKABLE; } // ********************************************************************************** bool ViewProviderSketch::keyPressed(bool pressed, int key) { switch (key) { case SoKeyboardEvent::ESCAPE: { // make the handler quit but not the edit mode if (edit && edit->sketchHandler) { if (!pressed) edit->sketchHandler->quit(); return true; } if (edit && edit->editDatumDialog) { edit->editDatumDialog = false; return true; } if (edit && (edit->DragConstraintSet.empty() == false)) { if (!pressed) { edit->DragConstraintSet.clear(); } return true; } if (edit && edit->DragCurve >= 0) { if (!pressed) { getSketchObject()->movePoint(edit->DragCurve, Sketcher::none, Base::Vector3d(0,0,0), true); edit->DragCurve = -1; resetPositionText(); Mode = STATUS_NONE; } return true; } if (edit && edit->DragPoint >= 0) { if (!pressed) { int GeoId; Sketcher::PointPos PosId; getSketchObject()->getGeoVertexIndex(edit->DragPoint, GeoId, PosId); getSketchObject()->movePoint(GeoId, PosId, Base::Vector3d(0,0,0), true); edit->DragPoint = -1; resetPositionText(); Mode = STATUS_NONE; } return true; } if (edit) { // #0001479: 'Escape' key dismissing dialog cancels Sketch editing // If we receive a button release event but not a press event before // then ignore this one. if (!pressed && !edit->buttonPress) return true; edit->buttonPress = pressed; } return false; } default: { if (edit && edit->sketchHandler) edit->sketchHandler->registerPressedKey(pressed,key); } } return true; // handle all other key events } void ViewProviderSketch::snapToGrid(double &x, double &y) { if (GridSnap.getValue() != false) { // Snap Tolerance in pixels const double snapTol = GridSize.getValue() / 5; double tmpX = x, tmpY = y; // Find Nearest Snap points tmpX = tmpX / GridSize.getValue(); tmpX = tmpX < 0.0 ? ceil(tmpX - 0.5) : floor(tmpX + 0.5); tmpX *= GridSize.getValue(); tmpY = tmpY / GridSize.getValue(); tmpY = tmpY < 0.0 ? ceil(tmpY - 0.5) : floor(tmpY + 0.5); tmpY *= GridSize.getValue(); // Check if x within snap tolerance if (x < tmpX + snapTol && x > tmpX - snapTol) x = tmpX; // Snap X Mouse Position // Check if y within snap tolerance if (y < tmpY + snapTol && y > tmpY - snapTol) y = tmpY; // Snap Y Mouse Position } } void ViewProviderSketch::getProjectingLine(const SbVec2s& pnt, const Gui::View3DInventorViewer *viewer, SbLine& line) const { const SbViewportRegion& vp = viewer->getSoRenderManager()->getViewportRegion(); short x,y; pnt.getValue(x,y); SbVec2f siz = vp.getViewportSize(); float dX, dY; siz.getValue(dX, dY); float fRatio = vp.getViewportAspectRatio(); float pX = (float)x / float(vp.getViewportSizePixels()[0]); float pY = (float)y / float(vp.getViewportSizePixels()[1]); // now calculate the real points respecting aspect ratio information // if (fRatio > 1.0f) { pX = (pX - 0.5f*dX) * fRatio + 0.5f*dX; } else if (fRatio < 1.0f) { pY = (pY - 0.5f*dY) / fRatio + 0.5f*dY; } SoCamera* pCam = viewer->getSoRenderManager()->getCamera(); if (!pCam) return; SbViewVolume vol = pCam->getViewVolume(); vol.projectPointToLine(SbVec2f(pX,pY), line); } void ViewProviderSketch::getCoordsOnSketchPlane(double &u, double &v,const SbVec3f &point, const SbVec3f &normal) { // Plane form Base::Vector3d R0(0,0,0),RN(0,0,1),RX(1,0,0),RY(0,1,0); // move to position of Sketch Base::Placement Plz = getSketchObject()->Placement.getValue(); R0 = Plz.getPosition() ; Base::Rotation tmp(Plz.getRotation()); tmp.multVec(RN,RN); tmp.multVec(RX,RX); tmp.multVec(RY,RY); Plz.setRotation(tmp); // line Base::Vector3d R1(point[0],point[1],point[2]),RA(normal[0],normal[1],normal[2]); if (fabs(RN*RA) < FLT_EPSILON) throw Base::DivisionByZeroError("View direction is parallel to sketch plane"); // intersection point on plane Base::Vector3d S = R1 + ((RN * (R0-R1))/(RN*RA))*RA; // distance to x Axle of the sketch S.TransformToCoordinateSystem(R0,RX,RY); u = S.x; v = S.y; } bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVec2s &cursorPos, const Gui::View3DInventorViewer *viewer) { assert(edit); // Calculate 3d point to the mouse position SbLine line; getProjectingLine(cursorPos, viewer, line); SbVec3f point = line.getPosition(); SbVec3f normal = line.getDirection(); // use scoped_ptr to make sure that instance gets deleted in all cases boost::scoped_ptr<SoPickedPoint> pp(this->getPointOnRay(cursorPos, viewer)); // Radius maximum to allow double click event const int dblClickRadius = 5; double x,y; SbVec3f pos = point; if (pp) { const SoDetail *detail = pp->getDetail(); if (detail && detail->getTypeId() == SoPointDetail::getClassTypeId()) { pos = pp->getPoint(); } } try { getCoordsOnSketchPlane(x,y,pos,normal); snapToGrid(x, y); } catch (const Base::DivisionByZeroError&) { return false; } // Left Mouse button **************************************************** if (Button == 1) { if (pressed) { // Do things depending on the mode of the user interaction switch (Mode) { case STATUS_NONE:{ bool done=false; if (edit->PreselectPoint != -1) { //Base::Console().Log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Point; done = true; } else if (edit->PreselectCurve != -1) { //Base::Console().Log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Edge; done = true; } else if (edit->PreselectCross != -1) { //Base::Console().Log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Cross; done = true; } else if (edit->PreselectConstraintSet.empty() != true) { //Base::Console().Log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Constraint; done = true; } // Double click events variables float dci = (float) QApplication::doubleClickInterval()/1000.0f; if (done && (point - prvClickPoint).length() < dblClickRadius && (SbTime::getTimeOfDay() - prvClickTime).getValue() < dci) { // Double Click Event Occured editDoubleClicked(); // Reset Double Click Static Variables prvClickTime = SbTime(); prvClickPoint = SbVec3f(0.0f, 0.0f, 0.0f); Mode = STATUS_NONE; } else { prvClickTime = SbTime::getTimeOfDay(); prvClickPoint = point; prvCursorPos = cursorPos; newCursorPos = cursorPos; if (!done) Mode = STATUS_SKETCH_StartRubberBand; } return done; } case STATUS_SKETCH_UseHandler: return edit->sketchHandler->pressButton(Base::Vector2D(x,y)); default: return false; } } else { // Button 1 released // Do things depending on the mode of the user interaction switch (Mode) { case STATUS_SELECT_Point: if (pp) { //Base::Console().Log("Select Point:%d\n",this->DragPoint); // Do selection std::stringstream ss; ss << "Vertex" << edit->PreselectPoint + 1; if (Gui::Selection().isSelected(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(),ss.str().c_str()) ) { Gui::Selection().rmvSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(), ss.str().c_str()); } else { Gui::Selection().addSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,ss.str().c_str() ,pp->getPoint()[0] ,pp->getPoint()[1] ,pp->getPoint()[2]); this->edit->DragPoint = -1; this->edit->DragCurve = -1; this->edit->DragConstraintSet.clear(); } } Mode = STATUS_NONE; return true; case STATUS_SELECT_Edge: if (pp) { //Base::Console().Log("Select Point:%d\n",this->DragPoint); std::stringstream ss; if (edit->PreselectCurve >= 0) ss << "Edge" << edit->PreselectCurve + 1; else // external geometry ss << "ExternalEdge" << -edit->PreselectCurve - 2; // If edge already selected move from selection if (Gui::Selection().isSelected(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(),ss.str().c_str()) ) { Gui::Selection().rmvSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(), ss.str().c_str()); } else { // Add edge to the selection Gui::Selection().addSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,ss.str().c_str() ,pp->getPoint()[0] ,pp->getPoint()[1] ,pp->getPoint()[2]); this->edit->DragPoint = -1; this->edit->DragCurve = -1; this->edit->DragConstraintSet.clear(); } } Mode = STATUS_NONE; return true; case STATUS_SELECT_Cross: if (pp) { //Base::Console().Log("Select Point:%d\n",this->DragPoint); std::stringstream ss; switch(edit->PreselectCross){ case 0: ss << "RootPoint" ; break; case 1: ss << "H_Axis" ; break; case 2: ss << "V_Axis" ; break; } // If cross already selected move from selection if (Gui::Selection().isSelected(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(),ss.str().c_str()) ) { Gui::Selection().rmvSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(), ss.str().c_str()); } else { // Add cross to the selection Gui::Selection().addSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,ss.str().c_str() ,pp->getPoint()[0] ,pp->getPoint()[1] ,pp->getPoint()[2]); this->edit->DragPoint = -1; this->edit->DragCurve = -1; this->edit->DragConstraintSet.clear(); } } Mode = STATUS_NONE; return true; case STATUS_SELECT_Constraint: if (pp) { for(std::set<int>::iterator it = edit->PreselectConstraintSet.begin(); it != edit->PreselectConstraintSet.end(); ++it) { std::string constraintName(Sketcher::PropertyConstraintList::getConstraintName(*it)); // If the constraint already selected remove if (Gui::Selection().isSelected(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(),constraintName.c_str()) ) { Gui::Selection().rmvSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument(), constraintName.c_str()); } else { // Add constraint to current selection Gui::Selection().addSelection(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,constraintName.c_str() ,pp->getPoint()[0] ,pp->getPoint()[1] ,pp->getPoint()[2]); this->edit->DragPoint = -1; this->edit->DragCurve = -1; this->edit->DragConstraintSet.clear(); } } } Mode = STATUS_NONE; return true; case STATUS_SKETCH_DragPoint: if (edit->DragPoint != -1) { int GeoId; Sketcher::PointPos PosId; getSketchObject()->getGeoVertexIndex(edit->DragPoint, GeoId, PosId); if (GeoId != Sketcher::Constraint::GeoUndef && PosId != Sketcher::none) { Gui::Command::openCommand("Drag Point"); try { Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.movePoint(%i,%i,App.Vector(%f,%f,0),%i)" ,getObject()->getNameInDocument() ,GeoId, PosId, x-xInit, y-yInit, relative ? 1 : 0 ); Gui::Command::commitCommand(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); bool autoRecompute = hGrp->GetBool("AutoRecompute",false); if(autoRecompute) Gui::Command::updateActive(); } catch (const Base::Exception& e) { Gui::Command::abortCommand(); Base::Console().Error("Drag point: %s\n", e.what()); } } setPreselectPoint(edit->DragPoint); edit->DragPoint = -1; //updateColor(); } resetPositionText(); Mode = STATUS_NONE; return true; case STATUS_SKETCH_DragCurve: if (edit->DragCurve != -1) { const Part::Geometry *geo = getSketchObject()->getGeometry(edit->DragCurve); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId() || geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId() || geo->getTypeId() == Part::GeomCircle::getClassTypeId() || geo->getTypeId() == Part::GeomEllipse::getClassTypeId()|| geo->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { Gui::Command::openCommand("Drag Curve"); try { Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.movePoint(%i,%i,App.Vector(%f,%f,0),%i)" ,getObject()->getNameInDocument() ,edit->DragCurve, Sketcher::none, x-xInit, y-yInit, relative ? 1 : 0 ); Gui::Command::commitCommand(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); bool autoRecompute = hGrp->GetBool("AutoRecompute",false); if(autoRecompute) Gui::Command::updateActive(); } catch (const Base::Exception& e) { Gui::Command::abortCommand(); Base::Console().Error("Drag curve: %s\n", e.what()); } } edit->PreselectCurve = edit->DragCurve; edit->DragCurve = -1; //updateColor(); } resetPositionText(); Mode = STATUS_NONE; return true; case STATUS_SKETCH_DragConstraint: if (edit->DragConstraintSet.empty() == false) { Gui::Command::openCommand("Drag Constraint"); for(std::set<int>::iterator it = edit->DragConstraintSet.begin(); it != edit->DragConstraintSet.end(); ++it) { moveConstraint(*it, Base::Vector2D(x, y)); //updateColor(); } edit->PreselectConstraintSet = edit->DragConstraintSet; edit->DragConstraintSet.clear(); } Mode = STATUS_NONE; return true; case STATUS_SKETCH_StartRubberBand: // a single click happened, so clear selection Mode = STATUS_NONE; Gui::Selection().clearSelection(); return true; case STATUS_SKETCH_UseRubberBand: doBoxSelection(prvCursorPos, cursorPos, viewer); rubberband->setWorking(false); //disable framebuffer drawing in viewer const_cast<Gui::View3DInventorViewer *>(viewer)->setRenderType(Gui::View3DInventorViewer::Native); // a redraw is required in order to clear the rubberband draw(true); Mode = STATUS_NONE; return true; case STATUS_SKETCH_UseHandler: return edit->sketchHandler->releaseButton(Base::Vector2D(x,y)); case STATUS_NONE: default: return false; } } } // Right mouse button **************************************************** else if (Button == 2) { if (!pressed) { switch (Mode) { case STATUS_SKETCH_UseHandler: // make the handler quit edit->sketchHandler->quit(); return true; case STATUS_NONE: { // A right click shouldn't change the Edit Mode if (edit->PreselectPoint != -1) { return true; } else if (edit->PreselectCurve != -1) { return true; } else if (edit->PreselectConstraintSet.empty() != true) { return true; } else { Gui::MenuItem *geom = new Gui::MenuItem(); geom->setCommand("Sketcher geoms"); *geom << "Sketcher_CreatePoint" << "Sketcher_CreateArc" << "Sketcher_Create3PointArc" << "Sketcher_CreateCircle" << "Sketcher_Create3PointCircle" << "Sketcher_CreateLine" << "Sketcher_CreatePolyline" << "Sketcher_CreateRectangle" << "Sketcher_CreateHexagon" << "Sketcher_CreateFillet" << "Sketcher_Trimming" << "Sketcher_External" << "Sketcher_ToggleConstruction" /*<< "Sketcher_CreateText"*/ /*<< "Sketcher_CreateDraftLine"*/ << "Separator"; Gui::Application::Instance->setupContextMenu("View", geom); //Create the Context Menu using the Main View Qt Widget QMenu contextMenu(viewer->getGLWidget()); Gui::MenuManager::getInstance()->setupContextMenu(geom, contextMenu); contextMenu.exec(QCursor::pos()); return true; } } case STATUS_SELECT_Point: break; case STATUS_SELECT_Edge: { Gui::MenuItem *geom = new Gui::MenuItem(); geom->setCommand("Sketcher constraints"); *geom << "Sketcher_ConstrainVertical" << "Sketcher_ConstrainHorizontal"; // Gets a selection vector std::vector<Gui::SelectionObject> selection = Gui::Selection().getSelectionEx(); bool rightClickOnSelectedLine = false; /* * Add Multiple Line Constraints to the menu */ // only one sketch with its subelements are allowed to be selected if (selection.size() == 1) { // get the needed lists and objects const std::vector<std::string> &SubNames = selection[0].getSubNames(); // Two Objects are selected if (SubNames.size() == 2) { // go through the selected subelements for (std::vector<std::string>::const_iterator it=SubNames.begin(); it!=SubNames.end();++it) { // If the object selected is of type edge if (it->size() > 4 && it->substr(0,4) == "Edge") { // Get the index of the object selected int GeoId = std::atoi(it->substr(4,4000).c_str()) - 1; if (edit->PreselectCurve == GeoId) rightClickOnSelectedLine = true; } else { // The selection is not exclusively edges rightClickOnSelectedLine = false; } } // End of Iteration } } if (rightClickOnSelectedLine) { *geom << "Sketcher_ConstrainParallel" << "Sketcher_ConstrainPerpendicular"; } Gui::Application::Instance->setupContextMenu("View", geom); //Create the Context Menu using the Main View Qt Widget QMenu contextMenu(viewer->getGLWidget()); Gui::MenuManager::getInstance()->setupContextMenu(geom, contextMenu); contextMenu.exec(QCursor::pos()); return true; } case STATUS_SELECT_Cross: case STATUS_SELECT_Constraint: case STATUS_SKETCH_DragPoint: case STATUS_SKETCH_DragCurve: case STATUS_SKETCH_DragConstraint: case STATUS_SKETCH_StartRubberBand: case STATUS_SKETCH_UseRubberBand: break; } } } return false; } void ViewProviderSketch::editDoubleClicked(void) { if (edit->PreselectPoint != -1) { Base::Console().Log("double click point:%d\n",edit->PreselectPoint); } else if (edit->PreselectCurve != -1) { Base::Console().Log("double click edge:%d\n",edit->PreselectCurve); } else if (edit->PreselectCross != -1) { Base::Console().Log("double click cross:%d\n",edit->PreselectCross); } else if (edit->PreselectConstraintSet.empty() != true) { // Find the constraint const std::vector<Sketcher::Constraint *> &constrlist = getSketchObject()->Constraints.getValues(); for(std::set<int>::iterator it = edit->PreselectConstraintSet.begin(); it != edit->PreselectConstraintSet.end(); ++it) { Constraint *Constr = constrlist[*it]; // if its the right constraint if ((Constr->Type == Sketcher::Distance || Constr->Type == Sketcher::DistanceX || Constr->Type == Sketcher::DistanceY || Constr->Type == Sketcher::Radius || Constr->Type == Sketcher::Angle || Constr->Type == Sketcher::SnellsLaw) && Constr->isDriving ) { // Coin's SoIdleSensor causes problems on some platform while Qt seems to work properly (#0001517) EditDatumDialog *editDatumDialog = new EditDatumDialog(this, *it); QCoreApplication::postEvent(editDatumDialog, new QEvent(QEvent::User)); edit->editDatumDialog = true; // avoid to double handle "ESC" } } } } bool ViewProviderSketch::mouseMove(const SbVec2s &cursorPos, Gui::View3DInventorViewer *viewer) { // maximum radius for mouse moves when selecting a geometry before switching to drag mode const int dragIgnoredDistance = 3; if (!edit) return false; // ignore small moves after selection switch (Mode) { case STATUS_SELECT_Point: case STATUS_SELECT_Edge: case STATUS_SELECT_Constraint: case STATUS_SKETCH_StartRubberBand: short dx, dy; (cursorPos - prvCursorPos).getValue(dx, dy); if(std::abs(dx) < dragIgnoredDistance && std::abs(dy) < dragIgnoredDistance) return false; default: break; } // Calculate 3d point to the mouse position SbLine line; getProjectingLine(cursorPos, viewer, line); double x,y; try { getCoordsOnSketchPlane(x,y,line.getPosition(),line.getDirection()); snapToGrid(x, y); } catch (const Base::DivisionByZeroError&) { return false; } bool preselectChanged = false; if (Mode != STATUS_SELECT_Point && Mode != STATUS_SELECT_Edge && Mode != STATUS_SELECT_Constraint && Mode != STATUS_SKETCH_DragPoint && Mode != STATUS_SKETCH_DragCurve && Mode != STATUS_SKETCH_DragConstraint && Mode != STATUS_SKETCH_UseRubberBand) { boost::scoped_ptr<SoPickedPoint> pp(this->getPointOnRay(cursorPos, viewer)); preselectChanged = detectPreselection(pp.get(), viewer, cursorPos); } switch (Mode) { case STATUS_NONE: if (preselectChanged) { this->drawConstraintIcons(); this->updateColor(); return true; } return false; case STATUS_SELECT_Point: if (!getSketchObject()->getSolvedSketch().hasConflicts() && edit->PreselectPoint != -1 && edit->DragPoint != edit->PreselectPoint) { Mode = STATUS_SKETCH_DragPoint; edit->DragPoint = edit->PreselectPoint; int GeoId; Sketcher::PointPos PosId; getSketchObject()->getGeoVertexIndex(edit->DragPoint, GeoId, PosId); if (GeoId != Sketcher::Constraint::GeoUndef && PosId != Sketcher::none) { getSketchObject()->getSolvedSketch().initMove(GeoId, PosId, false); relative = false; xInit = 0; yInit = 0; } } else { Mode = STATUS_NONE; } resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); return true; case STATUS_SELECT_Edge: if (!getSketchObject()->getSolvedSketch().hasConflicts() && edit->PreselectCurve != -1 && edit->DragCurve != edit->PreselectCurve) { Mode = STATUS_SKETCH_DragCurve; edit->DragCurve = edit->PreselectCurve; getSketchObject()->getSolvedSketch().initMove(edit->DragCurve, Sketcher::none, false); const Part::Geometry *geo = getSketchObject()->getGeometry(edit->DragCurve); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { relative = true; //xInit = x; //yInit = y; // Since the cursor moved from where it was clicked, and this is a relative move, // calculate the click position and use it as initial point. SbLine line2; getProjectingLine(prvCursorPos, viewer, line2); getCoordsOnSketchPlane(xInit,yInit,line2.getPosition(),line2.getDirection()); snapToGrid(xInit, yInit); } else { relative = false; xInit = 0; yInit = 0; } } else { Mode = STATUS_NONE; } resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); return true; case STATUS_SELECT_Constraint: Mode = STATUS_SKETCH_DragConstraint; edit->DragConstraintSet = edit->PreselectConstraintSet; resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); return true; case STATUS_SKETCH_DragPoint: if (edit->DragPoint != -1) { //Base::Console().Log("Drag Point:%d\n",edit->DragPoint); int GeoId; Sketcher::PointPos PosId; getSketchObject()->getGeoVertexIndex(edit->DragPoint, GeoId, PosId); Base::Vector3d vec(x-xInit,y-yInit,0); if (GeoId != Sketcher::Constraint::GeoUndef && PosId != Sketcher::none) { if (getSketchObject()->getSolvedSketch().movePoint(GeoId, PosId, vec, relative) == 0) { setPositionText(Base::Vector2D(x,y)); draw(true); signalSolved(QString::fromLatin1("Solved in %1 sec").arg(getSketchObject()->getSolvedSketch().SolveTime)); } else { signalSolved(QString::fromLatin1("Unsolved (%1 sec)").arg(getSketchObject()->getSolvedSketch().SolveTime)); //Base::Console().Log("Error solving:%d\n",ret); } } } return true; case STATUS_SKETCH_DragCurve: if (edit->DragCurve != -1) { Base::Vector3d vec(x-xInit,y-yInit,0); if (getSketchObject()->getSolvedSketch().movePoint(edit->DragCurve, Sketcher::none, vec, relative) == 0) { setPositionText(Base::Vector2D(x,y)); draw(true); signalSolved(QString::fromLatin1("Solved in %1 sec").arg(getSketchObject()->getSolvedSketch().SolveTime)); } else { signalSolved(QString::fromLatin1("Unsolved (%1 sec)").arg(getSketchObject()->getSolvedSketch().SolveTime)); } } return true; case STATUS_SKETCH_DragConstraint: if (edit->DragConstraintSet.empty() == false) { for(std::set<int>::iterator it = edit->DragConstraintSet.begin(); it != edit->DragConstraintSet.end(); ++it) moveConstraint(*it, Base::Vector2D(x,y)); } return true; case STATUS_SKETCH_UseHandler: edit->sketchHandler->mouseMove(Base::Vector2D(x,y)); if (preselectChanged) { this->drawConstraintIcons(); this->updateColor(); } return true; case STATUS_SKETCH_StartRubberBand: { Mode = STATUS_SKETCH_UseRubberBand; rubberband->setWorking(true); viewer->setRenderType(Gui::View3DInventorViewer::Image); return true; } case STATUS_SKETCH_UseRubberBand: { newCursorPos = cursorPos; rubberband->setCoords(prvCursorPos.getValue()[0], viewer->getGLWidget()->height() - prvCursorPos.getValue()[1], newCursorPos.getValue()[0], viewer->getGLWidget()->height() - newCursorPos.getValue()[1]); viewer->redraw(); return true; } default: return false; } return false; } void ViewProviderSketch::moveConstraint(int constNum, const Base::Vector2D &toPos) { // are we in edit? if (!edit) return; const std::vector<Sketcher::Constraint *> &constrlist = getSketchObject()->Constraints.getValues(); Constraint *Constr = constrlist[constNum]; #ifdef _DEBUG int intGeoCount = getSketchObject()->getHighestCurveIndex() + 1; int extGeoCount = getSketchObject()->getExternalGeometryCount(); #endif // with memory allocation const std::vector<Part::Geometry *> geomlist = getSketchObject()->getSolvedSketch().extractGeometry(true, true); #ifdef _DEBUG assert(int(geomlist.size()) == extGeoCount + intGeoCount); assert((Constr->First >= -extGeoCount && Constr->First < intGeoCount) || Constr->First != Constraint::GeoUndef); #endif if (Constr->Type == Distance || Constr->Type == DistanceX || Constr->Type == DistanceY || Constr->Type == Radius) { Base::Vector3d p1(0.,0.,0.), p2(0.,0.,0.); if (Constr->SecondPos != Sketcher::none) { // point to point distance p1 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); p2 = getSketchObject()->getSolvedSketch().getPoint(Constr->Second, Constr->SecondPos); } else if (Constr->Second != Constraint::GeoUndef) { // point to line distance p1 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); const Part::Geometry *geo = GeoById(geomlist, Constr->Second); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(geo); Base::Vector3d l2p1 = lineSeg->getStartPoint(); Base::Vector3d l2p2 = lineSeg->getEndPoint(); // calculate the projection of p1 onto line2 p2.ProjToLine(p1-l2p1, l2p2-l2p1); p2 += p1; } else return; } else if (Constr->FirstPos != Sketcher::none) { p2 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); } else if (Constr->First != Constraint::GeoUndef) { const Part::Geometry *geo = GeoById(geomlist, Constr->First); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(geo); p1 = lineSeg->getStartPoint(); p2 = lineSeg->getEndPoint(); } else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo); double radius = arc->getRadius(); p1 = arc->getCenter(); double angle = Constr->LabelPosition; if (angle == 10) { double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); angle = (startangle + endangle)/2; } else { Base::Vector3d tmpDir = Base::Vector3d(toPos.fX, toPos.fY, 0) - p1; angle = atan2(tmpDir.y, tmpDir.x); } p2 = p1 + radius * Base::Vector3d(cos(angle),sin(angle),0.); } else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(geo); double radius = circle->getRadius(); p1 = circle->getCenter(); Base::Vector3d tmpDir = Base::Vector3d(toPos.fX, toPos.fY, 0) - p1; double angle = atan2(tmpDir.y, tmpDir.x); p2 = p1 + radius * Base::Vector3d(cos(angle),sin(angle),0.); } else return; } else return; Base::Vector3d vec = Base::Vector3d(toPos.fX, toPos.fY, 0) - p2; Base::Vector3d dir; if (Constr->Type == Distance || Constr->Type == Radius) dir = (p2-p1).Normalize(); else if (Constr->Type == DistanceX) dir = Base::Vector3d( (p2.x - p1.x >= FLT_EPSILON) ? 1 : -1, 0, 0); else if (Constr->Type == DistanceY) dir = Base::Vector3d(0, (p2.y - p1.y >= FLT_EPSILON) ? 1 : -1, 0); if (Constr->Type == Radius) { Constr->LabelDistance = vec.x * dir.x + vec.y * dir.y; Constr->LabelPosition = atan2(dir.y, dir.x); } else { Base::Vector3d norm(-dir.y,dir.x,0); Constr->LabelDistance = vec.x * norm.x + vec.y * norm.y; if (Constr->Type == Distance || Constr->Type == DistanceX || Constr->Type == DistanceY) { vec = Base::Vector3d(toPos.fX, toPos.fY, 0) - (p2 + p1) / 2; Constr->LabelPosition = vec.x * dir.x + vec.y * dir.y; } } } else if (Constr->Type == Angle) { Base::Vector3d p0(0.,0.,0.); if (Constr->Second != Constraint::GeoUndef) { // line to line angle Base::Vector3d dir1, dir2; if(Constr->Third == Constraint::GeoUndef) { //angle between two lines const Part::Geometry *geo1 = GeoById(geomlist, Constr->First); const Part::Geometry *geo2 = GeoById(geomlist, Constr->Second); if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() || geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) return; const Part::GeomLineSegment *lineSeg1 = dynamic_cast<const Part::GeomLineSegment *>(geo1); const Part::GeomLineSegment *lineSeg2 = dynamic_cast<const Part::GeomLineSegment *>(geo2); bool flip1 = (Constr->FirstPos == end); bool flip2 = (Constr->SecondPos == end); dir1 = (flip1 ? -1. : 1.) * (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()); dir2 = (flip2 ? -1. : 1.) * (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()); Base::Vector3d pnt1 = flip1 ? lineSeg1->getEndPoint() : lineSeg1->getStartPoint(); Base::Vector3d pnt2 = flip2 ? lineSeg2->getEndPoint() : lineSeg2->getStartPoint(); // line-line intersection { double det = dir1.x*dir2.y - dir1.y*dir2.x; if ((det > 0 ? det : -det) < 1e-10) return;// lines are parallel - constraint unmoveable (DeepSOIC: why?..) double c1 = dir1.y*pnt1.x - dir1.x*pnt1.y; double c2 = dir2.y*pnt2.x - dir2.x*pnt2.y; double x = (dir1.x*c2 - dir2.x*c1)/det; double y = (dir1.y*c2 - dir2.y*c1)/det; p0 = Base::Vector3d(x,y,0); } } else {//angle-via-point Base::Vector3d p = getSketchObject()->getSolvedSketch().getPoint(Constr->Third, Constr->ThirdPos); p0 = Base::Vector3d(p.x, p.y, 0); dir1 = getSketchObject()->getSolvedSketch().calculateNormalAtPoint(Constr->First, p.x, p.y); dir1.RotateZ(-M_PI/2);//convert to vector of tangency by rotating dir2 = getSketchObject()->getSolvedSketch().calculateNormalAtPoint(Constr->Second, p.x, p.y); dir2.RotateZ(-M_PI/2); } } else if (Constr->First != Constraint::GeoUndef) { // line/arc angle const Part::Geometry *geo = GeoById(geomlist, Constr->First); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(geo); p0 = (lineSeg->getEndPoint()+lineSeg->getStartPoint())/2; } else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo); p0 = arc->getCenter(); } else { return; } } else return; Base::Vector3d vec = Base::Vector3d(toPos.fX, toPos.fY, 0) - p0; Constr->LabelDistance = vec.Length()/2; } // delete the cloned objects for (std::vector<Part::Geometry *>::const_iterator it=geomlist.begin(); it != geomlist.end(); ++it) if (*it) delete *it; draw(true); } Base::Vector3d ViewProviderSketch::seekConstraintPosition(const Base::Vector3d &origPos, const Base::Vector3d &norm, const Base::Vector3d &dir, float step, const SoNode *constraint) { assert(edit); Gui::MDIView *mdi = this->getEditingView(); if (!(mdi && mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId()))) return Base::Vector3d(0, 0, 0); Gui::View3DInventorViewer *viewer = static_cast<Gui::View3DInventor *>(mdi)->getViewer(); SoRayPickAction rp(viewer->getSoRenderManager()->getViewportRegion()); float scaled_step = step * getScaleFactor(); int multiplier = 0; Base::Vector3d relPos, freePos; bool isConstraintAtPosition = true; while (isConstraintAtPosition && multiplier < 10) { // Calculate new position of constraint relPos = norm * 0.5f + dir * multiplier; freePos = origPos + relPos * scaled_step; rp.setRadius(0.1f); rp.setPickAll(true); rp.setRay(SbVec3f(freePos.x, freePos.y, -1.f), SbVec3f(0, 0, 1) ); //problem rp.apply(edit->constrGroup); // We could narrow it down to just the SoGroup containing the constraints // returns a copy of the point SoPickedPoint *pp = rp.getPickedPoint(); const SoPickedPointList ppl = rp.getPickedPointList(); if (ppl.getLength() <= 1 && pp) { SoPath *path = pp->getPath(); int length = path->getLength(); SoNode *tailFather1 = path->getNode(length-2); SoNode *tailFather2 = path->getNode(length-3); // checking if a constraint is the same as the one selected if (tailFather1 == constraint || tailFather2 == constraint) isConstraintAtPosition = false; } else { isConstraintAtPosition = false; } multiplier *= -1; // search in both sides if (multiplier >= 0) multiplier++; // Increment the multiplier } if (multiplier == 10) relPos = norm * 0.5f; // no free position found return relPos * step; } bool ViewProviderSketch::isSelectable(void) const { if (isEditing()) return false; else return PartGui::ViewProvider2DObject::isSelectable(); } void ViewProviderSketch::onSelectionChanged(const Gui::SelectionChanges& msg) { // are we in edit? if (edit) { bool handled=false; if (Mode == STATUS_SKETCH_UseHandler) { handled = edit->sketchHandler->onSelectionChanged(msg); } if (handled) return; std::string temp; if (msg.Type == Gui::SelectionChanges::ClrSelection) { // if something selected in this object? if (edit->SelPointSet.size() > 0 || edit->SelCurvSet.size() > 0 || edit->SelConstraintSet.size() > 0) { // clear our selection and update the color of the viewed edges and points clearSelectPoints(); edit->SelCurvSet.clear(); edit->SelConstraintSet.clear(); this->drawConstraintIcons(); this->updateColor(); } } else if (msg.Type == Gui::SelectionChanges::AddSelection) { // is it this object?? if (strcmp(msg.pDocName,getSketchObject()->getDocument()->getName())==0 && strcmp(msg.pObjectName,getSketchObject()->getNameInDocument())== 0) { if (msg.pSubName) { std::string shapetype(msg.pSubName); if (shapetype.size() > 4 && shapetype.substr(0,4) == "Edge") { int GeoId = std::atoi(&shapetype[4]) - 1; edit->SelCurvSet.insert(GeoId); this->updateColor(); } else if (shapetype.size() > 12 && shapetype.substr(0,12) == "ExternalEdge") { int GeoId = std::atoi(&shapetype[12]) - 1; GeoId = -GeoId - 3; edit->SelCurvSet.insert(GeoId); this->updateColor(); } else if (shapetype.size() > 6 && shapetype.substr(0,6) == "Vertex") { int VtId = std::atoi(&shapetype[6]) - 1; addSelectPoint(VtId); this->updateColor(); } else if (shapetype == "RootPoint") { addSelectPoint(-1); this->updateColor(); } else if (shapetype == "H_Axis") { edit->SelCurvSet.insert(-1); this->updateColor(); } else if (shapetype == "V_Axis") { edit->SelCurvSet.insert(-2); this->updateColor(); } else if (shapetype.size() > 10 && shapetype.substr(0,10) == "Constraint") { int ConstrId = Sketcher::PropertyConstraintList::getIndexFromConstraintName(shapetype); edit->SelConstraintSet.insert(ConstrId); this->drawConstraintIcons(); this->updateColor(); } } } } else if (msg.Type == Gui::SelectionChanges::RmvSelection) { // Are there any objects selected if (edit->SelPointSet.size() > 0 || edit->SelCurvSet.size() > 0 || edit->SelConstraintSet.size() > 0) { // is it this object?? if (strcmp(msg.pDocName,getSketchObject()->getDocument()->getName())==0 && strcmp(msg.pObjectName,getSketchObject()->getNameInDocument())== 0) { if (msg.pSubName) { std::string shapetype(msg.pSubName); if (shapetype.size() > 4 && shapetype.substr(0,4) == "Edge") { int GeoId = std::atoi(&shapetype[4]) - 1; edit->SelCurvSet.erase(GeoId); this->updateColor(); } else if (shapetype.size() > 12 && shapetype.substr(0,12) == "ExternalEdge") { int GeoId = std::atoi(&shapetype[12]) - 1; GeoId = -GeoId - 3; edit->SelCurvSet.erase(GeoId); this->updateColor(); } else if (shapetype.size() > 6 && shapetype.substr(0,6) == "Vertex") { int VtId = std::atoi(&shapetype[6]) - 1; removeSelectPoint(VtId); this->updateColor(); } else if (shapetype == "RootPoint") { removeSelectPoint(-1); this->updateColor(); } else if (shapetype == "H_Axis") { edit->SelCurvSet.erase(-1); this->updateColor(); } else if (shapetype == "V_Axis") { edit->SelCurvSet.erase(-2); this->updateColor(); } else if (shapetype.size() > 10 && shapetype.substr(0,10) == "Constraint") { int ConstrId = Sketcher::PropertyConstraintList::getIndexFromConstraintName(shapetype); edit->SelConstraintSet.erase(ConstrId); this->drawConstraintIcons(); this->updateColor(); } } } } } else if (msg.Type == Gui::SelectionChanges::SetSelection) { // remove all items //selectionView->clear(); //std::vector<SelectionSingleton::SelObj> objs = Gui::Selection().getSelection(Reason.pDocName); //for (std::vector<SelectionSingleton::SelObj>::iterator it = objs.begin(); it != objs.end(); ++it) { // // build name // temp = it->DocName; // temp += "."; // temp += it->FeatName; // if (it->SubName && it->SubName[0] != '\0') { // temp += "."; // temp += it->SubName; // } // new QListWidgetItem(QString::fromLatin1(temp.c_str()), selectionView); //} } else if (msg.Type == Gui::SelectionChanges::SetPreselect) { if (strcmp(msg.pDocName,getSketchObject()->getDocument()->getName())==0 && strcmp(msg.pObjectName,getSketchObject()->getNameInDocument())== 0) { if (msg.pSubName) { std::string shapetype(msg.pSubName); if (shapetype.size() > 4 && shapetype.substr(0,4) == "Edge") { int GeoId = std::atoi(&shapetype[4]) - 1; resetPreselectPoint(); edit->PreselectCurve = GeoId; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); if (edit->sketchHandler) edit->sketchHandler->applyCursor(); this->updateColor(); } else if (shapetype.size() > 6 && shapetype.substr(0,6) == "Vertex") { int PtIndex = std::atoi(&shapetype[6]) - 1; setPreselectPoint(PtIndex); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); if (edit->sketchHandler) edit->sketchHandler->applyCursor(); this->updateColor(); } } } } else if (msg.Type == Gui::SelectionChanges::RmvPreselect) { resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); if (edit->sketchHandler) edit->sketchHandler->applyCursor(); this->updateColor(); } } } std::set<int> ViewProviderSketch::detectPreselectionConstr(const SoPickedPoint *Point, const Gui::View3DInventorViewer *viewer, const SbVec2s &cursorPos) { std::set<int> constrIndices; SoPath *path = Point->getPath(); SoNode *tail = path->getTail(); SoNode *tailFather = path->getNode(path->getLength()-2); for (int i=0; i < edit->constrGroup->getNumChildren(); ++i) if (edit->constrGroup->getChild(i) == tailFather) { SoSeparator *sep = static_cast<SoSeparator *>(tailFather); if(sep->getNumChildren() > CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID) { SoInfo *constrIds = NULL; if(tail == sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON)) { // First icon was hit constrIds = static_cast<SoInfo *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID)); } else { // Assume second icon was hit if(CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID<sep->getNumChildren()){ constrIds = static_cast<SoInfo *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID)); } } if(constrIds) { QString constrIdsStr = QString::fromLatin1(constrIds->string.getValue().getString()); if(edit->combinedConstrBoxes.count(constrIdsStr) && dynamic_cast<SoImage *>(tail)) { // If it's a combined constraint icon // Screen dimensions of the icon SbVec3s iconSize = getDisplayedSize(static_cast<SoImage *>(tail)); // Center of the icon SbVec2f iconCoords = viewer->screenCoordsOfPath(path); // Coordinates of the mouse cursor on the icon, origin at top-left int iconX = cursorPos[0] - iconCoords[0] + iconSize[0]/2, iconY = iconCoords[1] - cursorPos[1] + iconSize[1]/2; for(ConstrIconBBVec::iterator b = edit->combinedConstrBoxes[constrIdsStr].begin(); b != edit->combinedConstrBoxes[constrIdsStr].end(); ++b) { if(b->first.contains(iconX, iconY)) // We've found a bounding box that contains the mouse pointer! for(std::set<int>::iterator k = b->second.begin(); k != b->second.end(); ++k) constrIndices.insert(*k); } } else { // It's a constraint icon, not a combined one QStringList constrIdStrings = constrIdsStr.split(QString::fromLatin1(",")); while(!constrIdStrings.empty()) constrIndices.insert(constrIdStrings.takeAt(0).toInt()); } } } else { // other constraint icons - eg radius... constrIndices.clear(); constrIndices.insert(i); } break; } return constrIndices; } bool ViewProviderSketch::detectPreselection(const SoPickedPoint *Point, const Gui::View3DInventorViewer *viewer, const SbVec2s &cursorPos) { assert(edit); int PtIndex = -1; int GeoIndex = -1; // valid values are 0,1,2,... for normal geometry and -3,-4,-5,... for external geometry int CrossIndex = -1; std::set<int> constrIndices; if (Point) { //Base::Console().Log("Point pick\n"); SoPath *path = Point->getPath(); SoNode *tail = path->getTail(); SoNode *tailFather2 = path->getNode(path->getLength()-3); // checking for a hit in the points if (tail == edit->PointSet) { const SoDetail *point_detail = Point->getDetail(edit->PointSet); if (point_detail && point_detail->getTypeId() == SoPointDetail::getClassTypeId()) { // get the index PtIndex = static_cast<const SoPointDetail *>(point_detail)->getCoordinateIndex(); PtIndex -= 1; // shift corresponding to RootPoint if (PtIndex == -1) CrossIndex = 0; // RootPoint was hit } } else { // checking for a hit in the curves if (tail == edit->CurveSet) { const SoDetail *curve_detail = Point->getDetail(edit->CurveSet); if (curve_detail && curve_detail->getTypeId() == SoLineDetail::getClassTypeId()) { // get the index int curveIndex = static_cast<const SoLineDetail *>(curve_detail)->getLineIndex(); GeoIndex = edit->CurvIdToGeoId[curveIndex]; } // checking for a hit in the cross } else if (tail == edit->RootCrossSet) { const SoDetail *cross_detail = Point->getDetail(edit->RootCrossSet); if (cross_detail && cross_detail->getTypeId() == SoLineDetail::getClassTypeId()) { // get the index (reserve index 0 for root point) CrossIndex = 1 + static_cast<const SoLineDetail *>(cross_detail)->getLineIndex(); } } else { // checking if a constraint is hit if (tailFather2 == edit->constrGroup) constrIndices = detectPreselectionConstr(Point, viewer, cursorPos); } } if (PtIndex != -1 && PtIndex != edit->PreselectPoint) { // if a new point is hit std::stringstream ss; ss << "Vertex" << PtIndex + 1; bool accepted = Gui::Selection().setPreselect(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,ss.str().c_str() ,Point->getPoint()[0] ,Point->getPoint()[1] ,Point->getPoint()[2]); edit->blockedPreselection = !accepted; if (accepted) { setPreselectPoint(PtIndex); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); if (edit->sketchHandler) edit->sketchHandler->applyCursor(); return true; } } else if (GeoIndex != -1 && GeoIndex != edit->PreselectCurve) { // if a new curve is hit std::stringstream ss; if (GeoIndex >= 0) ss << "Edge" << GeoIndex + 1; else // external geometry ss << "ExternalEdge" << -GeoIndex - 2; // convert index start from -3 to 1 bool accepted = Gui::Selection().setPreselect(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,ss.str().c_str() ,Point->getPoint()[0] ,Point->getPoint()[1] ,Point->getPoint()[2]); edit->blockedPreselection = !accepted; if (accepted) { resetPreselectPoint(); edit->PreselectCurve = GeoIndex; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); if (edit->sketchHandler) edit->sketchHandler->applyCursor(); return true; } } else if (CrossIndex != -1 && CrossIndex != edit->PreselectCross) { // if a cross line is hit std::stringstream ss; switch(CrossIndex){ case 0: ss << "RootPoint" ; break; case 1: ss << "H_Axis" ; break; case 2: ss << "V_Axis" ; break; } bool accepted = Gui::Selection().setPreselect(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,ss.str().c_str() ,Point->getPoint()[0] ,Point->getPoint()[1] ,Point->getPoint()[2]); edit->blockedPreselection = !accepted; if (accepted) { if (CrossIndex == 0) setPreselectPoint(-1); else resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = CrossIndex; edit->PreselectConstraintSet.clear(); if (edit->sketchHandler) edit->sketchHandler->applyCursor(); return true; } } else if (constrIndices.empty() == false && constrIndices != edit->PreselectConstraintSet) { // if a constraint is hit bool accepted = true; for(std::set<int>::iterator it = constrIndices.begin(); it != constrIndices.end(); ++it) { std::string constraintName(Sketcher::PropertyConstraintList::getConstraintName(*it)); accepted &= Gui::Selection().setPreselect(getSketchObject()->getDocument()->getName() ,getSketchObject()->getNameInDocument() ,constraintName.c_str() ,Point->getPoint()[0] ,Point->getPoint()[1] ,Point->getPoint()[2]); edit->blockedPreselection = !accepted; //TODO: Should we clear preselections that went through, if one fails? } if (accepted) { resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet = constrIndices; if (edit->sketchHandler) edit->sketchHandler->applyCursor(); return true;//Preselection changed } } else if ((PtIndex == -1 && GeoIndex == -1 && CrossIndex == -1 && constrIndices.empty()) && (edit->PreselectPoint != -1 || edit->PreselectCurve != -1 || edit->PreselectCross != -1 || edit->PreselectConstraintSet.empty() != true || edit->blockedPreselection)) { // we have just left a preselection resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); edit->blockedPreselection = false; if (edit->sketchHandler) edit->sketchHandler->applyCursor(); return true; } Gui::Selection().setPreselectCoord(Point->getPoint()[0] ,Point->getPoint()[1] ,Point->getPoint()[2]); // if(Point) } else if (edit->PreselectCurve != -1 || edit->PreselectPoint != -1 || edit->PreselectConstraintSet.empty() != true || edit->PreselectCross != -1 || edit->blockedPreselection) { resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); edit->blockedPreselection = false; if (edit->sketchHandler) edit->sketchHandler->applyCursor(); return true; } return false; } SbVec3s ViewProviderSketch::getDisplayedSize(const SoImage *iconPtr) const { #if (COIN_MAJOR_VERSION >= 3) SbVec3s iconSize = iconPtr->image.getValue().getSize(); #else SbVec2s size; int nc; const unsigned char * bytes = iconPtr->image.getValue(size, nc); SbImage img (bytes, size, nc); SbVec3s iconSize = img.getSize(); #endif if (iconPtr->width.getValue() != -1) iconSize[0] = iconPtr->width.getValue(); if (iconPtr->height.getValue() != -1) iconSize[1] = iconPtr->height.getValue(); return iconSize; } void ViewProviderSketch::centerSelection() { Gui::MDIView *mdi = this->getActiveView(); Gui::View3DInventor *view = qobject_cast<Gui::View3DInventor*>(mdi); if (!view || !edit) return; SoGroup* group = new SoGroup(); group->ref(); for (int i=0; i < edit->constrGroup->getNumChildren(); i++) { if (edit->SelConstraintSet.find(i) != edit->SelConstraintSet.end()) { SoSeparator *sep = dynamic_cast<SoSeparator *>(edit->constrGroup->getChild(i)); group->addChild(sep); } } Gui::View3DInventorViewer* viewer = view->getViewer(); SoGetBoundingBoxAction action(viewer->getSoRenderManager()->getViewportRegion()); action.apply(group); group->unref(); SbBox3f box = action.getBoundingBox(); if (!box.isEmpty()) { SoCamera* camera = viewer->getSoRenderManager()->getCamera(); SbVec3f direction; camera->orientation.getValue().multVec(SbVec3f(0, 0, 1), direction); SbVec3f box_cnt = box.getCenter(); SbVec3f cam_pos = box_cnt + camera->focalDistance.getValue() * direction; camera->position.setValue(cam_pos); } } void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s &endPos, const Gui::View3DInventorViewer *viewer) { std::vector<SbVec2s> corners0; corners0.push_back(startPos); corners0.push_back(endPos); std::vector<SbVec2f> corners = viewer->getGLPolygon(corners0); // all calculations with polygon and proj are in dimensionless [0 1] screen coordinates Base::Polygon2D polygon; polygon.Add(Base::Vector2D(corners[0].getValue()[0], corners[0].getValue()[1])); polygon.Add(Base::Vector2D(corners[0].getValue()[0], corners[1].getValue()[1])); polygon.Add(Base::Vector2D(corners[1].getValue()[0], corners[1].getValue()[1])); polygon.Add(Base::Vector2D(corners[1].getValue()[0], corners[0].getValue()[1])); Gui::ViewVolumeProjection proj(viewer->getSoRenderManager()->getCamera()->getViewVolume()); Sketcher::SketchObject *sketchObject = getSketchObject(); App::Document *doc = sketchObject->getDocument(); Base::Placement Plm = sketchObject->Placement.getValue(); int intGeoCount = sketchObject->getHighestCurveIndex() + 1; int extGeoCount = sketchObject->getExternalGeometryCount(); const std::vector<Part::Geometry *> geomlist = sketchObject->getCompleteGeometry(); // without memory allocation assert(int(geomlist.size()) == extGeoCount + intGeoCount); assert(int(geomlist.size()) >= 2); Base::Vector3d pnt0, pnt1, pnt2, pnt; int VertexId = -1; // the loop below should be in sync with the main loop in ViewProviderSketch::draw // so that the vertex indices are calculated correctly int GeoId = 0; for (std::vector<Part::Geometry *>::const_iterator it = geomlist.begin(); it != geomlist.end()-2; ++it, ++GeoId) { if (GeoId >= intGeoCount) GeoId = -extGeoCount; if ((*it)->getTypeId() == Part::GeomPoint::getClassTypeId()) { // ----- Check if single point lies inside box selection -----/ const Part::GeomPoint *point = dynamic_cast<const Part::GeomPoint *>(*it); Plm.multVec(point->getPoint(), pnt0); pnt0 = proj(pnt0); VertexId += 1; if (polygon.Contains(Base::Vector2D(pnt0.x, pnt0.y))) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } } else if ((*it)->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { // ----- Check if line segment lies inside box selection -----/ const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(*it); Plm.multVec(lineSeg->getStartPoint(), pnt1); Plm.multVec(lineSeg->getEndPoint(), pnt2); pnt1 = proj(pnt1); pnt2 = proj(pnt2); VertexId += 2; bool pnt1Inside = polygon.Contains(Base::Vector2D(pnt1.x, pnt1.y)); bool pnt2Inside = polygon.Contains(Base::Vector2D(pnt2.x, pnt2.y)); if (pnt1Inside) { std::stringstream ss; ss << "Vertex" << VertexId; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (pnt2Inside) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (pnt1Inside && pnt2Inside) { std::stringstream ss; ss << "Edge" << GeoId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } } else if ((*it)->getTypeId() == Part::GeomCircle::getClassTypeId()) { // ----- Check if circle lies inside box selection -----/ const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(*it); pnt0 = circle->getCenter(); VertexId += 1; Plm.multVec(pnt0, pnt0); pnt0 = proj(pnt0); if (polygon.Contains(Base::Vector2D(pnt0.x, pnt0.y))) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); int countSegments = 12; float segment = float(2 * M_PI) / countSegments; // circumscribed polygon radius float radius = float(circle->getRadius()) / cos(segment/2); bool bpolyInside = true; pnt0 = circle->getCenter(); float angle = 0.f; for (int i = 0; i < countSegments; ++i, angle += segment) { pnt = Base::Vector3d(pnt0.x + radius * cos(angle), pnt0.y + radius * sin(angle), 0.f); Plm.multVec(pnt, pnt); pnt = proj(pnt); if (!polygon.Contains(Base::Vector2D(pnt.x, pnt.y))) { bpolyInside = false; break; } } if (bpolyInside) { ss.clear(); ss.str(""); ss << "Edge" << GeoId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(),ss.str().c_str()); } } } else if ((*it)->getTypeId() == Part::GeomEllipse::getClassTypeId()) { // ----- Check if circle lies inside box selection -----/ const Part::GeomEllipse *ellipse = dynamic_cast<const Part::GeomEllipse *>(*it); pnt0 = ellipse->getCenter(); VertexId += 1; Plm.multVec(pnt0, pnt0); pnt0 = proj(pnt0); if (polygon.Contains(Base::Vector2D(pnt0.x, pnt0.y))) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); int countSegments = 12; double segment = (2 * M_PI) / countSegments; // circumscribed polygon radius double a = (ellipse->getMajorRadius()) / cos(segment/2); double b = (ellipse->getMinorRadius()) / cos(segment/2); Base::Vector3d majdir = ellipse->getMajorAxisDir(); Base::Vector3d mindir = Base::Vector3d(-majdir.y, majdir.x, 0.0); bool bpolyInside = true; pnt0 = ellipse->getCenter(); double angle = 0.; for (int i = 0; i < countSegments; ++i, angle += segment) { pnt = pnt0 + (cos(angle)*a)*majdir + sin(angle)*b*mindir; Plm.multVec(pnt, pnt); pnt = proj(pnt); if (!polygon.Contains(Base::Vector2D(pnt.x, pnt.y))) { bpolyInside = false; break; } } if (bpolyInside) { ss.clear(); ss.str(""); ss << "Edge" << GeoId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(),ss.str().c_str()); } } } else if ((*it)->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { // Check if arc lies inside box selection const Part::GeomArcOfCircle *aoc = dynamic_cast<const Part::GeomArcOfCircle *>(*it); pnt0 = aoc->getStartPoint(/*emulateCCW=*/true); pnt1 = aoc->getEndPoint(/*emulateCCW=*/true); pnt2 = aoc->getCenter(); VertexId += 3; Plm.multVec(pnt0, pnt0); Plm.multVec(pnt1, pnt1); Plm.multVec(pnt2, pnt2); pnt0 = proj(pnt0); pnt1 = proj(pnt1); pnt2 = proj(pnt2); bool pnt0Inside = polygon.Contains(Base::Vector2D(pnt0.x, pnt0.y)); if (pnt0Inside) { std::stringstream ss; ss << "Vertex" << VertexId - 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } bool pnt1Inside = polygon.Contains(Base::Vector2D(pnt1.x, pnt1.y)); if (pnt1Inside) { std::stringstream ss; ss << "Vertex" << VertexId; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (polygon.Contains(Base::Vector2D(pnt2.x, pnt2.y))) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (pnt0Inside && pnt1Inside) { double startangle, endangle; aoc->getRange(startangle, endangle, /*emulateCCW=*/true); if (startangle > endangle) // if arc is reversed std::swap(startangle, endangle); double range = endangle-startangle; int countSegments = std::max(2, int(12.0 * range / (2 * M_PI))); float segment = float(range) / countSegments; // circumscribed polygon radius float radius = float(aoc->getRadius()) / cos(segment/2); bool bpolyInside = true; pnt0 = aoc->getCenter(); float angle = float(startangle) + segment/2; for (int i = 0; i < countSegments; ++i, angle += segment) { pnt = Base::Vector3d(pnt0.x + radius * cos(angle), pnt0.y + radius * sin(angle), 0.f); Plm.multVec(pnt, pnt); pnt = proj(pnt); if (!polygon.Contains(Base::Vector2D(pnt.x, pnt.y))) { bpolyInside = false; break; } } if (bpolyInside) { std::stringstream ss; ss << "Edge" << GeoId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } } } else if ((*it)->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { // Check if arc lies inside box selection const Part::GeomArcOfEllipse *aoe = dynamic_cast<const Part::GeomArcOfEllipse *>(*it); pnt0 = aoe->getStartPoint(/*emulateCCW=*/true); pnt1 = aoe->getEndPoint(/*emulateCCW=*/true); pnt2 = aoe->getCenter(); VertexId += 3; Plm.multVec(pnt0, pnt0); Plm.multVec(pnt1, pnt1); Plm.multVec(pnt2, pnt2); pnt0 = proj(pnt0); pnt1 = proj(pnt1); pnt2 = proj(pnt2); bool pnt0Inside = polygon.Contains(Base::Vector2D(pnt0.x, pnt0.y)); if (pnt0Inside) { std::stringstream ss; ss << "Vertex" << VertexId - 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } bool pnt1Inside = polygon.Contains(Base::Vector2D(pnt1.x, pnt1.y)); if (pnt1Inside) { std::stringstream ss; ss << "Vertex" << VertexId; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (polygon.Contains(Base::Vector2D(pnt2.x, pnt2.y))) { std::stringstream ss; ss << "Vertex" << VertexId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } if (pnt0Inside && pnt1Inside) { double startangle, endangle; aoe->getRange(startangle, endangle, /*emulateCCW=*/true); if (startangle > endangle) // if arc is reversed std::swap(startangle, endangle); double range = endangle-startangle; int countSegments = std::max(2, int(12.0 * range / (2 * M_PI))); double segment = (range) / countSegments; // circumscribed polygon radius double a = (aoe->getMajorRadius()) / cos(segment/2); double b = (aoe->getMinorRadius()) / cos(segment/2); Base::Vector3d majdir = aoe->getMajorAxisDir(); Base::Vector3d mindir = Base::Vector3d(-majdir.y, majdir.x, 0.0); bool bpolyInside = true; pnt0 = aoe->getCenter(); double angle = (startangle) + segment/2; for (int i = 0; i < countSegments; ++i, angle += segment) { pnt = pnt0 + cos(angle)*a*majdir + sin(angle)*b*mindir; Plm.multVec(pnt, pnt); pnt = proj(pnt); if (!polygon.Contains(Base::Vector2D(pnt.x, pnt.y))) { bpolyInside = false; break; } } if (bpolyInside) { std::stringstream ss; ss << "Edge" << GeoId + 1; Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), ss.str().c_str()); } } } else if ((*it)->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { const Part::GeomBSplineCurve *spline = dynamic_cast<const Part::GeomBSplineCurve *>(*it); std::vector<Base::Vector3d> poles = spline->getPoles(); VertexId += poles.size(); // TODO } } pnt0 = proj(Plm.getPosition()); if (polygon.Contains(Base::Vector2D(pnt0.x, pnt0.y))) Gui::Selection().addSelection(doc->getName(), sketchObject->getNameInDocument(), "RootPoint"); } void ViewProviderSketch::updateColor(void) { assert(edit); //Base::Console().Log("Draw preseletion\n"); int PtNum = edit->PointsMaterials->diffuseColor.getNum(); SbColor *pcolor = edit->PointsMaterials->diffuseColor.startEditing(); int CurvNum = edit->CurvesMaterials->diffuseColor.getNum(); SbColor *color = edit->CurvesMaterials->diffuseColor.startEditing(); SbColor *crosscolor = edit->RootCrossMaterials->diffuseColor.startEditing(); SbVec3f *verts = edit->CurvesCoordinate->point.startEditing(); //int32_t *index = edit->CurveSet->numVertices.startEditing(); // colors of the point set if (edit->FullyConstrained) { for (int i=0; i < PtNum; i++) pcolor[i] = FullyConstrainedColor; } else { for (int i=0; i < PtNum; i++) pcolor[i] = VertexColor; } if (edit->PreselectCross == 0) { pcolor[0] = PreselectColor; } else if (edit->PreselectPoint != -1) { if (edit->PreselectPoint + 1 < PtNum) pcolor[edit->PreselectPoint + 1] = PreselectColor; } for (std::set<int>::iterator it = edit->SelPointSet.begin(); it != edit->SelPointSet.end(); ++it) { if (*it < PtNum) { pcolor[*it] = (*it==(edit->PreselectPoint + 1) && (edit->PreselectPoint != -1)) ? PreselectSelectedColor : SelectColor; } } // colors of the curves //int intGeoCount = getSketchObject()->getHighestCurveIndex() + 1; //int extGeoCount = getSketchObject()->getExternalGeometryCount(); float x,y,z; int j=0; // vertexindex for (int i=0; i < CurvNum; i++) { int GeoId = edit->CurvIdToGeoId[i]; // CurvId has several vertex a ssociated to 1 material //edit->CurveSet->numVertices => [i] indicates number of vertex for line i. int indexes = (edit->CurveSet->numVertices[i]); bool selected = (edit->SelCurvSet.find(GeoId) != edit->SelCurvSet.end()); bool preselected = (edit->PreselectCurve == GeoId); if (selected && preselected) { color[i] = PreselectSelectedColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zHighLine); } } else if (selected){ color[i] = SelectColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zHighLine); } } else if (preselected){ color[i] = PreselectColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zHighLine); } } else if (GeoId < -2) { // external Geometry color[i] = CurveExternalColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zConstr); } } else if (getSketchObject()->getGeometry(GeoId)->Construction) { color[i] = CurveDraftColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zLines); } } else if (edit->FullyConstrained) { color[i] = FullyConstrainedColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zLines); } } else { color[i] = CurveColor; for (int k=j; j<k+indexes; j++) { verts[j].getValue(x,y,z); verts[j] = SbVec3f(x,y,zLines); } } } // colors of the cross if (edit->SelCurvSet.find(-1) != edit->SelCurvSet.end()) crosscolor[0] = SelectColor; else if (edit->PreselectCross == 1) crosscolor[0] = PreselectColor; else crosscolor[0] = CrossColorH; if (edit->SelCurvSet.find(-2) != edit->SelCurvSet.end()) crosscolor[1] = SelectColor; else if (edit->PreselectCross == 2) crosscolor[1] = PreselectColor; else crosscolor[1] = CrossColorV; // colors of the constraints for (int i=0; i < edit->constrGroup->getNumChildren(); i++) { SoSeparator *s = dynamic_cast<SoSeparator *>(edit->constrGroup->getChild(i)); // Check Constraint Type Sketcher::Constraint* constraint = getSketchObject()->Constraints.getValues()[i]; ConstraintType type = constraint->Type; bool hasDatumLabel = (type == Sketcher::Angle || type == Sketcher::Radius || type == Sketcher::Symmetric || type == Sketcher::Distance || type == Sketcher::DistanceX || type == Sketcher::DistanceY); // Non DatumLabel Nodes will have a material excluding coincident bool hasMaterial = false; SoMaterial *m = 0; if (!hasDatumLabel && type != Sketcher::Coincident && type != Sketcher::InternalAlignment) { hasMaterial = true; m = dynamic_cast<SoMaterial *>(s->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); } if (edit->SelConstraintSet.find(i) != edit->SelConstraintSet.end()) { if (hasDatumLabel) { SoDatumLabel *l = dynamic_cast<SoDatumLabel *>(s->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); l->textColor = SelectColor; } else if (hasMaterial) { m->diffuseColor = SelectColor; } else if (type == Sketcher::Coincident) { int index; index = getSketchObject()->getSolvedSketch().getPointId(constraint->First, constraint->FirstPos) + 1; if (index >= 0 && index < PtNum) pcolor[index] = SelectColor; index = getSketchObject()->getSolvedSketch().getPointId(constraint->Second, constraint->SecondPos) + 1; if (index >= 0 && index < PtNum) pcolor[index] = SelectColor; } else if (type == Sketcher::InternalAlignment) { switch(constraint->AlignmentType) { case EllipseMajorDiameter: case EllipseMinorDiameter: { // color line int CurvNum = edit->CurvesMaterials->diffuseColor.getNum(); for (int i=0; i < CurvNum; i++) { int cGeoId = edit->CurvIdToGeoId[i]; if(cGeoId == constraint->First) { color[i] = SelectColor; break; } } } break; case EllipseFocus1: case EllipseFocus2: { int index = getSketchObject()->getSolvedSketch().getPointId(constraint->First, constraint->FirstPos) + 1; if (index >= 0 && index < PtNum) pcolor[index] = SelectColor; } break; default: break; } } } else if (edit->PreselectConstraintSet.count(i)) { if (hasDatumLabel) { SoDatumLabel *l = dynamic_cast<SoDatumLabel *>(s->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); l->textColor = PreselectColor; } else if (hasMaterial) { m->diffuseColor = PreselectColor; } } else { if (hasDatumLabel) { SoDatumLabel *l = dynamic_cast<SoDatumLabel *>(s->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); l->textColor = constraint->isDriving?ConstrDimColor:NonDrivingConstrDimColor; } else if (hasMaterial) { m->diffuseColor = constraint->isDriving?ConstrDimColor:NonDrivingConstrDimColor; } } } // end editing edit->CurvesMaterials->diffuseColor.finishEditing(); edit->PointsMaterials->diffuseColor.finishEditing(); edit->RootCrossMaterials->diffuseColor.finishEditing(); edit->CurvesCoordinate->point.finishEditing(); edit->CurveSet->numVertices.finishEditing(); } bool ViewProviderSketch::isPointOnSketch(const SoPickedPoint *pp) const { // checks if we picked a point on the sketch or any other nodes like the grid SoPath *path = pp->getPath(); return path->containsNode(edit->EditRoot); } bool ViewProviderSketch::doubleClicked(void) { Gui::Application::Instance->activeDocument()->setEdit(this); return true; } QString ViewProviderSketch::iconTypeFromConstraint(Constraint *constraint) { /*! TODO: Consider pushing this functionality up into Constraint */ switch(constraint->Type) { case Horizontal: return QString::fromLatin1("small/Constraint_Horizontal_sm"); case Vertical: return QString::fromLatin1("small/Constraint_Vertical_sm"); case PointOnObject: return QString::fromLatin1("small/Constraint_PointOnObject_sm"); case Tangent: return QString::fromLatin1("small/Constraint_Tangent_sm"); case Parallel: return QString::fromLatin1("small/Constraint_Parallel_sm"); case Perpendicular: return QString::fromLatin1("small/Constraint_Perpendicular_sm"); case Equal: return QString::fromLatin1("small/Constraint_EqualLength_sm"); case Symmetric: return QString::fromLatin1("small/Constraint_Symmetric_sm"); case SnellsLaw: return QString::fromLatin1("small/Constraint_SnellsLaw_sm"); default: return QString(); } } void ViewProviderSketch::sendConstraintIconToCoin(const QImage &icon, SoImage *soImagePtr) { SoSFImage icondata = SoSFImage(); Gui::BitmapFactory().convert(icon, icondata); SbVec2s iconSize(icon.width(), icon.height()); int four = 4; soImagePtr->image.setValue(iconSize, 4, icondata.getValue(iconSize, four)); //Set Image Alignment to Center soImagePtr->vertAlignment = SoImage::HALF; soImagePtr->horAlignment = SoImage::CENTER; } void ViewProviderSketch::clearCoinImage(SoImage *soImagePtr) { soImagePtr->setToDefaults(); } QColor ViewProviderSketch::constrColor(int constraintId) { static QColor constrIcoColor((int)(ConstrIcoColor [0] * 255.0f), (int)(ConstrIcoColor[1] * 255.0f), (int)(ConstrIcoColor[2] * 255.0f)); static QColor nonDrivingConstrIcoColor((int)(NonDrivingConstrDimColor[0] * 255.0f), (int)(NonDrivingConstrDimColor[1] * 255.0f), (int)(NonDrivingConstrDimColor[2] * 255.0f)); static QColor constrIconSelColor ((int)(SelectColor[0] * 255.0f), (int)(SelectColor[1] * 255.0f), (int)(SelectColor[2] * 255.0f)); static QColor constrIconPreselColor ((int)(PreselectColor[0] * 255.0f), (int)(PreselectColor[1] * 255.0f), (int)(PreselectColor[2] * 255.0f)); const std::vector<Sketcher::Constraint *> &constraints = getSketchObject()->Constraints.getValues(); if (edit->PreselectConstraintSet.count(constraintId)) return constrIconPreselColor; else if (edit->SelConstraintSet.find(constraintId) != edit->SelConstraintSet.end()) return constrIconSelColor; else if(!constraints[constraintId]->isDriving) return nonDrivingConstrIcoColor; else return constrIcoColor; } int ViewProviderSketch::constrColorPriority(int constraintId) { if (edit->PreselectConstraintSet.count(constraintId)) return 3; else if (edit->SelConstraintSet.find(constraintId) != edit->SelConstraintSet.end()) return 2; else return 1; } // public function that triggers drawing of most constraint icons void ViewProviderSketch::drawConstraintIcons() { const std::vector<Sketcher::Constraint *> &constraints = getSketchObject()->Constraints.getValues(); int constrId = 0; std::vector<constrIconQueueItem> iconQueue; for (std::vector<Sketcher::Constraint *>::const_iterator it=constraints.begin(); it != constraints.end(); ++it, ++constrId) { // Check if Icon Should be created bool multipleIcons = false; QString icoType = iconTypeFromConstraint(*it); if(icoType.isEmpty()) continue; switch((*it)->Type) { case Tangent: { // second icon is available only for colinear line segments const Part::Geometry *geo1 = getSketchObject()->getGeometry((*it)->First); const Part::Geometry *geo2 = getSketchObject()->getGeometry((*it)->Second); if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { multipleIcons = true; } } break; case Parallel: multipleIcons = true; break; case Perpendicular: // second icon is available only when there is no common point if ((*it)->FirstPos == Sketcher::none && (*it)->Third == Constraint::GeoUndef) multipleIcons = true; break; case Equal: multipleIcons = true; break; default: break; } // Find the Constraint Icon SoImage Node SoSeparator *sep = static_cast<SoSeparator *>(edit->constrGroup->getChild(constrId)); SbVec3f absPos; // Somewhat hacky - we use SoZoomTranslations for most types of icon, // but symmetry icons use SoTranslations... SoTranslation *translationPtr = static_cast<SoTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION)); if(dynamic_cast<SoZoomTranslation *>(translationPtr)) absPos = static_cast<SoZoomTranslation *>(translationPtr)->abPos.getValue(); else absPos = translationPtr->translation.getValue(); SoImage *coinIconPtr = dynamic_cast<SoImage *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON)); SoInfo *infoPtr = static_cast<SoInfo *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID)); constrIconQueueItem thisIcon; thisIcon.type = icoType; thisIcon.constraintId = constrId; thisIcon.position = absPos; thisIcon.destination = coinIconPtr; thisIcon.infoPtr = infoPtr; if ((*it)->Type==Symmetric) { Base::Vector3d startingpoint = getSketchObject()->getPoint((*it)->First,(*it)->FirstPos); Base::Vector3d endpoint = getSketchObject()->getPoint((*it)->Second,(*it)->SecondPos); double x0,y0,x1,y1; SbVec3f pos0(startingpoint.x,startingpoint.y,startingpoint.z); SbVec3f pos1(endpoint.x,endpoint.y,endpoint.z); Gui::MDIView *mdi = this->getEditingView(); if (!(mdi && mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId()))) return; Gui::View3DInventorViewer *viewer = static_cast<Gui::View3DInventor *>(mdi)->getViewer(); SoCamera* pCam = viewer->getSoRenderManager()->getCamera(); if (!pCam) return; try { SbViewVolume vol = pCam->getViewVolume(); getCoordsOnSketchPlane(x0,y0,pos0,vol.getProjectionDirection()); getCoordsOnSketchPlane(x1,y1,pos1,vol.getProjectionDirection()); thisIcon.iconRotation = -atan2((y1-y0),(x1-x0))*180/M_PI; } catch (const Base::DivisionByZeroError&) { thisIcon.iconRotation = 0; } } else { thisIcon.iconRotation = 0; } if (multipleIcons) { if((*it)->Name.empty()) thisIcon.label = QString::number(constrId + 1); else thisIcon.label = QString::fromLatin1((*it)->Name.c_str()); iconQueue.push_back(thisIcon); // Note that the second translation is meant to be applied after the first. // So, to get the position of the second icon, we add the two translations together // // See note ~30 lines up. translationPtr = static_cast<SoTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION)); if(dynamic_cast<SoZoomTranslation *>(translationPtr)) thisIcon.position += static_cast<SoZoomTranslation *>(translationPtr)->abPos.getValue(); else thisIcon.position += translationPtr->translation.getValue(); thisIcon.destination = dynamic_cast<SoImage *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_ICON)); thisIcon.infoPtr = static_cast<SoInfo *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID)); } else if ((*it)->Name.empty()) thisIcon.label = QString(); else thisIcon.label = QString::fromLatin1((*it)->Name.c_str()); iconQueue.push_back(thisIcon); } combineConstraintIcons(iconQueue); } void ViewProviderSketch::combineConstraintIcons(IconQueue iconQueue) { // getScaleFactor gives us a ratio of pixels per some kind of real units // (Translation: this number is somewhat made-up.) float maxDistSquared = pow(0.05 * getScaleFactor(), 2); // There's room for optimisation here; we could reuse the combined icons... edit->combinedConstrBoxes.clear(); while(!iconQueue.empty()) { // A group starts with an item popped off the back of our initial queue IconQueue thisGroup; thisGroup.push_back(iconQueue.back()); ViewProviderSketch::constrIconQueueItem init = iconQueue.back(); iconQueue.pop_back(); // we group only icons not being Symmetry icons, because we want those on the line if(init.type != QString::fromLatin1("small/Constraint_Symmetric_sm")){ IconQueue::iterator i = iconQueue.begin(); while(i != iconQueue.end()) { bool addedToGroup = false; for(IconQueue::iterator j = thisGroup.begin(); j != thisGroup.end(); ++j) if(i->position.equals(j->position, maxDistSquared) && (*i).type != QString::fromLatin1("small/Constraint_Symmetric_sm")) { // Found an icon in iconQueue that's close enough to // a member of thisGroup, so move it into thisGroup thisGroup.push_back(*i); i = iconQueue.erase(i); addedToGroup = true; break; } if(addedToGroup) { if(i == iconQueue.end()) // We just got the last icon out of iconQueue break; else // Start looking through the iconQueue again, in case // we have an icon that's now close enough to thisGroup i = iconQueue.begin(); } else ++i; } } if(thisGroup.size() == 1) { drawTypicalConstraintIcon(thisGroup[0]); } else { drawMergedConstraintIcons(thisGroup); } } } void ViewProviderSketch::drawMergedConstraintIcons(IconQueue iconQueue) { SbVec3f avPos(0, 0, 0); for(IconQueue::iterator i = iconQueue.begin(); i != iconQueue.end(); ++i) { clearCoinImage(i->destination); avPos = avPos + i->position; } avPos = avPos/iconQueue.size(); QImage compositeIcon; float closest = FLT_MAX; // Closest distance between avPos and any icon SoImage *thisDest = 0; SoInfo *thisInfo = 0; // Tracks all constraint IDs that are combined into this icon QString idString; int lastVPad; QStringList labels; std::vector<int> ids; QString thisType; QColor iconColor; QList<QColor> labelColors; int maxColorPriority; double iconRotation; ConstrIconBBVec boundingBoxes; while(!iconQueue.empty()) { IconQueue::iterator i = iconQueue.begin(); labels.clear(); labels.append(i->label); ids.clear(); ids.push_back(i->constraintId); thisType = i->type; iconColor = constrColor(i->constraintId); labelColors.clear(); labelColors.append(iconColor); iconRotation= i->iconRotation; maxColorPriority = constrColorPriority(i->constraintId); if(idString.length()) idString.append(QString::fromLatin1(",")); idString.append(QString::number(i->constraintId)); if((avPos - i->position).length() < closest) { thisDest = i->destination; thisInfo = i->infoPtr; closest = (avPos - i->position).length(); } i = iconQueue.erase(i); while(i != iconQueue.end()) { if(i->type != thisType) { ++i; continue; } if((avPos - i->position).length() < closest) { thisDest = i->destination; thisInfo = i->infoPtr; closest = (avPos - i->position).length(); } labels.append(i->label); ids.push_back(i->constraintId); labelColors.append(constrColor(i->constraintId)); if(constrColorPriority(i->constraintId) > maxColorPriority) { maxColorPriority = constrColorPriority(i->constraintId); iconColor= constrColor(i->constraintId); } idString.append(QString::fromLatin1(",") + QString::number(i->constraintId)); i = iconQueue.erase(i); } // To be inserted into edit->combinedConstBoxes std::vector<QRect> boundingBoxesVec; int oldHeight = 0; // Render the icon here. if(compositeIcon.isNull()) { compositeIcon = renderConstrIcon(thisType, iconColor, labels, labelColors, iconRotation, &boundingBoxesVec, &lastVPad); } else { int thisVPad; QImage partialIcon = renderConstrIcon(thisType, iconColor, labels, labelColors, iconRotation, &boundingBoxesVec, &thisVPad); // Stack vertically for now. Down the road, it might make sense // to figure out the best orientation automatically. oldHeight = compositeIcon.height(); // This is overkill for the currently used (20 July 2014) font, // since it always seems to have the same vertical pad, but this // might not always be the case. The 3 pixel buffer might need // to vary depending on font size too... oldHeight -= std::max(lastVPad - 3, 0); compositeIcon = compositeIcon.copy(0, 0, std::max(partialIcon.width(), compositeIcon.width()), partialIcon.height() + compositeIcon.height()); QPainter qp(&compositeIcon); qp.drawImage(0, oldHeight, partialIcon); lastVPad = thisVPad; } // Add bounding boxes for the icon we just rendered to boundingBoxes std::vector<int>::iterator id = ids.begin(); std::set<int> nextIds; for(std::vector<QRect>::iterator bb = boundingBoxesVec.begin(); bb != boundingBoxesVec.end(); ++bb) { nextIds.clear(); if(bb == boundingBoxesVec.begin()) { // The first bounding box is for the icon at left, so assign // all IDs for that type of constraint to the icon. for(std::vector<int>::iterator j = ids.begin(); j != ids.end(); ++j) nextIds.insert(*j); } else nextIds.insert(*(id++)); ConstrIconBB newBB(bb->adjusted(0, oldHeight, 0, oldHeight), nextIds); boundingBoxes.push_back(newBB); } } edit->combinedConstrBoxes[idString] = boundingBoxes; thisInfo->string.setValue(idString.toLatin1().data()); sendConstraintIconToCoin(compositeIcon, thisDest); } /// Note: labels, labelColors, and boundignBoxes are all /// assumed to be the same length. QImage ViewProviderSketch::renderConstrIcon(const QString &type, const QColor &iconColor, const QStringList &labels, const QList<QColor> &labelColors, double iconRotation, std::vector<QRect> *boundingBoxes, int *vPad) { // Constants to help create constraint icons QString joinStr = QString::fromLatin1(", "); QImage icon = Gui::BitmapFactory().pixmap(type.toLatin1()).toImage(); QFont font = QApplication::font(); font.setPixelSize(11); font.setBold(true); QFontMetrics qfm = QFontMetrics(font); int labelWidth = qfm.boundingRect(labels.join(joinStr)).width(); // See Qt docs on qRect::bottom() for explanation of the +1 int pxBelowBase = qfm.boundingRect(labels.join(joinStr)).bottom() + 1; if(vPad) *vPad = pxBelowBase; QTransform rotation; rotation.rotate(iconRotation); QImage roticon = icon.transformed(rotation); QImage image = roticon.copy(0, 0, roticon.width() + labelWidth, roticon.height() + pxBelowBase); // Make a bounding box for the icon if(boundingBoxes) boundingBoxes->push_back(QRect(0, 0, roticon.width(), roticon.height())); // Render the Icons QPainter qp(&image); qp.setCompositionMode(QPainter::CompositionMode_SourceIn); qp.fillRect(roticon.rect(), iconColor); // Render constraint label if necessary if (!labels.join(QString()).isEmpty()) { qp.setCompositionMode(QPainter::CompositionMode_SourceOver); qp.setFont(font); int cursorOffset = 0; //In Python: "for label, color in zip(labels, labelColors):" QStringList::const_iterator labelItr; QString labelStr; QList<QColor>::const_iterator colorItr; QRect labelBB; for(labelItr = labels.begin(), colorItr = labelColors.begin(); labelItr != labels.end() && colorItr != labelColors.end(); ++labelItr, ++colorItr) { qp.setPen(*colorItr); if(labelItr + 1 == labels.end()) // if this is the last label labelStr = *labelItr; else labelStr = *labelItr + joinStr; // Note: text can sometimes draw to the left of the starting // position, eg italic fonts. Check QFontMetrics // documentation for more info, but be mindful if the // icon.width() is ever very small (or removed). qp.drawText(icon.width() + cursorOffset, icon.height(), labelStr); if(boundingBoxes) { labelBB = qfm.boundingRect(labelStr); labelBB.moveTo(icon.width() + cursorOffset, icon.height() - qfm.height() + pxBelowBase); boundingBoxes->push_back(labelBB); } cursorOffset += qfm.width(labelStr); } } return image; } void ViewProviderSketch::drawTypicalConstraintIcon(const constrIconQueueItem &i) { QColor color = constrColor(i.constraintId); QImage image = renderConstrIcon(i.type, color, QStringList(i.label), QList<QColor>() << color, i.iconRotation); i.infoPtr->string.setValue(QString::number(i.constraintId).toLatin1().data()); sendConstraintIconToCoin(image, i.destination); } float ViewProviderSketch::getScaleFactor() { Gui::MDIView *mdi = this->getEditingView(); if (mdi && mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId())) { Gui::View3DInventorViewer *viewer = static_cast<Gui::View3DInventor *>(mdi)->getViewer(); return viewer->getSoRenderManager()->getCamera()->getViewVolume(viewer->getSoRenderManager()->getCamera()->aspectRatio.getValue()).getWorldToScreenScale(SbVec3f(0.f, 0.f, 0.f), 0.1f) / 3; } else { return 1.f; } } void ViewProviderSketch::draw(bool temp) { assert(edit); // Render Geometry =================================================== std::vector<Base::Vector3d> Coords; std::vector<Base::Vector3d> Points; std::vector<unsigned int> Index; int intGeoCount = getSketchObject()->getHighestCurveIndex() + 1; int extGeoCount = getSketchObject()->getExternalGeometryCount(); const std::vector<Part::Geometry *> *geomlist; std::vector<Part::Geometry *> tempGeo; if (temp) tempGeo = getSketchObject()->getSolvedSketch().extractGeometry(true, true); // with memory allocation else tempGeo = getSketchObject()->getCompleteGeometry(); // without memory allocation geomlist = &tempGeo; assert(int(geomlist->size()) == extGeoCount + intGeoCount); assert(int(geomlist->size()) >= 2); edit->CurvIdToGeoId.clear(); int GeoId = 0; // RootPoint Points.push_back(Base::Vector3d(0.,0.,0.)); for (std::vector<Part::Geometry *>::const_iterator it = geomlist->begin(); it != geomlist->end()-2; ++it, GeoId++) { if (GeoId >= intGeoCount) GeoId = -extGeoCount; if ((*it)->getTypeId() == Part::GeomPoint::getClassTypeId()) { // add a point const Part::GeomPoint *point = dynamic_cast<const Part::GeomPoint *>(*it); Points.push_back(point->getPoint()); } else if ((*it)->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { // add a line const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(*it); // create the definition struct for that geom Coords.push_back(lineSeg->getStartPoint()); Coords.push_back(lineSeg->getEndPoint()); Points.push_back(lineSeg->getStartPoint()); Points.push_back(lineSeg->getEndPoint()); Index.push_back(2); edit->CurvIdToGeoId.push_back(GeoId); } else if ((*it)->getTypeId() == Part::GeomCircle::getClassTypeId()) { // add a circle const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(*it); Handle_Geom_Circle curve = Handle_Geom_Circle::DownCast(circle->handle()); int countSegments = 50; Base::Vector3d center = circle->getCenter(); double segment = (2 * M_PI) / countSegments; for (int i=0; i < countSegments; i++) { gp_Pnt pnt = curve->Value(i*segment); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); } gp_Pnt pnt = curve->Value(0); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); Index.push_back(countSegments+1); edit->CurvIdToGeoId.push_back(GeoId); Points.push_back(center); } else if ((*it)->getTypeId() == Part::GeomEllipse::getClassTypeId()) { // add an ellipse const Part::GeomEllipse *ellipse = dynamic_cast<const Part::GeomEllipse *>(*it); Handle_Geom_Ellipse curve = Handle_Geom_Ellipse::DownCast(ellipse->handle()); int countSegments = 50; Base::Vector3d center = ellipse->getCenter(); double segment = (2 * M_PI) / countSegments; for (int i=0; i < countSegments; i++) { gp_Pnt pnt = curve->Value(i*segment); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); } gp_Pnt pnt = curve->Value(0); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); Index.push_back(countSegments+1); edit->CurvIdToGeoId.push_back(GeoId); Points.push_back(center); } else if ((*it)->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { // add an arc const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(*it); Handle_Geom_TrimmedCurve curve = Handle_Geom_TrimmedCurve::DownCast(arc->handle()); double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/false); if (startangle > endangle) // if arc is reversed std::swap(startangle, endangle); double range = endangle-startangle; int countSegments = std::max(6, int(50.0 * range / (2 * M_PI))); double segment = range / countSegments; Base::Vector3d center = arc->getCenter(); Base::Vector3d start = arc->getStartPoint(/*emulateCCW=*/true); Base::Vector3d end = arc->getEndPoint(/*emulateCCW=*/true); for (int i=0; i < countSegments; i++) { gp_Pnt pnt = curve->Value(startangle); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); startangle += segment; } // end point gp_Pnt pnt = curve->Value(endangle); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); Index.push_back(countSegments+1); edit->CurvIdToGeoId.push_back(GeoId); Points.push_back(start); Points.push_back(end); Points.push_back(center); } else if ((*it)->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { // add an arc const Part::GeomArcOfEllipse *arc = dynamic_cast<const Part::GeomArcOfEllipse *>(*it); Handle_Geom_TrimmedCurve curve = Handle_Geom_TrimmedCurve::DownCast(arc->handle()); double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/false); if (startangle > endangle) // if arc is reversed std::swap(startangle, endangle); double range = endangle-startangle; int countSegments = std::max(6, int(50.0 * range / (2 * M_PI))); double segment = range / countSegments; Base::Vector3d center = arc->getCenter(); Base::Vector3d start = arc->getStartPoint(/*emulateCCW=*/true); Base::Vector3d end = arc->getEndPoint(/*emulateCCW=*/true); for (int i=0; i < countSegments; i++) { gp_Pnt pnt = curve->Value(startangle); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); startangle += segment; } // end point gp_Pnt pnt = curve->Value(endangle); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); Index.push_back(countSegments+1); edit->CurvIdToGeoId.push_back(GeoId); Points.push_back(start); Points.push_back(end); Points.push_back(center); } else if ((*it)->getTypeId() == Part::GeomBSplineCurve::getClassTypeId()) { // add a bspline const Part::GeomBSplineCurve *spline = dynamic_cast<const Part::GeomBSplineCurve *>(*it); Handle_Geom_BSplineCurve curve = Handle_Geom_BSplineCurve::DownCast(spline->handle()); double first = curve->FirstParameter(); double last = curve->LastParameter(); if (first > last) // if arc is reversed std::swap(first, last); double range = last-first; int countSegments = 50; double segment = range / countSegments; for (int i=0; i < countSegments; i++) { gp_Pnt pnt = curve->Value(first); Coords.push_back(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); first += segment; } // end point gp_Pnt end = curve->Value(last); Coords.push_back(Base::Vector3d(end.X(), end.Y(), end.Z())); std::vector<Base::Vector3d> poles = spline->getPoles(); for (std::vector<Base::Vector3d>::iterator it = poles.begin(); it != poles.end(); ++it) { Points.push_back(*it); } Index.push_back(countSegments+1); edit->CurvIdToGeoId.push_back(GeoId); } else { } } edit->CurvesCoordinate->point.setNum(Coords.size()); edit->CurveSet->numVertices.setNum(Index.size()); edit->CurvesMaterials->diffuseColor.setNum(Index.size()); edit->PointsCoordinate->point.setNum(Points.size()); edit->PointsMaterials->diffuseColor.setNum(Points.size()); SbVec3f *verts = edit->CurvesCoordinate->point.startEditing(); int32_t *index = edit->CurveSet->numVertices.startEditing(); SbVec3f *pverts = edit->PointsCoordinate->point.startEditing(); int i=0; // setting up the line set for (std::vector<Base::Vector3d>::const_iterator it = Coords.begin(); it != Coords.end(); ++it,i++) verts[i].setValue(it->x,it->y,zLines); i=0; // setting up the indexes of the line set for (std::vector<unsigned int>::const_iterator it = Index.begin(); it != Index.end(); ++it,i++) index[i] = *it; i=0; // setting up the point set for (std::vector<Base::Vector3d>::const_iterator it = Points.begin(); it != Points.end(); ++it,i++) pverts[i].setValue(it->x,it->y,zPoints); edit->CurvesCoordinate->point.finishEditing(); edit->CurveSet->numVertices.finishEditing(); edit->PointsCoordinate->point.finishEditing(); // set cross coordinates edit->RootCrossSet->numVertices.set1Value(0,2); edit->RootCrossSet->numVertices.set1Value(1,2); float MiX = -exp(ceil(log(std::abs(MinX)))); MiX = std::min(MiX,(float)-exp(ceil(log(std::abs(0.1f*MaxX))))); float MaX = exp(ceil(log(std::abs(MaxX)))); MaX = std::max(MaX,(float)exp(ceil(log(std::abs(0.1f*MinX))))); float MiY = -exp(ceil(log(std::abs(MinY)))); MiY = std::min(MiY,(float)-exp(ceil(log(std::abs(0.1f*MaxY))))); float MaY = exp(ceil(log(std::abs(MaxY)))); MaY = std::max(MaY,(float)exp(ceil(log(std::abs(0.1f*MinY))))); edit->RootCrossCoordinate->point.set1Value(0,SbVec3f(MiX, 0.0f, zCross)); edit->RootCrossCoordinate->point.set1Value(1,SbVec3f(MaX, 0.0f, zCross)); edit->RootCrossCoordinate->point.set1Value(2,SbVec3f(0.0f, MiY, zCross)); edit->RootCrossCoordinate->point.set1Value(3,SbVec3f(0.0f, MaY, zCross)); // Render Constraints =================================================== const std::vector<Sketcher::Constraint *> &constrlist = getSketchObject()->Constraints.getValues(); // After an undo/redo it can happen that we have an empty geometry list but a non-empty constraint list // In this case just ignore the constraints. (See bug #0000421) if (geomlist->size() <= 2 && !constrlist.empty()) { rebuildConstraintsVisual(); return; } // reset point if the constraint type has changed Restart: // check if a new constraint arrived if (constrlist.size() != edit->vConstrType.size()) rebuildConstraintsVisual(); assert(int(constrlist.size()) == edit->constrGroup->getNumChildren()); assert(int(edit->vConstrType.size()) == edit->constrGroup->getNumChildren()); // go through the constraints and update the position i = 0; for (std::vector<Sketcher::Constraint *>::const_iterator it=constrlist.begin(); it != constrlist.end(); ++it, i++) { // check if the type has changed if ((*it)->Type != edit->vConstrType[i]) { // clearing the type vector will force a rebuild of the visual nodes edit->vConstrType.clear(); //TODO: The 'goto' here is unsafe as it can happen that we cause an endless loop (see bug #0001956). goto Restart; } try{//because calculateNormalAtPoint, used in there, can throw // root separator for this constraint SoSeparator *sep = dynamic_cast<SoSeparator *>(edit->constrGroup->getChild(i)); const Constraint *Constr = *it; // distinquish different constraint types to build up switch (Constr->Type) { case Horizontal: // write the new position of the Horizontal constraint Same as vertical position. case Vertical: // write the new position of the Vertical constraint { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); // get the geometry const Part::Geometry *geo = GeoById(*geomlist, Constr->First); // Vertical can only be a GeomLineSegment assert(geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()); const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(geo); // calculate the half distance between the start and endpoint Base::Vector3d midpos = ((lineSeg->getEndPoint()+lineSeg->getStartPoint())/2); //Get a set of vectors perpendicular and tangential to these Base::Vector3d dir = (lineSeg->getEndPoint()-lineSeg->getStartPoint()).Normalize(); Base::Vector3d norm(-dir.y,dir.x,0); Base::Vector3d relpos = seekConstraintPosition(midpos, norm, dir, 2.5, edit->constrGroup->getChild(i)); dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->abPos = SbVec3f(midpos.x, midpos.y, zConstr); //Absolute Reference //Reference Position that is scaled according to zoom dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = SbVec3f(relpos.x, relpos.y, 0); } break; case Perpendicular: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); // get the geometry const Part::Geometry *geo1 = GeoById(*geomlist, Constr->First); const Part::Geometry *geo2 = GeoById(*geomlist, Constr->Second); Base::Vector3d midpos1, dir1, norm1; Base::Vector3d midpos2, dir2, norm2; bool twoIcons = false;//a very local flag. It's set to true to indicate that the second dir+norm are valid and should be used if (Constr->Third != Constraint::GeoUndef || //perpty via point Constr->FirstPos != Sketcher::none) { //endpoint-to-curve or endpoint-to-endpoint perpty int ptGeoId; Sketcher::PointPos ptPosId; do {//dummy loop to use break =) Maybe goto? ptGeoId = Constr->First; ptPosId = Constr->FirstPos; if (ptPosId != Sketcher::none) break; ptGeoId = Constr->Second; ptPosId = Constr->SecondPos; if (ptPosId != Sketcher::none) break; ptGeoId = Constr->Third; ptPosId = Constr->ThirdPos; if (ptPosId != Sketcher::none) break; assert(0);//no point found! } while (false); if (temp) midpos1 = getSketchObject()->getSolvedSketch().getPoint(ptGeoId, ptPosId); else midpos1 = getSketchObject()->getPoint(ptGeoId, ptPosId); norm1 = getSketchObject()->getSolvedSketch().calculateNormalAtPoint(Constr->Second, midpos1.x, midpos1.y); norm1.Normalize(); dir1 = norm1; dir1.RotateZ(-M_PI/2.0); } else if (Constr->FirstPos == Sketcher::none) { if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg1 = dynamic_cast<const Part::GeomLineSegment *>(geo1); midpos1 = ((lineSeg1->getEndPoint()+lineSeg1->getStartPoint())/2); dir1 = (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()).Normalize(); norm1 = Base::Vector3d(-dir1.y,dir1.x,0.); } else if (geo1->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo1); double startangle, endangle, midangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); midangle = (startangle + endangle)/2; norm1 = Base::Vector3d(cos(midangle),sin(midangle),0); dir1 = Base::Vector3d(-norm1.y,norm1.x,0); midpos1 = arc->getCenter() + arc->getRadius() * norm1; } else if (geo1->getTypeId() == Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(geo1); norm1 = Base::Vector3d(cos(M_PI/4),sin(M_PI/4),0); dir1 = Base::Vector3d(-norm1.y,norm1.x,0); midpos1 = circle->getCenter() + circle->getRadius() * norm1; } else break; if (geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg2 = dynamic_cast<const Part::GeomLineSegment *>(geo2); midpos2 = ((lineSeg2->getEndPoint()+lineSeg2->getStartPoint())/2); dir2 = (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()).Normalize(); norm2 = Base::Vector3d(-dir2.y,dir2.x,0.); } else if (geo2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo2); double startangle, endangle, midangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); midangle = (startangle + endangle)/2; norm2 = Base::Vector3d(cos(midangle),sin(midangle),0); dir2 = Base::Vector3d(-norm2.y,norm2.x,0); midpos2 = arc->getCenter() + arc->getRadius() * norm2; } else if (geo2->getTypeId() == Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(geo2); norm2 = Base::Vector3d(cos(M_PI/4),sin(M_PI/4),0); dir2 = Base::Vector3d(-norm2.y,norm2.x,0); midpos2 = circle->getCenter() + circle->getRadius() * norm2; } else break; twoIcons = true; } Base::Vector3d relpos1 = seekConstraintPosition(midpos1, norm1, dir1, 2.5, edit->constrGroup->getChild(i)); dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->abPos = SbVec3f(midpos1.x, midpos1.y, zConstr); dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = SbVec3f(relpos1.x, relpos1.y, 0); if (twoIcons) { Base::Vector3d relpos2 = seekConstraintPosition(midpos2, norm2, dir2, 2.5, edit->constrGroup->getChild(i)); Base::Vector3d secondPos = midpos2 - midpos1; dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION))->abPos = SbVec3f(secondPos.x, secondPos.y, zConstr); dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION))->translation = SbVec3f(relpos2.x -relpos1.x, relpos2.y -relpos1.y, 0); } } break; case Parallel: case Equal: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); // get the geometry const Part::Geometry *geo1 = GeoById(*geomlist, Constr->First); const Part::Geometry *geo2 = GeoById(*geomlist, Constr->Second); Base::Vector3d midpos1, dir1, norm1; Base::Vector3d midpos2, dir2, norm2; if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() || geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) { if (Constr->Type == Equal) { double r1a=0,r1b=0,r2a=0,r2b=0; double angle1,angle1plus=0., angle2, angle2plus=0.;//angle1 = rotation of object as a whole; angle1plus = arc angle (t parameter for ellipses). if (geo1->getTypeId() == Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(geo1); r1a = circle->getRadius(); angle1 = M_PI/4; midpos1 = circle->getCenter(); } else if (geo1->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo1); r1a = arc->getRadius(); double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); angle1 = (startangle + endangle)/2; midpos1 = arc->getCenter(); } else if (geo1->getTypeId() == Part::GeomEllipse::getClassTypeId()) { const Part::GeomEllipse *ellipse = dynamic_cast<const Part::GeomEllipse *>(geo1); r1a = ellipse->getMajorRadius(); r1b = ellipse->getMinorRadius(); Base::Vector3d majdir = ellipse->getMajorAxisDir(); angle1 = atan2(majdir.y, majdir.x); angle1plus = M_PI/4; midpos1 = ellipse->getCenter(); } else if (geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { const Part::GeomArcOfEllipse *aoe = dynamic_cast<const Part::GeomArcOfEllipse *>(geo1); r1a = aoe->getMajorRadius(); r1b = aoe->getMinorRadius(); double startangle, endangle; aoe->getRange(startangle, endangle, /*emulateCCW=*/true); Base::Vector3d majdir = aoe->getMajorAxisDir(); angle1 = atan2(majdir.y, majdir.x); angle1plus = (startangle + endangle)/2; midpos1 = aoe->getCenter(); } else break; if (geo2->getTypeId() == Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(geo2); r2a = circle->getRadius(); angle2 = M_PI/4; midpos2 = circle->getCenter(); } else if (geo2->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo2); r2a = arc->getRadius(); double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); angle2 = (startangle + endangle)/2; midpos2 = arc->getCenter(); } else if (geo2->getTypeId() == Part::GeomEllipse::getClassTypeId()) { const Part::GeomEllipse *ellipse = dynamic_cast<const Part::GeomEllipse *>(geo2); r2a = ellipse->getMajorRadius(); r2b = ellipse->getMinorRadius(); Base::Vector3d majdir = ellipse->getMajorAxisDir(); angle2 = atan2(majdir.y, majdir.x); angle2plus = M_PI/4; midpos2 = ellipse->getCenter(); } else if (geo2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId()) { const Part::GeomArcOfEllipse *aoe = dynamic_cast<const Part::GeomArcOfEllipse *>(geo2); r2a = aoe->getMajorRadius(); r2b = aoe->getMinorRadius(); double startangle, endangle; aoe->getRange(startangle, endangle, /*emulateCCW=*/true); Base::Vector3d majdir = aoe->getMajorAxisDir(); angle2 = atan2(majdir.y, majdir.x); angle2plus = (startangle + endangle)/2; midpos2 = aoe->getCenter(); } else break; if( geo1->getTypeId() == Part::GeomEllipse::getClassTypeId() || geo1->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() ){ Base::Vector3d majDir, minDir, rvec; majDir = Base::Vector3d(cos(angle1),sin(angle1),0);//direction of major axis of ellipse minDir = Base::Vector3d(-majDir.y,majDir.x,0);//direction of minor axis of ellipse rvec = (r1a*cos(angle1plus)) * majDir + (r1b*sin(angle1plus)) * minDir; midpos1 += rvec; rvec.Normalize(); norm1 = rvec; dir1 = Base::Vector3d(-rvec.y,rvec.x,0);//DeepSOIC: I'm not sure what dir is supposed to mean. } else { norm1 = Base::Vector3d(cos(angle1),sin(angle1),0); dir1 = Base::Vector3d(-norm1.y,norm1.x,0); midpos1 += r1a*norm1; } if( geo2->getTypeId() == Part::GeomEllipse::getClassTypeId() || geo2->getTypeId() == Part::GeomArcOfEllipse::getClassTypeId() ) { Base::Vector3d majDir, minDir, rvec; majDir = Base::Vector3d(cos(angle2),sin(angle2),0);//direction of major axis of ellipse minDir = Base::Vector3d(-majDir.y,majDir.x,0);//direction of minor axis of ellipse rvec = (r2a*cos(angle2plus)) * majDir + (r2b*sin(angle2plus)) * minDir; midpos2 += rvec; rvec.Normalize(); norm2 = rvec; dir2 = Base::Vector3d(-rvec.y,rvec.x,0); } else { norm2 = Base::Vector3d(cos(angle2),sin(angle2),0); dir2 = Base::Vector3d(-norm2.y,norm2.x,0); midpos2 += r2a*norm2; } } else // Parallel can only apply to a GeomLineSegment break; } else { const Part::GeomLineSegment *lineSeg1 = dynamic_cast<const Part::GeomLineSegment *>(geo1); const Part::GeomLineSegment *lineSeg2 = dynamic_cast<const Part::GeomLineSegment *>(geo2); // calculate the half distance between the start and endpoint midpos1 = ((lineSeg1->getEndPoint()+lineSeg1->getStartPoint())/2); midpos2 = ((lineSeg2->getEndPoint()+lineSeg2->getStartPoint())/2); //Get a set of vectors perpendicular and tangential to these dir1 = (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()).Normalize(); dir2 = (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()).Normalize(); norm1 = Base::Vector3d(-dir1.y,dir1.x,0.); norm2 = Base::Vector3d(-dir2.y,dir2.x,0.); } Base::Vector3d relpos1 = seekConstraintPosition(midpos1, norm1, dir1, 2.5, edit->constrGroup->getChild(i)); Base::Vector3d relpos2 = seekConstraintPosition(midpos2, norm2, dir2, 2.5, edit->constrGroup->getChild(i)); dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->abPos = SbVec3f(midpos1.x, midpos1.y, zConstr); //Absolute Reference //Reference Position that is scaled according to zoom dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = SbVec3f(relpos1.x, relpos1.y, 0); Base::Vector3d secondPos = midpos2 - midpos1; dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION))->abPos = SbVec3f(secondPos.x, secondPos.y, zConstr); //Absolute Reference //Reference Position that is scaled according to zoom dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION))->translation = SbVec3f(relpos2.x - relpos1.x, relpos2.y -relpos1.y, 0); } break; case Distance: case DistanceX: case DistanceY: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); Base::Vector3d pnt1(0.,0.,0.), pnt2(0.,0.,0.); if (Constr->SecondPos != Sketcher::none) { // point to point distance if (temp) { pnt1 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); pnt2 = getSketchObject()->getSolvedSketch().getPoint(Constr->Second, Constr->SecondPos); } else { pnt1 = getSketchObject()->getPoint(Constr->First, Constr->FirstPos); pnt2 = getSketchObject()->getPoint(Constr->Second, Constr->SecondPos); } } else if (Constr->Second != Constraint::GeoUndef) { // point to line distance if (temp) { pnt1 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); } else { pnt1 = getSketchObject()->getPoint(Constr->First, Constr->FirstPos); } const Part::Geometry *geo = GeoById(*geomlist, Constr->Second); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(geo); Base::Vector3d l2p1 = lineSeg->getStartPoint(); Base::Vector3d l2p2 = lineSeg->getEndPoint(); // calculate the projection of p1 onto line2 pnt2.ProjToLine(pnt1-l2p1, l2p2-l2p1); pnt2 += pnt1; } else break; } else if (Constr->FirstPos != Sketcher::none) { if (temp) { pnt2 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); } else { pnt2 = getSketchObject()->getPoint(Constr->First, Constr->FirstPos); } } else if (Constr->First != Constraint::GeoUndef) { const Part::Geometry *geo = GeoById(*geomlist, Constr->First); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(geo); pnt1 = lineSeg->getStartPoint(); pnt2 = lineSeg->getEndPoint(); } else break; } else break; SoDatumLabel *asciiText = dynamic_cast<SoDatumLabel *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); asciiText->string = SbString(Base::Quantity(Constr->getPresentationValue(),Base::Unit::Length).getUserString().toUtf8().constData()); if (Constr->Type == Distance) asciiText->datumtype = SoDatumLabel::DISTANCE; else if (Constr->Type == DistanceX) asciiText->datumtype = SoDatumLabel::DISTANCEX; else if (Constr->Type == DistanceY) asciiText->datumtype = SoDatumLabel::DISTANCEY; // Assign the Datum Points asciiText->pnts.setNum(2); SbVec3f *verts = asciiText->pnts.startEditing(); verts[0] = SbVec3f (pnt1.x,pnt1.y,zConstr); verts[1] = SbVec3f (pnt2.x,pnt2.y,zConstr); asciiText->pnts.finishEditing(); //Assign the Label Distance asciiText->param1 = Constr->LabelDistance; asciiText->param2 = Constr->LabelPosition; } break; case PointOnObject: case Tangent: case SnellsLaw: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); Base::Vector3d pos, relPos; if ( Constr->Type == PointOnObject || Constr->Type == SnellsLaw || (Constr->Type == Tangent && Constr->Third != Constraint::GeoUndef) || //Tangency via point (Constr->Type == Tangent && Constr->FirstPos != Sketcher::none) //endpoint-to-curve or endpoint-to-endpoint tangency ) { //find the point of tangency/point that is on object //just any point among first/second/third should be OK int ptGeoId; Sketcher::PointPos ptPosId; do {//dummy loop to use break =) Maybe goto? ptGeoId = Constr->First; ptPosId = Constr->FirstPos; if (ptPosId != Sketcher::none) break; ptGeoId = Constr->Second; ptPosId = Constr->SecondPos; if (ptPosId != Sketcher::none) break; ptGeoId = Constr->Third; ptPosId = Constr->ThirdPos; if (ptPosId != Sketcher::none) break; assert(0);//no point found! } while (false); pos = getSketchObject()->getSolvedSketch().getPoint(ptGeoId, ptPosId); Base::Vector3d norm = getSketchObject()->getSolvedSketch().calculateNormalAtPoint(Constr->Second, pos.x, pos.y); norm.Normalize(); Base::Vector3d dir = norm; dir.RotateZ(-M_PI/2.0); relPos = seekConstraintPosition(pos, norm, dir, 2.5, edit->constrGroup->getChild(i)); dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->abPos = SbVec3f(pos.x, pos.y, zConstr); //Absolute Reference dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = SbVec3f(relPos.x, relPos.y, 0); } else if (Constr->Type == Tangent) { // get the geometry const Part::Geometry *geo1 = GeoById(*geomlist, Constr->First); const Part::Geometry *geo2 = GeoById(*geomlist, Constr->Second); if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg1 = dynamic_cast<const Part::GeomLineSegment *>(geo1); const Part::GeomLineSegment *lineSeg2 = dynamic_cast<const Part::GeomLineSegment *>(geo2); // tangency between two lines Base::Vector3d midpos1 = ((lineSeg1->getEndPoint()+lineSeg1->getStartPoint())/2); Base::Vector3d midpos2 = ((lineSeg2->getEndPoint()+lineSeg2->getStartPoint())/2); Base::Vector3d dir1 = (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()).Normalize(); Base::Vector3d dir2 = (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()).Normalize(); Base::Vector3d norm1 = Base::Vector3d(-dir1.y,dir1.x,0.f); Base::Vector3d norm2 = Base::Vector3d(-dir2.y,dir2.x,0.f); Base::Vector3d relpos1 = seekConstraintPosition(midpos1, norm1, dir1, 2.5, edit->constrGroup->getChild(i)); Base::Vector3d relpos2 = seekConstraintPosition(midpos2, norm2, dir2, 2.5, edit->constrGroup->getChild(i)); dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->abPos = SbVec3f(midpos1.x, midpos1.y, zConstr); //Absolute Reference //Reference Position that is scaled according to zoom dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = SbVec3f(relpos1.x, relpos1.y, 0); Base::Vector3d secondPos = midpos2 - midpos1; dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION))->abPos = SbVec3f(secondPos.x, secondPos.y, zConstr); //Absolute Reference //Reference Position that is scaled according to zoom dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION))->translation = SbVec3f(relpos2.x -relpos1.x, relpos2.y -relpos1.y, 0); break; } else if (geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { std::swap(geo1,geo2); } if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(geo1); Base::Vector3d dir = (lineSeg->getEndPoint() - lineSeg->getStartPoint()).Normalize(); Base::Vector3d norm(-dir.y, dir.x, 0); if (geo2->getTypeId()== Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(geo2); // tangency between a line and a circle float length = (circle->getCenter() - lineSeg->getStartPoint())*dir; pos = lineSeg->getStartPoint() + dir * length; relPos = norm * 1; //TODO Huh? } else if (geo2->getTypeId()== Part::GeomEllipse::getClassTypeId() || geo2->getTypeId()== Part::GeomArcOfEllipse::getClassTypeId()) { Base::Vector3d center; if(geo2->getTypeId()== Part::GeomEllipse::getClassTypeId()){ const Part::GeomEllipse *ellipse = dynamic_cast<const Part::GeomEllipse *>(geo2); center=ellipse->getCenter(); } else { const Part::GeomArcOfEllipse *aoc = dynamic_cast<const Part::GeomArcOfEllipse *>(geo2); center=aoc->getCenter(); } // tangency between a line and an ellipse float length = (center - lineSeg->getStartPoint())*dir; pos = lineSeg->getStartPoint() + dir * length; relPos = norm * 1; } else if (geo2->getTypeId()== Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo2); // tangency between a line and an arc float length = (arc->getCenter() - lineSeg->getStartPoint())*dir; pos = lineSeg->getStartPoint() + dir * length; relPos = norm * 1; //TODO Huh? } } if (geo1->getTypeId()== Part::GeomCircle::getClassTypeId() && geo2->getTypeId()== Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle1 = dynamic_cast<const Part::GeomCircle *>(geo1); const Part::GeomCircle *circle2 = dynamic_cast<const Part::GeomCircle *>(geo2); // tangency between two cicles Base::Vector3d dir = (circle2->getCenter() - circle1->getCenter()).Normalize(); pos = circle1->getCenter() + dir * circle1->getRadius(); relPos = dir * 1; } else if (geo2->getTypeId()== Part::GeomCircle::getClassTypeId()) { std::swap(geo1,geo2); } if (geo1->getTypeId()== Part::GeomCircle::getClassTypeId() && geo2->getTypeId()== Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(geo1); const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo2); // tangency between a circle and an arc Base::Vector3d dir = (arc->getCenter() - circle->getCenter()).Normalize(); pos = circle->getCenter() + dir * circle->getRadius(); relPos = dir * 1; } else if (geo1->getTypeId()== Part::GeomArcOfCircle::getClassTypeId() && geo2->getTypeId()== Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc1 = dynamic_cast<const Part::GeomArcOfCircle *>(geo1); const Part::GeomArcOfCircle *arc2 = dynamic_cast<const Part::GeomArcOfCircle *>(geo2); // tangency between two arcs Base::Vector3d dir = (arc2->getCenter() - arc1->getCenter()).Normalize(); pos = arc1->getCenter() + dir * arc1->getRadius(); relPos = dir * 1; } dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->abPos = SbVec3f(pos.x, pos.y, zConstr); //Absolute Reference dynamic_cast<SoZoomTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = SbVec3f(relPos.x, relPos.y, 0); } } break; case Symmetric: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); Base::Vector3d pnt1 = getSketchObject()->getSolvedSketch().getPoint(Constr->First, Constr->FirstPos); Base::Vector3d pnt2 = getSketchObject()->getSolvedSketch().getPoint(Constr->Second, Constr->SecondPos); SbVec3f p1(pnt1.x,pnt1.y,zConstr); SbVec3f p2(pnt2.x,pnt2.y,zConstr); SbVec3f dir = (p2-p1); dir.normalize(); SbVec3f norm (-dir[1],dir[0],0); SoDatumLabel *asciiText = dynamic_cast<SoDatumLabel *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); asciiText->datumtype = SoDatumLabel::SYMMETRIC; asciiText->pnts.setNum(2); SbVec3f *verts = asciiText->pnts.startEditing(); verts[0] = p1; verts[1] = p2; asciiText->pnts.finishEditing(); dynamic_cast<SoTranslation *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION))->translation = (p1 + p2)/2; } break; case Angle: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); assert((Constr->Second >= -extGeoCount && Constr->Second < intGeoCount) || Constr->Second == Constraint::GeoUndef); SbVec3f p0; double startangle,range,endangle; if (Constr->Second != Constraint::GeoUndef) { Base::Vector3d dir1, dir2; if(Constr->Third == Constraint::GeoUndef) { //angle between two lines const Part::Geometry *geo1 = GeoById(*geomlist, Constr->First); const Part::Geometry *geo2 = GeoById(*geomlist, Constr->Second); if (geo1->getTypeId() != Part::GeomLineSegment::getClassTypeId() || geo2->getTypeId() != Part::GeomLineSegment::getClassTypeId()) break; const Part::GeomLineSegment *lineSeg1 = dynamic_cast<const Part::GeomLineSegment *>(geo1); const Part::GeomLineSegment *lineSeg2 = dynamic_cast<const Part::GeomLineSegment *>(geo2); bool flip1 = (Constr->FirstPos == end); bool flip2 = (Constr->SecondPos == end); dir1 = (flip1 ? -1. : 1.) * (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()); dir2 = (flip2 ? -1. : 1.) * (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()); Base::Vector3d pnt1 = flip1 ? lineSeg1->getEndPoint() : lineSeg1->getStartPoint(); Base::Vector3d pnt2 = flip2 ? lineSeg2->getEndPoint() : lineSeg2->getStartPoint(); // line-line intersection { double det = dir1.x*dir2.y - dir1.y*dir2.x; if ((det > 0 ? det : -det) < 1e-10) { // lines are coincident (or parallel) and in this case the center // of the point pairs with the shortest distance is used Base::Vector3d p1[2], p2[2]; p1[0] = lineSeg1->getStartPoint(); p1[1] = lineSeg1->getEndPoint(); p2[0] = lineSeg2->getStartPoint(); p2[1] = lineSeg2->getEndPoint(); double length = DBL_MAX; for (int i=0; i <= 1; i++) { for (int j=0; j <= 1; j++) { double tmp = (p2[j]-p1[i]).Length(); if (tmp < length) { length = tmp; p0.setValue((p2[j].x+p1[i].x)/2,(p2[j].y+p1[i].y)/2,0); } } } } else { double c1 = dir1.y*pnt1.x - dir1.x*pnt1.y; double c2 = dir2.y*pnt2.x - dir2.x*pnt2.y; double x = (dir1.x*c2 - dir2.x*c1)/det; double y = (dir1.y*c2 - dir2.y*c1)/det; p0 = SbVec3f(x,y,0); } } } else {//angle-via-point Base::Vector3d p = getSketchObject()->getSolvedSketch().getPoint(Constr->Third, Constr->ThirdPos); p0 = SbVec3f(p.x, p.y, 0); dir1 = getSketchObject()->getSolvedSketch().calculateNormalAtPoint(Constr->First, p.x, p.y); dir1.RotateZ(-M_PI/2);//convert to vector of tangency by rotating dir2 = getSketchObject()->getSolvedSketch().calculateNormalAtPoint(Constr->Second, p.x, p.y); dir2.RotateZ(-M_PI/2); } startangle = atan2(dir1.y,dir1.x); range = atan2(-dir1.y*dir2.x+dir1.x*dir2.y, dir1.x*dir2.x+dir1.y*dir2.y); endangle = startangle + range; } else if (Constr->First != Constraint::GeoUndef) { const Part::Geometry *geo = GeoById(*geomlist, Constr->First); if (geo->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { const Part::GeomLineSegment *lineSeg = dynamic_cast<const Part::GeomLineSegment *>(geo); p0 = Base::convertTo<SbVec3f>((lineSeg->getEndPoint()+lineSeg->getStartPoint())/2); Base::Vector3d dir = lineSeg->getEndPoint()-lineSeg->getStartPoint(); startangle = 0.; range = atan2(dir.y,dir.x); endangle = startangle + range; } else if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo); p0 = Base::convertTo<SbVec3f>(arc->getCenter()); arc->getRange(startangle, endangle,/*emulateCCWXY=*/true); range = endangle - startangle; } else { break; } } else break; SoDatumLabel *asciiText = dynamic_cast<SoDatumLabel *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); asciiText->string = SbString(Base::Quantity(Base::toDegrees<double>(Constr->getPresentationValue()),Base::Unit::Angle).getUserString().toUtf8().constData()); asciiText->datumtype = SoDatumLabel::ANGLE; asciiText->param1 = Constr->LabelDistance; asciiText->param2 = startangle; asciiText->param3 = range; asciiText->pnts.setNum(2); SbVec3f *verts = asciiText->pnts.startEditing(); verts[0] = p0; asciiText->pnts.finishEditing(); } break; case Radius: { assert(Constr->First >= -extGeoCount && Constr->First < intGeoCount); Base::Vector3d pnt1(0.,0.,0.), pnt2(0.,0.,0.); if (Constr->First != Constraint::GeoUndef) { const Part::Geometry *geo = GeoById(*geomlist, Constr->First); if (geo->getTypeId() == Part::GeomArcOfCircle::getClassTypeId()) { const Part::GeomArcOfCircle *arc = dynamic_cast<const Part::GeomArcOfCircle *>(geo); double radius = arc->getRadius(); double angle = (double) Constr->LabelPosition; if (angle == 10) { double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); angle = (startangle + endangle)/2; } pnt1 = arc->getCenter(); pnt2 = pnt1 + radius * Base::Vector3d(cos(angle),sin(angle),0.); } else if (geo->getTypeId() == Part::GeomCircle::getClassTypeId()) { const Part::GeomCircle *circle = dynamic_cast<const Part::GeomCircle *>(geo); double radius = circle->getRadius(); double angle = (double) Constr->LabelPosition; if (angle == 10) { angle = 0; } pnt1 = circle->getCenter(); pnt2 = pnt1 + radius * Base::Vector3d(cos(angle),sin(angle),0.); } else break; } else break; SbVec3f p1(pnt1.x,pnt1.y,zConstr); SbVec3f p2(pnt2.x,pnt2.y,zConstr); SoDatumLabel *asciiText = dynamic_cast<SoDatumLabel *>(sep->getChild(CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL)); asciiText->string = SbString(Base::Quantity(Constr->getPresentationValue(),Base::Unit::Length).getUserString().toUtf8().constData()); asciiText->datumtype = SoDatumLabel::RADIUS; asciiText->param1 = Constr->LabelDistance; asciiText->param2 = Constr->LabelPosition; asciiText->pnts.setNum(2); SbVec3f *verts = asciiText->pnts.startEditing(); verts[0] = p1; verts[1] = p2; asciiText->pnts.finishEditing(); } break; case Coincident: // nothing to do for coincident case None: case InternalAlignment: case NumConstraintTypes: break; } } catch (Base::Exception e) { Base::Console().Error("Exception during draw: %s\n", e.what()); } catch (...){ Base::Console().Error("Exception during draw: unknown\n"); } } this->drawConstraintIcons(); this->updateColor(); // delete the cloned objects if (temp) { for (std::vector<Part::Geometry *>::iterator it=tempGeo.begin(); it != tempGeo.end(); ++it) { if (*it) delete *it; } } Gui::MDIView *mdi = this->getActiveView(); if (mdi && mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId())) { static_cast<Gui::View3DInventor *>(mdi)->getViewer()->redraw(); } } void ViewProviderSketch::rebuildConstraintsVisual(void) { const std::vector<Sketcher::Constraint *> &constrlist = getSketchObject()->Constraints.getValues(); // clean up edit->constrGroup->removeAllChildren(); edit->vConstrType.clear(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); int fontSize = hGrp->GetInt("EditSketcherFontSize", 17); for (std::vector<Sketcher::Constraint *>::const_iterator it=constrlist.begin(); it != constrlist.end(); ++it) { // root separator for one constraint SoSeparator *sep = new SoSeparator(); sep->ref(); // no caching for fluctuand data structures sep->renderCaching = SoSeparator::OFF; // every constrained visual node gets its own material for preselection and selection SoMaterial *mat = new SoMaterial; mat->ref(); mat->diffuseColor = (*it)->isDriving?ConstrDimColor:NonDrivingConstrDimColor; // Get sketch normal Base::Vector3d RN(0,0,1); // move to position of Sketch Base::Placement Plz = getSketchObject()->Placement.getValue(); Base::Rotation tmp(Plz.getRotation()); tmp.multVec(RN,RN); Plz.setRotation(tmp); SbVec3f norm(RN.x, RN.y, RN.z); // distinguish different constraint types to build up switch ((*it)->Type) { case Distance: case DistanceX: case DistanceY: case Radius: case Angle: { SoDatumLabel *text = new SoDatumLabel(); text->norm.setValue(norm); text->string = ""; text->textColor = (*it)->isDriving?ConstrDimColor:NonDrivingConstrDimColor;; text->size.setValue(fontSize); text->useAntialiasing = false; SoAnnotation *anno = new SoAnnotation(); anno->renderCaching = SoSeparator::OFF; anno->addChild(text); // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 sep->addChild(text); edit->constrGroup->addChild(anno); edit->vConstrType.push_back((*it)->Type); // nodes not needed sep->unref(); mat->unref(); continue; // jump to next constraint } break; case Horizontal: case Vertical: { // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 sep->addChild(mat); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1 sep->addChild(new SoZoomTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON 2 sep->addChild(new SoImage()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID 3 sep->addChild(new SoInfo()); // remember the type of this constraint node edit->vConstrType.push_back((*it)->Type); } break; case Coincident: // no visual for coincident so far edit->vConstrType.push_back(Coincident); break; case Parallel: case Perpendicular: case Equal: { // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 sep->addChild(mat); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1 sep->addChild(new SoZoomTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON 2 sep->addChild(new SoImage()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID 3 sep->addChild(new SoInfo()); // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION 4 sep->addChild(new SoZoomTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_ICON 5 sep->addChild(new SoImage()); // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID 6 sep->addChild(new SoInfo()); // remember the type of this constraint node edit->vConstrType.push_back((*it)->Type); } break; case PointOnObject: case Tangent: case SnellsLaw: { // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 sep->addChild(mat); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1 sep->addChild(new SoZoomTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON 2 sep->addChild(new SoImage()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID 3 sep->addChild(new SoInfo()); if ((*it)->Type == Tangent) { const Part::Geometry *geo1 = getSketchObject()->getGeometry((*it)->First); const Part::Geometry *geo2 = getSketchObject()->getGeometry((*it)->Second); if (geo1->getTypeId() == Part::GeomLineSegment::getClassTypeId() && geo2->getTypeId() == Part::GeomLineSegment::getClassTypeId()) { // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION 4 sep->addChild(new SoZoomTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_ICON 5 sep->addChild(new SoImage()); // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_CONSTRAINTID 6 sep->addChild(new SoInfo()); } } edit->vConstrType.push_back((*it)->Type); } break; case Symmetric: { SoDatumLabel *arrows = new SoDatumLabel(); arrows->norm.setValue(norm); arrows->string = ""; arrows->textColor = ConstrDimColor; // #define CONSTRAINT_SEPARATOR_INDEX_MATERIAL_OR_DATUMLABEL 0 sep->addChild(arrows); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_TRANSLATION 1 sep->addChild(new SoTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_ICON 2 sep->addChild(new SoImage()); // #define CONSTRAINT_SEPARATOR_INDEX_FIRST_CONSTRAINTID 3 sep->addChild(new SoInfo()); edit->vConstrType.push_back((*it)->Type); } break; case InternalAlignment: { edit->vConstrType.push_back((*it)->Type); } break; default: edit->vConstrType.push_back((*it)->Type); } edit->constrGroup->addChild(sep); // decrement ref counter again sep->unref(); mat->unref(); } } void ViewProviderSketch::drawEdit(const std::vector<Base::Vector2D> &EditCurve) { assert(edit); edit->EditCurveSet->numVertices.setNum(1); edit->EditCurvesCoordinate->point.setNum(EditCurve.size()); SbVec3f *verts = edit->EditCurvesCoordinate->point.startEditing(); int32_t *index = edit->EditCurveSet->numVertices.startEditing(); int i=0; // setting up the line set for (std::vector<Base::Vector2D>::const_iterator it = EditCurve.begin(); it != EditCurve.end(); ++it,i++) verts[i].setValue(it->fX,it->fY,zEdit); index[0] = EditCurve.size(); edit->EditCurvesCoordinate->point.finishEditing(); edit->EditCurveSet->numVertices.finishEditing(); } void ViewProviderSketch::updateData(const App::Property *prop) { ViewProvider2DObject::updateData(prop); if (edit && (prop == &(getSketchObject()->Geometry) || prop == &(getSketchObject()->Constraints))) { edit->FullyConstrained = false; // At this point, we do not need to solve the Sketch // If we are adding geometry an update can be triggered before the sketch is actually solved. // Because a solve is mandatory to any addition (at least to update the DoF of the solver), // only when the solver geometry is the same in number than the sketch geometry an update // should trigger a redraw. This reduces even more the number of redraws per insertion of geometry // solver information is also updated when no matching geometry, so that if a solving fails // this failed solving info is presented to the user UpdateSolverInformation(); // just update the solver window with the last SketchObject solving information if(getSketchObject()->getExternalGeometryCount()+getSketchObject()->getHighestCurveIndex() + 1 == getSketchObject()->getSolvedSketch().getGeometrySize()) { Gui::MDIView *mdi = Gui::Application::Instance->activeDocument()->getActiveView(); if (mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId())) draw(false); signalConstraintsChanged(); signalElementsChanged(); } } } void ViewProviderSketch::onChanged(const App::Property *prop) { // call father PartGui::ViewProvider2DObject::onChanged(prop); } void ViewProviderSketch::attach(App::DocumentObject *pcFeat) { ViewProviderPart::attach(pcFeat); } void ViewProviderSketch::setupContextMenu(QMenu *menu, QObject *receiver, const char *member) { menu->addAction(tr("Edit sketch"), receiver, member); } bool ViewProviderSketch::setEdit(int ModNum) { // When double-clicking on the item for this sketch the // object unsets and sets its edit mode without closing // the task panel Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); TaskDlgEditSketch *sketchDlg = qobject_cast<TaskDlgEditSketch *>(dlg); if (sketchDlg && sketchDlg->getSketchView() != this) sketchDlg = 0; // another sketch left open its task panel if (dlg && !sketchDlg) { QMessageBox msgBox; msgBox.setText(tr("A dialog is already open in the task panel")); msgBox.setInformativeText(tr("Do you want to close this dialog?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); if (ret == QMessageBox::Yes) Gui::Control().reject(); else return false; } Sketcher::SketchObject* sketch = getSketchObject(); if (!sketch->evaluateConstraints()) { QMessageBox box(Gui::getMainWindow()); box.setIcon(QMessageBox::Critical); box.setWindowTitle(tr("Invalid sketch")); box.setText(tr("Do you want to open the sketch validation tool?")); box.setInformativeText(tr("The sketch is invalid and cannot be edited.")); box.setStandardButtons(QMessageBox::Yes | QMessageBox::No); box.setDefaultButton(QMessageBox::Yes); switch (box.exec()) { case QMessageBox::Yes: Gui::Control().showDialog(new TaskSketcherValidation(getSketchObject())); break; default: break; } return false; } // clear the selection (convenience) Gui::Selection().clearSelection(); // create the container for the additional edit data assert(!edit); edit = new EditData(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); edit->MarkerSize = hGrp->GetInt("EditSketcherMarkerSize", 7); createEditInventorNodes(); edit->visibleBeforeEdit = this->isVisible(); this->hide(); // avoid that the wires interfere with the edit lines ShowGrid.setValue(true); TightGrid.setValue(false); float transparency; // set the point color unsigned long color = (unsigned long)(VertexColor.getPackedValue()); color = hGrp->GetUnsigned("EditedVertexColor", color); VertexColor.setPackedValue((uint32_t)color, transparency); // set the curve color color = (unsigned long)(CurveColor.getPackedValue()); color = hGrp->GetUnsigned("EditedEdgeColor", color); CurveColor.setPackedValue((uint32_t)color, transparency); // set the construction curve color color = (unsigned long)(CurveDraftColor.getPackedValue()); color = hGrp->GetUnsigned("ConstructionColor", color); CurveDraftColor.setPackedValue((uint32_t)color, transparency); // set the cross lines color //CrossColorV.setPackedValue((uint32_t)color, transparency); //CrossColorH.setPackedValue((uint32_t)color, transparency); // set the fully constrained color color = (unsigned long)(FullyConstrainedColor.getPackedValue()); color = hGrp->GetUnsigned("FullyConstrainedColor", color); FullyConstrainedColor.setPackedValue((uint32_t)color, transparency); // set the constraint dimension color color = (unsigned long)(ConstrDimColor.getPackedValue()); color = hGrp->GetUnsigned("ConstrainedDimColor", color); ConstrDimColor.setPackedValue((uint32_t)color, transparency); // set the constraint color color = (unsigned long)(ConstrIcoColor.getPackedValue()); color = hGrp->GetUnsigned("ConstrainedIcoColor", color); ConstrIcoColor.setPackedValue((uint32_t)color, transparency); // set non-driving constraint color color = (unsigned long)(NonDrivingConstrDimColor.getPackedValue()); color = hGrp->GetUnsigned("NonDrivingConstrDimColor", color); NonDrivingConstrDimColor.setPackedValue((uint32_t)color, transparency); // set the external geometry color color = (unsigned long)(CurveExternalColor.getPackedValue()); color = hGrp->GetUnsigned("ExternalColor", color); CurveExternalColor.setPackedValue((uint32_t)color, transparency); // set the highlight color unsigned long highlight = (unsigned long)(PreselectColor.getPackedValue()); highlight = hGrp->GetUnsigned("HighlightColor", highlight); PreselectColor.setPackedValue((uint32_t)highlight, transparency); // set the selection color highlight = (unsigned long)(SelectColor.getPackedValue()); highlight = hGrp->GetUnsigned("SelectionColor", highlight); SelectColor.setPackedValue((uint32_t)highlight, transparency); // start the edit dialog if (sketchDlg) Gui::Control().showDialog(sketchDlg); else Gui::Control().showDialog(new TaskDlgEditSketch(this)); // This call to the solver is needed to initialize the DoF and solve time controls // The false parameter indicates that the geometry of the SketchObject shall not be updateData // so as not to trigger an onChanged that would set the document as modified and trigger a recompute // if we just close the sketch without touching anything. if (getSketchObject()->Support.getValue()) { if (!getSketchObject()->evaluateSupport()) getSketchObject()->validateExternalLinks(); } getSketchObject()->solve(false); UpdateSolverInformation(); draw(false); connectUndoDocument = Gui::Application::Instance->activeDocument() ->signalUndoDocument.connect(boost::bind(&ViewProviderSketch::slotUndoDocument, this, _1)); connectRedoDocument = Gui::Application::Instance->activeDocument() ->signalRedoDocument.connect(boost::bind(&ViewProviderSketch::slotRedoDocument, this, _1)); return true; } QString ViewProviderSketch::appendConflictMsg(const std::vector<int> &conflicting) { QString msg; QTextStream ss(&msg); if (conflicting.size() > 0) { if (conflicting.size() == 1) ss << tr("Please remove the following constraint:"); else ss << tr("Please remove at least one of the following constraints:"); ss << "\n"; ss << conflicting[0]; for (unsigned int i=1; i < conflicting.size(); i++) ss << ", " << conflicting[i]; ss << "\n"; } return msg; } QString ViewProviderSketch::appendRedundantMsg(const std::vector<int> &redundant) { QString msg; QTextStream ss(&msg); if (redundant.size() > 0) { if (redundant.size() == 1) ss << tr("Please remove the following redundant constraint:"); else ss << tr("Please remove the following redundant constraints:"); ss << "\n"; ss << redundant[0]; for (unsigned int i=1; i < redundant.size(); i++) ss << ", " << redundant[i]; ss << "\n"; } return msg; } void ViewProviderSketch::UpdateSolverInformation() { // Updates Solver Information with the Last solver execution at SketchObject level int dofs = getSketchObject()->getLastDoF(); bool hasConflicts = getSketchObject()->getLastHasConflicts(); bool hasRedundancies = getSketchObject()->getLastHasRedundancies(); if (getSketchObject()->Geometry.getSize() == 0) { signalSetUp(tr("Empty sketch")); signalSolved(QString()); } else if (dofs < 0) { // over-constrained sketch std::string msg; SketchObject::appendConflictMsg(getSketchObject()->getLastConflicting(), msg); signalSetUp(QString::fromLatin1("<font color='red'>%1<a href=\"#conflicting\"><span style=\" text-decoration: underline; color:#0000ff;\">%2</span></a><br/>%3</font><br/>") .arg(tr("Over-constrained sketch ")) .arg(tr("(click to select)")) .arg(QString::fromStdString(msg))); signalSolved(QString()); } else if (hasConflicts) { // conflicting constraints signalSetUp(QString::fromLatin1("<font color='red'>%1<a href=\"#conflicting\"><span style=\" text-decoration: underline; color:#0000ff;\">%2</span></a><br/>%3</font><br/>") .arg(tr("Sketch contains conflicting constraints ")) .arg(tr("(click to select)")) .arg(appendConflictMsg(getSketchObject()->getLastConflicting()))); signalSolved(QString()); } else { if (hasRedundancies) { // redundant constraints signalSetUp(QString::fromLatin1("<font color='orangered'>%1<a href=\"#redundant\"><span style=\" text-decoration: underline; color:#0000ff;\">%2</span></a><br/>%3</font><br/>") .arg(tr("Sketch contains redundant constraints ")) .arg(tr("(click to select)")) .arg(appendRedundantMsg(getSketchObject()->getLastRedundant()))); } if (getSketchObject()->getLastSolverStatus() == 0) { if (dofs == 0) { // color the sketch as fully constrained if it has geometry (other than the axes) if(getSketchObject()->getSolvedSketch().getGeometrySize()>2) edit->FullyConstrained = true; if (!hasRedundancies) { signalSetUp(QString::fromLatin1("<font color='green'>%1</font>").arg(tr("Fully constrained sketch"))); } } else if (!hasRedundancies) { if (dofs == 1) signalSetUp(tr("Under-constrained sketch with 1 degree of freedom")); else signalSetUp(tr("Under-constrained sketch with %1 degrees of freedom").arg(dofs)); } signalSolved(QString::fromLatin1("<font color='green'>%1</font>").arg(tr("Solved in %1 sec").arg(getSketchObject()->getLastSolveTime()))); } else { signalSolved(QString::fromLatin1("<font color='red'>%1</font>").arg(tr("Unsolved (%1 sec)").arg(getSketchObject()->getLastSolveTime()))); } } } void ViewProviderSketch::createEditInventorNodes(void) { assert(edit); edit->EditRoot = new SoSeparator; edit->EditRoot->setName("Sketch_EditRoot"); pcRoot->addChild(edit->EditRoot); edit->EditRoot->renderCaching = SoSeparator::OFF ; // stuff for the points ++++++++++++++++++++++++++++++++++++++ SoSeparator* pointsRoot = new SoSeparator; edit->EditRoot->addChild(pointsRoot); edit->PointsMaterials = new SoMaterial; edit->PointsMaterials->setName("PointsMaterials"); pointsRoot->addChild(edit->PointsMaterials); SoMaterialBinding *MtlBind = new SoMaterialBinding; MtlBind->setName("PointsMaterialBinding"); MtlBind->value = SoMaterialBinding::PER_VERTEX; pointsRoot->addChild(MtlBind); edit->PointsCoordinate = new SoCoordinate3; edit->PointsCoordinate->setName("PointsCoordinate"); pointsRoot->addChild(edit->PointsCoordinate); SoDrawStyle *DrawStyle = new SoDrawStyle; DrawStyle->setName("PointsDrawStyle"); DrawStyle->pointSize = 8; pointsRoot->addChild(DrawStyle); edit->PointSet = new SoMarkerSet; edit->PointSet->setName("PointSet"); edit->PointSet->markerIndex = Gui::Inventor::MarkerBitmaps::getMarkerIndex("CIRCLE_FILLED", edit->MarkerSize); pointsRoot->addChild(edit->PointSet); // stuff for the Curves +++++++++++++++++++++++++++++++++++++++ SoSeparator* curvesRoot = new SoSeparator; edit->EditRoot->addChild(curvesRoot); edit->CurvesMaterials = new SoMaterial; edit->CurvesMaterials->setName("CurvesMaterials"); curvesRoot->addChild(edit->CurvesMaterials); MtlBind = new SoMaterialBinding; MtlBind->setName("CurvesMaterialsBinding"); MtlBind->value = SoMaterialBinding::PER_FACE; curvesRoot->addChild(MtlBind); edit->CurvesCoordinate = new SoCoordinate3; edit->CurvesCoordinate->setName("CurvesCoordinate"); curvesRoot->addChild(edit->CurvesCoordinate); DrawStyle = new SoDrawStyle; DrawStyle->setName("CurvesDrawStyle"); DrawStyle->lineWidth = 3; curvesRoot->addChild(DrawStyle); edit->CurveSet = new SoLineSet; edit->CurveSet->setName("CurvesLineSet"); curvesRoot->addChild(edit->CurveSet); // stuff for the RootCross lines +++++++++++++++++++++++++++++++++++++++ SoGroup* crossRoot = new Gui::SoSkipBoundingGroup; edit->pickStyleAxes = new SoPickStyle(); edit->pickStyleAxes->style = SoPickStyle::SHAPE; crossRoot->addChild(edit->pickStyleAxes); edit->EditRoot->addChild(crossRoot); MtlBind = new SoMaterialBinding; MtlBind->setName("RootCrossMaterialBinding"); MtlBind->value = SoMaterialBinding::PER_FACE; crossRoot->addChild(MtlBind); DrawStyle = new SoDrawStyle; DrawStyle->setName("RootCrossDrawStyle"); DrawStyle->lineWidth = 2; crossRoot->addChild(DrawStyle); edit->RootCrossMaterials = new SoMaterial; edit->RootCrossMaterials->setName("RootCrossMaterials"); edit->RootCrossMaterials->diffuseColor.set1Value(0,CrossColorH); edit->RootCrossMaterials->diffuseColor.set1Value(1,CrossColorV); crossRoot->addChild(edit->RootCrossMaterials); edit->RootCrossCoordinate = new SoCoordinate3; edit->RootCrossCoordinate->setName("RootCrossCoordinate"); crossRoot->addChild(edit->RootCrossCoordinate); edit->RootCrossSet = new SoLineSet; edit->RootCrossSet->setName("RootCrossLineSet"); crossRoot->addChild(edit->RootCrossSet); // stuff for the EditCurves +++++++++++++++++++++++++++++++++++++++ SoSeparator* editCurvesRoot = new SoSeparator; edit->EditRoot->addChild(editCurvesRoot); edit->EditCurvesMaterials = new SoMaterial; edit->EditCurvesMaterials->setName("EditCurvesMaterials"); editCurvesRoot->addChild(edit->EditCurvesMaterials); edit->EditCurvesCoordinate = new SoCoordinate3; edit->EditCurvesCoordinate->setName("EditCurvesCoordinate"); editCurvesRoot->addChild(edit->EditCurvesCoordinate); DrawStyle = new SoDrawStyle; DrawStyle->setName("EditCurvesDrawStyle"); DrawStyle->lineWidth = 3; editCurvesRoot->addChild(DrawStyle); edit->EditCurveSet = new SoLineSet; edit->EditCurveSet->setName("EditCurveLineSet"); editCurvesRoot->addChild(edit->EditCurveSet); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); float transparency; SbColor cursorTextColor(0,0,1); cursorTextColor.setPackedValue((uint32_t)hGrp->GetUnsigned("CursorTextColor", cursorTextColor.getPackedValue()), transparency); // stuff for the edit coordinates ++++++++++++++++++++++++++++++++++++++ SoSeparator *Coordsep = new SoSeparator(); Coordsep->setName("CoordSeparator"); // no caching for fluctuand data structures Coordsep->renderCaching = SoSeparator::OFF; SoMaterial *CoordTextMaterials = new SoMaterial; CoordTextMaterials->setName("CoordTextMaterials"); CoordTextMaterials->diffuseColor = cursorTextColor; Coordsep->addChild(CoordTextMaterials); SoFont *font = new SoFont(); font->size = 10.0; Coordsep->addChild(font); edit->textPos = new SoTranslation(); Coordsep->addChild(edit->textPos); edit->textX = new SoText2(); edit->textX->justification = SoText2::LEFT; edit->textX->string = ""; Coordsep->addChild(edit->textX); edit->EditRoot->addChild(Coordsep); // group node for the Constraint visual +++++++++++++++++++++++++++++++++++ MtlBind = new SoMaterialBinding; MtlBind->setName("ConstraintMaterialBinding"); MtlBind->value = SoMaterialBinding::OVERALL ; edit->EditRoot->addChild(MtlBind); // use small line width for the Constraints DrawStyle = new SoDrawStyle; DrawStyle->setName("ConstraintDrawStyle"); DrawStyle->lineWidth = 1; edit->EditRoot->addChild(DrawStyle); // add the group where all the constraints has its SoSeparator edit->constrGroup = new SoGroup(); edit->constrGroup->setName("ConstraintGroup"); edit->EditRoot->addChild(edit->constrGroup); } void ViewProviderSketch::unsetEdit(int ModNum) { ShowGrid.setValue(false); TightGrid.setValue(true); if (edit) { if (edit->sketchHandler) deactivateHandler(); edit->EditRoot->removeAllChildren(); pcRoot->removeChild(edit->EditRoot); if (edit->visibleBeforeEdit) this->show(); else this->hide(); delete edit; edit = 0; } try { // and update the sketch getSketchObject()->getDocument()->recompute(); } catch (...) { } // clear the selection and set the new/edited sketch(convenience) Gui::Selection().clearSelection(); std::string ObjName = getSketchObject()->getNameInDocument(); std::string DocName = getSketchObject()->getDocument()->getName(); Gui::Selection().addSelection(DocName.c_str(),ObjName.c_str()); connectUndoDocument.disconnect(); connectRedoDocument.disconnect(); // when pressing ESC make sure to close the dialog Gui::Control().closeDialog(); } void ViewProviderSketch::setEditViewer(Gui::View3DInventorViewer* viewer, int ModNum) { Base::Placement plm = getSketchObject()->Placement.getValue(); Base::Rotation tmp(plm.getRotation()); SbRotation rot((float)tmp[0],(float)tmp[1],(float)tmp[2],(float)tmp[3]); // Will the sketch be visible from the new position (#0000957)? // SoCamera* camera = viewer->getSoRenderManager()->getCamera(); SbVec3f curdir; // current view direction camera->orientation.getValue().multVec(SbVec3f(0, 0, -1), curdir); SbVec3f focal = camera->position.getValue() + camera->focalDistance.getValue() * curdir; SbVec3f newdir; // future view direction rot.multVec(SbVec3f(0, 0, -1), newdir); SbVec3f newpos = focal - camera->focalDistance.getValue() * newdir; SbVec3f plnpos = Base::convertTo<SbVec3f>(plm.getPosition()); double dist = (plnpos - newpos).dot(newdir); if (dist < 0) { float focalLength = camera->focalDistance.getValue() - dist + 5; camera->position = focal - focalLength * curdir; camera->focalDistance.setValue(focalLength); } viewer->setCameraOrientation(rot); viewer->setEditing(true); SoNode* root = viewer->getSceneGraph(); static_cast<Gui::SoFCUnifiedSelection*>(root)->selectionRole.setValue(false); viewer->addGraphicsItem(rubberband); rubberband->setViewer(viewer); } void ViewProviderSketch::unsetEditViewer(Gui::View3DInventorViewer* viewer) { viewer->removeGraphicsItem(rubberband); viewer->setEditing(false); SoNode* root = viewer->getSceneGraph(); static_cast<Gui::SoFCUnifiedSelection*>(root)->selectionRole.setValue(true); } void ViewProviderSketch::setPositionText(const Base::Vector2D &Pos, const SbString &text) { edit->textX->string = text; edit->textPos->translation = SbVec3f(Pos.fX,Pos.fY,zText); } void ViewProviderSketch::setPositionText(const Base::Vector2D &Pos) { SbString text; text.sprintf(" (%.1f,%.1f)", Pos.fX, Pos.fY); edit->textX->string = text; edit->textPos->translation = SbVec3f(Pos.fX,Pos.fY,zText); } void ViewProviderSketch::resetPositionText(void) { edit->textX->string = ""; } void ViewProviderSketch::setPreselectPoint(int PreselectPoint) { if (edit) { int oldPtId = -1; if (edit->PreselectPoint != -1) oldPtId = edit->PreselectPoint + 1; else if (edit->PreselectCross == 0) oldPtId = 0; int newPtId = PreselectPoint + 1; SbVec3f *pverts = edit->PointsCoordinate->point.startEditing(); float x,y,z; if (oldPtId != -1 && edit->SelPointSet.find(oldPtId) == edit->SelPointSet.end()) { // send to background pverts[oldPtId].getValue(x,y,z); pverts[oldPtId].setValue(x,y,zPoints); } // bring to foreground pverts[newPtId].getValue(x,y,z); pverts[newPtId].setValue(x,y,zHighlight); edit->PreselectPoint = PreselectPoint; edit->PointsCoordinate->point.finishEditing(); } } void ViewProviderSketch::resetPreselectPoint(void) { if (edit) { int oldPtId = -1; if (edit->PreselectPoint != -1) oldPtId = edit->PreselectPoint + 1; else if (edit->PreselectCross == 0) oldPtId = 0; if (oldPtId != -1 && edit->SelPointSet.find(oldPtId) == edit->SelPointSet.end()) { // send to background SbVec3f *pverts = edit->PointsCoordinate->point.startEditing(); float x,y,z; pverts[oldPtId].getValue(x,y,z); pverts[oldPtId].setValue(x,y,zPoints); edit->PointsCoordinate->point.finishEditing(); } edit->PreselectPoint = -1; } } void ViewProviderSketch::addSelectPoint(int SelectPoint) { if (edit) { int PtId = SelectPoint + 1; SbVec3f *pverts = edit->PointsCoordinate->point.startEditing(); // bring to foreground float x,y,z; pverts[PtId].getValue(x,y,z); pverts[PtId].setValue(x,y,zHighlight); edit->SelPointSet.insert(PtId); edit->PointsCoordinate->point.finishEditing(); } } void ViewProviderSketch::removeSelectPoint(int SelectPoint) { if (edit) { int PtId = SelectPoint + 1; SbVec3f *pverts = edit->PointsCoordinate->point.startEditing(); // send to background float x,y,z; pverts[PtId].getValue(x,y,z); pverts[PtId].setValue(x,y,zPoints); edit->SelPointSet.erase(PtId); edit->PointsCoordinate->point.finishEditing(); } } void ViewProviderSketch::clearSelectPoints(void) { if (edit) { SbVec3f *pverts = edit->PointsCoordinate->point.startEditing(); // send to background float x,y,z; for (std::set<int>::const_iterator it=edit->SelPointSet.begin(); it != edit->SelPointSet.end(); ++it) { pverts[*it].getValue(x,y,z); pverts[*it].setValue(x,y,zPoints); } edit->PointsCoordinate->point.finishEditing(); edit->SelPointSet.clear(); } } int ViewProviderSketch::getPreselectPoint(void) const { if (edit) return edit->PreselectPoint; return -1; } int ViewProviderSketch::getPreselectCurve(void) const { if (edit) return edit->PreselectCurve; return -1; } int ViewProviderSketch::getPreselectCross(void) const { if (edit) return edit->PreselectCross; return -1; } Sketcher::SketchObject *ViewProviderSketch::getSketchObject(void) const { return dynamic_cast<Sketcher::SketchObject *>(pcObject); } bool ViewProviderSketch::onDelete(const std::vector<std::string> &subList) { if (edit) { std::vector<std::string> SubNames = subList; Gui::Selection().clearSelection(); resetPreselectPoint(); edit->PreselectCurve = -1; edit->PreselectCross = -1; edit->PreselectConstraintSet.clear(); std::set<int> delInternalGeometries, delExternalGeometries, delCoincidents, delConstraints; // go through the selected subelements for (std::vector<std::string>::const_iterator it=SubNames.begin(); it != SubNames.end(); ++it) { if (it->size() > 4 && it->substr(0,4) == "Edge") { int GeoId = std::atoi(it->substr(4,4000).c_str()) - 1; if( GeoId >= 0 ) delInternalGeometries.insert(GeoId); else delExternalGeometries.insert(-3-GeoId); } else if (it->size() > 12 && it->substr(0,12) == "ExternalEdge") { int GeoId = std::atoi(it->substr(12,4000).c_str()) - 1; delExternalGeometries.insert(GeoId); } else if (it->size() > 6 && it->substr(0,6) == "Vertex") { int VtId = std::atoi(it->substr(6,4000).c_str()) - 1; int GeoId; Sketcher::PointPos PosId; getSketchObject()->getGeoVertexIndex(VtId, GeoId, PosId); if (getSketchObject()->getGeometry(GeoId)->getTypeId() == Part::GeomPoint::getClassTypeId()) { if(GeoId>=0) delInternalGeometries.insert(GeoId); else delExternalGeometries.insert(-3-GeoId); } else delCoincidents.insert(VtId); } else if (*it == "RootPoint") { delCoincidents.insert(-1); } else if (it->size() > 10 && it->substr(0,10) == "Constraint") { int ConstrId = Sketcher::PropertyConstraintList::getIndexFromConstraintName(*it); delConstraints.insert(ConstrId); } } std::set<int>::const_reverse_iterator rit; for (rit = delConstraints.rbegin(); rit != delConstraints.rend(); ++rit) { try { Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.delConstraint(%i)" ,getObject()->getNameInDocument(), *rit); } catch (const Base::Exception& e) { Base::Console().Error("%s\n", e.what()); } } for (rit = delCoincidents.rbegin(); rit != delCoincidents.rend(); ++rit) { try { Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.delConstraintOnPoint(%i)" ,getObject()->getNameInDocument(), *rit); } catch (const Base::Exception& e) { Base::Console().Error("%s\n", e.what()); } } for (rit = delInternalGeometries.rbegin(); rit != delInternalGeometries.rend(); ++rit) { try { Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.delGeometry(%i)" ,getObject()->getNameInDocument(), *rit); } catch (const Base::Exception& e) { Base::Console().Error("%s\n", e.what()); } } for (rit = delExternalGeometries.rbegin(); rit != delExternalGeometries.rend(); ++rit) { try { Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.delExternal(%i)" ,getObject()->getNameInDocument(), *rit); } catch (const Base::Exception& e) { Base::Console().Error("%s\n", e.what()); } } int ret=getSketchObject()->solve(); if(ret!=0){ // if the sketched could not be solved, we first redraw to update the UI geometry as // onChanged did not update it. UpdateSolverInformation(); draw(); signalConstraintsChanged(); signalElementsChanged(); } /*this->drawConstraintIcons(); this->updateColor();*/ // if in edit not delete the object return false; } // if not in edit delete the whole object return true; }
lgpl-2.1
pranavrc/gluon
smarts/lib/btperceptionviewcone.cpp
996
/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "btperceptionviewcone.h" btPerceptionViewcone::btPerceptionViewcone() { this->extentAngleHorizontal = 0; this->extentAngleVertical = 0; this->offsetAngleHorizontal = 0; this->offsetAngleVertical = 0; this->radius = 0; this->knowledgePrecision = 1.0; }
lgpl-2.1
mlba-team/open-lighting
tools/rdm/rdm_responder_test.py
8444
#!/usr/bin/python # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # ola_rdm_get.py # Copyright (C) 2010 Simon Newton '''Automated testing for RDM responders.''' __author__ = 'nomis52@gmail.com (Simon Newton)' from ola.testing.rdm import TestDefinitions, TestRunner from ola.testing.rdm.DMXSender import DMXSender from ola.testing.rdm.TestState import TestState import logging import re import sys import textwrap import time from ola import PidStore from ola.ClientWrapper import ClientWrapper from ola.UID import UID from optparse import OptionParser, OptionGroup, OptionValueError def ParseOptions(): usage = 'Usage: %prog [options] <uid>' description = textwrap.dedent("""\ Run a series of tests on a RDM responder to check the behaviour. This requires the OLA server to be running, and the RDM device to have been detected. You can confirm this by running ola_rdm_discover -u UNIVERSE. This will send SET commands to the broadcast UIDs which means the start address, device label etc. will be changed for all devices connected to the responder. Think twice about running this on your production lighting rig. """) parser = OptionParser(usage, description=description) parser.add_option('-c', '--slot-count', default=10, help='Number of slots to send when sending DMX.') parser.add_option('-d', '--debug', action='store_true', help='Print debug information to assist in diagnosing ' 'failures.') parser.add_option('-f', '--dmx-frame-rate', default=0, type='int', help='Send DMX frames at this rate in the background.') parser.add_option('-l', '--log', metavar='FILE', help='Also log to the file named FILE.uid.timestamp.') parser.add_option('--list-tests', action='store_true', help='Display a list of all tests') parser.add_option('-p', '--pid-store', metavar='FILE', help='The location of the PID definitions.') parser.add_option('-s', '--skip-check', action='store_true', help='Skip the check for multiple devices.') parser.add_option('-t', '--tests', metavar='TEST1,TEST2', help='A comma separated list of tests to run.') parser.add_option('--timestamp', action='store_true', help='Add timestamps to each test.') parser.add_option('--no-factory-defaults', action='store_true', help="Don't run the SET factory defaults tests") parser.add_option('-w', '--broadcast-write-delay', default=0, type='int', help='The time in ms to wait after sending broadcast set' 'commands.') parser.add_option('-u', '--universe', default=0, type='int', help='The universe number to use, default is universe 0.') options, args = parser.parse_args() if options.list_tests: return options if not args: parser.print_help() sys.exit(2) uid = UID.FromString(args[0]) if uid is None: parser.print_usage() print 'Invalid UID: %s' % args[0] sys.exit(2) options.uid = uid return options class MyFilter(object): """Filter out the ascii coloring.""" def filter(self, record): msg = record.msg record.msg = re.sub('\x1b\[\d*m', '', str(msg)) return True def SetupLogging(options): """Setup the logging for test results.""" level = logging.INFO if options.debug: level = logging.DEBUG logging.basicConfig( level=level, format='%(message)s') if options.log: file_name = '%s.%s.%d' % (options.log, options.uid, time.time()) file_handler =logging.FileHandler(file_name, 'w') file_handler.addFilter(MyFilter()) if options.debug: file_handler.setLevel(logging.DEBUG) logging.getLogger('').addHandler(file_handler) def DisplaySummary(tests): """Print a summary of the tests.""" by_category = {} warnings = [] advisories = [] count_by_state = {} for test in tests: state = test.state count_by_state[state] = count_by_state.get(state, 0) + 1 warnings.extend(test.warnings) advisories.extend(test.advisories) by_category.setdefault(test.category, {}) by_category[test.category][state] = (1 + by_category[test.category].get(state, 0)) total = sum(count_by_state.values()) logging.info('------------------- Warnings --------------------') for warning in sorted(warnings): logging.info(warning) logging.info('------------------ Advisories -------------------') for advisory in sorted(advisories): logging.info(advisory) logging.info('------------------ By Category ------------------') for category, counts in by_category.iteritems(): passed = counts.get(TestState.PASSED, 0) total_run = (passed + counts.get(TestState.FAILED, 0)) if total_run == 0: continue percent = 1.0 * passed / total_run logging.info(' %26s: %3d / %3d %.0f%%' % (category, passed, total_run, percent * 100)) logging.info('-------------------------------------------------') logging.info('%d / %d tests run, %d passed, %d failed, %d broken' % ( total - count_by_state.get(TestState.NOT_RUN, 0), total, count_by_state.get(TestState.PASSED, 0), count_by_state.get(TestState.FAILED, 0), count_by_state.get(TestState.BROKEN, 0))) def main(): options = ParseOptions() test_classes = TestRunner.GetTestClasses(TestDefinitions) if options.list_tests: for test_name in sorted(c.__name__ for c in test_classes): print test_name sys.exit(0) SetupLogging(options) pid_store = PidStore.GetStore(options.pid_store, ('pids.proto',)) wrapper = ClientWrapper() global uid_ok uid_ok = False def UIDList(state, uids): wrapper.Stop() global uid_ok if not state.Succeeded(): logging.error('Fetch failed: %s' % state.message) return for uid in uids: if uid == options.uid: logging.debug('Found UID %s' % options.uid) uid_ok = True if not uid_ok: logging.error('UID %s not found in universe %d' % (options.uid, options.universe)) return if len(uids) > 1: logging.info( 'The following devices were detected and will be reconfigured') for uid in uids: logging.info(' %s' % uid) if not options.skip_check: logging.info('Continue ? [Y/n]') response = raw_input().strip().lower() uid_ok = response == 'y' or response == '' logging.debug('Fetching UID list from server') wrapper.Client().FetchUIDList(options.universe, UIDList) wrapper.Run() wrapper.Reset() if not uid_ok: sys.exit() test_filter = None if options.tests is not None: logging.info('Restricting tests to %s' % options.tests) test_filter = set(options.tests.split(',')) logging.info( 'Starting tests, universe %d, UID %s, broadcast write delay %dms' % (options.universe, options.uid, options.broadcast_write_delay)) runner = TestRunner.TestRunner(options.universe, options.uid, options.broadcast_write_delay, pid_store, wrapper, options.timestamp) for test_class in test_classes: runner.RegisterTest(test_class) dmx_sender = DMXSender(wrapper, options.universe, options.dmx_frame_rate, options.slot_count) tests, device = runner.RunTests(test_filter, options.no_factory_defaults) DisplaySummary(tests) if __name__ == '__main__': main()
lgpl-2.1
mbert/mulberry-lib-jx
ACE/ACE_wrappers/ace/Select_Reactor_Base.h
18900
/* -*- C++ -*- */ //============================================================================= /** * @file Select_Reactor_Base.h * * Select_Reactor_Base.h,v 4.42 2005/05/01 08:16:08 ossama Exp * * @author Douglas C. Schmidt <schmidt@cs.wustl.edu> */ //============================================================================= #ifndef ACE_SELECT_REACTOR_BASE_H #define ACE_SELECT_REACTOR_BASE_H #include /**/ "ace/pre.h" #include "ace/Timer_Queuefwd.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ #include "ace/Event_Handler.h" #include "ace/Handle_Set.h" #include "ace/Token.h" #include "ace/Pipe.h" #include "ace/Reactor_Impl.h" #if defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) #include "ace/Unbounded_Queue.h" #endif /* ACE_HAS_REACTOR_NOTIFICATION_QUEUE */ // Add useful typedefs to simplify the following code. typedef void (ACE_Handle_Set::*ACE_FDS_PTMF) (ACE_HANDLE); typedef int (ACE_Event_Handler::*ACE_EH_PTMF) (ACE_HANDLE); #if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) typedef ACE_Token ACE_SELECT_TOKEN; #else typedef ACE_Noop_Token ACE_SELECT_TOKEN; #endif /* ACE_MT_SAFE && ACE_MT_SAFE != 0 */ // Forward declaration. class ACE_Select_Reactor_Impl; /** * @class ACE_Select_Reactor_Handle_Set * * @brief Track handles we are interested for various events. */ class ACE_Export ACE_Select_Reactor_Handle_Set { public: /// Read events (e.g., input pending, accept pending). ACE_Handle_Set rd_mask_; /// Write events (e.g., flow control abated, non-blocking connection /// complete). ACE_Handle_Set wr_mask_; /// Exception events (e.g., SIG_URG). ACE_Handle_Set ex_mask_; }; /** * @class ACE_Event_Tuple * * @brief An ACE_Event_Handler and its associated ACE_HANDLE. * * One <ACE_Event_Handler> is registered for one or more * <ACE_HANDLE>. At various points, this information must be * stored explicitly. This class provides a lightweight * mechanism to do so. */ class ACE_Export ACE_Event_Tuple { public: /// Default constructor. ACE_Event_Tuple (void); /// Constructor. ACE_Event_Tuple (ACE_Event_Handler *eh, ACE_HANDLE h); /// Destructor. ~ACE_Event_Tuple (void); /// Equality operator. bool operator== (const ACE_Event_Tuple &rhs) const; /// Inequality operator. bool operator!= (const ACE_Event_Tuple &rhs) const; /// Handle. ACE_HANDLE handle_; /// <ACE_Event_Handler> associated with the <ACE_HANDLE>. ACE_Event_Handler *event_handler_; }; /** * @class ACE_Select_Reactor_Notify * * @brief Unblock the ACE_Select_Reactor from its event loop. * * This implementation is necessary for cases where the * ACE_Select_Reactor is run in a multi-threaded program. In * this case, we need to be able to unblock @c select or @c poll * when updates occur other than in the main * ACE_Select_Reactor thread. To do this, we signal an * auto-reset event the ACE_Select_Reactor is listening on. * If an ACE_Event_Handler and ACE_Select_Reactor_Mask is * passed to @c notify, the appropriate @c handle_* method is * dispatched in the context of the ACE_Select_Reactor thread. */ class ACE_Export ACE_Select_Reactor_Notify : public ACE_Reactor_Notify { public: /// Constructor. ACE_Select_Reactor_Notify (void); /// Destructor. virtual ~ACE_Select_Reactor_Notify (void); // = Initialization and termination methods. /// Initialize. virtual int open (ACE_Reactor_Impl *, ACE_Timer_Queue * = 0, int disable_notify_pipe = 0); /// Destroy. virtual int close (void); /** * Called by a thread when it wants to unblock the * ACE_Select_Reactor. This wakeups the ACE_Select_Reactor if * currently blocked in @c select/poll. Pass over both the * @c Event_Handler *and* the @c mask to allow the caller to dictate * which @c Event_Handler method the ACE_Select_Reactor will * invoke. The ACE_Time_Value indicates how long to blocking * trying to notify the ACE_Select_Reactor. If @a timeout == 0, * the caller will block until action is possible, else will wait * until the relative time specified in @c *timeout elapses). */ virtual int notify (ACE_Event_Handler * = 0, ACE_Reactor_Mask = ACE_Event_Handler::EXCEPT_MASK, ACE_Time_Value * timeout = 0); /// Handles pending threads (if any) that are waiting to unblock the /// ACE_Select_Reactor. virtual int dispatch_notifications (int &number_of_active_handles, ACE_Handle_Set &rd_mask); /// Returns the ACE_HANDLE of the notify pipe on which the reactor /// is listening for notifications so that other threads can unblock /// the Select_Reactor virtual ACE_HANDLE notify_handle (void); /// Handle one of the notify call on the @c handle. This could be /// because of a thread trying to unblock the <Reactor_Impl> virtual int dispatch_notify (ACE_Notification_Buffer &buffer); /// Read one of the notify call on the <handle> into the /// <buffer>. This could be because of a thread trying to unblock /// the <Reactor_Impl> virtual int read_notify_pipe (ACE_HANDLE handle, ACE_Notification_Buffer &buffer); /// Verify whether the buffer has dispatchable info or not. virtual int is_dispatchable (ACE_Notification_Buffer &buffer); /// Called back by the <ACE_Select_Reactor> when a thread wants to /// unblock us. virtual int handle_input (ACE_HANDLE handle); /** * Set the maximum number of times that the * <ACE_Select_Reactor_Notify::handle_input> method will iterate and * dispatch the <ACE_Event_Handlers> that are passed in via the * notify pipe before breaking out of its <recv> loop. By default, * this is set to -1, which means "iterate until the pipe is empty." * Setting this to a value like "1 or 2" will increase "fairness" * (and thus prevent starvation) at the expense of slightly higher * dispatching overhead. */ virtual void max_notify_iterations (int); /** * Get the maximum number of times that the * <ACE_Select_Reactor_Notify::handle_input> method will iterate and * dispatch the <ACE_Event_Handlers> that are passed in via the * notify pipe before breaking out of its <recv> loop. */ virtual int max_notify_iterations (void); /** * Purge any notifications pending in this reactor for the specified * <ACE_Event_Handler> object. If <eh> == 0, all notifications for all * handlers are removed (but not any notifications posted just to wake up * the reactor itself). Returns the number of notifications purged. * Returns -1 on error. */ virtual int purge_pending_notifications ( ACE_Event_Handler *, ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); /// Dump the state of an object. virtual void dump (void) const; /// Declare the dynamic allocation hooks. ACE_ALLOC_HOOK_DECLARE; protected: /** * Keep a back pointer to the <ACE_Select_Reactor>. If this value * if NULL then the <ACE_Select_Reactor> has been initialized with * <disable_notify_pipe>. */ ACE_Select_Reactor_Impl *select_reactor_; /** * Contains the <ACE_HANDLE> the <ACE_Select_Reactor> is listening * on, as well as the <ACE_HANDLE> that threads wanting the * attention of the <ACE_Select_Reactor> will write to. */ ACE_Pipe notification_pipe_; /** * Keeps track of the maximum number of times that the * <ACE_Select_Reactor_Notify::handle_input> method will iterate and * dispatch the <ACE_Event_Handlers> that are passed in via the * notify pipe before breaking out of its <recv> loop. By default, * this is set to -1, which means "iterate until the pipe is empty." */ int max_notify_iterations_; #if defined (ACE_HAS_REACTOR_NOTIFICATION_QUEUE) // = This configuration queues up notifications in separate buffers that // are in user-space, rather than stored in a pipe in the OS // kernel. The kernel-level notifications are used only to trigger // the Reactor to check its notification queue. This enables many // more notifications to be stored than would otherwise be the case. /// Keeps track of allocated arrays of type /// <ACE_Notification_Buffer>. ACE_Unbounded_Queue <ACE_Notification_Buffer *> alloc_queue_; /// Keeps track of all pending notifications. ACE_Unbounded_Queue <ACE_Notification_Buffer *> notify_queue_; /// Keeps track of all free buffers. ACE_Unbounded_Queue <ACE_Notification_Buffer *> free_queue_; /// Synchronization for handling of queues. ACE_SYNCH_MUTEX notify_queue_lock_; #endif /* ACE_HAS_REACTOR_NOTIFICATION_QUEUE */ }; /** * @class ACE_Select_Reactor_Handler_Repository * * @brief Used to map <ACE_HANDLE>s onto the appropriate * <ACE_Event_Handler> *. * * This class is necessary to shield differences between UNIX * and Win32. In UNIX, <ACE_HANDLE> is an int, whereas in Win32 * it's a void *. This class hides all these details from the * bulk of the <ACE_Select_Reactor> code. All of these methods * are called with the main <Select_Reactor> token lock held. */ class ACE_Export ACE_Select_Reactor_Handler_Repository { public: friend class ACE_Select_Reactor_Handler_Repository_Iterator; // = Initialization and termination methods. /// Default "do-nothing" constructor. ACE_Select_Reactor_Handler_Repository (ACE_Select_Reactor_Impl &); /// Destructor. ~ACE_Select_Reactor_Handler_Repository (void); /// Initialize a repository of the appropriate <size>. /** * On Unix platforms, the size parameter should be as large as the * maximum number of file descriptors allowed for a given process. * This is necessary since a file descriptor is used to directly * index the array of event handlers maintained by the Reactor's * handler repository. Direct indexing is used for efficiency * reasons. */ int open (size_t size); /// Close down the repository. int close (void); // = Search structure operations. /** * Return the <ACE_Event_Handler *> associated with <ACE_HANDLE>. * If <index_p> is non-0, then return the index location of the * <handle>, if found. */ ACE_Event_Handler *find (ACE_HANDLE handle, size_t *index_p = 0); /// Bind the <ACE_Event_Handler *> to the <ACE_HANDLE> with the /// appropriate <ACE_Reactor_Mask> settings. int bind (ACE_HANDLE, ACE_Event_Handler *, ACE_Reactor_Mask); /// Remove the binding of <ACE_HANDLE> in accordance with the <mask>. int unbind (ACE_HANDLE, ACE_Reactor_Mask mask); /// Remove all the <ACE_HANDLE, ACE_Event_Handler> tuples. int unbind_all (void); // = Sanity checking. // Check the <handle> to make sure it's a valid ACE_HANDLE that // within the range of legal handles (i.e., >= 0 && < max_size_). int invalid_handle (ACE_HANDLE handle); // Check the <handle> to make sure it's a valid ACE_HANDLE that // within the range of currently registered handles (i.e., >= 0 && < // max_handlep1_). int handle_in_range (ACE_HANDLE handle); // = Accessors. /// Returns the current table size. size_t size (void) const; /// Maximum ACE_HANDLE value, plus 1. size_t max_handlep1 (void); /// Dump the state of an object. void dump (void) const; /// Declare the dynamic allocation hooks. ACE_ALLOC_HOOK_DECLARE; private: /// Reference to our <Select_Reactor>. ACE_Select_Reactor_Impl &select_reactor_; /// Maximum number of handles. ssize_t max_size_; /// The highest currently active handle, plus 1 (ranges between 0 and /// <max_size_>. int max_handlep1_; #if defined (ACE_WIN32) // = The mapping from <HANDLES> to <Event_Handlers>. /** * The NT version implements this via a dynamically allocated * array of <ACE_Event_Tuple *>. Since NT implements ACE_HANDLE * as a void * we can't directly index into this array. Therefore, * we just do a linear search (for now). Next, we'll modify * things to use hashing or something faster... */ ACE_Event_Tuple *event_handlers_; #else /** * The UNIX version implements this via a dynamically allocated * array of <ACE_Event_Handler *> that is indexed directly using * the ACE_HANDLE value. */ ACE_Event_Handler **event_handlers_; #endif /* ACE_WIN32 */ }; /** * @class ACE_Select_Reactor_Handler_Repository_Iterator * * @brief Iterate through the <ACE_Select_Reactor_Handler_Repository>. */ class ACE_Export ACE_Select_Reactor_Handler_Repository_Iterator { public: // = Initialization method. ACE_Select_Reactor_Handler_Repository_Iterator (const ACE_Select_Reactor_Handler_Repository *s); /// dtor. ~ACE_Select_Reactor_Handler_Repository_Iterator (void); // = Iteration methods. /// Pass back the <next_item> that hasn't been seen in the Set. /// Returns 0 when all items have been seen, else 1. int next (ACE_Event_Handler *&next_item); /// Returns 1 when all items have been seen, else 0. int done (void) const; /// Move forward by one element in the set. Returns 0 when all the /// items in the set have been seen, else 1. int advance (void); /// Dump the state of an object. void dump (void) const; /// Declare the dynamic allocation hooks. ACE_ALLOC_HOOK_DECLARE; private: /// Reference to the Handler_Repository we are iterating over. const ACE_Select_Reactor_Handler_Repository *rep_; /// Pointer to the current iteration level. ssize_t current_; }; /** * @class ACE_Select_Reactor_Impl * * @brief This class simply defines how Select_Reactor's basic interface * functions should look like and provides a common base class for * <Select_Reactor> using various locking mechanism. */ class ACE_Export ACE_Select_Reactor_Impl : public ACE_Reactor_Impl { public: enum { /// Default size of the Select_Reactor's handle table. DEFAULT_SIZE = ACE_DEFAULT_SELECT_REACTOR_SIZE }; /// Constructor. ACE_Select_Reactor_Impl (bool mask_signals = true); friend class ACE_Select_Reactor_Notify; friend class ACE_Select_Reactor_Handler_Repository; /** * Purge any notifications pending in this reactor for the specified * <ACE_Event_Handler> object. Returns the number of notifications * purged. Returns -1 on error. */ virtual int purge_pending_notifications (ACE_Event_Handler * = 0, ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); /// Does the reactor allow the application to resume the handle on /// its own ie. can it pass on the control of handle resumption to /// the application. The select reactor has no handlers that can be /// resumed by the application. So return 0; virtual int resumable_handler (void); protected: /// Allow manipulation of the <wait_set_> mask and <ready_set_> mask. virtual int bit_ops (ACE_HANDLE handle, ACE_Reactor_Mask mask, ACE_Select_Reactor_Handle_Set &wait_Set, int ops); /// Enqueue ourselves into the list of waiting threads at the /// appropriate point specified by <requeue_position_>. virtual void renew (void) = 0; /// Check to see if the <Event_Handler> associated with <handle> is /// suspended. Returns 0 if not, 1 if so. virtual int is_suspended_i (ACE_HANDLE handle) = 0; /// When register/unregister occur, then we need to re-eval our /// wait/suspend/dispatch set. virtual void clear_dispatch_mask (ACE_HANDLE handle, ACE_Reactor_Mask mask); /// Table that maps <ACE_HANDLEs> to <ACE_Event_Handler *>'s. ACE_Select_Reactor_Handler_Repository handler_rep_; /// Tracks handles that are ready for dispatch from <select> ACE_Select_Reactor_Handle_Set dispatch_set_; /// Tracks handles that are waited for by <select>. ACE_Select_Reactor_Handle_Set wait_set_; /// Tracks handles that are currently suspended. ACE_Select_Reactor_Handle_Set suspend_set_; /// Track HANDLES we are interested in for various events that must /// be dispatched *without* going through <select>. ACE_Select_Reactor_Handle_Set ready_set_; /// Defined as a pointer to allow overriding by derived classes... ACE_Timer_Queue *timer_queue_; /// Keeps track of whether we should delete the timer queue (if we /// didn't create it, then we don't delete it). int delete_timer_queue_; /// Handle signals without requiring global/static variables. ACE_Sig_Handler *signal_handler_; /// Keeps track of whether we should delete the signal handler (if we /// didn't create it, then we don't delete it). int delete_signal_handler_; /// Callback object that unblocks the <ACE_Select_Reactor> if it's /// sleeping. ACE_Reactor_Notify *notify_handler_; /// Keeps track of whether we need to delete the notify handler (if /// we didn't create it, then we don't delete it). int delete_notify_handler_; /// Restart the <handle_events> event-loop method automatically when /// <select> is interrupted via <EINTR>. int restart_; /** * Position that the main ACE_Select_Reactor thread is requeued in * the list of waiters during a <notify> callback. If this value == * -1 we are requeued at the end of the list. Else if it's 0 then * we are requeued at the front of the list. Else if it's > 1 then * that indicates the number of waiters to skip over. */ int requeue_position_; /// True if we've been initialized yet... int initialized_; /// The original thread that created this Select_Reactor. ACE_thread_t owner_; /** * True if state has changed during dispatching of * <ACE_Event_Handlers>, else false. This is used to determine * whether we need to make another trip through the * <Select_Reactor>'s <wait_for_multiple_events> loop. */ bool state_changed_; /** * If 0 then the Reactor will not mask the signals during the event * dispatching. This is useful for applications that do not * register any signal handlers and want to reduce the overhead * introduce by the kernel level locks required to change the mask. */ bool mask_signals_; /// Controls/access whether the notify handler should renew the /// Select_Reactor's token or not. int supress_notify_renew (void); void supress_notify_renew (int sr); private: /// Determine whether we should renew Select_Reactor's token after handling /// the notification message. int supress_renew_; /// Deny access since member-wise won't work... ACE_Select_Reactor_Impl (const ACE_Select_Reactor_Impl &); ACE_Select_Reactor_Impl &operator = (const ACE_Select_Reactor_Impl &); }; #if defined (__ACE_INLINE__) #include "ace/Select_Reactor_Base.inl" #endif /* __ACE_INLINE__ */ #include /**/ "ace/post.h" #endif /* ACE_SELECT_REACTOR_BASE_H */
lgpl-2.1
fjalvingh/domui
to.etc.domui/src/main/java/to/etc/domui/component/binding/IBindingListener.java
1628
/* * DomUI Java User Interface library * Copyright (c) 2010 by Frits Jalvingh, Itris B.V. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * See the "sponsors" file for a list of supporters. * * The latest version of DomUI and related code, support and documentation * can be found at http://www.domui.org/ * The contact for the project is Frits Jalvingh <jal@etc.to>. */ package to.etc.domui.component.binding; import org.eclipse.jdt.annotation.NonNull; import to.etc.domui.dom.html.NodeBase; /** * EXPERIMENTAL - DO NOT USE. * This defines a control binding event interface which gets called when the control's * movement calls are used. * * @author <a href="mailto:jal@etc.to">Frits Jalvingh</a> * Created on Oct 13, 2009 */ public interface IBindingListener<T extends NodeBase> { void moveControlToModel(@NonNull T control) throws Exception; void moveModelToControl(@NonNull T control) throws Exception; }
lgpl-2.1
cacheonix/cacheonix-core
src/org/cacheonix/impl/config/CoherenceConfiguration.java
2778
/* * Cacheonix Systems licenses this file to You under the LGPL 2.1 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.cacheonix.org/products/cacheonix/license-lgpl-2.1.htm * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cacheonix.impl.config; import org.w3c.dom.Attr; import org.w3c.dom.Node; /** * Class CoherenceConfiguration. */ public final class CoherenceConfiguration extends DocumentReader { /** * A parent. */ private PartitionedCacheStoreConfiguration partitionedCacheStoreConfiguration = null; /** * Field lease. */ private LeaseConfiguration lease = null; /** * Sets the parent. * * @param configuration the parent. */ public void setPartitionedCacheStoreConfiguration(final PartitionedCacheStoreConfiguration configuration) { this.partitionedCacheStoreConfiguration = configuration; } /** * Returns the parent. * * @return the parent. */ public PartitionedCacheStoreConfiguration getPartitionedCacheStoreConfiguration() { return partitionedCacheStoreConfiguration; } /** * Returns the value of field 'lease'. * * @return the value of field 'Lease'. */ public LeaseConfiguration getLease() { return this.lease; } /** * Sets the value of field 'lease'. * * @param lease the value of field 'lease'. */ public void setLease(final LeaseConfiguration lease) { this.lease = lease; } public void setUpDefaults() { // Create lease configuration setUpDefaultLease(); } private void setUpDefaultLease() { lease = new LeaseConfiguration(); lease.setCoherenceConfiguration(this); lease.setUpDefaults(); } protected void readNode(final String nodeName, final Node node) { if ("lease".equals(nodeName)) { lease = new LeaseConfiguration(); lease.setCoherenceConfiguration(this); lease.read(node); } } protected void readAttribute(final String attributeName, final Attr attributeNode, final String attributeValue) { // This element doesn't have attributes yet } protected void postProcessRead() { if (lease == null) { setUpDefaultLease(); } } public String toString() { return "CoherenceConfiguration{" + "lease=" + lease + '}'; } }
lgpl-2.1
sunblithe/qt-everywhere-opensource-src-4.7.1
doc/html/qfileiconprovider-members.html
9388
<?xml version="1.0" encoding="UTF-8"?> <!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_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- qfileiconprovider.cpp --> <title>Qt 4.7: List of All Members for QFileIconProvider</title> <link rel="stylesheet" type="text/css" href="style/style.css" /> <script src="scripts/jquery.js" type="text/javascript"></script> <script src="scripts/functions.js" type="text/javascript"></script> </head> <body class="offline narrow creator"> <div class="header" id="qtdocheader"> <div class="content"> <div id="nav-logo"> <a href="index.html">Home</a></div> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> <div id="nav-topright"> <ul> <li class="nav-topright-home"><a href="http://qt.nokia.com/">Qt HOME</a></li> <li class="nav-topright-dev"><a href="http://developer.qt.nokia.com/">DEV</a></li> <li class="nav-topright-labs"><a href="http://labs.qt.nokia.com/blogs/">LABS</a></li> <li class="nav-topright-doc nav-topright-doc-active"><a href="http://doc.qt.nokia.com/"> DOC</a></li> <li class="nav-topright-blog"><a href="http://blog.qt.nokia.com/">BLOG</a></li> </ul> </div> <div id="shortCut"> <ul> <li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.7</a></span></li> <li class="shortCut-topleft-active"><a href="http://doc.qt.nokia.com">ALL VERSIONS </a></li> </ul> </div> <ul class="sf-menu sf-js-enabled sf-shadow" id="narrowmenu"> <li><a href="#">API Lookup</a> <ul id="topmenuLook"> <li><a href="classes.html">Class index</a></li> <li><a href="functions.html">Function index</a></li> <li><a href="modules.html">Modules</a></li> <li><a href="namespaces.html">Namespaces</a></li> <li><a href="qtglobal.html">Global Declarations</a></li> <li><a href="licensing.html">Licenses and Credits</a></li> </ul> </li> <li><a href="#">Qt Topics</a> <ul id="topmenuTopic"> <li><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li><a href="qtquick.html">Device UI's &amp; Qt Quick</a></li> <li><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li><a href="developing-with-qt.html">Cross-platform and Platform-specific</a></li> <li><a href="platform-specific.html">Platform-specific info</a></li> <li><a href="technology-apis.html">Qt and Key Technologies</a></li> <li><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </li> <li><a href="#">Examples</a> <ul id="topmenuexample"> <li><a href="all-examples.html">Examples</a></li> <li><a href="tutorials.html">Tutorials</a></li> <li><a href="demos.html">Demos</a></li> <li><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </li> </ul> </div> </div> <div class="wrapper"> <div class="hd"> <span></span> </div> <div class="bd group"> <div class="sidebar"> <div class="searchlabel"> Search index:</div> <div class="search"> <form id="qtdocsearch" action="" onsubmit="return false;"> <fieldset> <input type="text" name="searchstring" id="pageType" value="" /> </fieldset> </form> </div> <div class="box first bottombar" id="lookup"> <h2 title="API Lookup"><span></span> API Lookup</h2> <div id="list001" class="list"> <ul id="ul001" > <li class="defaultLink"><a href="classes.html">Class index</a></li> <li class="defaultLink"><a href="functions.html">Function index</a></li> <li class="defaultLink"><a href="modules.html">Modules</a></li> <li class="defaultLink"><a href="namespaces.html">Namespaces</a></li> <li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li> <li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </div> </div> <div class="box bottombar" id="topics"> <h2 title="Qt Topics"><span></span> Qt Topics</h2> <div id="list002" class="list"> <ul id="ul002" > <li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li class="defaultLink"><a href="qtquick.html">Device UI's &amp; Qt Quick</a></li> <li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li class="defaultLink"><a href="developing-with-qt.html">Cross-platform and Platform-specific</a></li> <li class="defaultLink"><a href="platform-specific.html">Platform-specific info</a></li> <li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li> <li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </div> </div> <div class="box" id="examples"> <h2 title="Examples"><span></span> Examples</h2> <div id="list003" class="list"> <ul id="ul003"> <li class="defaultLink"><a href="all-examples.html">Examples</a></li> <li class="defaultLink"><a href="tutorials.html">Tutorials</a></li> <li class="defaultLink"><a href="demos.html">Demos</a></li> <li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </div> </div> </div> <div class="wrap"> <div class="toolbar"> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Bread crumbs goes here --> <li><a href="modules.html">Modules</a></li> <li><a href="qtgui.html">QtGui</a></li> <li>QFileIconProvider</li> </ul> </div> <div class="toolbuttons toolblock"> <ul> <li id="smallA" class="t_button">A</li> <li id="medA" class="t_button active">A</li> <li id="bigA" class="t_button">A</li> <li id="print" class="t_button"><a href="javascript:this.print();"> <span>Print</span></a></li> </ul> </div> </div> <div class="content"> <h1 class="title">List of All Members for QFileIconProvider</h1> <p>This is the complete list of members for <a href="qfileiconprovider.html">QFileIconProvider</a>, including inherited members.</p> <ul> <li class="fn">enum <b><a href="qfileiconprovider.html#IconType-enum">IconType</a></b></li> <li class="fn"><b><a href="qfileiconprovider.html#QFileIconProvider">QFileIconProvider</a></b> ()</li> <li class="fn"><b><a href="qfileiconprovider.html#dtor.QFileIconProvider">~QFileIconProvider</a></b> ()</li> <li class="fn"><b><a href="qfileiconprovider.html#icon">icon</a></b> ( IconType ) const : QIcon</li> <li class="fn"><b><a href="qfileiconprovider.html#icon-2">icon</a></b> ( const QFileInfo &amp; ) const : QIcon</li> <li class="fn"><b><a href="qfileiconprovider.html#type">type</a></b> ( const QFileInfo &amp; ) const : QString</li> </ul> <div class="feedback t_button"> [+] Documentation Feedback</div> </div> </div> </div> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2008-2010 Nokia Corporation and/or its subsidiaries. Nokia, Qt and their respective logos are trademarks of Nokia Corporation in Finland and/or other countries worldwide.</p> <p> All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://qt.nokia.com/about/privacy-policy">Privacy Policy</a></p> <br /> <p> Licensees holding valid Qt Commercial licenses may use this document in accordance with the Qt Commercial License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Nokia.</p> <p> Alternatively, this document may be used under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> </div> <div id="feedbackBox"> <div id="feedcloseX" class="feedclose t_button">X</div> <form id="feedform" action="http://doc.qt.nokia.com/docFeedbck/feedback.php" method="get"> <p id="noteHead">Thank you for giving your feedback.</p> <p class="note">Make sure it is related to this specific page. For more general bugs and requests, please use the <a href="http://bugreports.qt.nokia.com/secure/Dashboard.jspa">Qt Bug Tracker</a>.</p> <p><textarea id="feedbox" name="feedText" rows="5" cols="40"></textarea></p> <p><input id="feedsubmit" class="feedclose" type="submit" name="feedback" /></p> </form> </div> <div id="blurpage"> </div> </body> </html>
lgpl-2.1
mbatchelor/pentaho-reporting
engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/layout/process/util/MinorAxisParagraphBreakState.java
3462
/* * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2001 - 2013 Object Refinery Ltd, Hitachi Vantara and Contributors.. All rights reserved. */ package org.pentaho.reporting.engine.classic.core.layout.process.util; import org.pentaho.reporting.engine.classic.core.layout.model.ParagraphRenderBox; import org.pentaho.reporting.engine.classic.core.layout.model.RenderNode; import org.pentaho.reporting.engine.classic.core.layout.process.layoutrules.DefaultSequenceList; import org.pentaho.reporting.engine.classic.core.layout.process.layoutrules.InlineNodeSequenceElement; import org.pentaho.reporting.engine.classic.core.layout.process.layoutrules.InlineSequenceElement; import org.pentaho.reporting.engine.classic.core.layout.process.layoutrules.ReplacedContentSequenceElement; import org.pentaho.reporting.engine.classic.core.layout.process.layoutrules.SequenceList; import org.pentaho.reporting.engine.classic.core.layout.process.layoutrules.TextSequenceElement; import org.pentaho.reporting.engine.classic.core.util.InstanceID; public final class MinorAxisParagraphBreakState { private InstanceID suspendItem; private SequenceList elementSequence; private ParagraphRenderBox paragraph; private boolean containsContent; public MinorAxisParagraphBreakState() { this.elementSequence = new DefaultSequenceList(); } public void init( final ParagraphRenderBox paragraph ) { if ( paragraph == null ) { throw new NullPointerException(); } this.paragraph = paragraph; this.elementSequence.clear(); this.suspendItem = null; this.containsContent = false; } public void deinit() { this.paragraph = null; this.elementSequence.clear(); this.suspendItem = null; this.containsContent = false; } public boolean isInsideParagraph() { return paragraph != null; } public ParagraphRenderBox getParagraph() { return paragraph; } /* * public InstanceID getSuspendItem() { return suspendItem; } * * public void setSuspendItem(final InstanceID suspendItem) { this.suspendItem = suspendItem; } */ public void add( final InlineSequenceElement element, final RenderNode node ) { elementSequence.add( element, node ); if ( element instanceof TextSequenceElement || element instanceof InlineNodeSequenceElement || element instanceof ReplacedContentSequenceElement ) { containsContent = true; } } public boolean isContainsContent() { return containsContent; } public boolean isSuspended() { return suspendItem != null; } public SequenceList getSequence() { return elementSequence; } public void clear() { elementSequence.clear(); suspendItem = null; containsContent = false; } }
lgpl-2.1
toddtreece/esp8266-Arduino
package/libraries/SPI/SPI.cpp
1984
/* SPI.cpp - SPI library for esp8266 Copyright (c) 2015 Hristo Gochkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "SPI.h" SPIClass SPI; SPIClass::SPIClass(){} void SPIClass::begin(){ pinMode(SCK, SPECIAL); pinMode(MISO, SPECIAL); pinMode(MOSI, SPECIAL); GPMUX = 0x105; SPI1C = 0; SPI1CLK = SPI_CLOCK_DIV16;//1MHz SPI1U = SPIUMOSI | SPIUDUPLEX | SPIUSSE; SPI1U1 = (7 << SPILMOSI) | (7 << SPILMISO); SPI1C1 = 0; } void SPIClass::end() { pinMode(SCK, INPUT); pinMode(MISO, INPUT); pinMode(MOSI, INPUT); } void SPIClass::beginTransaction(SPISettings settings) { setClockDivider(settings._clock); setBitOrder(settings._bitOrder); setDataMode(settings._dataMode); } void SPIClass::endTransaction() {} void SPIClass::setDataMode(uint8_t dataMode) { } void SPIClass::setBitOrder(uint8_t bitOrder) { if (bitOrder == MSBFIRST){ SPI1C &= ~(SPICWBO | SPICRBO); } else { SPI1C |= (SPICWBO | SPICRBO); } } void SPIClass::setClockDivider(uint32_t clockDiv) { SPI1CLK = clockDiv; } uint8_t SPIClass::transfer(uint8_t data) { while(SPI1CMD & SPIBUSY); SPI1W0 = data; SPI1CMD |= SPIBUSY; while(SPI1CMD & SPIBUSY); return (uint8_t)(SPI1W0 & 0xff); }
lgpl-2.1
youfoh/webkit-efl
Source/WebKit/chromium/tests/WebLayerTest.cpp
8366
/* * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "platform/WebLayer.h" #include "CompositorFakeWebGraphicsContext3D.h" #include "WebCompositor.h" #include "platform/WebContentLayer.h" #include "platform/WebContentLayerClient.h" #include "platform/WebExternalTextureLayer.h" #include "platform/WebFloatPoint.h" #include "platform/WebFloatRect.h" #include "platform/WebLayerTreeView.h" #include "platform/WebLayerTreeViewClient.h" #include "platform/WebRect.h" #include "platform/WebSize.h" #include <gmock/gmock.h> using namespace WebKit; using testing::AnyNumber; using testing::AtLeast; using testing::Mock; using testing::Test; using testing::_; namespace { class MockWebLayerTreeViewClient : public WebLayerTreeViewClient { public: MOCK_METHOD0(scheduleComposite, void()); virtual void updateAnimations(double frameBeginTime) { } virtual void didBeginFrame() { } virtual void layout() { } virtual void applyScrollAndScale(const WebSize& scrollDelta, float scaleFactor) { } virtual WebGraphicsContext3D* createContext3D() { return CompositorFakeWebGraphicsContext3D::create(WebGraphicsContext3D::Attributes()).leakPtr(); } virtual void didRebindGraphicsContext(bool success) { } virtual void willCommit() { } virtual void didCommitAndDrawFrame() { } virtual void didCompleteSwapBuffers() { } }; class MockWebContentLayerClient : public WebContentLayerClient { public: MOCK_METHOD3(paintContents, void(WebCanvas*, const WebRect& clip, WebFloatRect& opaque)); }; class WebLayerTest : public Test { public: virtual void SetUp() { // Initialize without threading support. WebKit::WebCompositor::initialize(0); m_rootLayer = WebLayer::create(); EXPECT_CALL(m_client, scheduleComposite()).Times(AnyNumber()); EXPECT_TRUE(m_view.initialize(&m_client, m_rootLayer, WebLayerTreeView::Settings())); Mock::VerifyAndClearExpectations(&m_client); } virtual void TearDown() { // We may get any number of scheduleComposite calls during shutdown. EXPECT_CALL(m_client, scheduleComposite()).Times(AnyNumber()); m_view.setRootLayer(0); m_rootLayer.reset(); m_view.reset(); WebKit::WebCompositor::shutdown(); } protected: MockWebLayerTreeViewClient m_client; WebLayer m_rootLayer; WebLayerTreeView m_view; }; // Tests that the client gets called to ask for a composite if we change the // fields. TEST_F(WebLayerTest, Client) { // Base layer. EXPECT_CALL(m_client, scheduleComposite()).Times(AnyNumber()); WebLayer layer = WebLayer::create(); m_rootLayer.addChild(layer); Mock::VerifyAndClearExpectations(&m_client); WebFloatPoint point(3, 4); EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1)); layer.setAnchorPoint(point); Mock::VerifyAndClearExpectations(&m_client); EXPECT_EQ(point, layer.anchorPoint()); EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1)); float anchorZ = 5; layer.setAnchorPointZ(anchorZ); Mock::VerifyAndClearExpectations(&m_client); EXPECT_EQ(anchorZ, layer.anchorPointZ()); WebSize size(7, 8); EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1)); layer.setBounds(size); Mock::VerifyAndClearExpectations(&m_client); EXPECT_EQ(size, layer.bounds()); EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1)); layer.setMasksToBounds(true); Mock::VerifyAndClearExpectations(&m_client); EXPECT_TRUE(layer.masksToBounds()); EXPECT_CALL(m_client, scheduleComposite()).Times(AnyNumber()); WebLayer otherLayer = WebLayer::create(); m_rootLayer.addChild(otherLayer); EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1)); layer.setMaskLayer(otherLayer); Mock::VerifyAndClearExpectations(&m_client); EXPECT_EQ(otherLayer, layer.maskLayer()); EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1)); float opacity = 0.123f; layer.setOpacity(opacity); Mock::VerifyAndClearExpectations(&m_client); EXPECT_EQ(opacity, layer.opacity()); EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1)); layer.setOpaque(true); Mock::VerifyAndClearExpectations(&m_client); EXPECT_TRUE(layer.opaque()); EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1)); layer.setPosition(point); Mock::VerifyAndClearExpectations(&m_client); EXPECT_EQ(point, layer.position()); // Texture layer. EXPECT_CALL(m_client, scheduleComposite()).Times(AnyNumber()); WebExternalTextureLayer textureLayer = WebExternalTextureLayer::create(); m_rootLayer.addChild(textureLayer); Mock::VerifyAndClearExpectations(&m_client); EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1)); textureLayer.setTextureId(3); Mock::VerifyAndClearExpectations(&m_client); EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1)); textureLayer.setFlipped(true); Mock::VerifyAndClearExpectations(&m_client); EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1)); WebFloatRect uvRect(0.1f, 0.1f, 0.9f, 0.9f); textureLayer.setUVRect(uvRect); Mock::VerifyAndClearExpectations(&m_client); // Content layer. MockWebContentLayerClient contentClient; EXPECT_CALL(contentClient, paintContents(_, _, _)).Times(AnyNumber()); EXPECT_CALL(m_client, scheduleComposite()).Times(AnyNumber()); WebContentLayer contentLayer = WebContentLayer::create(&contentClient); m_rootLayer.addChild(contentLayer); Mock::VerifyAndClearExpectations(&m_client); EXPECT_CALL(m_client, scheduleComposite()).Times(AtLeast(1)); contentLayer.setDrawsContent(false); Mock::VerifyAndClearExpectations(&m_client); EXPECT_FALSE(contentLayer.drawsContent()); } TEST_F(WebLayerTest, Hierarchy) { EXPECT_CALL(m_client, scheduleComposite()).Times(AnyNumber()); WebLayer layer1 = WebLayer::create(); WebLayer layer2 = WebLayer::create(); EXPECT_TRUE(layer1.parent().isNull()); EXPECT_TRUE(layer2.parent().isNull()); layer1.addChild(layer2); EXPECT_TRUE(layer1.parent().isNull()); EXPECT_EQ(layer1, layer2.parent()); layer2.removeFromParent(); EXPECT_TRUE(layer2.parent().isNull()); layer1.addChild(layer2); EXPECT_EQ(layer1, layer2.parent()); layer1.removeAllChildren(); EXPECT_TRUE(layer2.parent().isNull()); MockWebContentLayerClient contentClient; EXPECT_CALL(contentClient, paintContents(_, _, _)).Times(AnyNumber()); WebContentLayer contentLayer = WebContentLayer::create(&contentClient); WebExternalTextureLayer textureLayer = WebExternalTextureLayer::create(); textureLayer.addChild(contentLayer); contentLayer.addChild(layer1); layer1.addChild(layer2); // Release reference on all layers, checking that destruction (which may // generate calls to the client) doesn't crash. layer2.reset(); layer1.reset(); contentLayer.reset(); textureLayer.reset(); } }
lgpl-2.1
iklim/essencia
src/main/java/org/uengine/kernel/designer/ui/MessageTransitionView.java
1872
package org.uengine.kernel.designer.ui; import org.metaworks.EventContext; import org.metaworks.annotation.ServiceMethod; import org.uengine.essencia.modeling.ConnectorSymbol; import org.uengine.kernel.graph.MessageTransition; import org.uengine.kernel.graph.Transition; import org.uengine.modeling.IRelation; import org.uengine.modeling.RelationPropertiesView; import org.uengine.modeling.Symbol; public class MessageTransitionView extends TransitionView{ public final static String SHAPE_ID = "OG.shape.bpmn.C_Message"; public MessageTransitionView(){ } public MessageTransitionView(IRelation relation){ super(relation); } @ServiceMethod(callByContent=true, eventBinding=EventContext.EVENT_DBLCLICK) public Object properties() throws Exception { Transition transition; if(this.getRelation() == null) transition = new Transition(); else transition = (Transition)this.getRelation(); return new RelationPropertiesView(transition); } public static Symbol createSymbol() { Symbol symbol = new Symbol(); symbol.setName("메시지 플로우"); return fillSymbol(symbol); } public static Symbol createSymbol(Class<? extends Symbol> symbolType) { Symbol symbol = new ConnectorSymbol(); try { symbol = (Symbol)Thread.currentThread().getContextClassLoader().loadClass(symbolType.getName()).newInstance(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } symbol.setName("커낵터"); return fillSymbol(symbol); } private static Symbol fillSymbol (Symbol symbol){ symbol.setShapeId(SHAPE_ID); symbol.setHeight(150); symbol.setWidth(200); symbol.setElementClassName(MessageTransition.class.getName()); symbol.setShapeType("EDGE"); return symbol; } }
lgpl-2.1
Emergya/opensir
sir-admin/sir-admin-extensions/subdere-geoexplorer/app/static/externals/jsts/doc/api/symbols/src/src_jsts_geomgraph_NodeFactory.js.html
2720
<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"> <style> .KEYW {color: #933;} .COMM {color: #bbb; font-style: italic;} .NUMB {color: #393;} .STRN {color: #393;} .REGX {color: #339;} .line {border-right: 1px dotted #666; color: #666; font-style: normal;} </style></head><body><pre><span class='line'> 1</span> <span class="COMM">/* Copyright (c) 2011 by The Authors. <span class='line'> 2</span> * Published under the LGPL 2.1 license. <span class='line'> 3</span> * See /license-notice.txt for the full text of the license notice. <span class='line'> 4</span> * See /license.txt for the full text of the license. <span class='line'> 5</span> */</span><span class="WHIT"> <span class='line'> 6</span> <span class='line'> 7</span> <span class='line'> 8</span> <span class='line'> 9</span> </span><span class="COMM">/** <span class='line'> 10</span> * @constructor <span class='line'> 11</span> */</span><span class="WHIT"> <span class='line'> 12</span> </span><span class="NAME">jsts.geomgraph.NodeFactory</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="KEYW">function</span><span class="PUNC">(</span><span class="PUNC">)</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="WHIT"> <span class='line'> 13</span> <span class='line'> 14</span> </span><span class="PUNC">}</span><span class="PUNC">;</span><span class="WHIT"> <span class='line'> 15</span> <span class='line'> 16</span> <span class='line'> 17</span> </span><span class="COMM">/** <span class='line'> 18</span> * The basic node constructor does not allow for incident edges <span class='line'> 19</span> */</span><span class="WHIT"> <span class='line'> 20</span> </span><span class="NAME">jsts.geomgraph.NodeFactory.prototype.createNode</span><span class="WHIT"> </span><span class="PUNC">=</span><span class="WHIT"> </span><span class="KEYW">function</span><span class="PUNC">(</span><span class="NAME">coord</span><span class="PUNC">)</span><span class="WHIT"> </span><span class="PUNC">{</span><span class="WHIT"> <span class='line'> 21</span> </span><span class="WHIT"> </span><span class="KEYW">return</span><span class="WHIT"> </span><span class="KEYW">new</span><span class="WHIT"> </span><span class="NAME">jsts.geomgraph.Node</span><span class="PUNC">(</span><span class="NAME">coord</span><span class="PUNC">,</span><span class="WHIT"> </span><span class="KEYW">null</span><span class="PUNC">)</span><span class="PUNC">;</span><span class="WHIT"> <span class='line'> 22</span> </span><span class="PUNC">}</span><span class="PUNC">;</span><span class="WHIT"> <span class='line'> 23</span> </span></pre></body></html>
lgpl-2.1
joao-lima/starpu-1.2.0rc2
starpu-top/main.cpp
2638
/* = StarPU-Top for StarPU = Copyright (C) 2011 William Braik Yann Courtois Jean-Marie Couteyen Anthony Roy This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <QtGui/QApplication> #include "mainwindow.h" #include <string.h> #include <config.h> #define PROGNAME "starpu_top" static void parse_args(int argc, char **argv) { if (argc == 1) return; if (argc > 2 || /* Argc should be either 1 or 2 */ strncmp(argv[1], "--help", 6) == 0 || strncmp(argv[1], "-h", 2) == 0) { (void) fprintf(stderr, "\ starpu-top is an interface which remotely displays the \n\ on-line state of a StarPU application and permits the user \n\ to change parameters on the fly. \n\ \n\ Usage: %s [OPTION] \n\ \n\ Options: \n\ -h, --help display this help and exit \n\ -v, --version output version information and exit \n\ \n\ Report bugs to <" PACKAGE_BUGREPORT ">.", PROGNAME); } else if (strncmp(argv[1], "--version", 9) == 0 || strncmp(argv[1], "-v", 2) == 0) { fprintf(stderr, "%s (%s) %s\n", PROGNAME, PACKAGE_NAME, PACKAGE_VERSION); } else { fprintf(stderr, "Unknown arg %s\n", argv[1]); } exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { parse_args(argc, argv); QApplication a(argc, argv); // Application description QCoreApplication::setOrganizationName("INRIA Bordeaux Sud-Ouest"); QCoreApplication::setOrganizationDomain("runtime.bordeaux.inria.fr"); QCoreApplication::setApplicationName("StarPU-Top"); QCoreApplication::setApplicationVersion("0.1"); MainWindow w; w.show(); return a.exec(); }
lgpl-2.1
coapp-packages/qdbm
plus/xapidoc/functions_0x77.html
3525
<!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>QDBM for C++: Class Members</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.6.3 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="main.html"><span>Main&nbsp;Page</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 class="tabs"> <ul> <li><a href="annotated.html"><span>Class&nbsp;List</span></a></li> <li><a href="hierarchy.html"><span>Class&nbsp;Hierarchy</span></a></li> <li class="current"><a href="functions.html"><span>Class&nbsp;Members</span></a></li> </ul> </div> <div class="tabs"> <ul> <li class="current"><a href="functions.html"><span>All</span></a></li> <li><a href="functions_func.html"><span>Functions</span></a></li> <li><a href="functions_vars.html"><span>Variables</span></a></li> </ul> </div> <div class="tabs"> <ul> <li><a href="functions.html#index_b"><span>b</span></a></li> <li><a href="functions_0x63.html#index_c"><span>c</span></a></li> <li><a href="functions_0x64.html#index_d"><span>d</span></a></li> <li><a href="functions_0x65.html#index_e"><span>e</span></a></li> <li><a href="functions_0x66.html#index_f"><span>f</span></a></li> <li><a href="functions_0x67.html#index_g"><span>g</span></a></li> <li><a href="functions_0x69.html#index_i"><span>i</span></a></li> <li><a href="functions_0x6a.html#index_j"><span>j</span></a></li> <li><a href="functions_0x6c.html#index_l"><span>l</span></a></li> <li><a href="functions_0x6d.html#index_m"><span>m</span></a></li> <li><a href="functions_0x6e.html#index_n"><span>n</span></a></li> <li><a href="functions_0x6f.html#index_o"><span>o</span></a></li> <li><a href="functions_0x70.html#index_p"><span>p</span></a></li> <li><a href="functions_0x72.html#index_r"><span>r</span></a></li> <li><a href="functions_0x73.html#index_s"><span>s</span></a></li> <li><a href="functions_0x74.html#index_t"><span>t</span></a></li> <li><a href="functions_0x76.html#index_v"><span>v</span></a></li> <li class="current"><a href="functions_0x77.html#index_w"><span>w</span></a></li> <li><a href="functions_0x7e.html#index_~"><span>~</span></a></li> </ul> </div> </div> <div class="contents"> Here is a list of all documented class members with links to the class documentation for each member: <h3><a class="anchor" id="index_w">- w -</a></h3><ul> <li>writable() : <a class="el" href="classqdbm_1_1Curia.html#ae91dc7efcc8a4e0134d91c03e29dc333">qdbm::Curia</a> , <a class="el" href="classqdbm_1_1Villa.html#a9f1a2cf8d141a4a889a53b88de8f45a0">qdbm::Villa</a> , <a class="el" href="classqdbm_1_1Depot.html#a21308a7de25b2a4d1b367fdfa12896c1">qdbm::Depot</a> </li> </ul> </div> <hr class="footer"/><address style="text-align: right;"><small>Generated on Thu Aug 5 02:15:30 2010 for QDBM for C++ by&nbsp; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.6.3 </small></address> </body> </html>
lgpl-2.1
KDE/superkaramba
src/sensors/program.cpp
4624
/*************************************************************************** * Copyright (C) 2003 by Hans Karlsson * * karlsson.h@home.se * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #include "program.h" #include "karamba.h" ProgramSensor::ProgramSensor(Karamba* k, const QString &progName, int interval, const QString &encoding) : Sensor(interval), m_karamba(k) { if (!encoding.isEmpty()) { codec = QTextCodec::codecForName(encoding.toAscii().constData()); if (codec == 0) codec = QTextCodec::codecForLocale(); } else codec = QTextCodec::codecForLocale(); programName = progName; //update(); connect(&ksp, SIGNAL(receivedStdout(K3Process*,char*,int)), this, SLOT(receivedStdout(K3Process*,char*,int))); connect(&ksp, SIGNAL(processExited(K3Process*)), this, SLOT(processExited(K3Process*))); } ProgramSensor::~ProgramSensor() {} void ProgramSensor::receivedStdout(K3Process *, char *buffer, int len) { buffer[len] = 0; sensorResult += codec->toUnicode(buffer); } void ProgramSensor::replaceLine(QString &format, const QString &line) { const QStringList tokens = line.split(QRegExp("\\s+"), QString::SkipEmptyParts); QRegExp dblDigit("%(\\d\\d)"); replaceArgs(dblDigit, format, tokens); QRegExp digit("%(\\d)"); replaceArgs(digit, format, tokens); } void ProgramSensor::replaceArgs(QRegExp& regEx, QString& format, const QStringList& tokens) { int pos = 0; while (pos >= 0) { pos = regEx.indexIn(format, pos); if (pos > -1) { QString matched = regEx.cap(1); int tokenIndex = matched.toInt() - 1; QString replacement = ""; if (tokenIndex < tokens.size()) { replacement = tokens.at(tokenIndex); } format.replace(QRegExp('%' + matched), replacement); pos += regEx.matchedLength(); } } } void ProgramSensor::processExited(K3Process *) { int lineNbr; SensorParams *sp; Meter *meter; QString value; QVector<QString> lines; QStringList stringList = sensorResult.split('\n'); QStringList::ConstIterator end(stringList.constEnd()); for (QStringList::ConstIterator it = stringList.constBegin(); it != end; ++it) { lines.push_back(*it); } int count = (int) lines.size(); QObject *object; foreach(object, *objList) { sp = (SensorParams*)(object); meter = sp->getMeter(); if (meter != 0) { lineNbr = (sp->getParam("LINE")).toInt(); if (lineNbr >= 1 && lineNbr <= (int) count) { value = lines[lineNbr-1]; } else if (-lineNbr >= 1 && -lineNbr <= (int) count) { value = lines[count+lineNbr]; } else if (lineNbr != 0) { value.clear(); } else { value = sensorResult; } QString format = sp->getParam("FORMAT"); if (!format.isEmpty()) { QString returnValue; QStringList lineList = value.split('\n'); QStringList::ConstIterator lineListEnd(lineList.constEnd()); for (QStringList::ConstIterator line = lineList.constBegin(); line != lineListEnd; ++line) { QString formatCopy = format; replaceLine(formatCopy, *line); returnValue += formatCopy; if ( lineList.size() > 1) { returnValue += '\n'; } } value = returnValue; } meter->setValue(value); } } sensorResult = ""; } void ProgramSensor::update() { QString prog = programName; m_karamba->replaceNamedValues(&prog); if ( prog.isEmpty() || prog.startsWith("%echo ")) { sensorResult += prog.mid(6); processExited(NULL); } else { ksp.clearArguments(); ksp << prog; ksp.start(K3ProcIO::NotifyOnExit, K3ProcIO::Stdout); } } #include "program.moc"
lgpl-2.1
Azaler/MagusTechnica
src/main/java/magustechnica/common/lib/LibGuiIDs.java
100
package magustechnica.common.lib; public class LibGuiIDs { public static final int MANUAL = 0; }
lgpl-2.1
megacoder/restfs
src/main/java/nofs/restfs/RestfulRoot.java
2225
package nofs.restfs; import java.util.List; import nofs.Library.Annotations.DomainObject; import nofs.Library.Annotations.FolderObject; import nofs.Library.Annotations.NeedsContainerManager; import nofs.Library.Annotations.RootFolderObject; import nofs.Library.Containers.IDomainObjectContainer; import nofs.Library.Containers.IDomainObjectContainerManager; import nofs.restfs.rules.RulesFolder; @RootFolderObject @FolderObject(ChildTypeFilterMethod="Filter") @DomainObject public class RestfulRoot extends RestfulFolderWithSettings { public boolean Filter(Class<?> possibleChildType) { return possibleChildType == RestfulFolderWithSettings.class || possibleChildType == RestfulFile.class; } private IDomainObjectContainerManager _containerManager; @NeedsContainerManager public void setContainerManager(IDomainObjectContainerManager containerManager) { _containerManager = containerManager; super.setContainerManager(containerManager); } @Override protected void CreatingList(List<BaseFileObject> list) { try { list.add(CreateAuthFolder()); list.add(CreateRulesFolder()); } catch (Exception e) { e.printStackTrace(); } } private RulesFolder CreateRulesFolder() throws Exception { IDomainObjectContainer<RulesFolder> container = _containerManager.GetContainer(RulesFolder.class); RulesFolder folder; if(container.GetAllInstances().size() > 0) { folder = container.GetAllInstances().iterator().next(); } else { folder = container.NewPersistentInstance(); folder.setName("rules"); container.ObjectChanged(folder); } return folder; } @SuppressWarnings("unchecked") private OAuthFolder CreateAuthFolder() throws Exception { IDomainObjectContainer<OAuthFolder> container = _containerManager.GetContainer(OAuthFolder.class); OAuthFolder folder; if(container.GetAllInstances().size() > 0) { folder = container.GetAllInstances().iterator().next(); } else { folder = container.NewPersistentInstance(); folder.setName("auth"); container.ObjectChanged(folder); } return folder; } }
lgpl-2.1
MikeMcShaffry/gamecode3
Dev/Dev2Dox/html/class_evt___phys_obj_collision-members.html
3643
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"> <title>GameCode: Member List</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.4.3 --> <div class="qindex"><a class="qindex" href="main.html">Main&nbsp;Page</a> | <a class="qindex" href="hierarchy.html">Class&nbsp;Hierarchy</a> | <a class="qindex" href="annotated.html">Class&nbsp;List</a> | <a class="qindex" href="dirs.html">Directories</a> | <a class="qindex" href="files.html">File&nbsp;List</a> | <a class="qindex" href="functions.html">Class&nbsp;Members</a> | <a class="qindex" href="globals.html">File&nbsp;Members</a></div> <h1>Evt_PhysObjCollision Member List</h1>This is the complete list of members for <a class="el" href="class_evt___phys_obj_collision.html">Evt_PhysObjCollision</a>, including all inherited members.<p><table> <tr class="memlist"><td><a class="el" href="class_event.html#a0">Event</a>(char const *const inEventTypeName, float inTime=0.f, IEventDataPtr inData=IEventDataPtr((IEventData *) NULL))</td><td><a class="el" href="class_event.html">Event</a></td><td><code> [inline, explicit]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_event.html#a1">Event</a>(Event const &amp;o)</td><td><a class="el" href="class_event.html">Event</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_evt___phys_obj_collision.html#a0">Evt_PhysObjCollision</a>(ActorId actorA, ActorId actorB, Vec3 sumNormalForce, Vec3 sumFrictionForce, Vec3List collisionPoints)</td><td><a class="el" href="class_evt___phys_obj_collision.html">Evt_PhysObjCollision</a></td><td><code> [inline, explicit]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_event.html#a5">getData</a>() const </td><td><a class="el" href="class_event.html">Event</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_event.html#a6">getDataPtr</a>() const </td><td><a class="el" href="class_event.html">Event</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_event.html#a4">getTime</a>() const </td><td><a class="el" href="class_event.html">Event</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_event.html#a3">getType</a>() const </td><td><a class="el" href="class_event.html">Event</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_evt___phys_obj_collision.html#s0">gkName</a></td><td><a class="el" href="class_evt___phys_obj_collision.html">Evt_PhysObjCollision</a></td><td><code> [static]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_event.html#a8">serialize</a>(std::ostrstream &amp;out) const </td><td><a class="el" href="class_event.html">Event</a></td><td><code> [inline, virtual]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_event.html#a7">setDataPtr</a>(IEventDataPtr userData)</td><td><a class="el" href="class_event.html">Event</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_event.html#a2">~Event</a>()</td><td><a class="el" href="class_event.html">Event</a></td><td><code> [inline, virtual]</code></td></tr> </table><hr size="1"><address style="align: right;"><small>Generated on Tue Aug 22 14:08:29 2006 for GameCode by&nbsp; <a href="http://www.doxygen.org/index.html"> <img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.4.3 </small></address> </body> </html>
lgpl-2.1
hychyc07/mosesdecoder
moses/mbr.cpp
5622
#include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <vector> #include <map> #include <cstdlib> #include <cmath> #include <algorithm> #include <cstdio> #include "moses/TrellisPathList.h" #include "moses/TrellisPath.h" #include "moses/StaticData.h" #include "moses/Util.h" #include "mbr.h" using namespace std ; using namespace Moses; /* Input : 1. a sorted n-best list, with duplicates filtered out in the following format 0 ||| amr moussa is currently on a visit to libya , tomorrow , sunday , to hold talks with regard to the in sudan . ||| 0 -4.94418 0 0 -2.16036 0 0 -81.4462 -106.593 -114.43 -105.55 -12.7873 -26.9057 -25.3715 -52.9336 7.99917 -24 ||| -4.58432 2. a weight vector 3. bleu order ( default = 4) 4. scaling factor to weigh the weight vector (default = 1.0) Output : translations that minimise the Bayes Risk of the n-best list */ int BLEU_ORDER = 4; int SMOOTH = 1; float min_interval = 1e-4; void extract_ngrams(const vector<const Factor* >& sentence, map < vector < const Factor* >, int > & allngrams) { vector< const Factor* > ngram; for (int k = 0; k < BLEU_ORDER; k++) { for(int i =0; i < max((int)sentence.size()-k,0); i++) { for ( int j = i; j<= i+k; j++) { ngram.push_back(sentence[j]); } ++allngrams[ngram]; ngram.clear(); } } } float calculate_score(const vector< vector<const Factor*> > & sents, int ref, int hyp, vector < map < vector < const Factor *>, int > > & ngram_stats ) { int comps_n = 2*BLEU_ORDER+1; vector<int> comps(comps_n); float logbleu = 0.0, brevity; int hyp_length = sents[hyp].size(); for (int i =0; i<BLEU_ORDER; i++) { comps[2*i] = 0; comps[2*i+1] = max(hyp_length-i,0); } map< vector < const Factor * > ,int > & hyp_ngrams = ngram_stats[hyp] ; map< vector < const Factor * >, int > & ref_ngrams = ngram_stats[ref] ; for (map< vector< const Factor * >, int >::iterator it = hyp_ngrams.begin(); it != hyp_ngrams.end(); it++) { map< vector< const Factor * >, int >::iterator ref_it = ref_ngrams.find(it->first); if(ref_it != ref_ngrams.end()) { comps[2* (it->first.size()-1)] += min(ref_it->second,it->second); } } comps[comps_n-1] = sents[ref].size(); for (int i=0; i<BLEU_ORDER; i++) { if (comps[0] == 0) return 0.0; if ( i > 0 ) logbleu += log((float)comps[2*i]+SMOOTH)-log((float)comps[2*i+1]+SMOOTH); else logbleu += log((float)comps[2*i])-log((float)comps[2*i+1]); } logbleu /= BLEU_ORDER; brevity = 1.0-(float)comps[comps_n-1]/comps[1]; // comps[comps_n-1] is the ref length, comps[1] is the test length if (brevity < 0.0) logbleu += brevity; return exp(logbleu); } const TrellisPath doMBR(const TrellisPathList& nBestList) { float marginal = 0; float mbr_scale = StaticData::Instance().options().mbr.scale; vector<float> joint_prob_vec; vector< vector<const Factor*> > translations; float joint_prob; vector< map < vector <const Factor *>, int > > ngram_stats; TrellisPathList::const_iterator iter; // get max score to prevent underflow float maxScore = -1e20; for (iter = nBestList.begin() ; iter != nBestList.end() ; ++iter) { const TrellisPath &path = **iter; float score = mbr_scale * path.GetScoreBreakdown()->GetWeightedScore(); if (maxScore < score) maxScore = score; } for (iter = nBestList.begin() ; iter != nBestList.end() ; ++iter) { const TrellisPath &path = **iter; joint_prob = UntransformScore(mbr_scale * path.GetScoreBreakdown()->GetWeightedScore() - maxScore); marginal += joint_prob; joint_prob_vec.push_back(joint_prob); // get words in translation vector<const Factor*> translation; GetOutputFactors(path, translation); // collect n-gram counts map < vector < const Factor *>, int > counts; extract_ngrams(translation,counts); ngram_stats.push_back(counts); translations.push_back(translation); } vector<float> mbr_loss; float bleu, weightedLoss; float weightedLossCumul = 0; float minMBRLoss = 1000000; int minMBRLossIdx = -1; /* Main MBR computation done here */ iter = nBestList.begin(); for (unsigned int i = 0; i < nBestList.GetSize(); i++) { weightedLossCumul = 0; for (unsigned int j = 0; j < nBestList.GetSize(); j++) { if ( i != j) { bleu = calculate_score(translations, j, i,ngram_stats ); weightedLoss = ( 1 - bleu) * ( joint_prob_vec[j]/marginal); weightedLossCumul += weightedLoss; if (weightedLossCumul > minMBRLoss) break; } } if (weightedLossCumul < minMBRLoss) { minMBRLoss = weightedLossCumul; minMBRLossIdx = i; } iter++; } /* Find sentence that minimises Bayes Risk under 1- BLEU loss */ return nBestList.at(minMBRLossIdx); //return translations[minMBRLossIdx]; } void GetOutputFactors(const TrellisPath &path, vector <const Factor*> &translation) { const std::vector<const Hypothesis *> &edges = path.GetEdges(); const std::vector<FactorType>& outputFactorOrder = StaticData::Instance().GetOutputFactorOrder(); assert (outputFactorOrder.size() == 1); // print the surface factor of the translation for (int currEdge = (int)edges.size() - 1 ; currEdge >= 0 ; currEdge--) { const Hypothesis &edge = *edges[currEdge]; const Phrase &phrase = edge.GetCurrTargetPhrase(); size_t size = phrase.GetSize(); for (size_t pos = 0 ; pos < size ; pos++) { const Factor *factor = phrase.GetFactor(pos, outputFactorOrder[0]); translation.push_back(factor); } } }
lgpl-2.1
caicaiking/MyQwt
doc/html/class_qwt_dial_scale_draw-members.html
12780
<!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>Qwt User&#39;s Guide: 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">Qwt User's Guide&#160;<span id="projectnumber">6.0.0</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="pages.html"><span>Related&#160;Pages</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</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> <div class="header"> <div class="headertitle"> <h1>QwtDialScaleDraw Member List</h1> </div> </div> <div class="contents"> This is the complete list of members for <a class="el" href="class_qwt_dial_scale_draw.html">QwtDialScaleDraw</a>, including all inherited members.<table> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#a26215d06a4d48adf401d0aa05d4193c5a61a6c4f4dec2b089edfb655e2b21c3a2">Backbone</a> enum value</td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_round_scale_draw.html#ae3d163159f0771bc05958faf798a1500">center</a>() const </td><td><a class="el" href="class_qwt_round_scale_draw.html">QwtRoundScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#aca3c3a7499112f52616d0ee8518fa5a6">draw</a>(QPainter *, const QPalette &amp;) const </td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td><code> [virtual]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_round_scale_draw.html#a845dc48b006ee168415112f39e80da09">drawBackbone</a>(QPainter *p) const </td><td><a class="el" href="class_qwt_round_scale_draw.html">QwtRoundScaleDraw</a></td><td><code> [protected, virtual]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_round_scale_draw.html#aa43bf3624c464727bb4f0cab28c3f6fe">drawLabel</a>(QPainter *p, double val) const </td><td><a class="el" href="class_qwt_round_scale_draw.html">QwtRoundScaleDraw</a></td><td><code> [protected, virtual]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_round_scale_draw.html#a8e0363f57f85b8dcf316c9351ab72fc2">drawTick</a>(QPainter *p, double val, double len) const </td><td><a class="el" href="class_qwt_round_scale_draw.html">QwtRoundScaleDraw</a></td><td><code> [protected, virtual]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#af975410588db6103f281e49d0b43c6a6">enableComponent</a>(ScaleComponent, bool enable=true)</td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_round_scale_draw.html#a786fd49ec94ab51bb75d7a2f495b2727">extent</a>(const QFont &amp;) const </td><td><a class="el" href="class_qwt_round_scale_draw.html">QwtRoundScaleDraw</a></td><td><code> [virtual]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#a95d74d9eaa5520754295efb33a4db50f">hasComponent</a>(ScaleComponent) const </td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#a4ed95cd23c5d779c1b05aa5295409aa6">invalidateCache</a>()</td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_dial_scale_draw.html#aa497b0ca0f1c4d27a0bcc3c30556cb09">label</a>(double value) const </td><td><a class="el" href="class_qwt_dial_scale_draw.html">QwtDialScaleDraw</a></td><td><code> [virtual]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#a26215d06a4d48adf401d0aa05d4193c5ad2709d7efbb6f1618f0a8a3b6cafae96">Labels</a> enum value</td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#afac6ad0e98fefd9d103366726542a055">maxTickLength</a>() const </td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#a563f102ef1370ecdfdc47133fb0c78ec">minimumExtent</a>() const </td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_round_scale_draw.html#af7e08b85826c5e1e5b1762fa07830107">moveCenter</a>(double x, double y)</td><td><a class="el" href="class_qwt_round_scale_draw.html">QwtRoundScaleDraw</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_round_scale_draw.html#a7be4951c2998474a79e4f1d621ea412a">moveCenter</a>(const QPointF &amp;)</td><td><a class="el" href="class_qwt_round_scale_draw.html">QwtRoundScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_dial_scale_draw.html#ada6f34e92c47bbe2916c50e67494a542">penWidth</a>() const </td><td><a class="el" href="class_qwt_dial_scale_draw.html">QwtDialScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#a19c944664a2e36f06ae71b745fbd442e">QwtAbstractScaleDraw</a>()</td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_dial_scale_draw.html#aa410c51b310d1492db2c0bbc0c1df163">QwtDialScaleDraw</a>(QwtDial *)</td><td><a class="el" href="class_qwt_dial_scale_draw.html">QwtDialScaleDraw</a></td><td><code> [explicit]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_round_scale_draw.html#a9c44d19488567825d826528b701587c8">QwtRoundScaleDraw</a>()</td><td><a class="el" href="class_qwt_round_scale_draw.html">QwtRoundScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_round_scale_draw.html#a2eb03d12749a44f7ca8a8ff92514dd56">radius</a>() const </td><td><a class="el" href="class_qwt_round_scale_draw.html">QwtRoundScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#a26215d06a4d48adf401d0aa05d4193c5">ScaleComponent</a> enum name</td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#a0dd3ccdfa074fb6b1781b84ed2a4729a">ScaleComponents</a> typedef</td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#a82510027cd5bee269628c9d6302a19a9">scaleDiv</a>() const </td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#aac87f593525666a47a57d9e2b4f02c66">scaleMap</a>() const </td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#ae7488eb63ad73a2e69acb29ff069c904">scaleMap</a>()</td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_round_scale_draw.html#a5d85678fdb9fbb4d622425aab9ecc681">setAngleRange</a>(double angle1, double angle2)</td><td><a class="el" href="class_qwt_round_scale_draw.html">QwtRoundScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#ac174255c334b995ca010a6964597d5f2">setMinimumExtent</a>(double)</td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_dial_scale_draw.html#a2fcfdac93eb80c92f6841b140654bb46">setPenWidth</a>(double)</td><td><a class="el" href="class_qwt_dial_scale_draw.html">QwtDialScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#a098e1f813077c9bb0c5f83266035943a">QwtRoundScaleDraw::setPenWidth</a>(int width)</td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_round_scale_draw.html#a069d658989db2ad96f26b79a298f7d10">setRadius</a>(int radius)</td><td><a class="el" href="class_qwt_round_scale_draw.html">QwtRoundScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#a4399aac94a294f5ed6c52114dde00d2f">setScaleDiv</a>(const QwtScaleDiv &amp;s)</td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#ae5bdaadb303510f7eb9dbec5c52f7a47">setSpacing</a>(double margin)</td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#a7fed388e435aae791d61f48cc9ddf632">setTickLength</a>(QwtScaleDiv::TickType, double length)</td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#a0011367eb32519070e6f276ac393dcfb">setTransformation</a>(QwtScaleTransformation *)</td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#a93561d85e879402086f2607e45e89cc2">spacing</a>() const </td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#a5e703dcb115a51024f89f92e61c2c8d8">tickLabel</a>(const QFont &amp;, double value) const </td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#aa43034f7ad87c33e9790c730ed48c55d">tickLength</a>(QwtScaleDiv::TickType) const </td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#a26215d06a4d48adf401d0aa05d4193c5a1f23d080ce1229a0c4f70469e88acce0">Ticks</a> enum value</td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_abstract_scale_draw.html#adc4d3f491b28ee39d728a4a4a9cdd494">~QwtAbstractScaleDraw</a>()</td><td><a class="el" href="class_qwt_abstract_scale_draw.html">QwtAbstractScaleDraw</a></td><td><code> [virtual]</code></td></tr> <tr class="memlist"><td><a class="el" href="class_qwt_round_scale_draw.html#a81583432e629cd8a14524b05fabb4731">~QwtRoundScaleDraw</a>()</td><td><a class="el" href="class_qwt_round_scale_draw.html">QwtRoundScaleDraw</a></td><td><code> [virtual]</code></td></tr> </table></div> <hr class="footer"/><address class="footer"><small>Generated 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>
lgpl-2.1
jelix/minify-module
jminify/install/configure.php
4071
<?php /** * @author Laurent Jouanneau * @copyright 2018 Laurent Jouanneau * @link http://www.jelix.org * @licence GNU Lesser General Public Licence see LICENCE file or http://www.gnu.org/licenses/lgpl.html */ use \Jelix\Installer\Module\API\ConfigurationHelpers; class jminifyModuleConfigurator extends \Jelix\Installer\Module\Configurator { public function getDefaultParameters() { return array( 'eps'=>array('index') ); } public function configure(ConfigurationHelpers $helpers) { $this->parameters['eps'] = $helpers->cli()->askEntryPoints( 'Select entry points on which to setup jminify', 'classic', true ); $helpers->copyFile('files/minifyConfig.php', 'config:minifyConfig.php'); $helpers->copyFile('files/minifyGroupsConfig.php', 'config:minifyGroupsConfig.php'); foreach($this->getParameter('eps') as $epId) { $this->configureEntryPoint($helpers, $epId); } } public function configureEntryPoint(ConfigurationHelpers $helpers, $epId) { $entryPoint = $helpers->getEntryPointsById($epId); $config = $entryPoint->getConfigIni(); $plugins = $config->getValue('plugins','jResponseHtml'); if (strpos($plugins, 'minify') === false) { $plugins .= ',minify'; $config->setValue('plugins',$plugins,'jResponseHtml', null, true); } if (null == $config->getValue('minifyCSS','jResponseHtml', null, true)) { $config->setValue('minifyCSS','off','jResponseHtml', null, true); } if (null == $config->getValue('minifyJS','jResponseHtml', null, true)) { $config->setValue('minifyJS','on','jResponseHtml', null, true); } if (null == $config->getValue('minifyExcludeCSS','jResponseHtml', null, true)) { $config->setValue('minifyExcludeCSS','','jResponseHtml', null, true); } if (null == $config->getValue('minifyExcludeJS','jResponseHtml', null, true)) { $config->setValue('minifyExcludeJS','jelix/wymeditor/jquery.wymeditor.js','jResponseHtml', null, true); } $entrypointMinify = $config->getValue('minifyEntryPoint','jResponseHtml', null, true); if ($entrypointMinify === null) { $config->setValue('minifyEntryPoint','minify.php','jResponseHtml', null, true); $entrypointMinify = 'minify.php'; } if (!file_exists(jApp::wwwPath($entrypointMinify))) { $this->copyFile('files/minify.php', jApp::wwwPath($entrypointMinify)); } } public function unconfigure(ConfigurationHelpers $helpers) { $helpers->removeFile('config:minifyConfig.php'); $helpers->removeFile('config:minifyGroupsConfig.php'); foreach($this->getParameter('eps') as $epId) { $this->unconfigureEntryPoint($epId); } } public function unconfigureEntryPoint(ConfigurationHelpers $helpers, $epId) { $entryPoint = $helpers->getEntryPointsById($epId); $config = $entryPoint->getConfigIni(); $plugins = $config->getValue('plugins','jResponseHtml'); if (strpos($plugins, 'minify') !== false) { $plugins = str_replace('minify', '', $plugins); $plugins = str_replace(',,', ',', $plugins); $config->setValue('plugins',$plugins,'jResponseHtml', null, true); } $config->removeValue('minifyCSS', 'jResponseHtml'); $config->removeValue('minifyJS','jResponseHtml'); $config->removeValue('minifyExcludeCSS','jResponseHtml'); $config->removeValue('minifyExcludeJS','jResponseHtml'); $entrypointMinify = $config->getValue('minifyEntryPoint','jResponseHtml', null, true); if ($entrypointMinify !== null) { $config->removeValue('minifyEntryPoint','jResponseHtml'); } if (file_exists(jApp::wwwPath($entrypointMinify))) { unlink(jApp::wwwPath($entrypointMinify)); } } }
lgpl-2.1
ned14/tnfox
Python/environment.py
2231
#! /usr/bin/python # Copyright 2004 Roman Yakovenko. # Distributed under the Boost Software License, Version 1.0. (See # accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) import sys, os class settings: module_name='TnFOX' boost_path = '' boost_libs_path = '' gccxml_path = '' pygccxml_path = '' pyplusplus_path = '' tnfox_path = '' tnfox_include_path = '' tnfox_python_include_path = '' tnfox_libs_path = '' python_libs_path = '' python_include_path = '' working_dir = '' generated_files_dir = '' unittests_dir = '' xml_files = '' defined_symbols = [ "FXDISABLE_GLOBALALLOCATORREPLACEMENTS" , "FX_INCLUDE_ABSOLUTELY_EVERYTHING" , "FOXPYTHONDLL_EXPORTS" , "FX_NO_GLOBAL_NAMESPACE" ] # For debugging purposes to get far smaller bindings, you can define FX_DISABLEGUI #defined_symbols.append("FX_DISABLEGUI=1") if 'big'==sys.byteorder: defined_symbols.append("FOX_BIGENDIAN=1") else: defined_symbols.append("FOX_BIGENDIAN=0") if 'win32'==sys.platform or 'win64'==sys.platform: defined_symbols.append("WIN32") defined_symbols_gccxml = defined_symbols + ["__GCCXML__" , "_NATIVE_WCHAR_T_DEFINED=1" ] def setup_environment(): sys.path.append( settings.pygccxml_path ) sys.path.append( settings.pyplusplus_path ) setup_environment = staticmethod(setup_environment) rootdir=os.path.normpath(os.getcwd()+'/../..') settings.boost_path = rootdir+'/boost' settings.boost_libs_path = rootdir+'/boost/libs' #settings.gccxml_path = '' #settings.pygccxml_path = '' #settings.pyplusplus_path = '' settings.python_include_path = os.getenv('PYTHON_INCLUDE') settings.python_libs_path = os.getenv('PYTHON_ROOT')+'/libs' settings.tnfox_path = rootdir+'/TnFOX' settings.tnfox_include_path = rootdir+'/TnFOX/include' settings.tnfox_libs_path = rootdir+'/TnFOX/lib' settings.working_dir = os.getcwd() settings.generated_files_dir = rootdir+'/TnFOX/Python/generated' settings.unittests_dir = rootdir+'/TnFOX/Python/unittests' settings.setup_environment()
lgpl-2.1
raedle/univis
lib/hibernate-3.1.3/src/org/hibernate/transaction/JDBCTransactionFactory.java
1002
//$Id: JDBCTransactionFactory.java 8820 2005-12-10 17:25:56Z steveebersole $ package org.hibernate.transaction; import java.util.Properties; import org.hibernate.ConnectionReleaseMode; import org.hibernate.Transaction; import org.hibernate.HibernateException; import org.hibernate.jdbc.JDBCContext; /** * Factory for <tt>JDBCTransaction</tt>. * @see JDBCTransaction * @author Anton van Straaten */ public final class JDBCTransactionFactory implements TransactionFactory { public ConnectionReleaseMode getDefaultReleaseMode() { return ConnectionReleaseMode.AFTER_TRANSACTION; } public Transaction createTransaction(JDBCContext jdbcContext, Context transactionContext) throws HibernateException { return new JDBCTransaction( jdbcContext, transactionContext ); } public void configure(Properties props) throws HibernateException {} public boolean isTransactionManagerRequired() { return false; } public boolean areCallbacksLocalToHibernateTransactions() { return true; } }
lgpl-2.1
einon/affymetrix-power-tools
sdk/dox/html/classCBackgroundZoneTypeCOM-members.html
4119
<!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>Affymetrix Power Tools: 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.1 --> <div class="navigation" id="top"> <div class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="pages.html"><span>Related&nbsp;Pages</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> <li><a href="files.html"><span>Files</span></a></li> <li><a href="dirs.html"><span>Directories</span></a></li> </ul> </div> <div class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&nbsp;List</span></a></li> <li><a href="classes.html"><span>Class&nbsp;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&nbsp;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&nbsp;Members</span></a></li> </ul> </div> </div> <div class="header"> <div class="headertitle"> <h1>CBackgroundZoneTypeCOM Member List</h1> </div> </div> <div class="contents"> This is the complete list of members for <a class="el" href="classCBackgroundZoneTypeCOM.html">CBackgroundZoneTypeCOM</a>, including all inherited members.<table> <tr bgcolor="#f0f0f0"><td><b>CBackgroundZoneTypeCOM</b>() (defined in <a class="el" href="classCBackgroundZoneTypeCOM.html">CBackgroundZoneTypeCOM</a>)</td><td><a class="el" href="classCBackgroundZoneTypeCOM.html">CBackgroundZoneTypeCOM</a></td><td><code> [inline]</code></td></tr> <tr bgcolor="#f0f0f0"><td><b>FinalConstruct</b>() (defined in <a class="el" href="classCBackgroundZoneTypeCOM.html">CBackgroundZoneTypeCOM</a>)</td><td><a class="el" href="classCBackgroundZoneTypeCOM.html">CBackgroundZoneTypeCOM</a></td><td><code> [inline]</code></td></tr> <tr bgcolor="#f0f0f0"><td><b>FinalRelease</b>() (defined in <a class="el" href="classCBackgroundZoneTypeCOM.html">CBackgroundZoneTypeCOM</a>)</td><td><a class="el" href="classCBackgroundZoneTypeCOM.html">CBackgroundZoneTypeCOM</a></td><td><code> [inline]</code></td></tr> <tr bgcolor="#f0f0f0"><td><b>get_background</b>(float *pVal) (defined in <a class="el" href="classCBackgroundZoneTypeCOM.html">CBackgroundZoneTypeCOM</a>)</td><td><a class="el" href="classCBackgroundZoneTypeCOM.html">CBackgroundZoneTypeCOM</a></td><td></td></tr> <tr bgcolor="#f0f0f0"><td><b>get_centerx</b>(float *pVal) (defined in <a class="el" href="classCBackgroundZoneTypeCOM.html">CBackgroundZoneTypeCOM</a>)</td><td><a class="el" href="classCBackgroundZoneTypeCOM.html">CBackgroundZoneTypeCOM</a></td><td></td></tr> <tr bgcolor="#f0f0f0"><td><b>get_centery</b>(float *pVal) (defined in <a class="el" href="classCBackgroundZoneTypeCOM.html">CBackgroundZoneTypeCOM</a>)</td><td><a class="el" href="classCBackgroundZoneTypeCOM.html">CBackgroundZoneTypeCOM</a></td><td></td></tr> <tr bgcolor="#f0f0f0"><td><b>InterfaceSupportsErrorInfo</b>(REFIID riid) (defined in <a class="el" href="classCBackgroundZoneTypeCOM.html">CBackgroundZoneTypeCOM</a>)</td><td><a class="el" href="classCBackgroundZoneTypeCOM.html">CBackgroundZoneTypeCOM</a></td><td></td></tr> <tr bgcolor="#f0f0f0"><td><b>SetBg</b>(affxchp::BackgroundZoneType b) (defined in <a class="el" href="classCBackgroundZoneTypeCOM.html">CBackgroundZoneTypeCOM</a>)</td><td><a class="el" href="classCBackgroundZoneTypeCOM.html">CBackgroundZoneTypeCOM</a></td><td><code> [inline]</code></td></tr> </table></div> <hr class="footer"/><address class="footer"><small>Generated on Fri Mar 20 2015 18:03:35 for Affymetrix Power Tools by&nbsp; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.1 </small></address> </body> </html>
lgpl-2.1
cockpituous/cockpit
pkg/lib/journal.js
19214
/* * This file is part of Cockpit. * * Copyright (C) 2015 Red Hat, Inc. * * Cockpit is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * Cockpit is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Cockpit; If not, see <http://www.gnu.org/licenses/>. */ import cockpit from "cockpit"; import { mustache } from "mustache"; import day_header_template from 'raw-loader!journal_day_header.mustache'; import line_template from 'raw-loader!journal_line.mustache'; import reboot_template from 'raw-loader!journal_reboot.mustache'; import moment from "moment"; moment.locale(cockpit.language); const _ = cockpit.gettext; export var journal = { }; /** * journalctl([match, ...], [options]) * @match: any number of journal match strings * @options: an object containing further options * * Load and (by default) stream journal entries as * json objects. This function returns a jQuery deferred * object which delivers the various journal entries. * * The various @match strings are journalctl matches. * Zero, one or more can be specified. They must be in * string format, or arrays of strings. * * The optional @options object can contain the following: * * "host": the host to load journal from * * "count": number of entries to load and/or pre-stream. * Default is 10 * * "follow": if set to false just load entries and don't * stream further journal data. Default is true. * * "directory": optional directory to load journal files * * "boot": when set only list entries from this specific * boot id, or if null then the current boot. * * "since": if specified list entries since the date/time * * "until": if specified list entries until the date/time * * "cursor": a cursor to start listing entries from * * "after": a cursor to start listing entries after * * Returns a jQuery deferred promise. You can call these * functions on the deferred to handle the responses. Note that * there are additional non-jQuery methods. * * .done(function(entries) { }): Called when done, @entries is * an array of all journal entries loaded. If .stream() * has been invoked then @entries will be empty. * .fail(funciton(ex) { }): called if the operation fails * .stream(function(entries) { }): called when we receive entries * entries. Called once per batch of journal @entries, * whether following or not. * .stop(): stop following or retrieving entries. */ journal.build_cmd = function build_cmd(/* ... */) { var matches = []; var i, arg; var options = { follow: true }; for (i = 0; i < arguments.length; i++) { arg = arguments[i]; if (typeof arg == "string") { matches.push(arg); } else if (typeof arg == "object") { if (arg instanceof Array) { matches.push.apply(matches, arg); } else { cockpit.extend(options, arg); break; } } else { console.warn("journal.journalctl called with invalid argument:", arg); } } if (options.count === undefined) { if (options.follow) options.count = 10; else options.count = null; } var cmd = ["journalctl", "-q"]; if (!options.count) cmd.push("--no-tail"); else cmd.push("--lines=" + options.count); cmd.push("--output=" + (options.output || "json")); if (options.directory) cmd.push("--directory=" + options.directory); if (options.boot) cmd.push("--boot=" + options.boot); else if (options.boot !== undefined) cmd.push("--boot"); if (options.since) cmd.push("--since=" + options.since); if (options.until) cmd.push("--until=" + options.until); if (options.cursor) cmd.push("--cursor=" + options.cursor); if (options.after) cmd.push("--after=" + options.after); /* journalctl doesn't allow reverse and follow together */ if (options.reverse) cmd.push("--reverse"); else if (options.follow) cmd.push("--follow"); cmd.push("--"); cmd.push.apply(cmd, matches); return [cmd, options]; }; journal.journalctl = function journalctl(/* ... */) { var [cmd, options] = journal.build_cmd.apply(null, arguments); var dfd = cockpit.defer(); var promise; var buffer = ""; var entries = []; var streamers = []; var interval = null; function fire_streamers() { var ents, i; if (streamers.length && entries.length > 0) { ents = entries; entries = []; for (i = 0; i < streamers.length; i++) streamers[i].apply(promise, [ents]); } else { window.clearInterval(interval); interval = null; } } var proc = cockpit.spawn(cmd, { host: options.host, batch: 8192, latency: 300, superuser: "try" }) .stream(function(data) { if (buffer) data = buffer + data; buffer = ""; var lines = data.split("\n"); var last = lines.length - 1; lines.forEach(function(line, i) { if (i == last) { buffer = line; } else if (line && line.indexOf("-- ") !== 0) { try { entries.push(JSON.parse(line)); } catch (e) { console.warn(e, line); } } }); if (streamers.length && interval === null) interval = window.setInterval(fire_streamers, 300); }) .done(function() { fire_streamers(); dfd.resolve(entries); }) .fail(function(ex) { /* The journalctl command fails when no entries are matched * so we just ignore this status code */ if (ex.problem == "cancelled" || ex.exit_status === 1) { fire_streamers(); dfd.resolve(entries); } else { dfd.reject(ex); } }) .always(function() { window.clearInterval(interval); }); promise = dfd.promise(); promise.stream = function stream(callback) { streamers.push(callback); return this; }; promise.stop = function stop() { proc.close("cancelled"); }; return promise; }; journal.printable = function printable(value) { if (value === undefined || value === null) return _("[no data]"); else if (typeof (value) == "string") return value; else if (value.length !== undefined) return cockpit.format(_("[$0 bytes of binary data]"), value.length); else return _("[binary data]"); }; function output_funcs_for_box(box) { /* Dereference any jQuery object here */ if (box.jquery) box = box[0]; mustache.parse(day_header_template); mustache.parse(line_template); mustache.parse(reboot_template); function render_line(ident, prio, message, count, time, entry) { var parts = { cursor: entry.__CURSOR, time: time, message: message, service: ident }; if (count > 1) parts.count = count; if (ident === 'abrt-notification') { parts.problem = true; parts.service = entry.PROBLEM_BINARY; } else if (prio < 4) parts.warning = true; return mustache.render(line_template, parts); } var reboot = _("Reboot"); var reboot_line = mustache.render(reboot_template, { message: reboot }); function render_reboot_separator() { return reboot_line; } function render_day_header(day) { return mustache.render(day_header_template, { day: day }); } function parse_html(string) { var div = document.createElement("div"); div.innerHTML = string.trim(); return div.children[0]; } return { render_line: render_line, render_day_header: render_day_header, render_reboot_separator: render_reboot_separator, append: function(elt) { if (typeof (elt) == "string") elt = parse_html(elt); box.appendChild(elt); }, prepend: function(elt) { if (typeof (elt) == "string") elt = parse_html(elt); if (box.firstChild) box.insertBefore(elt, box.firstChild); else box.appendChild(elt); }, remove_last: function() { if (box.lastChild) box.removeChild(box.lastChild); }, remove_first: function() { if (box.firstChild) box.removeChild(box.firstChild); }, }; } /* Render the journal entries by passing suitable HTML strings back to the caller via the 'output_funcs'. Rendering is context aware. It will insert 'reboot' markers, for example, and collapse repeated lines. You can extend the output at the bottom and also at the top. A new renderer is created by calling 'journal.renderer' like so: var renderer = journal.renderer(funcs); You can feed new entries into the renderer by calling various methods on the returned object: - renderer.append(journal_entry) - renderer.append_flush() - renderer.prepend(journal_entry) - renderer.prepend_flush() A 'journal_entry' is one element of the result array returned by a call to 'Query' with the 'cockpit.journal_fields' as the fields to return. Calling 'append' will append the given entry to the end of the output, naturally, and 'prepend' will prepend it to the start. The output might lag behind what has been input via 'append' and 'prepend', and you need to call 'append_flush' and 'prepend_flush' respectively to ensure that the output is up-to-date. Flushing a renderer does not introduce discontinuities into the output. You can continue to feed entries into the renderer after flushing and repeated lines will be correctly collapsed across the flush, for example. The renderer will call methods of the 'output_funcs' object to produce the desired output: - output_funcs.append(rendered) - output_funcs.remove_last() - output_funcs.prepend(rendered) - output_funcs.remove_first() The 'rendered' argument is the return value of one of the rendering functions described below. The 'append' and 'prepend' methods should add this element to the output, naturally, and 'remove_last' and 'remove_first' should remove the indicated element. If you never call 'prepend' on the renderer, 'output_func.prepend' isn't called either. If you never call 'renderer.prepend' after 'renderer.prepend_flush', then 'output_func.remove_first' will never be called. The same guarantees exist for the 'append' family of functions. The actual rendering is also done by calling methods on 'output_funcs': - output_funcs.render_line(ident, prio, message, count, time, cursor) - output_funcs.render_day_header(day) - output_funcs.render_reboot_separator() */ journal.renderer = function renderer(funcs_or_box) { var output_funcs; if (funcs_or_box.render_line) output_funcs = funcs_or_box; else output_funcs = output_funcs_for_box(funcs_or_box); function copy_object(o) { var c = { }; for (var p in o) c[p] = o[p]; return c; } // A 'entry' object describes a journal entry in formatted form. // It has fields 'bootid', 'ident', 'prio', 'message', 'time', // 'day', all of which are strings. function format_entry(journal_entry) { var d = moment(journal_entry.__REALTIME_TIMESTAMP / 1000); // timestamps are in µs return { cursor: journal_entry.__CURSOR, full: journal_entry, day: d.format('LL'), time: d.format('LT'), bootid: journal_entry._BOOT_ID, ident: journal_entry.SYSLOG_IDENTIFIER || journal_entry._COMM, prio: journal_entry.PRIORITY, message: journal.printable(journal_entry.MESSAGE) }; } function entry_is_equal(a, b) { return (a && b && a.day == b.day && a.bootid == b.bootid && a.ident == b.ident && a.prio == b.prio && a.message == b.message); } // A state object describes a line that should be eventually // output. It has an 'entry' field as per description above, and // also 'count', 'last_time', and 'first_time', which record // repeated entries. Additionally: // // line_present: When true, the line has been output already with // some preliminary data. It needs to be removed before // outputting more recent data. // // header_present: The day header has been output preliminarily // before the actual log lines. It needs to be removed before // prepending more lines. If both line_present and // header_present are true, then the header comes first in the // output, followed by the line. function render_state_line(state) { return output_funcs.render_line(state.entry.ident, state.entry.prio, state.entry.message, state.count, state.last_time, state.entry.full); } // We keep the state of the first and last journal lines, // respectively, in order to collapse repeated lines, and to // insert reboot markers and day headers. // // Normally, there are two state objects, but if only a single // line has been output so far, top_state and bottom_state point // to the same object. var top_state, bottom_state; top_state = bottom_state = { }; function start_new_line() { // If we now have two lines, split the state if (top_state === bottom_state && top_state.entry) { top_state = copy_object(bottom_state); } } function top_output() { if (top_state.header_present) { output_funcs.remove_first(); top_state.header_present = false; } if (top_state.line_present) { output_funcs.remove_first(); top_state.line_present = false; } if (top_state.entry) { output_funcs.prepend(render_state_line(top_state)); top_state.line_present = true; } } function prepend(journal_entry) { var entry = format_entry(journal_entry); if (entry_is_equal(top_state.entry, entry)) { top_state.count += 1; top_state.first_time = entry.time; } else { top_output(); if (top_state.entry) { if (entry.bootid != top_state.entry.bootid) output_funcs.prepend(output_funcs.render_reboot_separator()); if (entry.day != top_state.entry.day) output_funcs.prepend(output_funcs.render_day_header(top_state.entry.day)); } start_new_line(); top_state.entry = entry; top_state.count = 1; top_state.first_time = top_state.last_time = entry.time; top_state.line_present = false; } } function prepend_flush() { top_output(); if (top_state.entry) { output_funcs.prepend(output_funcs.render_day_header(top_state.entry.day)); top_state.header_present = true; } } function bottom_output() { if (bottom_state.line_present) { output_funcs.remove_last(); bottom_state.line_present = false; } if (bottom_state.entry) { output_funcs.append(render_state_line(bottom_state)); bottom_state.line_present = true; } } function append(journal_entry) { var entry = format_entry(journal_entry); if (entry_is_equal(bottom_state.entry, entry)) { bottom_state.count += 1; bottom_state.last_time = entry.time; } else { bottom_output(); if (!bottom_state.entry || entry.day != bottom_state.entry.day) { output_funcs.append(output_funcs.render_day_header(entry.day)); bottom_state.header_present = true; } if (bottom_state.entry && entry.bootid != bottom_state.entry.bootid) output_funcs.append(output_funcs.render_reboot_separator()); start_new_line(); bottom_state.entry = entry; bottom_state.count = 1; bottom_state.first_time = bottom_state.last_time = entry.time; bottom_state.line_present = false; } } function append_flush() { bottom_output(); } return { prepend: prepend, prepend_flush: prepend_flush, append: append, append_flush: append_flush }; }; journal.logbox = function logbox(match, max_entries) { var entries = []; var box = document.createElement("div"); function render() { var renderer = journal.renderer(box); while (box.firstChild) box.removeChild(box.firstChild); for (var i = 0; i < entries.length; i++) { renderer.prepend(entries[i]); } renderer.prepend_flush(); if (entries.length === 0) { const empty_message = document.createElement("span"); empty_message.textContent = _("No log entries"); empty_message.setAttribute("class", "empty-message"); box.appendChild(empty_message); } } render(); var promise = journal.journalctl(match, { count: max_entries }) .stream(function(tail) { entries = entries.concat(tail); if (entries.length > max_entries) entries = entries.slice(-max_entries); render(); }) .fail(function(error) { box.appendChild(document.createTextNode(error.message)); box.removeAttribute("hidden"); }); /* Both a DOM element and a promise */ return promise.promise(box); };
lgpl-2.1
MyOwnClone/sdljava-osx-port
testsrc/sdljavax/gfx/SDLGfxFramerateTest.java
3991
package sdljavax.gfx; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import sdljava.SDLException; import sdljava.SDLMain; import sdljava.SDLTimer; import sdljava.event.SDLEvent; import sdljava.video.SDLSurface; import sdljava.video.SDLVideo; import sdljavax.gfx.SDLGfx; /** * Framerate manager from SDL_gfx library test Class * <P> * * @author Bart LEBOEUF * @version $Id: SDLGfxFramerateTest.java,v 1.1 2005/02/18 03:16:46 doc_alton Exp $ */ public class SDLGfxFramerateTest { private int i, rate, x, y, dx, dy, r, g, b; private SDLSurface screen = null; private FPSmanager fpsm = null; private static SecureRandom sr = null; private final static String TITLE = "SDLGFX framerate test - "; static { try { sr = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { } } public SDLGfxFramerateTest() { fpsm = new FPSmanager(); sdl_init(800, 600, 32, (long) SDLVideo.SDL_HWSURFACE | SDLVideo.SDL_DOUBLEBUF); } public void sdl_init(int X, int Y, int bbp, long flags) { // Initialize SDL's subsystems - in this case, only video. try { SDLMain.init(SDLMain.SDL_INIT_VIDEO); } catch (SDLException e) { System.err.println("Unable initialize SDL: " + SDLMain.getError()); System.exit(1); } try { // Attempt to create a window with 32bit pixels. screen = SDLVideo.setVideoMode(X, Y, bbp, flags); } catch (SDLException se) { System.err.println("Unable to set video: " + SDLMain.getError()); System.exit(1); } try { init(); } catch (SDLException e2) { System.err.println("Unable to initialize : " + SDLMain.getError()); System.exit(1); } } public void destroy() { SDLMain.quit(); System.exit(0); } protected void work() { // Main loop: loop forever. while (true) { try { // Render stuff render(); } catch (SDLException e1) { System.err.println("Error while rendering : " + SDLMain.getError()); System.exit(1); } try { // Poll for events, and handle the ones we care about. SDLEvent event = SDLEvent.pollEvent(); if (event != null) eventOccurred(event); else try { SDLTimer.delay(50); } catch (InterruptedException e) { } } catch (SDLException se) { System.err.println("Error while polling event : " + SDLMain.getError()); System.exit(1); } } } public static void main(String[] args) { SDLGfxFramerateTest j = null; try { j = new SDLGfxFramerateTest(); j.work(); } finally { j.destroy(); } } void init() throws SDLException { i = 0; x = screen.getWidth() / 2; y = screen.getHeight() / 2; dx = 7; dy = 5; r = g = b = 255; fpsm.initFramerate(); } void render() throws SDLException { while (true) { /* Set/switch framerate */ i -= 1; if (i < 0) { /* Set new rate */ rate = 5 + 5 * (rand() % 10); fpsm.setFramerate(rate); System.out.println("\nFramerate set to " + rate + "Hz ..."); SDLVideo.wmSetCaption(TITLE + "Framerate set to " + rate + "Hz ...", null); /* New timeout */ i = 2 * rate; /* New Color */ r = rand() & 255; g = rand() & 255; b = rand() & 255; } /* Black screen */ screen.fillRect(SDLVideo.mapRGB(screen.getFormat(), 0, 0, 0)); /* Move */ x += dx; y += dy; /* Reflect */ if ((x < 0) || (x > screen.getWidth())) { dx = -dx; } if ((y < 0) || (y > screen.getHeight())) { dy = -dy; } /* Draw */ SDLGfx.filledCircleRGBA(screen, x, y, 30, r, g, b, 255); SDLGfx.circleRGBA(screen, x, y, 30, 255, 255, 255, 255); /* Display by flipping screens */ screen.updateRect(); /* Delay to fix rate */ fpsm.framerateDelay(); } } public void eventOccurred(SDLEvent event) { if (event == null) return; switch (event.getType()) { case SDLEvent.SDL_QUIT: destroy(); } } protected int rand() { int i; for (i = sr.nextInt(Integer.MAX_VALUE); i <= 0;) ; return i; } }
lgpl-2.1
GhostMonk3408/MidgarCrusade
src/main/java/fr/toss/FF7itemsj/itemj175.java
159
package fr.toss.FF7itemsj; public class itemj175 extends FF7itemsjbase { public itemj175(int id) { super(id); setUnlocalizedName("itemj175"); } }
lgpl-2.1
Warsaalk/OGetIt
src/OGetIt/Technology/Entity/Building/MissileSilo.php
1260
<?php /* * OGetIt, a open source PHP library for handling the new OGame API as of version 6. * Copyright (C) 2015 Klaas Van Parys * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ namespace OGetIt\Technology\Entity\Building; use OGetIt\Technology\TechnologyEconomy; class MissileSilo extends TechnologyEconomy { const TYPE = 44; const METAL = 20000, CRYSTAL = 20000, DEUTERIUM = 1000; public function __construct() { parent::__construct(self::TYPE, self::METAL, self::CRYSTAL, self::DEUTERIUM); } }
lgpl-2.1
plast-lab/soot
src/main/java/soot/jimple/toolkits/annotation/methods/UnreachableMethodsTagger.java
2595
package soot.jimple.toolkits.annotation.methods; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 2004 Jennifer Lhotak * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import soot.G; import soot.Scene; import soot.SceneTransformer; import soot.Singletons; import soot.SootClass; import soot.SootMethod; import soot.tagkit.ColorTag; import soot.tagkit.StringTag; /** A scene transformer that adds tags to unused methods. */ public class UnreachableMethodsTagger extends SceneTransformer { public UnreachableMethodsTagger(Singletons.Global g) { } public static UnreachableMethodsTagger v() { return G.v().soot_jimple_toolkits_annotation_methods_UnreachableMethodsTagger(); } protected void internalTransform(String phaseName, Map options) { // make list of all unreachable methods ArrayList<SootMethod> methodList = new ArrayList<SootMethod>(); Iterator getClassesIt = Scene.v().getApplicationClasses().iterator(); while (getClassesIt.hasNext()) { SootClass appClass = (SootClass) getClassesIt.next(); Iterator getMethodsIt = appClass.getMethods().iterator(); while (getMethodsIt.hasNext()) { SootMethod method = (SootMethod) getMethodsIt.next(); // System.out.println("adding method: "+method); if (!Scene.v().getReachableMethods().contains(method)) { methodList.add(method); } } } // tag unused methods Iterator<SootMethod> unusedIt = methodList.iterator(); while (unusedIt.hasNext()) { SootMethod unusedMethod = unusedIt.next(); unusedMethod.addTag(new StringTag("Method " + unusedMethod.getName() + " is not reachable!", "Unreachable Methods")); unusedMethod.addTag(new ColorTag(255, 0, 0, true, "Unreachable Methods")); // System.out.println("tagged method: "+unusedMethod); } } }
lgpl-2.1
richardmg/qtcreator
share/qtcreator/debugger/dumper.py
20529
############################################################################ # # Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). # Contact: http://www.qt-project.org/legal # # This file is part of Qt Creator. # # Commercial License Usage # Licensees holding valid commercial Qt licenses may use this file in # accordance with the commercial license agreement provided with the # Software or, alternatively, in accordance with the terms contained in # a written agreement between you and Digia. For licensing terms and # conditions see http://qt.digia.com/licensing. For further information # use the contact form at http://qt.digia.com/contact-us. # # GNU Lesser General Public License Usage # Alternatively, this file may be used under the terms of the GNU Lesser # General Public License version 2.1 as published by the Free Software # Foundation and appearing in the file LICENSE.LGPL included in the # packaging of this file. Please review the following information to # ensure the GNU Lesser General Public License version 2.1 requirements # will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. # # In addition, as a special exception, Digia gives you certain additional # rights. These rights are described in the Digia Qt LGPL Exception # version 1.1, included in the file LGPL_EXCEPTION.txt in this package. # ############################################################################ import os import sys import base64 if sys.version_info[0] >= 3: xrange = range toInteger = int else: toInteger = long verbosity = 0 verbosity = 1 def hasPlot(): fileName = "/usr/bin/gnuplot" return os.path.isfile(fileName) and os.access(fileName, os.X_OK) try: import subprocess def arrayForms(): if hasPlot(): return "Normal,Plot" return "Normal" except: def arrayForms(): return "Normal" def bytesToString(b): if sys.version_info[0] == 2: return b return b.decode("utf8") def stringToBytes(s): if sys.version_info[0] == 2: return s return s.encode("utf8") # Base 16 decoding operating on string->string def b16decode(s): return bytesToString(base64.b16decode(stringToBytes(s), True)) # Base 16 decoding operating on string->string def b16encode(s): return bytesToString(base64.b16encode(stringToBytes(s))) # Base 64 decoding operating on string->string def b64decode(s): return bytesToString(base64.b64decode(stringToBytes(s))) # Base 64 decoding operating on string->string def b64encode(s): return bytesToString(base64.b64encode(stringToBytes(s))) # # Gnuplot based display for array-like structures. # gnuplotPipe = {} gnuplotPid = {} def warn(message): print("XXX: %s\n" % message.encode("latin1")) def showException(msg, exType, exValue, exTraceback): warn("**** CAUGHT EXCEPTION: %s ****" % msg) try: import traceback for line in traceback.format_exception(exType, exValue, exTraceback): warn("%s" % line) except: pass def stripClassTag(typeName): if typeName.startswith("class "): return typeName[6:] if typeName.startswith("struct "): return typeName[7:] if typeName.startswith("const "): return typeName[6:] if typeName.startswith("volatile "): return typeName[9:] return typeName class Children: def __init__(self, d, numChild = 1, childType = None, childNumChild = None, maxNumChild = None, addrBase = None, addrStep = None): self.d = d self.numChild = numChild self.childNumChild = childNumChild self.maxNumChild = maxNumChild self.addrBase = addrBase self.addrStep = addrStep self.printsAddress = True if childType is None: self.childType = None else: self.childType = stripClassTag(str(childType)) self.d.put('childtype="%s",' % self.childType) if childNumChild is None: pass #if self.d.isSimpleType(childType): # self.d.put('childnumchild="0",') # self.childNumChild = 0 #elif childType.code == PointerCode: # self.d.put('childnumchild="1",') # self.childNumChild = 1 else: self.d.put('childnumchild="%s",' % childNumChild) self.childNumChild = childNumChild try: if not addrBase is None and not addrStep is None: self.d.put('addrbase="0x%x",' % toInteger(addrBase)) self.d.put('addrstep="0x%x",' % toInteger(addrStep)) self.printsAddress = False except: warn("ADDRBASE: %s" % addrBase) warn("ADDRSTEP: %s" % addrStep) #warn("CHILDREN: %s %s %s" % (numChild, childType, childNumChild)) def __enter__(self): self.savedChildType = self.d.currentChildType self.savedChildNumChild = self.d.currentChildNumChild self.savedNumChild = self.d.currentNumChild self.savedMaxNumChild = self.d.currentMaxNumChild self.savedPrintsAddress = self.d.currentPrintsAddress self.d.currentChildType = self.childType self.d.currentChildNumChild = self.childNumChild self.d.currentNumChild = self.numChild self.d.currentMaxNumChild = self.maxNumChild self.d.currentPrintsAddress = self.printsAddress self.d.put("children=[") def __exit__(self, exType, exValue, exTraceBack): if not exType is None: if self.d.passExceptions: showException("CHILDREN", exType, exValue, exTraceBack) self.d.putNumChild(0) self.d.putValue("<not accessible>") if not self.d.currentMaxNumChild is None: if self.d.currentMaxNumChild < self.d.currentNumChild: self.d.put('{name="<incomplete>",value="",type="",numchild="0"},') self.d.currentChildType = self.savedChildType self.d.currentChildNumChild = self.savedChildNumChild self.d.currentNumChild = self.savedNumChild self.d.currentMaxNumChild = self.savedMaxNumChild self.d.currentPrintsAddress = self.savedPrintsAddress self.d.put('],') return True class SubItem: def __init__(self, d, component): self.d = d self.name = component self.iname = None def __enter__(self): self.d.enterSubItem(self) def __exit__(self, exType, exValue, exTraceBack): return self.d.exitSubItem(self, exType, exValue, exTraceBack) class NoAddress: def __init__(self, d): self.d = d def __enter__(self): self.savedPrintsAddress = self.d.currentPrintsAddress self.d.currentPrintsAddress = False def __exit__(self, exType, exValue, exTraceBack): self.d.currentPrintsAddress = self.savedPrintsAddress class TopLevelItem(SubItem): def __init__(self, d, iname): self.d = d self.iname = iname self.name = None class UnnamedSubItem(SubItem): def __init__(self, d, component): self.d = d self.iname = "%s.%s" % (self.d.currentIName, component) self.name = None class DumperBase: def __init__(self): self.isCdb = False self.isGdb = False self.isLldb = False # Later set, or not set: # cachedQtVersion self.stringCutOff = 10000 # This is a cache mapping from 'type name' to 'display alternatives'. self.qqFormats = {} # This is a cache of all known dumpers. self.qqDumpers = {} # This is a cache of all dumpers that support writing. self.qqEditable = {} # This keeps canonical forms of the typenames, without array indices etc. self.cachedFormats = {} def stripForFormat(self, typeName): if typeName in self.cachedFormats: return self.cachedFormats[typeName] stripped = "" inArray = 0 for c in stripClassTag(typeName): if c == '<': break if c == ' ': continue if c == '[': inArray += 1 elif c == ']': inArray -= 1 if inArray and ord(c) >= 48 and ord(c) <= 57: continue stripped += c self.cachedFormats[typeName] = stripped return stripped def is32bit(self): return self.ptrSize() == 4 def computeLimit(self, size, limit): if limit is None: return size if limit == 0: return min(size, self.stringCutOff) return min(size, limit) def byteArrayDataHelper(self, addr): if self.qtVersion() >= 0x050000: # QTypedArray: # - QtPrivate::RefCount ref # - int size # - uint alloc : 31, capacityReserved : 1 # - qptrdiff offset size = self.extractInt(addr + 4) alloc = self.extractInt(addr + 8) & 0x7ffffff data = addr + self.dereference(addr + 8 + self.ptrSize()) if self.ptrSize() == 4: data = data & 0xffffffff else: data = data & 0xffffffffffffffff else: # Data: # - QBasicAtomicInt ref; # - int alloc, size; # - [padding] # - char *data; alloc = self.extractInt(addr + 4) size = self.extractInt(addr + 8) data = self.dereference(addr + 8 + self.ptrSize()) return data, size, alloc # addr is the begin of a QByteArrayData structure def encodeStringHelper(self, addr, limit = 0): # Should not happen, but we get it with LLDB as result # of inferior calls if addr == 0: return "" data, size, alloc = self.byteArrayDataHelper(addr) if alloc != 0: self.check(0 <= size and size <= alloc and alloc <= 100*1000*1000) limit = self.computeLimit(size, limit) s = self.readMemory(data, 2 * limit) if limit < size: s += "2e002e002e00" return s def encodeByteArrayHelper(self, addr, limit = None): data, size, alloc = self.byteArrayDataHelper(addr) if alloc != 0: self.check(0 <= size and size <= alloc and alloc <= 100*1000*1000) limit = self.computeLimit(size, limit) s = self.readMemory(data, limit) if limit < size: s += "2e2e2e" return s def encodeByteArray(self, value): return self.encodeByteArrayHelper(self.dereferenceValue(value)) def byteArrayData(self, value): return self.byteArrayDataHelper(self.dereferenceValue(value)) def putByteArrayValue(self, value): return self.putValue(self.encodeByteArray(value), Hex2EncodedLatin1) def putStringValueByAddress(self, addr): self.putValue(self.encodeStringHelper(self.dereference(addr)), Hex4EncodedLittleEndian) def encodeString(self, value): return self.encodeStringHelper(self.dereferenceValue(value)) def stringData(self, value): return self.byteArrayDataHelper(self.dereferenceValue(value)) def extractTemplateArgument(self, typename, position): level = 0 skipSpace = False inner = '' for c in typename[typename.find('<') + 1 : -1]: if c == '<': inner += c level += 1 elif c == '>': level -= 1 inner += c elif c == ',': if level == 0: if position == 0: return inner.strip() position -= 1 inner = '' else: inner += c skipSpace = True else: if skipSpace and c == ' ': pass else: inner += c skipSpace = False return inner.strip() def putStringValue(self, value): return self.putValue(self.encodeString(value), Hex4EncodedLittleEndian) def putAddressItem(self, name, value, type = ""): with SubItem(self, name): self.putValue("0x%x" % value) self.putType(type) self.putNumChild(0) def putIntItem(self, name, value): with SubItem(self, name): self.putValue(value) self.putType("int") self.putNumChild(0) def putBoolItem(self, name, value): with SubItem(self, name): self.putValue(value) self.putType("bool") self.putNumChild(0) def putGenericItem(self, name, type, value, encoding = None): with SubItem(self, name): self.putValue(value, encoding) self.putType(type) self.putNumChild(0) def putMapName(self, value): ns = self.qtNamespace() if str(value.type) == ns + "QString": self.put('key="%s",' % self.encodeString(value)) self.put('keyencoded="%s",' % Hex4EncodedLittleEndian) elif str(value.type) == ns + "QByteArray": self.put('key="%s",' % self.encodeByteArray(value)) self.put('keyencoded="%s",' % Hex2EncodedLatin1) else: if self.isLldb: self.put('name="%s",' % value.GetValue()) else: self.put('name="%s",' % value) def isMapCompact(self, keyType, valueType): format = self.currentItemFormat() if format == 2: return True # Compact. return self.isSimpleType(keyType) and self.isSimpleType(valueType) def check(self, exp): if not exp: raise RuntimeError("Check failed") def checkRef(self, ref): try: count = int(ref["atomic"]["_q_value"]) # Qt 5. minimum = -1 except: count = int(ref["_q_value"]) # Qt 4. minimum = 0 # Assume there aren't a million references to any object. self.check(count >= minimum) self.check(count < 1000000) def findFirstZero(self, p, maximum): for i in xrange(maximum): if int(p.dereference()) == 0: return i p = p + 1 return maximum + 1 def encodeCArray(self, p, innerType, suffix): t = self.lookupType(innerType) p = p.cast(t.pointer()) limit = self.findFirstZero(p, self.stringCutOff) s = self.readMemory(p, limit * t.sizeof) if limit > self.stringCutOff: s += suffix return s def encodeCharArray(self, p): return self.encodeCArray(p, "unsigned char", "2e2e2e") def encodeChar2Array(self, p): return self.encodeCArray(p, "unsigned short", "2e002e002e00") def encodeChar4Array(self, p): return self.encodeCArray(p, "unsigned int", "2e0000002e0000002e000000") def putItemCount(self, count, maximum = 1000000000): # This needs to override the default value, so don't use 'put' directly. if count > maximum: self.putValue('<>%s items>' % maximum) else: self.putValue('<%s items>' % count) def putNoType(self): # FIXME: replace with something that does not need special handling # in SubItem.__exit__(). self.putBetterType(" ") def putInaccessible(self): #self.putBetterType(" ") self.putNumChild(0) self.currentValue = None def putQObjectNameValue(self, value): try: intSize = self.intSize() ptrSize = self.ptrSize() # dd = value["d_ptr"]["d"] is just behind the vtable. dd = self.dereference(self.addressOf(value) + ptrSize) if self.qtVersion() < 0x050000: # Size of QObjectData: 5 pointer + 2 int # - vtable # - QObject *q_ptr; # - QObject *parent; # - QObjectList children; # - uint isWidget : 1; etc.. # - int postedEvents; # - QMetaObject *metaObject; # Offset of objectName in QObjectPrivate: 5 pointer + 2 int # - [QObjectData base] # - QString objectName objectName = self.dereference(dd + 5 * ptrSize + 2 * intSize) else: # Size of QObjectData: 5 pointer + 2 int # - vtable # - QObject *q_ptr; # - QObject *parent; # - QObjectList children; # - uint isWidget : 1; etc... # - int postedEvents; # - QDynamicMetaObjectData *metaObject; extra = self.dereference(dd + 5 * ptrSize + 2 * intSize) if extra == 0: return False # Offset of objectName in ExtraData: 6 pointer # - QVector<QObjectUserData *> userData; only #ifndef QT_NO_USERDATA # - QList<QByteArray> propertyNames; # - QList<QVariant> propertyValues; # - QVector<int> runningTimers; # - QList<QPointer<QObject> > eventFilters; # - QString objectName objectName = self.dereference(extra + 5 * ptrSize) data, size, alloc = self.byteArrayDataHelper(objectName) if size == 0: return False str = self.readMemory(data, 2 * size) self.putValue(str, Hex4EncodedLittleEndian, 1) return True except: pass def isKnownMovableType(self, type): if type in ( "QBrush", "QBitArray", "QByteArray", "QCustomTypeInfo", "QChar", "QDate", "QDateTime", "QFileInfo", "QFixed", "QFixedPoint", "QFixedSize", "QHashDummyValue", "QIcon", "QImage", "QLine", "QLineF", "QLatin1Char", "QLocale", "QMatrix", "QModelIndex", "QPoint", "QPointF", "QPen", "QPersistentModelIndex", "QResourceRoot", "QRect", "QRectF", "QRegExp", "QSize", "QSizeF", "QString", "QTime", "QTextBlock", "QUrl", "QVariant", "QXmlStreamAttribute", "QXmlStreamNamespaceDeclaration", "QXmlStreamNotationDeclaration", "QXmlStreamEntityDeclaration" ): return True return type == "QStringList" and self.qtVersion() >= 0x050000 def currentItemFormat(self, type = None): format = self.formats.get(self.currentIName) if format is None: if type is None: type = self.currentType needle = self.stripForFormat(str(type)) format = self.typeformats.get(needle) return format def cleanAddress(addr): if addr is None: return "<no address>" # We cannot use str(addr) as it yields rubbish for char pointers # that might trigger Unicode encoding errors. #return addr.cast(lookupType("void").pointer()) # We do not use "hex(...)" as it (sometimes?) adds a "L" suffix. return "0x%x" % toInteger(addr) # Some "Enums" # Encodings. Keep that synchronized with DebuggerEncoding in debuggerprotocol.h Unencoded8Bit, \ Base64Encoded8BitWithQuotes, \ Base64Encoded16BitWithQuotes, \ Base64Encoded32BitWithQuotes, \ Base64Encoded16Bit, \ Base64Encoded8Bit, \ Hex2EncodedLatin1, \ Hex4EncodedLittleEndian, \ Hex8EncodedLittleEndian, \ Hex2EncodedUtf8, \ Hex8EncodedBigEndian, \ Hex4EncodedBigEndian, \ Hex4EncodedLittleEndianWithoutQuotes, \ Hex2EncodedLocal8Bit, \ JulianDate, \ MillisecondsSinceMidnight, \ JulianDateAndMillisecondsSinceMidnight, \ Hex2EncodedInt1, \ Hex2EncodedInt2, \ Hex2EncodedInt4, \ Hex2EncodedInt8, \ Hex2EncodedUInt1, \ Hex2EncodedUInt2, \ Hex2EncodedUInt4, \ Hex2EncodedUInt8, \ Hex2EncodedFloat4, \ Hex2EncodedFloat8, \ IPv6AddressAndHexScopeId, \ Hex2EncodedUtf8WithoutQuotes, \ MillisecondsSinceEpoch \ = range(30) # Display modes. Keep that synchronized with DebuggerDisplay in watchutils.h StopDisplay, \ DisplayImageData, \ DisplayUtf16String, \ DisplayImageFile, \ DisplayProcess, \ DisplayLatin1String, \ DisplayUtf8String \ = range(7) def mapForms(): return "Normal,Compact" def arrayForms(): if hasPlot(): return "Normal,Plot" return "Normal"
lgpl-2.1
elkafoury/tux
src/org/herac/tuxguitar/gui/actions/composition/ChangeKeySignatureAction.java
6797
/* * Created on 17-dic-2005 * */ package org.herac.tuxguitar.gui.actions.composition; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.TypedEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.herac.tuxguitar.gui.TuxGuitar; import org.herac.tuxguitar.gui.actions.Action; import org.herac.tuxguitar.gui.actions.ActionLock; import org.herac.tuxguitar.gui.editors.tab.TGMeasureImpl; import org.herac.tuxguitar.gui.undo.undoables.custom.UndoableChangeKeySignature; import org.herac.tuxguitar.gui.util.DialogUtils; import org.herac.tuxguitar.gui.util.MessageDialog; import org.herac.tuxguitar.song.models.TGMeasure; import org.herac.tuxguitar.song.models.TGTrack; import org.herac.tuxguitar.util.TGSynchronizer; /** * @author julian * */ public class ChangeKeySignatureAction extends Action{ public static final String NAME = "action.composition.change-key-signature"; public ChangeKeySignatureAction() { super(NAME, AUTO_LOCK | AUTO_UNLOCK | AUTO_UPDATE | DISABLE_ON_PLAYING | KEY_BINDING_AVAILABLE); } protected int execute(TypedEvent e){ showDialog(getEditor().getTablature().getShell()); return 0; } public void showDialog(Shell shell) { TGMeasureImpl measure = getEditor().getTablature().getCaret().getMeasure(); if (measure != null) { final Shell dialog = DialogUtils.newDialog(shell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); dialog.setLayout(new GridLayout()); dialog.setText(TuxGuitar.getProperty("composition.keysignature")); //-------key Signature------------------------------------- Group keySignature = new Group(dialog,SWT.SHADOW_ETCHED_IN); keySignature.setLayout(new GridLayout(2,false)); keySignature.setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,true)); keySignature.setText(TuxGuitar.getProperty("composition.keysignature")); Label numeratorLabel = new Label(keySignature, SWT.NULL); numeratorLabel.setText(TuxGuitar.getProperty("composition.keysignature") + ":"); final Combo keySignatures = new Combo(keySignature, SWT.DROP_DOWN | SWT.READ_ONLY); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.natural")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.sharp-1")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.sharp-2")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.sharp-3")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.sharp-4")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.sharp-5")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.sharp-6")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.sharp-7")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.flat-1")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.flat-2")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.flat-3")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.flat-4")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.flat-5")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.flat-6")); keySignatures.add(TuxGuitar.getProperty("composition.keysignature.flat-7")); keySignatures.select(measure.getKeySignature()); keySignatures.setLayoutData(getComboData()); //--------------------To End Checkbox------------------------------- Group check = new Group(dialog,SWT.SHADOW_ETCHED_IN); check.setLayout(new GridLayout()); check.setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,true)); check.setText(TuxGuitar.getProperty("options")); final Button toEnd = new Button(check, SWT.CHECK); toEnd.setText(TuxGuitar.getProperty("composition.keysignature.to-the-end")); toEnd.setSelection(true); //------------------BUTTONS-------------------------- Composite buttons = new Composite(dialog, SWT.NONE); buttons.setLayout(new GridLayout(2,false)); buttons.setLayoutData(new GridData(SWT.END,SWT.FILL,true,true)); final Button buttonOK = new Button(buttons, SWT.PUSH); buttonOK.setText(TuxGuitar.getProperty("ok")); buttonOK.setLayoutData(getButtonData()); buttonOK.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { final boolean toEndValue = toEnd.getSelection(); final int keySignature = keySignatures.getSelectionIndex(); dialog.dispose(); try { TGSynchronizer.instance().runLater(new TGSynchronizer.TGRunnable() { public void run() throws Throwable { ActionLock.lock(); TuxGuitar.instance().loadCursor(SWT.CURSOR_WAIT); setKeySignature(keySignature,toEndValue); TuxGuitar.instance().updateCache( true ); TuxGuitar.instance().loadCursor(SWT.CURSOR_ARROW); ActionLock.unlock(); } }); } catch (Throwable throwable) { MessageDialog.errorMessage(throwable); } } }); Button buttonCancel = new Button(buttons, SWT.PUSH); buttonCancel.setText(TuxGuitar.getProperty("cancel")); buttonCancel.setLayoutData(getButtonData()); buttonCancel.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { dialog.dispose(); } }); dialog.setDefaultButton( buttonOK ); DialogUtils.openDialog(dialog,DialogUtils.OPEN_STYLE_CENTER | DialogUtils.OPEN_STYLE_PACK | DialogUtils.OPEN_STYLE_WAIT); } } private GridData getButtonData(){ GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); data.minimumWidth = 80; data.minimumHeight = 25; return data; } private GridData getComboData(){ GridData data = new GridData(SWT.FILL,SWT.FILL,true,true); data.minimumWidth = 150; return data; } protected void setKeySignature(int keySignature,boolean toEnd){ //comienza el undoable UndoableChangeKeySignature undoable = UndoableChangeKeySignature.startUndo(); TGMeasure measure = getEditor().getTablature().getCaret().getMeasure(); TGTrack track = getEditor().getTablature().getCaret().getTrack(); getSongManager().getTrackManager().changeKeySignature(track,measure.getStart(),keySignature,toEnd); TuxGuitar.instance().getFileHistory().setUnsavedFile(); //actualizo la tablatura updateTablature(); //termia el undoable addUndoableEdit(undoable.endUndo(keySignature,toEnd)); } }
lgpl-2.1
reed-jpm-alpert/OpenMAMA.233
mamda/c_cpp/doc/cpp/html/classWombat_1_1MamdaTradeReport.html
51881
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"> <title>OpenMAMDA C++ API: Wombat::MamdaTradeReport Class Reference</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> <link href="tabs.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.4.7 --> <div class="tabs"> <ul> <li><a href="main.html"><span>Main&nbsp;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li id="current"><a href="classes.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <form action="search.php" method="get"> <table cellspacing="0" cellpadding="0" border="0"> <tr> <td><label>&nbsp;<u>S</u>earch&nbsp;for&nbsp;</label></td> <td><input type="text" name="query" value="" size="20" accesskey="s"/></td> </tr> </table> </form> </li> </ul></div> <div class="tabs"> <ul> <li><a href="classes.html"><span>Alphabetical&nbsp;List</span></a></li> <li><a href="annotated.html"><span>Class&nbsp;List</span></a></li> <li><a href="hierarchy.html"><span>Class&nbsp;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&nbsp;Members</span></a></li> </ul></div> <div class="nav"> <a class="el" href="namespaceWombat.html">Wombat</a>::<a class="el" href="classWombat_1_1MamdaTradeReport.html">MamdaTradeReport</a></div> <h1>Wombat::MamdaTradeReport Class Reference</h1><!-- doxytag: class="Wombat::MamdaTradeReport" --><!-- doxytag: inherits="Wombat::MamdaBasicEvent" --><a class="el" href="classWombat_1_1MamdaTradeReport.html">MamdaTradeReport</a> is an interface that provides access to fields related to a trade report. <a href="#_details">More...</a> <p> <code>#include &lt;<a class="el" href="MamdaTradeReport_8h-source.html">MamdaTradeReport.h</a>&gt;</code> <p> <p>Inheritance diagram for Wombat::MamdaTradeReport: <p><center><img src="classWombat_1_1MamdaTradeReport.png" usemap="#Wombat::MamdaTradeReport_map" border="0" alt=""></center> <map name="Wombat::MamdaTradeReport_map"> <area href="classWombat_1_1MamdaBasicEvent.html" alt="Wombat::MamdaBasicEvent" shape="rect" coords="0,0,181,24"> <area href="classWombat_1_1MamdaTradeListener.html" alt="Wombat::MamdaTradeListener" shape="rect" coords="0,112,181,136"> </map> <a href="classWombat_1_1MamdaTradeReport-members.html">List of all members.</a><table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> <tr><td colspan="2"><br><h2>Public Member Functions</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual const MamaPrice &amp;&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#97a38026a45edb298ffe62530d43cde4">getTradePrice</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get the trade price. <a href="#97a38026a45edb298ffe62530d43cde4"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual mama_quantity_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#167dd8f71093494ce5d0ff7a85739cbf">getTradeVolume</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get the volume of shares in the trade. <a href="#167dd8f71093494ce5d0ff7a85739cbf"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual const char *&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#eb865e0b7c57732356d925d532364c7b">getTradePartId</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get the participant identifier for the trade. <a href="#eb865e0b7c57732356d925d532364c7b"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual const char *&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#01f6e34bc27e4c6a9d2262327c2961d7">getTradeQual</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get the NYSE Technologies normalized trade qualifier. <a href="#01f6e34bc27e4c6a9d2262327c2961d7"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual const char *&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#e904b58ff3ad3cb36442c4f1db2a7523">getTradeQualNative</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get the native feed trade qualifier. <a href="#e904b58ff3ad3cb36442c4f1db2a7523"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual const char *&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#ceb8234499a7ebd85378094dbed4705a">getSide</a> () const =0</td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#1ff93d3fe09098e58d436b2f273c1030">getSideFieldState</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The TradeSide or AggressorSide Field State. <a href="#1ff93d3fe09098e58d436b2f273c1030"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual mama_u32_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#c9ed0e49599c96128f6be2a1e3390a33">getTradeSellersSaleDays</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get the trade sellers sale days. <a href="#c9ed0e49599c96128f6be2a1e3390a33"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual char&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#5e97df5f0d331db50a07db5ebf9336da">getTradeStopStock</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get the trade stop stock indicator. <a href="#5e97df5f0d331db50a07db5ebf9336da"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual bool&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#ae1e4952c9fb7450300864c44c715637">getIsIrregular</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get whether the trade is irregular. <a href="#ae1e4952c9fb7450300864c44c715637"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual mama_u64_t&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#d4b975d041261a0dcca2e2413c25e72e">getOrderId</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get the order id, if available. <a href="#d4b975d041261a0dcca2e2413c25e72e"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual const char *&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#76e8e93ea2a7f53fb2b0287572dbf7ec">getUniqueId</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get the unique ID. <a href="#76e8e93ea2a7f53fb2b0287572dbf7ec"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual const char *&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#488ca9ba3b64fd6c0996e0df649c5834">getTradeAction</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get the trade action. <a href="#488ca9ba3b64fd6c0996e0df649c5834"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual const char *&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#8bccbbb68ce93d26fd87db95f2f7ff26">getTradeId</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Get the trade id. <a href="#8bccbbb68ce93d26fd87db95f2f7ff26"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual char&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#e772189728321b1bd833baf28e387c15">getShortSaleCircuitBreaker</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">get the ShortSaleCircuitBreaker <a href="#e772189728321b1bd833baf28e387c15"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#338b8a504dc519bff3fc7de0cd882423">getTradePriceFieldState</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The trade price Field State. <a href="#338b8a504dc519bff3fc7de0cd882423"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#3ce3d260e50a07bc6b9f93f8f866d973">getTradeVolumeFieldState</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The trade volume Field State. <a href="#3ce3d260e50a07bc6b9f93f8f866d973"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#3b5756a75180c823a4908d3d2b820d3a">getTradePartIdFieldState</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The trade part ID Field State. <a href="#3b5756a75180c823a4908d3d2b820d3a"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#902afe48248ed43e56d481ba755888b6">getTradeQualFieldState</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The trade qual Field State. <a href="#902afe48248ed43e56d481ba755888b6"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#871557683cafde19e08e1a2e5c6f1f42">getTradeQualNativeFieldState</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The trade quality native Field State. <a href="#871557683cafde19e08e1a2e5c6f1f42"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#da39a0b22fe34276bbf3fb4eefe510d3">getTradeSellersSaleDaysFieldState</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The trade sellers sale days Field State. <a href="#da39a0b22fe34276bbf3fb4eefe510d3"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#cca5c5f38da9a0a129b2c8b386ead49b">getTradeStopStockFieldState</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The trade stop stock Field State. <a href="#cca5c5f38da9a0a129b2c8b386ead49b"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#69578220fbe3f7892865d86384d35b4b">getIsIrregularFieldState</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The isIrregular Field State. <a href="#69578220fbe3f7892865d86384d35b4b"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#544b8f3a730cfc1553bdc756372cd12b">getOrderIdFieldState</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The order ID Field State. <a href="#544b8f3a730cfc1553bdc756372cd12b"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#32722ba8f872d14f9790fd3869b17640">getUniqueIdFieldState</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The unique ID Field State. <a href="#32722ba8f872d14f9790fd3869b17640"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#c5344ba42657f2ba5a35c30240a384f1">getTradeActionFieldState</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The trade action Field State. <a href="#c5344ba42657f2ba5a35c30240a384f1"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#9ff0c7bf7e478588bb42718123fc62ca">getTradeIdFieldState</a> () const =0</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The trade ID Field State. <a href="#9ff0c7bf7e478588bb42718123fc62ca"></a><br></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#346b7f2e68f75aef22d4a0c8640f1bf4">getShortSaleCircuitBreakerFieldState</a> () const =0</td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">virtual&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classWombat_1_1MamdaTradeReport.html#ea6554151d67418f4865dc9ba3bf22b9">~MamdaTradeReport</a> ()</td></tr> </table> <hr><a name="_details"></a><h2>Detailed Description</h2> <a class="el" href="classWombat_1_1MamdaTradeReport.html">MamdaTradeReport</a> is an interface that provides access to fields related to a trade report. <p> This class is used for all trade reports, whether those trades qualify as regular or irregular trades. (A regular trade generally qualifies to update the official last price and intraday high/low prices.) <p> <hr><h2>Constructor &amp; Destructor Documentation</h2> <a class="anchor" name="ea6554151d67418f4865dc9ba3bf22b9"></a><!-- doxytag: member="Wombat::MamdaTradeReport::~MamdaTradeReport" ref="ea6554151d67418f4865dc9ba3bf22b9" args="()" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual Wombat::MamdaTradeReport::~MamdaTradeReport </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"><code> [inline, virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> </div> </div><p> <hr><h2>Member Function Documentation</h2> <a class="anchor" name="97a38026a45edb298ffe62530d43cde4"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getTradePrice" ref="97a38026a45edb298ffe62530d43cde4" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual const MamaPrice&amp; Wombat::MamdaTradeReport::getTradePrice </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> Get the trade price. <p> <dl compact><dt><b>Returns:</b></dt><dd>The monetary value of an individual share of the security at the time of the trade. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#f2f5cd501bc1fcb6717a81c001004228">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="167dd8f71093494ce5d0ff7a85739cbf"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getTradeVolume" ref="167dd8f71093494ce5d0ff7a85739cbf" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual mama_quantity_t Wombat::MamdaTradeReport::getTradeVolume </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> Get the volume of shares in the trade. <p> <dl compact><dt><b>Returns:</b></dt><dd>The number of shares traded in a single transaction for an individual security. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#59830d5b7d9bf0df2e274f8f4ce49cc6">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="eb865e0b7c57732356d925d532364c7b"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getTradePartId" ref="eb865e0b7c57732356d925d532364c7b" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual const char* Wombat::MamdaTradeReport::getTradePartId </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> Get the participant identifier for the trade. <p> <dl compact><dt><b>Returns:</b></dt><dd>Trade participant ID. This is typically an exchange ID or a market maker ID. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#a9e5a20840963992b58ec19cf717cfab">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="01f6e34bc27e4c6a9d2262327c2961d7"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getTradeQual" ref="01f6e34bc27e4c6a9d2262327c2961d7" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual const char* Wombat::MamdaTradeReport::getTradeQual </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> Get the NYSE Technologies normalized trade qualifier. <p> <dl compact><dt><b>Returns:</b></dt><dd>Trade qualifier. A normalized set of qualifiers for the current trade for the security. This field may contain multiple string values, separated by the colon(:) character.</dd></dl> <table width="100%" border="1" cellspacing="3" cellpadding="3"> <tr> <td><b>Value</b></td><td><b>Meaning</b> </td></tr> <tr> <td>Normal </td><td>Regular trade. A trade made without stated conditions is deemed regular way for settlement on the third * business day following the transaction * date. </td></tr> <tr> <td>Acquisition </td><td>A transaction made on the Exchange as a result of an Exchange acquisition. </td></tr> <tr> <td>Bunched </td><td>A trade representing an aggregate of two or more regular trades in a security occurring at the same price either simultaneously or within the same 60 second period, with no individual trade exceeding 10,000 shares. </td></tr> <tr> <td>Cash </td><td>A transaction which calls for the delivery of securities and payment on the same day the trade takes place. </td></tr> <tr> <td>Distribution </td><td>Sale of a large block of stock in such a manner that the price is not adversely affected. </td></tr> <tr> <td>BunchedSold </td><td>A bunched trade which is reported late </td></tr> <tr> <td>Rule155 </td><td>To qualify as a 155 print, a specialist arranges for the sale of the block at one "clean-up" price or at the different price limits on his book. If the block is sold at a "clean-up" price, the specialist should execute at the same price all the executable buy orders on his book. The sale qualifier is only applicable for AMEX trades. </td></tr> <tr> <td>SoldLast </td><td>Sold Last is used when a trade prints in sequence but is reported late or printed in conformance to the One or Two Point Rule. </td></tr> <tr> <td>NextDay </td><td>A transaction which calls for delivery of securities on the first business day after the trade date. </td></tr> <tr> <td>Opened </td><td>Indicates an opening transaction that is printed out of sequence or reported late or printed in conformance to the One or Two Point Rule. </td></tr> <tr> <td>PriorRef </td><td>An executed trade that relates to an obligation to trade at an earlier point in the trading day or that refer to a prior reference price. This may be the result of an order that was lost or misplaced or a SelectNet order that was not executed on a timely basis. </td></tr> <tr> <td>Seller </td><td>A Seller's option transaction is a special transaction which gives the seller the right to deliver the stock at any time within a specific period, ranging from not less than four calendar days to no more than 60 calendar days. </td></tr> <tr> <td>SplitTrade </td><td>An execution in two markets when the specialist or Market Maker in the market first receiving the order agrees to execute a portion of it at whatever price is realized in another market to which the balance of the order is forwarded for execution. </td></tr> <tr> <td>FormT </td><td>See PrePostMkt. Currently, all feed handlers that post Form-T trades - except CTA - send this qualifier for Form-T trades. In the next major release, all fields will use PrePostMkt and FormT will be obsolete. </td></tr> <tr> <td>PrePostMkt </td><td>A trade reported before or after the normal trade reporting day. This is also known as a Form-T trade. The volume of Form-T trades will be included in the calculation of total volume. The price information in Form-T trades will not be used to update high, low and last sale data for individual securities or Indices since they occur outside of normal trade reporting hours. Currently, all feed handlers that post Form-T trades - except CTA - send the "FormT" qualifier for Fot-T trades. In the next major release, all feed handlers will use PrePostMkt and FormT will be obsolete. </td></tr> <tr> <td>AvPrice </td><td>A trade where the price reported is based upon an average of the prices for transactions in a security during all or any portion of the trading day. </td></tr> <tr> <td>Sold </td><td>Sold is used when a trade is printed (reported) out of sequence and at a time different from the actual transaction time. </td></tr> <tr> <td>Adjusted </td><td>&nbsp; </td></tr> <tr> <td>Auto </td><td>A sale condition code that identifies a NYSE trade that has been automatically executed without the potential benefit of price improvement. </td></tr> <tr> <td>Basket </td><td>&nbsp; </td></tr> <tr> <td>CashOnly </td><td>&nbsp; </td></tr> <tr> <td>NextDayOnly </td><td>&nbsp; </td></tr> <tr> <td>SpecTerms </td><td>&nbsp; </td></tr> <tr> <td>Stopped </td><td>&nbsp; </td></tr> <tr> <td>CATS </td><td>&nbsp; </td></tr> <tr> <td>VCT </td><td>&nbsp; </td></tr> <tr> <td>Rule127 </td><td>&nbsp; </td></tr> <tr> <td>BurstBasket </td><td>A burst basket execution signifies a trade wherein the equity Specialists, acting in the aggregate as a market maker, purchase or sell the component stocks required for execution of a specific basket trade. </td></tr> <tr> <td>OpenDetail </td><td>Opening trade detail message. Sent by CTS only and is a duplicate report of an earlier trade. Note: since feed handler version 2.14.32, it is configurable whether these detail messages are published. </td></tr> <tr> <td>Detail </td><td>Trade detail message. Sent by CTS only and is a duplicate report of an earlier trade. Note: since feed handler version 2.14.32, it is configurable whether these detail messages are published. </td></tr> <tr> <td>Reserved </td><td>&nbsp; </td></tr> <tr> <td>BasketCross </td><td>&nbsp; </td></tr> <tr> <td>BasketIndexOnClose </td><td>A basket index on close transaction signifies a trade involving paired basket orders,the execution of which is based on the closing value of the index. These trades are reported after the close when the index closing value is determined. </td></tr> <tr> <td>IntermarketSweep </td><td>Indicates to CTS data recipients that the execution price reflects the order instruction not to send the order to another market that may have a superior price. </td></tr> <tr> <td>YellowFlag </td><td>Regular trades reported during specific events as out of the ordinary. </td></tr> <tr> <td>MarketCenterOpen </td><td>&nbsp; </td></tr> <tr> <td>MarketCenterClose </td><td>&nbsp; </td></tr> <tr> <td>Unknown </td><td>&nbsp; </td></tr> </table> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#0f03f8d8b20f08eab587e439a939d0fc">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="e904b58ff3ad3cb36442c4f1db2a7523"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getTradeQualNative" ref="e904b58ff3ad3cb36442c4f1db2a7523" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual const char* Wombat::MamdaTradeReport::getTradeQualNative </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> Get the native feed trade qualifier. <p> <dl compact><dt><b>Returns:</b></dt><dd>Native trade qualifier (a.k.a. "sale condition"). Feed-specific trade qualifier code(s). This field is provided primarily for completeness and/or troubleshooting. </dd></dl> <dl compact><dt><b>See also:</b></dt><dd><a class="el" href="classWombat_1_1MamdaTradeReport.html#01f6e34bc27e4c6a9d2262327c2961d7">getTradeQual</a>. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#7b01373c290fe46a0a1e00a861996a06">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="ceb8234499a7ebd85378094dbed4705a"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getSide" ref="ceb8234499a7ebd85378094dbed4705a" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual const char* Wombat::MamdaTradeReport::getSide </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> <dl compact><dt><b>Returns:</b></dt><dd>the Aggressor Side or TradeSide TradeSide <ul> <li> 0 : No TradeSide is currently known/available. </li> <li> 1 or B : Buy </li> <li> 2 or S : Sell <ul> </ul> <ul> <li> 0 : No AggressorSide is currently known/available. </li> <li> 1 or B : Buy </li> <li> 2 or S : Sell <ul> </ul> </li> </ul> </li> </ul> </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#e3cca817a27a4e6b9e5b699f548cd22a">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="1ff93d3fe09098e58d436b2f273c1030"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getSideFieldState" ref="1ff93d3fe09098e58d436b2f273c1030" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a> Wombat::MamdaTradeReport::getSideFieldState </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> The TradeSide or AggressorSide Field State. <p> <dl compact><dt><b>Returns:</b></dt><dd>MamdaFieldState. An enumeration representing field state. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#9943001740bebfecd4801267dac6daca">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="c9ed0e49599c96128f6be2a1e3390a33"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getTradeSellersSaleDays" ref="c9ed0e49599c96128f6be2a1e3390a33" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual mama_u32_t Wombat::MamdaTradeReport::getTradeSellersSaleDays </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> Get the trade sellers sale days. <p> <dl compact><dt><b>Returns:</b></dt><dd>Seller's sale days. Used when the trade qualifier is "Seller". Specifies the number of days that may elapse before delivery of the security. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#719ed8fafd8f299b274ba2f11981b3ba">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="5e97df5f0d331db50a07db5ebf9336da"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getTradeStopStock" ref="5e97df5f0d331db50a07db5ebf9336da" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual char Wombat::MamdaTradeReport::getTradeStopStock </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> Get the trade stop stock indicator. <p> <dl compact><dt><b>Returns:</b></dt><dd>Stopped stock indicator. Condition related to certain NYSE trading rules. This is not related to a halted security status. (0 == N/A; 1 == Applicable) </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#2d4333ba424d00cbda5e88a846ef3c8c">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="ae1e4952c9fb7450300864c44c715637"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getIsIrregular" ref="ae1e4952c9fb7450300864c44c715637" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual bool Wombat::MamdaTradeReport::getIsIrregular </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> Get whether the trade is irregular. <p> <dl compact><dt><b>Returns:</b></dt><dd>Whether or not the trade qualifies as an irregular trade. In general, only "regular" trades qualify to update the official last price and high/low prices. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#1a5b54d3d63c62bf8720cc29dd40b25a">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="d4b975d041261a0dcca2e2413c25e72e"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getOrderId" ref="d4b975d041261a0dcca2e2413c25e72e" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual mama_u64_t Wombat::MamdaTradeReport::getOrderId </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> Get the order id, if available. <p> <dl compact><dt><b>Returns:</b></dt><dd>The trade message unique order id number (if available). </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#46c9913f3bc9f7e31f07afa76eaed7ff">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="76e8e93ea2a7f53fb2b0287572dbf7ec"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getUniqueId" ref="76e8e93ea2a7f53fb2b0287572dbf7ec" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual const char* Wombat::MamdaTradeReport::getUniqueId </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> Get the unique ID. <p> <dl compact><dt><b>Returns:</b></dt><dd>The unique ID </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#997416236d779434a70ff52427ac9b8f">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="488ca9ba3b64fd6c0996e0df649c5834"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getTradeAction" ref="488ca9ba3b64fd6c0996e0df649c5834" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual const char* Wombat::MamdaTradeReport::getTradeAction </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> Get the trade action. <p> <dl compact><dt><b>Returns:</b></dt><dd>The trade action </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#9201b4749efd0f17dc42abf5c2bc2060">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="8bccbbb68ce93d26fd87db95f2f7ff26"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getTradeId" ref="8bccbbb68ce93d26fd87db95f2f7ff26" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual const char* Wombat::MamdaTradeReport::getTradeId </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> Get the trade id. <p> <dl compact><dt><b>Returns:</b></dt><dd>the trade id </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#4dcba79f4a1e795b26c382b80b6f18b5">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="e772189728321b1bd833baf28e387c15"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getShortSaleCircuitBreaker" ref="e772189728321b1bd833baf28e387c15" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual char Wombat::MamdaTradeReport::getShortSaleCircuitBreaker </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> get the ShortSaleCircuitBreaker <p> <dl compact><dt><b>Returns:</b></dt><dd>ShortSaleCircuitBreaker <ul> <li> return values: </li> <li> Blank: Short Sale Restriction Not in Effect. </li> <li> A: Short Sale Restriction Activiated. </li> <li> C: Short Sale Restriction Continued. </li> <li> D: Sale Restriction Deactivated. </li> <li> E: Sale Restriction in Effect. </li> </ul> </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#8d5969ac94475afb4eeeb8b252106e6f">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="338b8a504dc519bff3fc7de0cd882423"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getTradePriceFieldState" ref="338b8a504dc519bff3fc7de0cd882423" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a> Wombat::MamdaTradeReport::getTradePriceFieldState </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> The trade price Field State. <p> <dl compact><dt><b>Returns:</b></dt><dd>MamdaFieldState. An enumeration representing field state. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#f1dc31d1863ca41868f8b4a384c7ac46">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="3ce3d260e50a07bc6b9f93f8f866d973"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getTradeVolumeFieldState" ref="3ce3d260e50a07bc6b9f93f8f866d973" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a> Wombat::MamdaTradeReport::getTradeVolumeFieldState </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> The trade volume Field State. <p> <dl compact><dt><b>Returns:</b></dt><dd>MamdaFieldState. An enumeration representing field state. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#5fa909b1c87c6380e204dba43ab9baa7">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="3b5756a75180c823a4908d3d2b820d3a"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getTradePartIdFieldState" ref="3b5756a75180c823a4908d3d2b820d3a" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a> Wombat::MamdaTradeReport::getTradePartIdFieldState </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> The trade part ID Field State. <p> <dl compact><dt><b>Returns:</b></dt><dd>MamdaFieldState. An enumeration representing field state. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#e386075d2c6a4d5f33d25e820ac81559">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="902afe48248ed43e56d481ba755888b6"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getTradeQualFieldState" ref="902afe48248ed43e56d481ba755888b6" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a> Wombat::MamdaTradeReport::getTradeQualFieldState </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> The trade qual Field State. <p> <dl compact><dt><b>Returns:</b></dt><dd>MamdaFieldState. An enumeration representing field state. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#958ea55776c3afa0a572b8819d9c04c8">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="871557683cafde19e08e1a2e5c6f1f42"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getTradeQualNativeFieldState" ref="871557683cafde19e08e1a2e5c6f1f42" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a> Wombat::MamdaTradeReport::getTradeQualNativeFieldState </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> The trade quality native Field State. <p> <dl compact><dt><b>Returns:</b></dt><dd>MamdaFieldState. An enumeration representing field state. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#2e60dd06819139125a4812e84d5803c0">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="da39a0b22fe34276bbf3fb4eefe510d3"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getTradeSellersSaleDaysFieldState" ref="da39a0b22fe34276bbf3fb4eefe510d3" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a> Wombat::MamdaTradeReport::getTradeSellersSaleDaysFieldState </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> The trade sellers sale days Field State. <p> <dl compact><dt><b>Returns:</b></dt><dd>MamdaFieldState. An enumeration representing field state. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#2090b9605a4191bf78b5cef58c7e1fbe">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="cca5c5f38da9a0a129b2c8b386ead49b"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getTradeStopStockFieldState" ref="cca5c5f38da9a0a129b2c8b386ead49b" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a> Wombat::MamdaTradeReport::getTradeStopStockFieldState </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> The trade stop stock Field State. <p> <dl compact><dt><b>Returns:</b></dt><dd>MamdaFieldState. An enumeration representing field state. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#ba6a73453e3956f883f40b5ae7d127d0">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="69578220fbe3f7892865d86384d35b4b"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getIsIrregularFieldState" ref="69578220fbe3f7892865d86384d35b4b" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a> Wombat::MamdaTradeReport::getIsIrregularFieldState </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> The isIrregular Field State. <p> <dl compact><dt><b>Returns:</b></dt><dd>MamdaFieldState. An enumeration representing field state. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#f8e874c8dc039fb83f1e9f4a8bdcbc6f">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="544b8f3a730cfc1553bdc756372cd12b"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getOrderIdFieldState" ref="544b8f3a730cfc1553bdc756372cd12b" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a> Wombat::MamdaTradeReport::getOrderIdFieldState </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> The order ID Field State. <p> <dl compact><dt><b>Returns:</b></dt><dd>MamdaFieldState. An enumeration representing field state. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#f0f77145439c12c8bae3640307b50401">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="32722ba8f872d14f9790fd3869b17640"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getUniqueIdFieldState" ref="32722ba8f872d14f9790fd3869b17640" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a> Wombat::MamdaTradeReport::getUniqueIdFieldState </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> The unique ID Field State. <p> <dl compact><dt><b>Returns:</b></dt><dd>MamdaFieldState. An enumeration representing field state. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#b0093f9dcf1bb03c17beb2915518a179">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="c5344ba42657f2ba5a35c30240a384f1"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getTradeActionFieldState" ref="c5344ba42657f2ba5a35c30240a384f1" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a> Wombat::MamdaTradeReport::getTradeActionFieldState </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> The trade action Field State. <p> <dl compact><dt><b>Returns:</b></dt><dd>MamdaFieldState. An enumeration representing field state. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#bf9d994153ef2fa8b823517c2a061a28">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="9ff0c7bf7e478588bb42718123fc62ca"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getTradeIdFieldState" ref="9ff0c7bf7e478588bb42718123fc62ca" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a> Wombat::MamdaTradeReport::getTradeIdFieldState </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> The trade ID Field State. <p> <dl compact><dt><b>Returns:</b></dt><dd>MamdaFieldState. An enumeration representing field state. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#2475e2a2f9dd0cbd3425b64f84beb258">Wombat::MamdaTradeListener</a>. </div> </div><p> <a class="anchor" name="346b7f2e68f75aef22d4a0c8640f1bf4"></a><!-- doxytag: member="Wombat::MamdaTradeReport::getShortSaleCircuitBreakerFieldState" ref="346b7f2e68f75aef22d4a0c8640f1bf4" args="() const =0" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">virtual <a class="el" href="namespaceWombat.html#93aac974f2ab713554fd12a1fa3b7d2a">MamdaFieldState</a> Wombat::MamdaTradeReport::getShortSaleCircuitBreakerFieldState </td> <td>(</td> <td class="paramname"> </td> <td>&nbsp;)&nbsp;</td> <td width="100%"> const<code> [pure virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p> <dl compact><dt><b>Returns:</b></dt><dd>MamdaFieldState. An enumeration representing field state. </dd></dl> <p> Implemented in <a class="el" href="classWombat_1_1MamdaTradeListener.html#2630b69a9a27a1772e3f4315c254a466">Wombat::MamdaTradeListener</a>. </div> </div><p> <d<!-- HTML footer for doxygen 1.8.7--> <!-- start footer part --> <!--BEGIN GENERATE_TREEVIEW--> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> $navpath <li class="footer"> <span>&copy; 2014 Linux Foundation</span> </ul> </div> <!--END GENERATE_TREEVIEW--> <!--BEGIN !GENERATE_TREEVIEW--> <hr class="footer"/><address class="footer"><small> $generatedby &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="$relpath^doxygen.png" alt="doxygen"/> </a> 1.4.7 </small></address> <!--END !GENERATE_TREEVIEW--> </body> </html>
lgpl-2.1
GNOME/gmime
gmime/gmime-multipart-signed.c
14291
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ /* GMime * Copyright (C) 2000-2020 Jeffrey Stedfast * * 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, 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <string.h> #include "gmime-multipart-signed.h" #include "gmime-multipart-encrypted.h" #include "gmime-message-part.h" #include "gmime-stream-filter.h" #include "gmime-filter-unix2dos.h" #include "gmime-filter-strip.h" #include "gmime-filter-from.h" #include "gmime-stream-mem.h" #include "gmime-internal.h" #include "gmime-parser.h" #include "gmime-error.h" #include "gmime-part.h" #ifdef ENABLE_DEBUG #define d(x) x #else #define d(x) #endif #define _(x) x /** * SECTION: gmime-multipart-signed * @title: GMimeMultipartSigned * @short_description: Signed MIME multiparts * @see_also: #GMimeMultipart * * A #GMimeMultipartSigned part is a special subclass of * #GMimeMultipart to make it easier to manipulate the * multipart/signed MIME type. **/ /* GObject class methods */ static void g_mime_multipart_signed_class_init (GMimeMultipartSignedClass *klass); static void g_mime_multipart_signed_init (GMimeMultipartSigned *mps, GMimeMultipartSignedClass *klass); static void g_mime_multipart_signed_finalize (GObject *object); /* GMimeObject class methods */ static void multipart_signed_encode (GMimeObject *object, GMimeEncodingConstraint constraint); static GMimeMultipartClass *parent_class = NULL; GType g_mime_multipart_signed_get_type (void) { static GType type = 0; if (!type) { static const GTypeInfo info = { sizeof (GMimeMultipartSignedClass), NULL, /* base_class_init */ NULL, /* base_class_finalize */ (GClassInitFunc) g_mime_multipart_signed_class_init, NULL, /* class_finalize */ NULL, /* class_data */ sizeof (GMimeMultipartSigned), 0, /* n_preallocs */ (GInstanceInitFunc) g_mime_multipart_signed_init, }; type = g_type_register_static (GMIME_TYPE_MULTIPART, "GMimeMultipartSigned", &info, 0); } return type; } static void g_mime_multipart_signed_class_init (GMimeMultipartSignedClass *klass) { GMimeObjectClass *object_class = GMIME_OBJECT_CLASS (klass); GObjectClass *gobject_class = G_OBJECT_CLASS (klass); parent_class = g_type_class_ref (GMIME_TYPE_MULTIPART); gobject_class->finalize = g_mime_multipart_signed_finalize; object_class->encode = multipart_signed_encode; } static void g_mime_multipart_signed_init (GMimeMultipartSigned *mps, GMimeMultipartSignedClass *klass) { } static void g_mime_multipart_signed_finalize (GObject *object) { G_OBJECT_CLASS (parent_class)->finalize (object); } static void multipart_signed_encode (GMimeObject *object, GMimeEncodingConstraint constraint) { /* Do NOT encode subparts of a multipart/signed */ return; } /** * g_mime_multipart_signed_new: * * Creates a new MIME multipart/signed object. * * Returns: an empty MIME multipart/signed object. **/ GMimeMultipartSigned * g_mime_multipart_signed_new (void) { GMimeMultipartSigned *multipart; GMimeContentType *content_type; multipart = g_object_new (GMIME_TYPE_MULTIPART_SIGNED, NULL); content_type = g_mime_content_type_new ("multipart", "signed"); g_mime_object_set_content_type ((GMimeObject *) multipart, content_type); g_object_unref (content_type); return multipart; } /** * sign_prepare: * @mime_part: MIME part * * Prepare a part (and all subparts) to be signed. To do this we need * to set the encoding of all parts (that are not already encoded to * either QP or Base64) to QP. **/ static void sign_prepare (GMimeObject *mime_part) { GMimeContentEncoding encoding; GMimeMultipart *multipart; GMimeObject *subpart; int i, n; if (GMIME_IS_MULTIPART (mime_part)) { multipart = (GMimeMultipart *) mime_part; if (GMIME_IS_MULTIPART_SIGNED (multipart) || GMIME_IS_MULTIPART_ENCRYPTED (multipart)) { /* must not modify these parts as they must be treated as opaque */ return; } n = g_mime_multipart_get_count (multipart); for (i = 0; i < n; i++) { subpart = g_mime_multipart_get_part (multipart, i); sign_prepare (subpart); } } else if (GMIME_IS_MESSAGE_PART (mime_part)) { subpart = GMIME_MESSAGE_PART (mime_part)->message->mime_part; sign_prepare (subpart); } else { encoding = g_mime_part_get_content_encoding ((GMimePart *) mime_part); if (encoding != GMIME_CONTENT_ENCODING_BASE64) g_mime_part_set_content_encoding ((GMimePart *) mime_part, GMIME_CONTENT_ENCODING_QUOTEDPRINTABLE); } } /** * g_mime_multipart_signed_sign: * @ctx: a #GMimeCryptoContext * @entity: MIME part to sign * @userid: user id to sign with * @err: a #GError * * Attempts to sign the @content MIME part with @userid's private key * using the @ctx signing context. If successful, a new multipart/signed * object is returned. * * Returns: (nullable) (transfer full): a new #GMimeMultipartSigned object on success * or %NULL on fail. If signing fails, an exception will be set on @err to provide * information as to why the failure occurred. **/ GMimeMultipartSigned * g_mime_multipart_signed_sign (GMimeCryptoContext *ctx, GMimeObject *entity, const char *userid, GError **err) { GMimeStream *stream, *filtered, *sigstream; GMimeContentType *content_type; GMimeDataWrapper *content; GMimeMultipartSigned *mps; GMimePart *signature; GMimeFilter *filter; GMimeParser *parser; const char *protocol; const char *micalg; int algo; g_return_val_if_fail (GMIME_IS_CRYPTO_CONTEXT (ctx), NULL); g_return_val_if_fail (GMIME_IS_OBJECT (entity), NULL); if (!(protocol = g_mime_crypto_context_get_signature_protocol (ctx))) { g_set_error_literal (err, GMIME_ERROR, GMIME_ERROR_NOT_SUPPORTED, _("Signing not supported.")); return NULL; } /* Prepare all the parts for signing... */ sign_prepare (entity); /* get the cleartext */ stream = g_mime_stream_mem_new (); filtered = g_mime_stream_filter_new (stream); /* Note: see rfc3156, section 3 - second note */ filter = g_mime_filter_from_new (GMIME_FILTER_FROM_MODE_ARMOR); g_mime_stream_filter_add ((GMimeStreamFilter *) filtered, filter); g_object_unref (filter); /* Note: see rfc3156, section 5.4 (this is the main difference between rfc2015 and rfc3156) */ filter = g_mime_filter_strip_new (); g_mime_stream_filter_add ((GMimeStreamFilter *) filtered, filter); g_object_unref (filter); /* write the entity out to the stream */ g_mime_object_write_to_stream (entity, NULL, filtered); g_mime_stream_flush (filtered); g_mime_stream_reset (stream); g_object_unref (filtered); /* Note: see rfc2015 or rfc3156, section 5.1 - we do this *after* writing out * the entity because we'll end up parsing the mime part back out again and * we don't want it to be in DOS format. */ filtered = g_mime_stream_filter_new (stream); filter = g_mime_filter_unix2dos_new (FALSE); g_mime_stream_filter_add ((GMimeStreamFilter *) filtered, filter); g_object_unref (filter); /* construct the signature stream */ sigstream = g_mime_stream_mem_new (); /* sign the content stream */ if ((algo = g_mime_crypto_context_sign (ctx, TRUE, userid, filtered, sigstream, err)) == -1) { g_object_unref (sigstream); g_object_unref (filtered); g_object_unref (stream); return NULL; } g_object_unref (filtered); g_mime_stream_reset (sigstream); g_mime_stream_reset (stream); /* construct the content part */ parser = g_mime_parser_new_with_stream (stream); entity = g_mime_parser_construct_part (parser, NULL); g_object_unref (stream); g_object_unref (parser); /* construct the signature part */ content_type = g_mime_content_type_parse (NULL, protocol); signature = g_mime_part_new_with_type (content_type->type, content_type->subtype); g_object_unref (content_type); content = g_mime_data_wrapper_new (); g_mime_data_wrapper_set_stream (content, sigstream); g_mime_part_set_content (signature, content); g_object_unref (sigstream); g_object_unref (content); /* FIXME: temporary hack, this info should probably be set in * the CryptoContext class - maybe ::sign can take/output a * GMimePart instead. */ if (!g_ascii_strcasecmp (protocol, "application/pkcs7-signature")) { g_mime_part_set_content_encoding (signature, GMIME_CONTENT_ENCODING_BASE64); g_mime_part_set_filename (signature, "smime.p7m"); } /* save the content and signature parts */ mps = g_mime_multipart_signed_new (); g_mime_multipart_add ((GMimeMultipart *) mps, entity); g_mime_multipart_add ((GMimeMultipart *) mps, (GMimeObject *) signature); g_object_unref (signature); g_object_unref (entity); /* set the multipart/signed protocol and micalg */ micalg = g_mime_crypto_context_digest_name (ctx, (GMimeDigestAlgo) algo); g_mime_object_set_content_type_parameter ((GMimeObject *) mps, "protocol", protocol); g_mime_object_set_content_type_parameter ((GMimeObject *) mps, "micalg", micalg); g_mime_multipart_set_boundary ((GMimeMultipart *) mps, NULL); return mps; } static gboolean check_protocol_supported (const char *protocol, const char *supported) { const char *subtype; char *xsupported; gboolean rv; if (!supported) return FALSE; if (!g_ascii_strcasecmp (protocol, supported)) return TRUE; if (!(subtype = strrchr (supported, '/'))) return FALSE; subtype++; /* If the subtype already begins with "x-", then there's * nothing else to check. */ if (!g_ascii_strncasecmp (subtype, "x-", 2)) return FALSE; /* Check if the "x-" version of the subtype matches the * protocol. For example, if the supported protocol is * "application/pkcs7-signature", then we also want to * match "application/x-pkcs7-signature". */ xsupported = g_strdup_printf ("%.*sx-%s", (int) (subtype - supported), supported, subtype); rv = !g_ascii_strcasecmp (protocol, xsupported); g_free (xsupported); return rv; } /** * g_mime_multipart_signed_verify: * @mps: a #GMimeMultipartSigned * @flags: a #GMimeVerifyFlags * @err: a #GError * * Attempts to verify the signed MIME part contained within the * multipart/signed object @mps. * * Returns: (nullable) (transfer full): a new #GMimeSignatureList object on * success or %NULL on fail. If the verification fails, an exception * will be set on @err to provide information as to why the failure * occurred. **/ GMimeSignatureList * g_mime_multipart_signed_verify (GMimeMultipartSigned *mps, GMimeVerifyFlags flags, GError **err) { const char *supported, *protocol; GMimeObject *content, *signature; GMimeStream *stream, *sigstream; GMimeSignatureList *signatures; GMimeFormatOptions *options; GMimeDataWrapper *wrapper; GMimeCryptoContext *ctx; char *mime_type; g_return_val_if_fail (GMIME_IS_MULTIPART_SIGNED (mps), NULL); if (g_mime_multipart_get_count ((GMimeMultipart *) mps) < 2) { g_set_error_literal (err, GMIME_ERROR, GMIME_ERROR_PARSE_ERROR, _("Cannot verify multipart/signed part due to missing subparts.")); return NULL; } if (!(protocol = g_mime_object_get_content_type_parameter ((GMimeObject *) mps, "protocol"))) { g_set_error_literal (err, GMIME_ERROR, GMIME_ERROR_PROTOCOL_ERROR, _("Cannot verify multipart/signed part: unspecified signature protocol.")); return NULL; } if (!(ctx = g_mime_crypto_context_new (protocol))) { g_set_error (err, GMIME_ERROR, GMIME_ERROR_PROTOCOL_ERROR, _("Cannot verify multipart/signed part: unregistered signature protocol '%s'."), protocol); return NULL; } supported = g_mime_crypto_context_get_signature_protocol (ctx); /* make sure the protocol matches the crypto sign protocol */ if (!check_protocol_supported (protocol, supported)) { g_set_error (err, GMIME_ERROR, GMIME_ERROR_PROTOCOL_ERROR, _("Cannot verify multipart/signed part: unsupported signature protocol '%s'."), protocol); g_object_unref (ctx); return NULL; } signature = g_mime_multipart_get_part ((GMimeMultipart *) mps, GMIME_MULTIPART_SIGNED_SIGNATURE); /* make sure the protocol matches the signature content-type */ mime_type = g_mime_content_type_get_mime_type (signature->content_type); if (g_ascii_strcasecmp (mime_type, protocol) != 0) { g_set_error_literal (err, GMIME_ERROR, GMIME_ERROR_PARSE_ERROR, _("Cannot verify multipart/signed part: signature content-type does not match protocol.")); g_object_unref (ctx); g_free (mime_type); return NULL; } g_free (mime_type); content = g_mime_multipart_get_part ((GMimeMultipart *) mps, GMIME_MULTIPART_SIGNED_CONTENT); /* get the content stream */ stream = g_mime_stream_mem_new (); /* Note: see rfc2015 or rfc3156, section 5.1 */ options = _g_mime_format_options_clone (NULL, FALSE); g_mime_format_options_set_newline_format (options, GMIME_NEWLINE_FORMAT_DOS); g_mime_object_write_to_stream (content, options, stream); g_mime_format_options_free (options); g_mime_stream_reset (stream); /* get the signature stream */ wrapper = g_mime_part_get_content ((GMimePart *) signature); sigstream = g_mime_stream_mem_new (); g_mime_data_wrapper_write_to_stream (wrapper, sigstream); g_mime_stream_reset (sigstream); /* verify the signature */ signatures = g_mime_crypto_context_verify (ctx, flags, stream, sigstream, NULL, err); d(printf ("attempted to verify:\n----- BEGIN SIGNED PART -----\n%.*s----- END SIGNED PART -----\n", (int) GMIME_STREAM_MEM (stream)->buffer->len, GMIME_STREAM_MEM (stream)->buffer->data)); g_object_unref (sigstream); g_object_unref (stream); g_object_unref (ctx); return signatures; }
lgpl-2.1
SanDisk-Open-Source/zetascale
fth/archive/fthSparseTest.c
5056
//---------------------------------------------------------------------------- // ZetaScale // Copyright (c) 2016, SanDisk Corp. and/or all its affiliates. // // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published by the Free // Software Foundation; // // 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 v2.1 for more details. // // A copy of the GNU Lesser General Public License v2.1 is provided with this package and // can also be found at: http://opensource.org/licenses/LGPL-2.1 // 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., 59 Temple // Place, Suite 330, Boston, MA 02111-1307 USA. //---------------------------------------------------------------------------- /* * File: fthSparseTest.c * Author: Jim * * Created on February 29, 2008 * * (c) Copyright 2008, Schooner Information Technology, Inc. * http: //www.schoonerinfotech.com/ * * $Id: fthSparseTest.h 396 2008-02-29 22:55:43Z jim $ */ // // Sparse lock test // #include <pthread.h> #include "fth.h" #include "fthMbox.h" #include "fthThread.h" #include "fthWaitEl.h" #include "fthMem.h" #include "fthMbox.h" #include "fthSparseLock.h" #include "platform/assert.h" #include "platform/errno.h" #include "platform/fcntl.h" #include "platform/logging.h" #include "platform/shmem.h" #include "platform/signal.h" #include "platform/stdlib.h" #include "platform/string.h" #include "platform/time.h" #include "platform/unistd.h" #include "misc/misc.h" #include <stdio.h> fthLock_t lock1; fthSparseLockTable_t *slt; int threadCount; int exitRV = 0; void threadRoutine2(uint64_t arg) { printf("Thread 2 start - %i\n", arg); (void) __sync_fetch_and_add(&threadCount, 1); fthWaitEl_t *waitR = fthSparseLock(slt, 100, 1, NULL); // Get lock printf("Thread 2 got read lock - %i\n", arg); fthSparseUnlock(slt, waitR); printf("Thread 2 released read lock - %i\n", arg); fthWaitEl_t *waitW = fthSparseLock(slt, arg, 1, NULL); // Write lock printf("Thread 2 got write lock - %i\n", arg); fthSparseUnlock(slt, waitW); printf("Thread 2 released write lock - %i\n", arg); if (__sync_fetch_and_add(&threadCount, -1) == 1) { printf("Thread 2 last man standing - %i\n", arg); fthKill(100); } } void threadRoutine1(uint64_t arg) { fthWaitEl_t *wait[100]; printf("Thread 1 start\n"); for (int i=0; i < 100; i++) { wait[i] = fthSparseLock(slt, i, 1, NULL); // Get 100 write locks } fthWaitEl_t *readLock = fthSparseLock(slt, 100, 0, NULL); // Get read lock printf("Thread 1 got locks\n"); fthWaitEl_t *stall = fthLock(&lock1, 1, NULL); // Wait for write lock printf("Thread 1 Got stall lock\n"); fthUnlock(stall); for (int i=0; i < 100; i++) { fthSparseUnlock(slt, wait[i]); // Release 100 write locks } fthSparseUnlock(slt, readLock); // release read lock printf("Thread 1 unlock complete\n"); } void initThread(uint64_t arg) { fthWaitEl_t *wait = fthLock(&lock1, 1, NULL); slt = FTH_MALLOC(FTH_SPARSE_LOCK_TABLE_SIZE(16)); fthSparseLockTableInit(slt, 16); fthResume(fthSpawn(&threadRoutine1, 4096), 0); fthYield(100); for (int i=0; i<100; i++) { fthResume(fthSpawn(&threadRoutine2, 4096), i); } fthYield(1000); fthUnlock(wait); } #define NUM_PTHREADS 4 void *pthreadRoutine(void *arg) { if ((uint64_t) arg == (NUM_PTHREADS - 1)) { // Wait for last scheduler XResume(XSpawn(&initThread, 4096), 0); } fthSchedulerPthread(0); printf("Scheduler %i halted\n", (uint64_t) arg); return (0); } #define SHM_SIZE 8 * 1024 *1024 int main(void) { pthread_t pthread[10]; struct plat_shmem_config *shmem_config = plat_alloc(sizeof(struct plat_shmem_config)); plat_shmem_config_init(shmem_config); shmem_config->size = SHM_SIZE; plat_shmem_prototype_init(shmem_config); int tmp = plat_shmem_attach(shmem_config->mmap); if (tmp) { plat_log_msg(20073, PLAT_LOG_CAT_PLATFORM_TEST_SHMEM, PLAT_LOG_LEVEL_FATAL, "shmem_attach(%s) failed: %s", shmem_config->mmap, plat_strerror(-tmp)); plat_abort(); } #ifdef MULTIQ_SCHED fthInitMultiQ(1,NUM_PTHREADS); // Tell the scheduler code NUM_PTHREADS schedulers starting up #else fthInit(); #endif for (uint64_t i = 0; i < NUM_PTHREADS; i++) { pthread_create(&pthread[i], NULL, &pthreadRoutine, (void *) i); } for (uint64_t i = 0; i < NUM_PTHREADS; i++) { pthread_join(pthread[i], NULL); } printf("Done\n"); plat_exit(exitRV); }
lgpl-2.1
HavenDV/ImprovedControls
ImprovedControls/MultipleMonthCalCtrl.h
1275
#pragma once #include <SDKDDKVer.h> #include <afxdtctl.h> #include <vector> class CMultipleMonthCalCtrl : public CMonthCalCtrl { DECLARE_DYNAMIC(CMultipleMonthCalCtrl) public: CMultipleMonthCalCtrl(); virtual ~CMultipleMonthCalCtrl(); static void RegisterControl(); static void UnregisterControl(); void SetOriginalColors(); void EnableMultiselect(int maxSelectCount = 0); void DisableMultiselect(); std::vector<SYSTEMTIME> GetSelection() const; /* This method set last date as first month in calendar. * Use SetRange() after for select need range. */ void SelectDate(const SYSTEMTIME & date); void SelectDates(const std::vector<SYSTEMTIME> & dates); void UnselectAll(); BOOL SetDayState(int count, MONTHDAYSTATE * states); protected: DECLARE_MESSAGE_MAP() public: virtual BOOL Create(DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID); }; /* * Utilities for T3000 */ std::vector<SYSTEMTIME> ToSystemTimeVector(int monthCount, MONTHDAYSTATE * states, const SYSTEMTIME & start); MONTHDAYSTATE* ToDayStates(const std::vector<SYSTEMTIME> & days, int & mCount, SYSTEMTIME & start); //Default - sunday //0 - sunday, 6 - monday std::vector<SYSTEMTIME> GetAllYearDaysForDayOfWeek(int year, int dayOfWeek = 0);
lgpl-2.1
geotools/geotools
modules/library/main/src/test/java/org/geotools/data/WorldFileWriterTest.java
1127
package org.geotools.data; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.awt.geom.AffineTransform; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import org.junit.Test; public class WorldFileWriterTest { @Test public void testWrite() throws Exception { AffineTransform at = new AffineTransform(42.34, 0, 0, -42.34, 347671.10, 5196940.18); File tmp = File.createTempFile("write", "wld", new File("target")); new WorldFileWriter(tmp, at); try (BufferedReader r = new BufferedReader(new FileReader(tmp))) { assertEquals(42.34, Double.parseDouble(r.readLine()), 0.1); assertEquals(0, Double.parseDouble(r.readLine()), 0.1); assertEquals(0, Double.parseDouble(r.readLine()), 0.1); assertEquals(-42.34, Double.parseDouble(r.readLine()), 0.1); assertEquals(347671.10, Double.parseDouble(r.readLine()), 0.1); assertEquals(5196940.18, Double.parseDouble(r.readLine()), 0.1); assertNull(r.readLine()); } } }
lgpl-2.1
mwgoldsmith/bluray
src/libbluray/bdj/java/java/awt/BDToolkitBase.java
8816
/* * This file is part of libbluray * Copyright (C) 2012 libbluray * Copyright (C) 2012-2014 Petri Hintukainen <phintuka@users.sourceforge.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see * <http://www.gnu.org/licenses/>. */ package java.awt; import java.awt.image.ColorModel; import java.awt.image.ImageObserver; import java.awt.image.ImageProducer; import java.io.File; import java.net.URL; import java.util.Collections; import java.util.Hashtable; import java.util.WeakHashMap; import java.util.Map; import java.util.Iterator; import sun.awt.image.ByteArrayImageSource; import sun.awt.image.FileImageSource; import sun.awt.image.URLImageSource; import org.videolan.BDJXletContext; import org.videolan.Logger; abstract class BDToolkitBase extends Toolkit { private EventQueue eventQueue = new EventQueue(); private BDGraphicsEnvironment localEnv = new BDGraphicsEnvironment(); private BDGraphicsConfiguration defaultGC = (BDGraphicsConfiguration)localEnv.getDefaultScreenDevice().getDefaultConfiguration(); private static Hashtable cachedImages = new Hashtable(); private static final Logger logger = Logger.getLogger(BDToolkit.class.getName()); // mapping of Components to AppContexts, WeakHashMap<Component,AppContext> private static final Map contextMap = Collections.synchronizedMap(new WeakHashMap()); public BDToolkitBase () { } public static void setFocusedWindow(Window window) { } public static void shutdownDisc() { try { Toolkit toolkit = getDefaultToolkit(); if (toolkit instanceof BDToolkit) { ((BDToolkit)toolkit).shutdown(); } } catch (Throwable t) { logger.error("shutdownDisc() failed: " + t + "\n" + Logger.dumpStack(t)); } } protected void shutdown() { /* if (eventQueue != null) { BDJHelper.stopEventQueue(eventQueue); eventQueue = null; } */ cachedImages.clear(); contextMap.clear(); } public Dimension getScreenSize() { Rectangle dims = defaultGC.getBounds(); return new Dimension(dims.width, dims.height); } Graphics getGraphics(Window window) { if (!(window instanceof BDRootWindow)) { logger.error("getGraphics(): not BDRootWindow"); throw new Error("Not implemented"); } return new BDWindowGraphics((BDRootWindow)window); } GraphicsEnvironment getLocalGraphicsEnvironment() { return localEnv; } public int getScreenResolution() { return 72; } public ColorModel getColorModel() { return defaultGC.getColorModel(); } public String[] getFontList() { return BDFontMetrics.getFontList(); } public FontMetrics getFontMetrics(Font font) { return BDFontMetrics.getFontMetrics(font); } static void clearCache(BDImage image) { synchronized (cachedImages) { Iterator i = cachedImages.entrySet().iterator(); while (i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); if (entry.getValue() == image) { i.remove(); return; } } } } public Image getImage(String filename) { if (BDJXletContext.getCurrentContext() == null) { logger.error("getImage(): no context " + Logger.dumpStack()); } if (cachedImages.containsKey(filename)) return (Image)cachedImages.get(filename); Image newImage = createImage(filename); if (newImage != null) cachedImages.put(filename, newImage); return newImage; } public Image getImage(URL url) { if (BDJXletContext.getCurrentContext() == null) { logger.error("getImage(): no context " + Logger.dumpStack()); } if (cachedImages.containsKey(url)) return (Image)cachedImages.get(url); Image newImage = createImage(url); if (newImage != null) cachedImages.put(url, newImage); return newImage; } public Image createImage(String filename) { if (BDJXletContext.getCurrentContext() == null) { logger.error("createImage(): no context " + Logger.dumpStack()); } if (!new File(filename).isAbsolute()) { String home = BDJXletContext.getCurrentXletHome(); if (home != null) { String homeFile = home + filename; if (new File(homeFile).exists()) { logger.warning("resource translated to " + homeFile); filename = homeFile; } else { logger.error("resource " + homeFile + " does not exist"); } } } ImageProducer ip = new FileImageSource(filename); Image newImage = createImage(ip); return newImage; } public Image createImage(URL url) { if (BDJXletContext.getCurrentContext() == null) { logger.error("createImage(): no context " + Logger.dumpStack()); } ImageProducer ip = new URLImageSource(url); Image newImage = createImage(ip); return newImage; } public Image createImage(byte[] imagedata, int imageoffset, int imagelength) { if (BDJXletContext.getCurrentContext() == null) { logger.error("createImage(): no context " + Logger.dumpStack()); } ImageProducer ip = new ByteArrayImageSource(imagedata, imageoffset, imagelength); Image newImage = createImage(ip); return newImage; } public Image createImage(ImageProducer producer) { if (BDJXletContext.getCurrentContext() == null) { logger.error("createImage(): no context " + Logger.dumpStack()); } return new BDImageConsumer(producer); } public Image createImage(Component component, int width, int height) { return new BDImage(component, width, height, defaultGC); } public boolean prepareImage(Image image, int width, int height, ImageObserver observer) { if (!(image instanceof BDImageConsumer)) return true; BDImageConsumer img = (BDImageConsumer)image; return img.prepareImage(observer); } public int checkImage(Image image, int width, int height, ImageObserver observer) { if (!(image instanceof BDImageConsumer)) { return ImageObserver.ALLBITS; } BDImageConsumer img = (BDImageConsumer)image; return img.checkImage(observer); } public void beep() { } public static void addComponent(Component component) { BDJXletContext context = BDJXletContext.getCurrentContext(); if (context == null) { logger.warning("addComponent() outside of app context"); return; } contextMap.put(component, context); } public static EventQueue getEventQueue(Component component) { if (component != null) { do { BDJXletContext ctx = (BDJXletContext)contextMap.get(component); if (ctx != null) { EventQueue eq = ctx.getEventQueue(); if (eq == null) { logger.warning("getEventQueue() failed: no context event queue"); } return eq; } component = component.getParent(); } while (component != null); logger.warning("getEventQueue() failed: no context"); return null; } logger.warning("getEventQueue() failed: no component"); return null; } protected EventQueue getSystemEventQueueImpl() { BDJXletContext ctx = BDJXletContext.getCurrentContext(); if (ctx != null) { EventQueue eq = ctx.getEventQueue(); if (eq != null) { return eq; } } logger.warning("getSystemEventQueue(): no context from:" + logger.dumpStack()); return eventQueue; } }
lgpl-2.1
Sackboy132/TheOrdinaryMod
src/main/java/com/Sackboy/TOM/init/TOMMobs.java
1060
package com.Sackboy.TOM.init; import com.Sackboy.TOM.TOM; import com.Sackboy.TOM.mob.EntityCardboardBox; import com.Sackboy.TOM.mob.EntityCrawler; import com.Sackboy.TOM.mob.EntityJoiter; import net.minecraft.entity.EnumCreatureType; import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.fml.common.registry.EntityRegistry; public class TOMMobs { // TODO: Finish up on mob AI and sizes public static void register() { createEntity(EntityCrawler.class, "Crawler", 0x175D5A, 0x9E1C1C); createEntity(EntityJoiter.class, "Joiter", 0x406533, 0xF38727); createEntity(EntityCardboardBox.class, "Cardboard Box", 0x406533, 0xF38727); } public static void createEntity(Class entity, String name, int solid, int spot) { int rand = EntityRegistry.findGlobalUniqueEntityId(); EntityRegistry.registerGlobalEntityID(entity, name, rand); EntityRegistry.registerModEntity(entity, name, rand, TOM.INSTANCE, 64, 1, false, solid, spot); EntityRegistry.addSpawn(entity, 10, 1, 2, EnumCreatureType.MONSTER, BiomeGenBase.getBiome(4)); } }
lgpl-2.1
OOjDREW/OOjDREW
src/main/java/org/ruleml/oojdrew/Builtins/StringEqualIgnoreCaseBuiltin.java
3031
// OO jDREW - An Object Oriented extension of the Java Deductive Reasoning Engine for the Web // Copyright (C) 2005 Marcel Ball // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA package org.ruleml.oojdrew.Builtins; import java.util.Vector; import org.ruleml.oojdrew.util.DefiniteClause; import org.ruleml.oojdrew.util.SymbolTable; import org.ruleml.oojdrew.util.Term; import org.ruleml.oojdrew.util.Types; /** * Implements a String Equal Ignore Case built-in relation. * * Calling format stringEqualIgnoreCase(?input1, ?input2). * * Satisfied iff the first argument is the same as the second * argument (upper/lower case ignored) * * <p>Title: OO jDREW</p> * * <p>Description: Reasoning Engine for the Semantic Web - Supporting OO RuleML * 0.88</p> * * <p>Copyright: Copyright (c) 2005</p> * * @author Marcel A. Ball * @version 0.89 */ public class StringEqualIgnoreCaseBuiltin implements Builtin { private int symbol = SymbolTable.internSymbol("stringEqualIgnoreCase"); public DefiniteClause buildResult(Term t) { if (t.getSymbol() != symbol) { return null; } if (t.subTerms.length != 3) { return null; } Term p1 = t.subTerms[1].deepCopy(); Term p2 = t.subTerms[2].deepCopy(); if (p1.getSymbol() < 0 || p2.getSymbol() < 0) { return null; } if (p1.getType() != Types.ISTRING || p2.getType() != Types.ISTRING) { return null; } String p1s = p1.getSymbolString(); String p2s = p2.getSymbolString(); if (!p1s.equalsIgnoreCase(p2s)) { return null; } Term roid = new Term(SymbolTable.internSymbol("$jdrew-strequalIC-" + p1s + "=" + p2s), SymbolTable.IOID, Types.ITHING); Vector v = new Vector(); v.add(roid); v.add(p1); v.add(p2); Term atm = new Term(symbol, SymbolTable.INOROLE, Types.IOBJECT, v); atm.setAtom(true); Vector v2 = new Vector(); v2.add(atm); return new DefiniteClause(v2, new Vector()); } public int getSymbol() { return symbol; } }
lgpl-2.1
lyohytch/FORVER2---Converter
query/mssqlquery.h
3409
#ifndef MSSQLQUERY_H #define MSSQLQUERY_H #include <QSqlDatabase> #include <QRunnable> #include "querymodel.h" //! mssqlquery запись сформированных SQL-запросов в базу данных /** * Класс для записи сформированных SQL-запросов классом querymodel в базу данных. Класс работает асинхронно, по завершении * работы выводится сообщение о результате добавления в базу данных. При отсутсвии нужно базы данных, она создаётся. При * отсутствии нужных таблиц, они пересоздаются. * \note Для установления собственных настроек нужно добавить в файле настроек "converter.ini" следующие строки \n * [SQL_Server_Settings] \n * Server=localhost\\SQLEXPRESS \n * Database=CrimDB \n * User=sa \n * Password=NNSU \n * Также следует учесть, что устанавливаемый здесь пользователь должен иметь соответствующие права для создания базы данных * и добавления таблиц, а также добавление в них данных. * \sa querymodel */ class mssqlquery : public QObject, public QRunnable { Q_OBJECT public: /** * Конструктор по-умолчанию * \param parent указатель на родительский объект * \param model указатель на querymodel */ mssqlquery(QObject* parent = 0, querymodel* model = 0); /** * Преобразованные SQL-строки для добавления в базу данных */ querymodel* queryModel; /** * Список SQL-запросов для добавления в базу данных */ QStringList iListofRequests; /** * Список SQL-запросов для создания новых таблиц в базе данных */ QVariantMap createRequestList; /** * Список SQL-запросов для удаления таблиц из базы данных */ QVariantMap removeRequestList; /** * Асинхронный запуск процедуры добавления данных в базу данных */ virtual void run(); signals: /** * Сигнал о завершении опереации добавления данных в базу данных * \param aError номер ошибки. 0 - отсутсвие ошибки * \param errStr сообщение об ошибке или "SUCCESS" */ void complete(int aError, QString errStr); private: bool execRequest(QSqlDatabase& db, const QString& requestString); bool checkAllTablesInDB(const QStringList& tables); bool makeRequests(QSqlDatabase& db); //String read from ini file QString serverName; QString dbName; QString uidName; QString pwdUid; QString dbPath; }; #endif // MSSQLQUERY_H
lgpl-2.1
enricoros/k-qt-creator-inspector
src/plugins/inspector/nokiaqtbackend/info/infopanel.h
1811
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009-2010 Enrico Ros ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #ifndef INFOPANEL_H #define INFOPANEL_H #include "abstractpanel.h" #include "ui_infopanel.h" namespace Inspector { namespace Internal { class InfoPanel : public AbstractPanel, public Ui::InfoPanel { Q_OBJECT public: InfoPanel(IBackendModule *parentModule); QString helpHtml() const; private slots: void slotRefreshInspectionData(); void slotRowsInserted(const QModelIndex &parent, int start, int end); private: void setFieldState(QWidget *field, int state); QPixmap m_okPixmap; QPixmap m_errorPixmap; }; } // namespace Internal } // namespace Inspector #endif // INFOPANEL_H
lgpl-2.1
markroxor/gensim
gensim/models/fasttext.py
29942
#!/usr/bin/env python # -*- coding: utf-8 -*- # Authors: Chinmaya Pancholi <chinmayapancholi13@gmail.com>, Shiva Manne <s.manne@rare-technologies.com> # Copyright (C) 2017 RaRe Technologies s.r.o. """Learn word representations via fasttext's "skip-gram and CBOW models", using either hierarchical softmax or negative sampling [1]_. Notes ----- There are more ways to get word vectors in Gensim than just FastText. See wrappers for VarEmbed and WordRank or Word2Vec This module allows training a word embedding from a training corpus with the additional ability to obtain word vectors for out-of-vocabulary words. For a tutorial on gensim's native fasttext, refer to the noteboook -- [2]_ **Make sure you have a C compiler before installing gensim, to use optimized (compiled) fasttext training** .. [1] P. Bojanowski, E. Grave, A. Joulin, T. Mikolov Enriching Word Vectors with Subword Information. In arXiv preprint arXiv:1607.04606. https://arxiv.org/abs/1607.04606 .. [2] https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/FastText_Tutorial.ipynb """ import logging import numpy as np from numpy import zeros, ones, vstack, sum as np_sum, empty, float32 as REAL from gensim.models.word2vec import Word2Vec, train_sg_pair, train_cbow_pair from gensim.models.wrappers.fasttext import FastTextKeyedVectors from gensim.models.wrappers.fasttext import FastText as Ft_Wrapper, compute_ngrams, ft_hash logger = logging.getLogger(__name__) try: from gensim.models.fasttext_inner import train_batch_sg, train_batch_cbow from gensim.models.fasttext_inner import FAST_VERSION, MAX_WORDS_IN_BATCH logger.debug('Fast version of Fasttext is being used') except ImportError: # failed... fall back to plain numpy (20-80x slower training than the above) logger.warning('Slow version of Fasttext is being used') FAST_VERSION = -1 MAX_WORDS_IN_BATCH = 10000 def train_batch_cbow(model, sentences, alpha, work=None, neu1=None): """Update CBOW model by training on a sequence of sentences. Each sentence is a list of string tokens, which are looked up in the model's vocab dictionary. Called internally from :meth:`gensim.models.fasttext.FastText.train()`. This is the non-optimized, Python version. If you have cython installed, gensim will use the optimized version from fasttext_inner instead. Parameters ---------- model : :class:`~gensim.models.fasttext.FastText` `FastText` instance. sentences : iterable of iterables Iterable of the sentences directly from disk/network. alpha : float Learning rate. work : :class:`numpy.ndarray` Private working memory for each worker. neu1 : :class:`numpy.ndarray` Private working memory for each worker. Returns ------- int Effective number of words trained. """ result = 0 for sentence in sentences: word_vocabs = [model.wv.vocab[w] for w in sentence if w in model.wv.vocab and model.wv.vocab[w].sample_int > model.random.rand() * 2**32] for pos, word in enumerate(word_vocabs): reduced_window = model.random.randint(model.window) start = max(0, pos - model.window + reduced_window) window_pos = enumerate(word_vocabs[start:(pos + model.window + 1 - reduced_window)], start) word2_indices = [word2.index for pos2, word2 in window_pos if (word2 is not None and pos2 != pos)] word2_subwords = [] vocab_subwords_indices = [] ngrams_subwords_indices = [] for index in word2_indices: vocab_subwords_indices += [index] word2_subwords += model.wv.ngrams_word[model.wv.index2word[index]] for subword in word2_subwords: ngrams_subwords_indices.append(model.wv.ngrams[subword]) l1_vocab = np_sum(model.wv.syn0_vocab[vocab_subwords_indices], axis=0) # 1 x vector_size l1_ngrams = np_sum(model.wv.syn0_ngrams[ngrams_subwords_indices], axis=0) # 1 x vector_size l1 = np_sum([l1_vocab, l1_ngrams], axis=0) subwords_indices = [vocab_subwords_indices] + [ngrams_subwords_indices] if (subwords_indices[0] or subwords_indices[1]) and model.cbow_mean: l1 /= (len(subwords_indices[0]) + len(subwords_indices[1])) # train on the sliding window for target word train_cbow_pair(model, word, subwords_indices, l1, alpha, is_ft=True) result += len(word_vocabs) return result def train_batch_sg(model, sentences, alpha, work=None, neu1=None): """Update skip-gram model by training on a sequence of sentences. Each sentence is a list of string tokens, which are looked up in the model's vocab dictionary. Called internally from :meth:`gensim.models.fasttext.FastText.train()`. This is the non-optimized, Python version. If you have cython installed, gensim will use the optimized version from fasttext_inner instead. Parameters ---------- model : :class:`~gensim.models.fasttext.FastText` `FastText` instance. sentences : iterable of iterables Iterable of the sentences directly from disk/network. alpha : float Learning rate. work : :class:`numpy.ndarray` Private working memory for each worker. neu1 : :class:`numpy.ndarray` Private working memory for each worker. Returns ------- int Effective number of words trained. """ result = 0 for sentence in sentences: word_vocabs = [model.wv.vocab[w] for w in sentence if w in model.wv.vocab and model.wv.vocab[w].sample_int > model.random.rand() * 2**32] for pos, word in enumerate(word_vocabs): reduced_window = model.random.randint(model.window) # `b` in the original word2vec code # now go over all words from the (reduced) window, predicting each one in turn start = max(0, pos - model.window + reduced_window) subwords_indices = [word.index] word2_subwords = model.wv.ngrams_word[model.wv.index2word[word.index]] for subword in word2_subwords: subwords_indices.append(model.wv.ngrams[subword]) for pos2, word2 in enumerate(word_vocabs[start:(pos + model.window + 1 - reduced_window)], start): if pos2 != pos: # don't train on the `word` itself train_sg_pair(model, model.wv.index2word[word2.index], subwords_indices, alpha, is_ft=True) result += len(word_vocabs) return result class FastText(Word2Vec): """Class for training, using and evaluating word representations learned using method described in [1]_ aka Fasttext. The model can be stored/loaded via its :meth:`~gensim.models.fasttext.FastText.save()` and :meth:`~gensim.models.fasttext.FastText.load()` methods, or loaded in a format compatible with the original fasttext implementation via :meth:`~gensim.models.fasttext.FastText.load_fasttext_format()`. """ def __init__( self, sentences=None, sg=0, hs=0, size=100, alpha=0.025, window=5, min_count=5, max_vocab_size=None, word_ngrams=1, sample=1e-3, seed=1, workers=3, min_alpha=0.0001, negative=5, cbow_mean=1, hashfxn=hash, iter=5, null_word=0, min_n=3, max_n=6, sorted_vocab=1, bucket=2000000, trim_rule=None, batch_words=MAX_WORDS_IN_BATCH): """Initialize the model from an iterable of `sentences`. Each sentence is a list of words (unicode strings) that will be used for training. Parameters ---------- sentences : iterable of iterables The `sentences` iterable can be simply a list of lists of tokens, but for larger corpora, consider an iterable that streams the sentences directly from disk/network. See :class:`~gensim.models.word2vec.BrownCorpus`, :class:`~gensim.models.word2vec.Text8Corpus` or :class:`~gensim.models.word2vec.LineSentence` in :mod:`~gensim.models.word2vec` module for such examples. If you don't supply `sentences`, the model is left uninitialized -- use if you plan to initialize it in some other way. sg : int {1, 0} Defines the training algorithm. If 1, CBOW is used, otherwise, skip-gram is employed. size : int Dimensionality of the feature vectors. window : int The maximum distance between the current and predicted word within a sentence. alpha : float The initial learning rate. min_alpha : float Learning rate will linearly drop to `min_alpha` as training progresses. seed : int Seed for the random number generator. Initial vectors for each word are seeded with a hash of the concatenation of word + `str(seed)`. Note that for a fully deterministically-reproducible run, you must also limit the model to a single worker thread (`workers=1`), to eliminate ordering jitter from OS thread scheduling. (In Python 3, reproducibility between interpreter launches also requires use of the `PYTHONHASHSEED` environment variable to control hash randomization). min_count : int Ignores all words with total frequency lower than this. max_vocab_size : int Limits the RAM during vocabulary building; if there are more unique words than this, then prune the infrequent ones. Every 10 million word types need about 1GB of RAM. Set to `None` for no limit. sample : float The threshold for configuring which higher-frequency words are randomly downsampled, useful range is (0, 1e-5). workers : int Use these many worker threads to train the model (=faster training with multicore machines). hs : int {1,0} If 1, hierarchical softmax will be used for model training. If set to 0, and `negative` is non-zero, negative sampling will be used. negative : int If > 0, negative sampling will be used, the int for negative specifies how many "noise words" should be drawn (usually between 5-20). If set to 0, no negative sampling is used. cbow_mean : int {1,0} If 0, use the sum of the context word vectors. If 1, use the mean, only applies when cbow is used. hashfxn : function Hash function to use to randomly initialize weights, for increased training reproducibility. iter : int Number of iterations (epochs) over the corpus. trim_rule : function Vocabulary trimming rule, specifies whether certain words should remain in the vocabulary, be trimmed away, or handled using the default (discard if word count < min_count). Can be None (min_count will be used, look to :func:`~gensim.utils.keep_vocab_item`), or a callable that accepts parameters (word, count, min_count) and returns either :attr:`gensim.utils.RULE_DISCARD`, :attr:`gensim.utils.RULE_KEEP` or :attr:`gensim.utils.RULE_DEFAULT`. Note: The rule, if given, is only used to prune vocabulary during build_vocab() and is not stored as part of the model. sorted_vocab : int {1,0} If 1, sort the vocabulary by descending frequency before assigning word indexes. batch_words : int Target size (in words) for batches of examples passed to worker threads (and thus cython routines).(Larger batches will be passed if individual texts are longer than 10000 words, but the standard cython code truncates to that maximum.) min_n : int Min length of char ngrams to be used for training word representations. max_n : int Max length of char ngrams to be used for training word representations. Set `max_n` to be lesser than `min_n` to avoid char ngrams being used. word_ngrams : int {1,0} If 1, uses enriches word vectors with subword(ngrams) information. If 0, this is equivalent to word2vec. bucket : int Character ngrams are hashed into a fixed number of buckets, in order to limit the memory usage of the model. This option specifies the number of buckets used by the model. Examples -------- Initialize and train a `FastText` model >>> from gensim.models import FastText >>> sentences = [["cat", "say", "meow"], ["dog", "say", "woof"]] >>> >>> model = FastText(sentences, min_count=1) >>> say_vector = model['say'] # get vector for word >>> of_vector = model['of'] # get vector for out-of-vocab word """ # fastText specific params self.bucket = bucket self.word_ngrams = word_ngrams self.min_n = min_n self.max_n = max_n if self.word_ngrams <= 1 and self.max_n == 0: self.bucket = 0 super(FastText, self).__init__( sentences=sentences, size=size, alpha=alpha, window=window, min_count=min_count, max_vocab_size=max_vocab_size, sample=sample, seed=seed, workers=workers, min_alpha=min_alpha, sg=sg, hs=hs, negative=negative, cbow_mean=cbow_mean, hashfxn=hashfxn, iter=iter, null_word=null_word, trim_rule=trim_rule, sorted_vocab=sorted_vocab, batch_words=batch_words) def initialize_word_vectors(self): """Initializes FastTextKeyedVectors instance to store all vocab/ngram vectors for the model.""" self.wv = FastTextKeyedVectors() self.wv.min_n = self.min_n self.wv.max_n = self.max_n def build_vocab(self, sentences, keep_raw_vocab=False, trim_rule=None, progress_per=10000, update=False): """Build vocabulary from a sequence of sentences (can be a once-only generator stream). Each sentence must be a list of unicode strings. Parameters ---------- sentences : iterable of iterables The `sentences` iterable can be simply a list of lists of tokens, but for larger corpora, consider an iterable that streams the sentences directly from disk/network. See :class:`~gensim.models.word2vec.BrownCorpus`, :class:`~gensim.models.word2vec.Text8Corpus` or :class:`~gensim.models.word2vec.LineSentence` in :mod:`~gensim.models.word2vec` module for such examples. keep_raw_vocab : bool If not true, delete the raw vocabulary after the scaling is done and free up RAM. trim_rule : function Vocabulary trimming rule, specifies whether certain words should remain in the vocabulary, be trimmed away, or handled using the default (discard if word count < min_count). Can be None (min_count will be used, look to :func:`~gensim.utils.keep_vocab_item`), or a callable that accepts parameters (word, count, min_count) and returns either :attr:`gensim.utils.RULE_DISCARD`, :attr:`gensim.utils.RULE_KEEP` or :attr:`gensim.utils.RULE_DEFAULT`. Note: The rule, if given, is only used to prune vocabulary during build_vocab() and is not stored as part of the model. progress_per : int Indicates how many words to process before showing/updating the progress. update: bool If true, the new words in `sentences` will be added to model's vocab. Example ------- Train a model and update vocab for online training >>> from gensim.models import FastText >>> sentences_1 = [["cat", "say", "meow"], ["dog", "say", "woof"]] >>> sentences_2 = [["dude", "say", "wazzup!"]] >>> >>> model = FastText(min_count=1) >>> model.build_vocab(sentences_1) >>> model.train(sentences_1, total_examples=model.corpus_count, epochs=model.iter) >>> model.build_vocab(sentences_2, update=True) >>> model.train(sentences_2, total_examples=model.corpus_count, epochs=model.iter) """ if update: if not len(self.wv.vocab): raise RuntimeError( "You cannot do an online vocabulary-update of a model which has no prior vocabulary. " "First build the vocabulary of your model with a corpus " "before doing an online update.") self.old_vocab_len = len(self.wv.vocab) self.old_hash2index_len = len(self.wv.hash2index) super(FastText, self).build_vocab( sentences, keep_raw_vocab=keep_raw_vocab, trim_rule=trim_rule, progress_per=progress_per, update=update) self.init_ngrams(update=update) def init_ngrams(self, update=False): """Compute ngrams of all words present in vocabulary and stores vectors for only those ngrams. Vectors for other ngrams are initialized with a random uniform distribution in FastText. Parameters ---------- update : bool If True, the new vocab words and their new ngrams word vectors are initialized with random uniform distribution and updated/added to the existing vocab word and ngram vectors. """ if not update: self.wv.ngrams = {} self.wv.syn0_vocab = empty((len(self.wv.vocab), self.vector_size), dtype=REAL) self.syn0_vocab_lockf = ones((len(self.wv.vocab), self.vector_size), dtype=REAL) self.wv.syn0_ngrams = empty((self.bucket, self.vector_size), dtype=REAL) self.syn0_ngrams_lockf = ones((self.bucket, self.vector_size), dtype=REAL) all_ngrams = [] for w, v in self.wv.vocab.items(): self.wv.ngrams_word[w] = compute_ngrams(w, self.min_n, self.max_n) all_ngrams += self.wv.ngrams_word[w] all_ngrams = list(set(all_ngrams)) self.num_ngram_vectors = len(all_ngrams) logger.info("Total number of ngrams is %d", len(all_ngrams)) self.wv.hash2index = {} ngram_indices = [] new_hash_count = 0 for i, ngram in enumerate(all_ngrams): ngram_hash = ft_hash(ngram) % self.bucket if ngram_hash in self.wv.hash2index: self.wv.ngrams[ngram] = self.wv.hash2index[ngram_hash] else: ngram_indices.append(ngram_hash % self.bucket) self.wv.hash2index[ngram_hash] = new_hash_count self.wv.ngrams[ngram] = self.wv.hash2index[ngram_hash] new_hash_count = new_hash_count + 1 self.wv.syn0_ngrams = self.wv.syn0_ngrams.take(ngram_indices, axis=0) self.syn0_ngrams_lockf = self.syn0_ngrams_lockf.take(ngram_indices, axis=0) self.reset_ngram_weights() else: new_ngrams = [] for w, v in self.wv.vocab.items(): self.wv.ngrams_word[w] = compute_ngrams(w, self.min_n, self.max_n) new_ngrams += [ng for ng in self.wv.ngrams_word[w] if ng not in self.wv.ngrams] new_ngrams = list(set(new_ngrams)) logger.info("Number of new ngrams is %d", len(new_ngrams)) new_hash_count = 0 for i, ngram in enumerate(new_ngrams): ngram_hash = ft_hash(ngram) % self.bucket if ngram_hash not in self.wv.hash2index: self.wv.hash2index[ngram_hash] = new_hash_count + self.old_hash2index_len self.wv.ngrams[ngram] = self.wv.hash2index[ngram_hash] new_hash_count = new_hash_count + 1 else: self.wv.ngrams[ngram] = self.wv.hash2index[ngram_hash] rand_obj = np.random rand_obj.seed(self.seed) new_vocab_rows = rand_obj.uniform( -1.0 / self.vector_size, 1.0 / self.vector_size, (len(self.wv.vocab) - self.old_vocab_len, self.vector_size) ).astype(REAL) new_vocab_lockf_rows = ones((len(self.wv.vocab) - self.old_vocab_len, self.vector_size), dtype=REAL) new_ngram_rows = rand_obj.uniform( -1.0 / self.vector_size, 1.0 / self.vector_size, (len(self.wv.hash2index) - self.old_hash2index_len, self.vector_size) ).astype(REAL) new_ngram_lockf_rows = ones( (len(self.wv.hash2index) - self.old_hash2index_len, self.vector_size), dtype=REAL) self.wv.syn0_vocab = vstack([self.wv.syn0_vocab, new_vocab_rows]) self.syn0_vocab_lockf = vstack([self.syn0_vocab_lockf, new_vocab_lockf_rows]) self.wv.syn0_ngrams = vstack([self.wv.syn0_ngrams, new_ngram_rows]) self.syn0_ngrams_lockf = vstack([self.syn0_ngrams_lockf, new_ngram_lockf_rows]) def reset_ngram_weights(self): """Reset all projection weights to an initial (untrained) state, but keep the existing vocabulary and their ngrams. """ rand_obj = np.random rand_obj.seed(self.seed) for index in range(len(self.wv.vocab)): self.wv.syn0_vocab[index] = rand_obj.uniform( -1.0 / self.vector_size, 1.0 / self.vector_size, self.vector_size ).astype(REAL) for index in range(len(self.wv.hash2index)): self.wv.syn0_ngrams[index] = rand_obj.uniform( -1.0 / self.vector_size, 1.0 / self.vector_size, self.vector_size ).astype(REAL) def _do_train_job(self, sentences, alpha, inits): """Train a single batch of sentences. Return 2-tuple `(effective word count after ignoring unknown words and sentence length trimming, total word count)`. Parameters ---------- sentences : iterable of iterables The `sentences` iterable can be simply a list of lists of tokens, but for larger corpora, consider an iterable that streams the sentences directly from disk/network. See :class:`~gensim.models.word2vec.BrownCorpus`, :class:`~gensim.models.word2vec.Text8Corpus` or :class:`~gensim.models.word2vec.LineSentence` in :mod:`~gensim.models.word2vec` module for such examples. alpha : float The current learning rate. inits : (:class:`numpy.ndarray`, :class:`numpy.ndarray`) Each worker's private work memory. Returns ------- (int, int) Tuple of (effective word count after ignoring unknown words and sentence length trimming, total word count) """ work, neu1 = inits tally = 0 if self.sg: tally += train_batch_sg(self, sentences, alpha, work, neu1) else: tally += train_batch_cbow(self, sentences, alpha, work, neu1) return tally, self._raw_word_count(sentences) def train(self, sentences, total_examples=None, total_words=None, epochs=None, start_alpha=None, end_alpha=None, word_count=0, queue_factor=2, report_delay=1.0): """Update the model's neural weights from a sequence of sentences (can be a once-only generator stream). For FastText, each sentence must be a list of unicode strings. (Subclasses may accept other examples.) To support linear learning-rate decay from (initial) alpha to min_alpha, and accurate progress-percentage logging, either total_examples (count of sentences) or total_words (count of raw words in sentences) **MUST** be provided (if the corpus is the same as was provided to :meth:`~gensim.models.fasttext.FastText.build_vocab()`, the count of examples in that corpus will be available in the model's :attr:`corpus_count` property). To avoid common mistakes around the model's ability to do multiple training passes itself, an explicit `epochs` argument **MUST** be provided. In the common and recommended case, where :meth:`~gensim.models.fasttext.FastText.train()` is only called once, the model's cached `iter` value should be supplied as `epochs` value. Parameters ---------- sentences : iterable of iterables The `sentences` iterable can be simply a list of lists of tokens, but for larger corpora, consider an iterable that streams the sentences directly from disk/network. See :class:`~gensim.models.word2vec.BrownCorpus`, :class:`~gensim.models.word2vec.Text8Corpus` or :class:`~gensim.models.word2vec.LineSentence` in :mod:`~gensim.models.word2vec` module for such examples. total_examples : int Count of sentences. total_words : int Count of raw words in sentences. epochs : int Number of iterations (epochs) over the corpus. start_alpha : float Initial learning rate. end_alpha : float Final learning rate. Drops linearly from `start_alpha`. word_count : int Count of words already trained. Set this to 0 for the usual case of training on all words in sentences. queue_factor : int Multiplier for size of queue (number of workers * queue_factor). report_delay : float Seconds to wait before reporting progress. Examples -------- >>> from gensim.models import FastText >>> sentences = [["cat", "say", "meow"], ["dog", "say", "woof"]] >>> >>> model = FastText(min_count=1) >>> model.build_vocab(sentences) >>> model.train(sentences, total_examples=model.corpus_count, epochs=model.iter) """ self.neg_labels = [] if self.negative > 0: # precompute negative labels optimization for pure-python training self.neg_labels = zeros(self.negative + 1) self.neg_labels[0] = 1. Word2Vec.train( self, sentences, total_examples=self.corpus_count, epochs=self.iter, start_alpha=self.alpha, end_alpha=self.min_alpha) self.get_vocab_word_vecs() def __getitem__(self, word): """Get `word` representations in vector space, as a 1D numpy array. Parameters ---------- word : str A single word whose vector needs to be returned. Returns ------- :class:`numpy.ndarray` The word's representations in vector space, as a 1D numpy array. Raises ------ KeyError For words with all ngrams absent, a KeyError is raised. Example ------- >>> from gensim.models import FastText >>> from gensim.test.utils import datapath >>> >>> trained_model = FastText.load_fasttext_format(datapath('lee_fasttext')) >>> meow_vector = trained_model['hello'] # get vector for word """ return self.word_vec(word) def get_vocab_word_vecs(self): """Calculate vectors for words in vocabulary and stores them in `wv.syn0`.""" for w, v in self.wv.vocab.items(): word_vec = np.copy(self.wv.syn0_vocab[v.index]) ngrams = self.wv.ngrams_word[w] ngram_weights = self.wv.syn0_ngrams for ngram in ngrams: word_vec += ngram_weights[self.wv.ngrams[ngram]] word_vec /= (len(ngrams) + 1) self.wv.syn0[v.index] = word_vec def word_vec(self, word, use_norm=False): """Get the word's representations in vector space, as a 1D numpy array. Parameters ---------- word : str A single word whose vector needs to be returned. use_norm : bool If True, returns normalized vector. Returns ------- :class:`numpy.ndarray` The word's representations in vector space, as a 1D numpy array. Raises ------ KeyError For words with all ngrams absent, a KeyError is raised. Example ------- >>> from gensim.models import FastText >>> sentences = [["cat", "say", "meow"], ["dog", "say", "woof"]] >>> >>> model = FastText(sentences, min_count=1) >>> meow_vector = model.word_vec('meow') # get vector for word """ return FastTextKeyedVectors.word_vec(self.wv, word, use_norm=use_norm) @classmethod def load_fasttext_format(cls, *args, **kwargs): """Load a :class:`~gensim.models.fasttext.FastText` model from a format compatible with the original fasttext implementation. Parameters ---------- fname : str Path to the file. """ return Ft_Wrapper.load_fasttext_format(*args, **kwargs) def save(self, *args, **kwargs): """Save the model. This saved model can be loaded again using :func:`~gensim.models.fasttext.FastText.load`, which supports online training and getting vectors for out-of-vocabulary words. Parameters ---------- fname : str Path to the file. """ kwargs['ignore'] = kwargs.get('ignore', ['syn0norm', 'syn0_vocab_norm', 'syn0_ngrams_norm']) super(FastText, self).save(*args, **kwargs)
lgpl-2.1
UWCS/choob
src/main/java/uk/co/uwcs/choob/plugins/package.html
108
<body> <p>Provides features relevant to plugins.</p> <p>This consists mainly of plugin managers.</p> </body>
lgpl-2.1
exxcellent/wings3
wingx/src/java/org/wingx/XPageScroller.java
3484
package org.wingx; import org.wings.*; import org.wings.border.SLineBorder; import org.wingx.plaf.css.XPageScrollerCG; import java.awt.*; import java.awt.event.AdjustmentListener; public class XPageScroller extends SContainer implements Adjustable { SPageScroller pageScroller = new SPageScroller(Adjustable.VERTICAL); private GridBagConstraints c = new GridBagConstraints(); public XPageScroller() { super(new SGridBagLayout()); SLineBorder border = new SLineBorder(new Color(200, 200, 200), 0); border.setThickness(1, SConstants.TOP); setBorder(border); setPreferredSize(SDimension.FULLWIDTH); c.anchor = GridBagConstraints.EAST; add(pageScroller); pageScroller.setCG(new XPageScrollerCG()); pageScroller.setLayoutMode(Adjustable.HORIZONTAL); pageScroller.setDirectPages(5); pageScroller.setShowAsFormComponent(false); } public SComponent add(SComponent component) { c.weightx = 0d; component.setVerticalAlignment(SConstants.CENTER_ALIGN); return super.addComponent(component, c); } public SComponent add(SComponent component, double weight) { c.weightx = weight; return super.addComponent(component, c); } public void reset(int total) { while (getComponentCount() > 1) { remove(1); } normalize(total); } public void normalize(int total) { int value = pageScroller.getValue(); int visible = pageScroller.getVisibleAmount(); if (value + visible > total) { value = Math.max(0, total - visible); pageScroller.setValue(value); } } public void setUnitIncrement(int i) { pageScroller.setUnitIncrement(i); } public void setBlockIncrement(int i) { pageScroller.setBlockIncrement(i); } public int getUnitIncrement() { return pageScroller.getUnitIncrement(); } public int getBlockIncrement() { return pageScroller.getBlockIncrement(); } public int getValue() { return pageScroller.getValue(); } public void setExtent(int value) { pageScroller.setExtent(value); } public int getVisibleAmount() { return pageScroller.getVisibleAmount(); } public void setVisibleAmount(int i) { pageScroller.setVisibleAmount(i); } public int getMinimum() { return pageScroller.getMinimum(); } public void setMinimum(int i) { pageScroller.setMinimum(i); } public int getMaximum() { return pageScroller.getMaximum(); } public void setMaximum(int i) { pageScroller.setMaximum(i); } public int getOrientation() { return pageScroller.getOrientation(); } public void setValue(int i) { pageScroller.setValue(i); } public void addAdjustmentListener(AdjustmentListener adjustmentListener) { pageScroller.addAdjustmentListener(adjustmentListener); } public void removeAdjustmentListener(AdjustmentListener adjustmentListener) { pageScroller.removeAdjustmentListener(adjustmentListener); } public SPageScroller getPageScroller() { return pageScroller; } public SBoundedRangeModel getModel() { return pageScroller.getModel(); } public void setModel(SBoundedRangeModel newModel) { pageScroller.setModel(newModel); } }
lgpl-2.1
cajus/qpid-cpp-store-debian
lib/JournalImpl.cpp
23571
/* Copyright (c) 2007, 2008, 2009, 2010 Red Hat, Inc. This file is part of the Qpid async store library msgstore.so. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA The GNU Lesser General Public License is available in the file COPYING. */ #include "JournalImpl.h" #include "jrnl/jerrno.hpp" #include "jrnl/jexception.hpp" #include "qpid/log/Statement.h" #include "qpid/management/ManagementAgent.h" #include "qmf/com/redhat/rhm/store/ArgsJournalExpand.h" #include "qmf/com/redhat/rhm/store/EventCreated.h" #include "qmf/com/redhat/rhm/store/EventEnqThresholdExceeded.h" #include "qmf/com/redhat/rhm/store/EventFull.h" #include "qmf/com/redhat/rhm/store/EventRecovered.h" #include "qpid/sys/Monitor.h" #include "qpid/sys/Timer.h" #include "StoreException.h" using namespace mrg::msgstore; using namespace mrg::journal; using qpid::management::ManagementAgent; namespace _qmf = qmf::com::redhat::rhm::store; InactivityFireEvent::InactivityFireEvent(JournalImpl* p, const qpid::sys::Duration timeout): qpid::sys::TimerTask(timeout, "JournalInactive:"+p->id()), _parent(p) {} void InactivityFireEvent::fire() { qpid::sys::Mutex::ScopedLock sl(_ife_lock); if (_parent) _parent->flushFire(); } GetEventsFireEvent::GetEventsFireEvent(JournalImpl* p, const qpid::sys::Duration timeout): qpid::sys::TimerTask(timeout, "JournalGetEvents:"+p->id()), _parent(p) {} void GetEventsFireEvent::fire() { qpid::sys::Mutex::ScopedLock sl(_gefe_lock); if (_parent) _parent->getEventsFire(); } JournalImpl::JournalImpl(qpid::sys::Timer& timer_, const std::string& journalId, const std::string& journalDirectory, const std::string& journalBaseFilename, const qpid::sys::Duration getEventsTimeout, const qpid::sys::Duration flushTimeout, qpid::management::ManagementAgent* a, DeleteCallback onDelete): jcntl(journalId, journalDirectory, journalBaseFilename), timer(timer_), getEventsTimerSetFlag(false), lastReadRid(0), writeActivityFlag(false), flushTriggeredFlag(true), _xidp(0), _datap(0), _dlen(0), _dtok(), _external(false), _mgmtObject(0), deleteCallback(onDelete) { getEventsFireEventsPtr = new GetEventsFireEvent(this, getEventsTimeout); inactivityFireEventPtr = new InactivityFireEvent(this, flushTimeout); { timer.start(); timer.add(inactivityFireEventPtr); } initManagement(a); log(LOG_NOTICE, "Created"); std::ostringstream oss; oss << "Journal directory = \"" << journalDirectory << "\"; Base file name = \"" << journalBaseFilename << "\""; log(LOG_DEBUG, oss.str()); } JournalImpl::~JournalImpl() { if (deleteCallback) deleteCallback(*this); if (_init_flag && !_stop_flag){ try { stop(true); } // NOTE: This will *block* until all outstanding disk aio calls are complete! catch (const jexception& e) { log(LOG_ERROR, e.what()); } } getEventsFireEventsPtr->cancel(); inactivityFireEventPtr->cancel(); free_read_buffers(); if (_mgmtObject != 0) { _mgmtObject->resourceDestroy(); _mgmtObject = 0; } log(LOG_NOTICE, "Destroyed"); } void JournalImpl::initManagement(qpid::management::ManagementAgent* a) { _agent = a; if (_agent != 0) { _mgmtObject = new _qmf::Journal (_agent, (qpid::management::Manageable*) this); _mgmtObject->set_name(_jid); _mgmtObject->set_directory(_jdir.dirname()); _mgmtObject->set_baseFileName(_base_filename); _mgmtObject->set_readPageSize(JRNL_RMGR_PAGE_SIZE * JRNL_SBLK_SIZE * JRNL_DBLK_SIZE); _mgmtObject->set_readPages(JRNL_RMGR_PAGES); // The following will be set on initialize(), but being properties, these must be set to 0 in the meantime _mgmtObject->set_initialFileCount(0); _mgmtObject->set_dataFileSize(0); _mgmtObject->set_currentFileCount(0); _mgmtObject->set_writePageSize(0); _mgmtObject->set_writePages(0); _agent->addObject(_mgmtObject, 0, true); } } void JournalImpl::initialize(const u_int16_t num_jfiles, const bool auto_expand, const u_int16_t ae_max_jfiles, const u_int32_t jfsize_sblks, const u_int16_t wcache_num_pages, const u_int32_t wcache_pgsize_sblks, mrg::journal::aio_callback* const cbp) { std::ostringstream oss; oss << "Initialize; num_jfiles=" << num_jfiles << " jfsize_sblks=" << jfsize_sblks; oss << " wcache_pgsize_sblks=" << wcache_pgsize_sblks; oss << " wcache_num_pages=" << wcache_num_pages; log(LOG_DEBUG, oss.str()); jcntl::initialize(num_jfiles, auto_expand, ae_max_jfiles, jfsize_sblks, wcache_num_pages, wcache_pgsize_sblks, cbp); log(LOG_DEBUG, "Initialization complete"); if (_mgmtObject != 0) { _mgmtObject->set_initialFileCount(_lpmgr.num_jfiles()); _mgmtObject->set_autoExpand(_lpmgr.is_ae()); _mgmtObject->set_currentFileCount(_lpmgr.num_jfiles()); _mgmtObject->set_maxFileCount(_lpmgr.ae_max_jfiles()); _mgmtObject->set_dataFileSize(_jfsize_sblks * JRNL_SBLK_SIZE * JRNL_DBLK_SIZE); _mgmtObject->set_writePageSize(wcache_pgsize_sblks * JRNL_SBLK_SIZE * JRNL_DBLK_SIZE); _mgmtObject->set_writePages(wcache_num_pages); } if (_agent != 0) _agent->raiseEvent(qmf::com::redhat::rhm::store::EventCreated(_jid, _jfsize_sblks * JRNL_SBLK_SIZE * JRNL_DBLK_SIZE, _lpmgr.num_jfiles()), qpid::management::ManagementAgent::SEV_NOTE); } void JournalImpl::recover(const u_int16_t num_jfiles, const bool auto_expand, const u_int16_t ae_max_jfiles, const u_int32_t jfsize_sblks, const u_int16_t wcache_num_pages, const u_int32_t wcache_pgsize_sblks, mrg::journal::aio_callback* const cbp, boost::ptr_list<msgstore::PreparedTransaction>* prep_tx_list_ptr, u_int64_t& highest_rid, u_int64_t queue_id) { std::ostringstream oss1; oss1 << "Recover; num_jfiles=" << num_jfiles << " jfsize_sblks=" << jfsize_sblks; oss1 << " queue_id = 0x" << std::hex << queue_id << std::dec; oss1 << " wcache_pgsize_sblks=" << wcache_pgsize_sblks; oss1 << " wcache_num_pages=" << wcache_num_pages; log(LOG_DEBUG, oss1.str()); if (_mgmtObject != 0) { _mgmtObject->set_initialFileCount(_lpmgr.num_jfiles()); _mgmtObject->set_autoExpand(_lpmgr.is_ae()); _mgmtObject->set_currentFileCount(_lpmgr.num_jfiles()); _mgmtObject->set_maxFileCount(_lpmgr.ae_max_jfiles()); _mgmtObject->set_dataFileSize(_jfsize_sblks * JRNL_SBLK_SIZE * JRNL_DBLK_SIZE); _mgmtObject->set_writePageSize(wcache_pgsize_sblks * JRNL_SBLK_SIZE * JRNL_DBLK_SIZE); _mgmtObject->set_writePages(wcache_num_pages); } if (prep_tx_list_ptr) { // Create list of prepared xids std::vector<std::string> prep_xid_list; for (msgstore::PreparedTransaction::list::iterator i = prep_tx_list_ptr->begin(); i != prep_tx_list_ptr->end(); i++) { prep_xid_list.push_back(i->xid); } jcntl::recover(num_jfiles, auto_expand, ae_max_jfiles, jfsize_sblks, wcache_num_pages, wcache_pgsize_sblks, cbp, &prep_xid_list, highest_rid); } else { jcntl::recover(num_jfiles, auto_expand, ae_max_jfiles, jfsize_sblks, wcache_num_pages, wcache_pgsize_sblks, cbp, 0, highest_rid); } // Populate PreparedTransaction lists from _tmap if (prep_tx_list_ptr) { for (msgstore::PreparedTransaction::list::iterator i = prep_tx_list_ptr->begin(); i != prep_tx_list_ptr->end(); i++) { txn_data_list tdl = _tmap.get_tdata_list(i->xid); // tdl will be empty if xid not found for (tdl_itr tdl_itr = tdl.begin(); tdl_itr < tdl.end(); tdl_itr++) { if (tdl_itr->_enq_flag) { // enqueue op i->enqueues->add(queue_id, tdl_itr->_rid); } else { // dequeue op i->dequeues->add(queue_id, tdl_itr->_drid); } } } } std::ostringstream oss2; oss2 << "Recover phase 1 complete; highest rid found = 0x" << std::hex << highest_rid; oss2 << std::dec << "; emap.size=" << _emap.size() << "; tmap.size=" << _tmap.size(); oss2 << "; journal now read-only."; log(LOG_DEBUG, oss2.str()); if (_mgmtObject != 0) { _mgmtObject->inc_recordDepth(_emap.size()); _mgmtObject->inc_enqueues(_emap.size()); _mgmtObject->inc_txn(_tmap.size()); _mgmtObject->inc_txnEnqueues(_tmap.enq_cnt()); _mgmtObject->inc_txnDequeues(_tmap.deq_cnt()); } } void JournalImpl::recover_complete() { jcntl::recover_complete(); log(LOG_DEBUG, "Recover phase 2 complete; journal now writable."); if (_agent != 0) _agent->raiseEvent(qmf::com::redhat::rhm::store::EventRecovered(_jid, _jfsize_sblks * JRNL_SBLK_SIZE * JRNL_DBLK_SIZE, _lpmgr.num_jfiles(), _emap.size(), _tmap.size(), _tmap.enq_cnt(), _tmap.deq_cnt()), qpid::management::ManagementAgent::SEV_NOTE); } //#define MAX_AIO_SLEEPS 1000000 // tot: ~10 sec //#define AIO_SLEEP_TIME_US 10 // 0.01 ms // Return true if content is recovered from store; false if content is external and must be recovered from an external store. // Throw exception for all errors. bool JournalImpl::loadMsgContent(u_int64_t rid, std::string& data, size_t length, size_t offset) { qpid::sys::Mutex::ScopedLock sl(_read_lock); if (_dtok.rid() != rid) { // Free any previous msg free_read_buffers(); // Last read encountered out-of-order rids, check if this rid is in that list bool oooFlag = false; for (std::vector<u_int64_t>::const_iterator i=oooRidList.begin(); i!=oooRidList.end() && !oooFlag; i++) { if (*i == rid) { oooFlag = true; } } // TODO: This is a brutal approach - very inefficient and slow. Rather introduce a system of remembering // jumpover points and allow the read to jump back to the first known jumpover point - but this needs // a mechanism in rrfc to accomplish it. Also helpful is a struct containing a journal address - a // combination of lid/offset. // NOTE: The second part of the if stmt (rid < lastReadRid) is required to handle browsing. if (oooFlag || rid < lastReadRid) { _rmgr.invalidate(); oooRidList.clear(); } _dlen = 0; _dtok.reset(); _dtok.set_wstate(DataTokenImpl::ENQ); _dtok.set_rid(0); _external = false; size_t xlen = 0; bool transient = false; bool done = false; bool rid_found = false; while (!done) { iores res = read_data_record(&_datap, _dlen, &_xidp, xlen, transient, _external, &_dtok); switch (res) { case mrg::journal::RHM_IORES_SUCCESS: if (_dtok.rid() != rid) { // Check if this is an out-of-order rid that may impact next read if (_dtok.rid() > rid) oooRidList.push_back(_dtok.rid()); free_read_buffers(); // Reset data token for next read _dlen = 0; _dtok.reset(); _dtok.set_wstate(DataTokenImpl::ENQ); _dtok.set_rid(0); } else { rid_found = _dtok.rid() == rid; lastReadRid = rid; done = true; } break; case mrg::journal::RHM_IORES_PAGE_AIOWAIT: if (get_wr_events(&_aio_cmpl_timeout) == journal::jerrno::AIO_TIMEOUT) { std::stringstream ss; ss << "read_data_record() returned " << mrg::journal::iores_str(res); ss << "; timed out waiting for page to be processed."; throw jexception(mrg::journal::jerrno::JERR__TIMEOUT, ss.str().c_str(), "JournalImpl", "loadMsgContent"); } break; default: std::stringstream ss; ss << "read_data_record() returned " << mrg::journal::iores_str(res); throw jexception(mrg::journal::jerrno::JERR__UNEXPRESPONSE, ss.str().c_str(), "JournalImpl", "loadMsgContent"); } } if (!rid_found) { std::stringstream ss; ss << "read_data_record() was unable to find rid 0x" << std::hex << rid << std::dec; ss << " (" << rid << "); last rid found was 0x" << std::hex << _dtok.rid() << std::dec; ss << " (" << _dtok.rid() << ")"; throw jexception(mrg::journal::jerrno::JERR__RECNFOUND, ss.str().c_str(), "JournalImpl", "loadMsgContent"); } } if (_external) return false; u_int32_t hdr_offs = qpid::framing::Buffer(static_cast<char*>(_datap), sizeof(u_int32_t)).getLong() + sizeof(u_int32_t); if (hdr_offs + offset + length > _dlen) { data.append((const char*)_datap + hdr_offs + offset, _dlen - hdr_offs - offset); } else { data.append((const char*)_datap + hdr_offs + offset, length); } return true; } void JournalImpl::enqueue_data_record(const void* const data_buff, const size_t tot_data_len, const size_t this_data_len, data_tok* dtokp, const bool transient) { handleIoResult(jcntl::enqueue_data_record(data_buff, tot_data_len, this_data_len, dtokp, transient)); if (_mgmtObject != 0) { _mgmtObject->inc_enqueues(); _mgmtObject->inc_recordDepth(); } } void JournalImpl::enqueue_extern_data_record(const size_t tot_data_len, data_tok* dtokp, const bool transient) { handleIoResult(jcntl::enqueue_extern_data_record(tot_data_len, dtokp, transient)); if (_mgmtObject != 0) { _mgmtObject->inc_enqueues(); _mgmtObject->inc_recordDepth(); } } void JournalImpl::enqueue_txn_data_record(const void* const data_buff, const size_t tot_data_len, const size_t this_data_len, data_tok* dtokp, const std::string& xid, const bool transient) { bool txn_incr = _mgmtObject != 0 ? _tmap.in_map(xid) : false; handleIoResult(jcntl::enqueue_txn_data_record(data_buff, tot_data_len, this_data_len, dtokp, xid, transient)); if (_mgmtObject != 0) { if (!txn_incr) // If this xid was not in _tmap, it will be now... _mgmtObject->inc_txn(); _mgmtObject->inc_enqueues(); _mgmtObject->inc_txnEnqueues(); _mgmtObject->inc_recordDepth(); } } void JournalImpl::enqueue_extern_txn_data_record(const size_t tot_data_len, data_tok* dtokp, const std::string& xid, const bool transient) { bool txn_incr = _mgmtObject != 0 ? _tmap.in_map(xid) : false; handleIoResult(jcntl::enqueue_extern_txn_data_record(tot_data_len, dtokp, xid, transient)); if (_mgmtObject != 0) { if (!txn_incr) // If this xid was not in _tmap, it will be now... _mgmtObject->inc_txn(); _mgmtObject->inc_enqueues(); _mgmtObject->inc_txnEnqueues(); _mgmtObject->inc_recordDepth(); } } void JournalImpl::dequeue_data_record(data_tok* const dtokp, const bool txn_coml_commit) { handleIoResult(jcntl::dequeue_data_record(dtokp, txn_coml_commit)); if (_mgmtObject != 0) { _mgmtObject->inc_dequeues(); _mgmtObject->inc_txnDequeues(); _mgmtObject->dec_recordDepth(); } } void JournalImpl::dequeue_txn_data_record(data_tok* const dtokp, const std::string& xid, const bool txn_coml_commit) { bool txn_incr = _mgmtObject != 0 ? _tmap.in_map(xid) : false; handleIoResult(jcntl::dequeue_txn_data_record(dtokp, xid, txn_coml_commit)); if (_mgmtObject != 0) { if (!txn_incr) // If this xid was not in _tmap, it will be now... _mgmtObject->inc_txn(); _mgmtObject->inc_dequeues(); _mgmtObject->inc_txnDequeues(); _mgmtObject->dec_recordDepth(); } } void JournalImpl::txn_abort(data_tok* const dtokp, const std::string& xid) { handleIoResult(jcntl::txn_abort(dtokp, xid)); if (_mgmtObject != 0) { _mgmtObject->dec_txn(); _mgmtObject->inc_txnAborts(); } } void JournalImpl::txn_commit(data_tok* const dtokp, const std::string& xid) { handleIoResult(jcntl::txn_commit(dtokp, xid)); if (_mgmtObject != 0) { _mgmtObject->dec_txn(); _mgmtObject->inc_txnCommits(); } } void JournalImpl::stop(bool block_till_aio_cmpl) { InactivityFireEvent* ifep = dynamic_cast<InactivityFireEvent*>(inactivityFireEventPtr.get()); assert(ifep); // dynamic_cast can return null if the cast fails ifep->cancel(); jcntl::stop(block_till_aio_cmpl); if (_mgmtObject != 0) { _mgmtObject->resourceDestroy(); _mgmtObject = 0; } } iores JournalImpl::flush(const bool block_till_aio_cmpl) { const iores res = jcntl::flush(block_till_aio_cmpl); { qpid::sys::Mutex::ScopedLock sl(_getf_lock); if (_wmgr.get_aio_evt_rem() && !getEventsTimerSetFlag) { setGetEventTimer(); } } return res; } void JournalImpl::log(mrg::journal::log_level ll, const std::string& log_stmt) const { log(ll, log_stmt.c_str()); } void JournalImpl::log(mrg::journal::log_level ll, const char* const log_stmt) const { switch (ll) { case LOG_TRACE: QPID_LOG(trace, "Journal \"" << _jid << "\": " << log_stmt); break; case LOG_DEBUG: QPID_LOG(debug, "Journal \"" << _jid << "\": " << log_stmt); break; case LOG_INFO: QPID_LOG(info, "Journal \"" << _jid << "\": " << log_stmt); break; case LOG_NOTICE: QPID_LOG(notice, "Journal \"" << _jid << "\": " << log_stmt); break; case LOG_WARN: QPID_LOG(warning, "Journal \"" << _jid << "\": " << log_stmt); break; case LOG_ERROR: QPID_LOG(error, "Journal \"" << _jid << "\": " << log_stmt); break; case LOG_CRITICAL: QPID_LOG(critical, "Journal \"" << _jid << "\": " << log_stmt); break; } } void JournalImpl::getEventsFire() { qpid::sys::Mutex::ScopedLock sl(_getf_lock); getEventsTimerSetFlag = false; if (_wmgr.get_aio_evt_rem()) { jcntl::get_wr_events(0); } if (_wmgr.get_aio_evt_rem()) { setGetEventTimer(); } } void JournalImpl::flushFire() { if (writeActivityFlag) { writeActivityFlag = false; flushTriggeredFlag = false; } else { if (!flushTriggeredFlag) { flush(); flushTriggeredFlag = true; } } inactivityFireEventPtr->setupNextFire(); { timer.add(inactivityFireEventPtr); } } void JournalImpl::wr_aio_cb(std::vector<data_tok*>& dtokl) { for (std::vector<data_tok*>::const_iterator i=dtokl.begin(); i!=dtokl.end(); i++) { DataTokenImpl* dtokp = static_cast<DataTokenImpl*>(*i); if (/*!is_stopped() &&*/ dtokp->getSourceMessage()) { switch (dtokp->wstate()) { case data_tok::ENQ: dtokp->getSourceMessage()->enqueueComplete(); break; case data_tok::DEQ: /* Don't need to signal until we have a way to ack completion of dequeue in AMQP dtokp->getSourceMessage()->dequeueComplete(); if ( dtokp->getSourceMessage()->isDequeueComplete() ) // clear id after last dequeue dtokp->getSourceMessage()->setPersistenceId(0); */ break; default: ; } } dtokp->release(); } } void JournalImpl::rd_aio_cb(std::vector<u_int16_t>& /*pil*/) {} void JournalImpl::free_read_buffers() { if (_xidp) { ::free(_xidp); _xidp = 0; _datap = 0; } else if (_datap) { ::free(_datap); _datap = 0; } } void JournalImpl::handleIoResult(const iores r) { writeActivityFlag = true; switch (r) { case mrg::journal::RHM_IORES_SUCCESS: return; case mrg::journal::RHM_IORES_ENQCAPTHRESH: { std::ostringstream oss; oss << "Enqueue capacity threshold exceeded on queue \"" << _jid << "\"."; log(LOG_WARN, oss.str()); if (_agent != 0) _agent->raiseEvent(qmf::com::redhat::rhm::store::EventEnqThresholdExceeded(_jid, "Journal enqueue capacity threshold exceeded"), qpid::management::ManagementAgent::SEV_WARN); THROW_STORE_FULL_EXCEPTION(oss.str()); } case mrg::journal::RHM_IORES_FULL: { std::ostringstream oss; oss << "Journal full on queue \"" << _jid << "\"."; log(LOG_CRITICAL, oss.str()); if (_agent != 0) _agent->raiseEvent(qmf::com::redhat::rhm::store::EventFull(_jid, "Journal full"), qpid::management::ManagementAgent::SEV_ERROR); THROW_STORE_FULL_EXCEPTION(oss.str()); } default: { std::ostringstream oss; oss << "Unexpected I/O response (" << mrg::journal::iores_str(r) << ") on queue " << _jid << "\"."; log(LOG_ERROR, oss.str()); THROW_STORE_FULL_EXCEPTION(oss.str()); } } } qpid::management::Manageable::status_t JournalImpl::ManagementMethod (uint32_t methodId, qpid::management::Args& /*args*/, std::string& /*text*/) { Manageable::status_t status = Manageable::STATUS_UNKNOWN_METHOD; switch (methodId) { case _qmf::Journal::METHOD_EXPAND : //_qmf::ArgsJournalExpand& eArgs = (_qmf::ArgsJournalExpand&) args; // Implement "expand" using eArgs.i_by (expand-by argument) status = Manageable::STATUS_NOT_IMPLEMENTED; break; } return status; }
lgpl-2.1
kazuyaujihara/NCDK
NCDKTests/Reactions/Mechanisms/TautomerizationMechanismTest.cs
1737
/* Copyright (C) 2008 Miguel Rojas <miguelrojasch@yahoo.es> * * Contact: cdk-devel@lists.sourceforge.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ using Microsoft.VisualStudio.TestTools.UnitTesting; namespace NCDK.Reactions.Mechanisms { /// <summary> /// Tests for TautomerizationMechanism implementations. /// </summary> // @cdk.module test-reaction [TestClass()] public class TautomerizationMechanismTest : ReactionMechanismTest { public TautomerizationMechanismTest() : base() { SetMechanism(typeof(TautomerizationMechanism)); } [TestMethod()] public void TestTautomerizationMechanism() { var mechanism = new TautomerizationMechanism(); Assert.IsNotNull(mechanism); } [TestMethod()] public void TestInitiate_IAtomContainerSet_ArrayList_ArrayList() { var mechanism = new TautomerizationMechanism(); Assert.IsNotNull(mechanism); } } }
lgpl-2.1
KDE/android-qt-mobility
src/gallery/maemo5/qgallerytrackertyperesultset.cpp
8155
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qgallerytrackertyperesultset_p.h" #include "qgallerytrackerschema_p.h" #include <QtCore/qdatetime.h> #include <QtDBus/qdbuspendingreply.h> #include "qdocumentgallery.h" #include "qgalleryresultset_p.h" Q_DECLARE_METATYPE(QVector<QStringList>) QTM_BEGIN_NAMESPACE class QGalleryTrackerTypeResultSetPrivate : public QGalleryResultSetPrivate { Q_DECLARE_PUBLIC(QGalleryTrackerTypeResultSet) public: QGalleryTrackerTypeResultSetPrivate(const QGalleryTrackerTypeResultSetArguments &arguments) : accumulative(arguments.accumulative) , canceled(false) , refresh(false) , updateMask(arguments.updateMask) , currentIndex(-1) , count(0) , workingCount(0) , currentOffset(0) , queryWatcher(0) , queryInterface(arguments.queryInterface) , queryMethod(arguments.queryMethod) , queryArguments(arguments.queryArguments) { } void _q_queryFinished(QDBusPendingCallWatcher *watcher); void queryFinished(const QDBusPendingCall &call); void queryCount(); const bool accumulative; bool canceled; bool refresh; const int updateMask; int currentIndex; int count; int workingCount; int currentOffset; QDBusPendingCallWatcher *queryWatcher; const QGalleryDBusInterfacePointer queryInterface; const QString queryMethod; const QVariantList queryArguments; }; void QGalleryTrackerTypeResultSetPrivate::_q_queryFinished(QDBusPendingCallWatcher *watcher) { if (queryWatcher == watcher) { queryWatcher->deleteLater(); queryWatcher = 0; watcher->deleteLater(); queryFinished(*watcher); } } void QGalleryTrackerTypeResultSetPrivate::queryFinished(const QDBusPendingCall &call) { const int oldCount = count; if (call.isError()) { q_func()->finish(QDocumentGallery::ConnectionError); return; } else if (!accumulative) { QDBusPendingReply<int> reply(call); count = reply.value(); if (refresh) { refresh = false; queryCount(); } } else { QDBusPendingReply<QVector<QStringList> > reply(call); const QVector<QStringList> counts = reply.value(); typedef QVector<QStringList>::const_iterator iterator; for (iterator it = counts.begin(), end = counts.end(); it != end; ++it) workingCount += it->value(1).toInt(); if (refresh) { refresh = false; currentOffset = 0; workingCount = 0; queryCount(); } else { currentOffset += counts.count(); if (counts.count() != 0) { if (count > workingCount) count = workingCount; if (canceled) q_func()->QGalleryAbstractResponse::cancel(); else queryCount(); } else { count = workingCount; } } } if (count != oldCount) emit q_func()->metaDataChanged(0, 1, QList<int>() << 0); if (!queryWatcher) q_func()->finish(); } void QGalleryTrackerTypeResultSetPrivate::queryCount() { QVariantList arguments = queryArguments; if (accumulative) arguments << currentOffset << int(0); QDBusPendingCall call = queryInterface->asyncCallWithArgumentList(queryMethod, arguments); if (call.isFinished()) { queryFinished(call); } else { queryWatcher = new QDBusPendingCallWatcher(call, q_func()); QObject::connect(queryWatcher, SIGNAL(finished(QDBusPendingCallWatcher*)), q_func(), SLOT(_q_queryFinished(QDBusPendingCallWatcher*))); } } QGalleryTrackerTypeResultSet::QGalleryTrackerTypeResultSet( const QGalleryTrackerTypeResultSetArguments &arguments, QObject *parent) : QGalleryResultSet(*new QGalleryTrackerTypeResultSetPrivate(arguments), parent) { Q_D(QGalleryTrackerTypeResultSet); d->queryCount(); } QGalleryTrackerTypeResultSet::~QGalleryTrackerTypeResultSet() { } int QGalleryTrackerTypeResultSet::propertyKey(const QString &property) const { return property == QLatin1String("count") ? 0 : -1; } QGalleryProperty::Attributes QGalleryTrackerTypeResultSet::propertyAttributes(int key) const { return key == 0 ? QGalleryProperty::CanRead : QGalleryProperty::Attributes(); } QVariant::Type QGalleryTrackerTypeResultSet::propertyType(int key) const { return key == 0 ? QVariant::Int : QVariant::Invalid; } int QGalleryTrackerTypeResultSet::itemCount() const { return 1; } QVariant QGalleryTrackerTypeResultSet::itemId() const { return QVariant(); } QUrl QGalleryTrackerTypeResultSet::itemUrl() const { return QUrl(); } QString QGalleryTrackerTypeResultSet::itemType() const { return QString(); } QVariant QGalleryTrackerTypeResultSet::metaData(int key) const { return d_func()->currentIndex == 0 && key == 0 ? d_func()->count : 0; } bool QGalleryTrackerTypeResultSet::setMetaData(int, const QVariant &) { return false; } int QGalleryTrackerTypeResultSet::currentIndex() const { return d_func()->currentIndex; } bool QGalleryTrackerTypeResultSet::fetch(int index) { if (index != d_func()->currentIndex) { bool itemChanged = index == 0 || d_func()->currentIndex == 0; d_func()->currentIndex = index; emit currentIndexChanged(index); if (itemChanged) emit currentItemChanged(); } return d_func()->currentIndex == 0; } void QGalleryTrackerTypeResultSet::cancel() { d_func()->canceled = true; d_func()->refresh = false; if (!d_func()->queryWatcher) QGalleryAbstractResponse::cancel(); } bool QGalleryTrackerTypeResultSet::waitForFinished(int msecs) { Q_D(QGalleryTrackerTypeResultSet); QTime timer; timer.start(); do { if (QDBusPendingCallWatcher *watcher = d->queryWatcher) { d->queryWatcher = 0; watcher->waitForFinished(); d->queryFinished(*watcher); delete watcher; if (d->state != QGalleryAbstractRequest::Active) return true; } else { return true; } } while ((msecs -= timer.restart()) > 0); return false; } void QGalleryTrackerTypeResultSet::refresh(int serviceId) { Q_D(QGalleryTrackerTypeResultSet); if (!d->canceled && (d->updateMask & serviceId)) { d->refresh = true; if (!d->queryWatcher) d->queryCount(); } } #include "moc_qgallerytrackertyperesultset_p.cpp" QTM_END_NAMESPACE
lgpl-2.1
omda12/akelosframework
vendor/pear/Image/Transform/Driver/Imagick.php
7352
<?php /* vim: set expandtab tabstop=4 shiftwidth=4: */ /** * Image Transformation interface using old ImageMagick extension * * PHP versions 4 and 5 * * LICENSE: This source file is subject to version 3.0 of the PHP license * that is available through the world-wide-web at the following URI: * http://www.php.net/license/3_0.txt. If you did not receive a copy of * the PHP License and are unable to obtain it through the web, please * send a note to license@php.net so we can mail you a copy immediately. * * @category Image * @package Image_Transform * @author Peter Bowyer <peter@mapledesign.co.uk> * @copyright 2002-2005 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: Imagick.php,v 1.6 2005/07/15 05:18:42 jausions Exp $ * @deprecated * @link http://pear.php.net/package/Image_Transform */ /** * Include of base class */ require_once "Image/Transform.php"; /** * Image Transformation interface using old ImageMagick extension * * DEPRECATED: current CVS/release imagick extension should use * the Imagick2 driver * * @deprecated */ class Image_Transform_Driver_Imagick extends Image_Transform { /** * Handler of the imagick image ressource * @var array */ var $imageHandle; /** * Handler of the image ressource before * the last transformation * @var array */ var $oldImage; /** * * */ function Image_Transform_Driver_Imagick() { if (!PEAR::loadExtension('imagick')) { return PEAR::raiseError('The imagick extension can not be found.', true); } include('Image/Transform/Driver/Imagick/ImageTypes.php'); return true; } // End Image_IM /** * Load image * * @param string filename * * @return mixed none or a PEAR error object on error * @see PEAR::isError() */ function load($image) { $this->imageHandle = imagick_create(); if ( !is_resource( $this->imageHandle ) ) { return PEAR::raiseError('Cannot initialize imagick image.', true); } if ( !imagick_read($this->imageHandle, $image) ){ return PEAR::raiseError('The image file ' . $image . ' does\'t exist', true); } $this->image = $image; $result = $this->_get_image_details($image); if (PEAR::isError($result)) { return $result; } } // End load /** * Resize Action * * @param int new_x new width * @param int new_y new width * * @return none * @see PEAR::isError() */ function _resize($new_x, $new_y) { if ($img2 = imagick_copy_resize($this->imageHandle, $new_x, $new_y, IMAGICK_FILTER_CUBIC, 1)){ $this->oldImage = $this->imageHandle; $this->imageHandle =$img2; $this->new_x = $new_x; $this->new_y = $new_y; } else { return PEAR::raiseError("Cannot create a new imagick imagick image for the resize.", true); } } // End resize /** * rotate * Note: color mask are currently not supported * * @param int Rotation angle in degree * @param array No option are actually allowed * * @return none * @see PEAR::isError() */ function rotate($angle,$options=null) { if ($img2 = imagick_copy_rotate ($this->imageHandle, $angle)){ $this->oldImage = $this->imageHandle; $this->imageHandle = $img2; $this->new_x = imagick_get_attribute($img2,'width'); $this->new_y = imagick_get_attribute($img2,'height'); } else { return PEAR::raiseError("Cannot create a new imagick imagick image for the resize.", true); } } // End rotate /** * addText * * @param array options Array contains options * array( * 'text' The string to draw * 'x' Horizontal position * 'y' Vertical Position * 'Color' Font color * 'font' Font to be used * 'size' Size of the fonts in pixel * 'resize_first' Tell if the image has to be resized * before drawing the text * ) * * @return none * @see PEAR::isError() */ function addText($params) { $default_params = array( 'text' => 'This is a Text', 'x' => 10, 'y' => 20, 'size' => 12, 'color' => 'red', 'font' => 'Arial.ttf', 'resize_first' => false // Carry out the scaling of the image before annotation? ); $params = array_merge($default_params, $params); extract($params); $color = is_array($color)?$this->colorarray2colorhex($color):strtolower($color); imagick_annotate($this->imageHandle,array( "primitive" => "text $x,$y ".$text, "pointsize" => $size, "antialias" => 0, "fill" => $color, "font" => $font, )); } // End addText /** * Save the image file * * @param $filename string the name of the file to write to * * @return none */ function save($filename, $type='', $quality = 75) { if ($type == '') { $type = strtoupper($type); imagick_write($this->imageHandle, $filename, $type); } else { imagick_write($this->imageHandle, $filename); } imagick_free($handle); } // End save /** * Display image without saving and lose changes * * @param string type (JPG,PNG...); * @param int quality 75 * * @return none */ function display($type = '', $quality = 75) { if ($type == '') { header('Content-type: image/' . $this->type); if (!imagick_dump($this->imageHandle)); } else { header('Content-type: image/' . $type); if (!imagick_dump($this->imageHandle, $this->type)); } $this->free(); } /** * Destroy image handle * * @return none */ function free() { if(is_resource($this->imageHandle)){ imagick_free($this->imageHandle); } if(is_resource($this->oldImage)){ imagick_free($this->oldImage); } return true; } } // End class ImageIM ?>
lgpl-2.1
einon/affymetrix-power-tools
sdk/dox/html/classDataSetTest__FStreamLoadEntireDataSet.html
11817
<!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>Affymetrix Power Tools: DataSetTest_FStreamLoadEntireDataSet Class Reference</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.1 --> <div class="navigation" id="top"> <div class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="pages.html"><span>Related&nbsp;Pages</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> <li><a href="files.html"><span>Files</span></a></li> <li><a href="dirs.html"><span>Directories</span></a></li> </ul> </div> <div class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&nbsp;List</span></a></li> <li><a href="classes.html"><span>Class&nbsp;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&nbsp;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&nbsp;Members</span></a></li> </ul> </div> </div> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> </div> <div class="headertitle"> <h1>DataSetTest_FStreamLoadEntireDataSet Class Reference</h1> </div> </div> <div class="contents"> <!-- doxytag: class="DataSetTest_FStreamLoadEntireDataSet" --> <p><a href="classDataSetTest__FStreamLoadEntireDataSet-members.html">List of all members.</a></p> <table class="memberdecls"> <tr><td colspan="2"><h2><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a1ee0e9ff9480b19b5df66707bde2379d"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::setUp" ref="a1ee0e9ff9480b19b5df66707bde2379d" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>setUp</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a0b4083c071f86bcff44d7ccbf6d739d7"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::tearDown" ref="a0b4083c071f86bcff44d7ccbf6d739d7" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>tearDown</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aad612d22c61d82a3e51a55a06591f080"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testCreation" ref="aad612d22c61d82a3e51a55a06591f080" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testCreation</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a9b6656492fb44778333e13e7c32af8c3"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testmethod_Delete" ref="a9b6656492fb44778333e13e7c32af8c3" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testmethod_Delete</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a4100d2e9269b547714bf268cbd4cc2d5"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testmethod_Open" ref="a4100d2e9269b547714bf268cbd4cc2d5" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testmethod_Open</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a315d17c46c684ebcce4c015e00600c30"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testmethod_Close" ref="a315d17c46c684ebcce4c015e00600c30" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testmethod_Close</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a10525da05dcf8f7a7cbf129ad7de7afc"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testproperty_BytesPerRow" ref="a10525da05dcf8f7a7cbf129ad7de7afc" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testproperty_BytesPerRow</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aeaf478096d6a6e12198c0860d0cc9179"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testproperty_Rows" ref="aeaf478096d6a6e12198c0860d0cc9179" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testproperty_Rows</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a3a39dd3de0ac50bc478a28a0ba7aaefd"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testproperty_Cols" ref="a3a39dd3de0ac50bc478a28a0ba7aaefd" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testproperty_Cols</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a1a0c8de5f13e48daf1e20eebf007a31b"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testproperty_Header" ref="a1a0c8de5f13e48daf1e20eebf007a31b" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testproperty_Header</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a3cc856da5cc93ce3d6c4cfaa6a344979"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testmethod_ReadUInt16_Single" ref="a3cc856da5cc93ce3d6c4cfaa6a344979" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testmethod_ReadUInt16_Single</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a9407cc4b3ede4e7fed9c3e9e43eb5c7a"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testmethod_ReadUInt16_Vector" ref="a9407cc4b3ede4e7fed9c3e9e43eb5c7a" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testmethod_ReadUInt16_Vector</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="afd031ef41b2986db6e50903a7c0e4041"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testmethod_ReadUInt16_Vector_TooManyRows" ref="afd031ef41b2986db6e50903a7c0e4041" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testmethod_ReadUInt16_Vector_TooManyRows</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a610815955c7b4cf27251e81edacdb18e"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testmethod_ReadUInt16_Vector_InChunks" ref="a610815955c7b4cf27251e81edacdb18e" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testmethod_ReadUInt16_Vector_InChunks</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad5b3c813cd332ea00a1ef5ddcb4aca0d"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testmethod_ReadUInt16_Raw" ref="ad5b3c813cd332ea00a1ef5ddcb4aca0d" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testmethod_ReadUInt16_Raw</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a4860efd1d46815d675a6a841a887dd7d"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testmethod_ReadUInt16_Raw_TooManyRows" ref="a4860efd1d46815d675a6a841a887dd7d" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testmethod_ReadUInt16_Raw_TooManyRows</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae5d1450130f7a38e2d215b81c8df191b"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testmethod_ReadUInt16_Raw_InChunks" ref="ae5d1450130f7a38e2d215b81c8df191b" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testmethod_ReadUInt16_Raw_InChunks</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="adea5c79a91efb4ee9b7482ca57246ef2"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testmethod_CheckRowColumnAndType_DataSetNotOpenException" ref="adea5c79a91efb4ee9b7482ca57246ef2" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testmethod_CheckRowColumnAndType_DataSetNotOpenException</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a704a1d428173b0fa6fc76031d3df8e6b"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testmethod_CheckRowColumnAndType_ColumnOutOfBoundsException" ref="a704a1d428173b0fa6fc76031d3df8e6b" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testmethod_CheckRowColumnAndType_ColumnOutOfBoundsException</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a3014d484d8b478cc82ac9cb9c0f6b916"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testmethod_CheckRowColumnAndType_RowOutofBoundsException" ref="a3014d484d8b478cc82ac9cb9c0f6b916" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testmethod_CheckRowColumnAndType_RowOutofBoundsException</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aad9bdbd751214e6757786d5fe7a1e40a"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testmethod_CheckRowColumnAndType_UnexpectedColumnTypeException" ref="aad9bdbd751214e6757786d5fe7a1e40a" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testmethod_CheckRowColumnAndType_UnexpectedColumnTypeException</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a960010c20898b222822971b0aa7475da"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testmethod_ReadUInt16_Single_DataSetNotOpenException" ref="a960010c20898b222822971b0aa7475da" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testmethod_ReadUInt16_Single_DataSetNotOpenException</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a3fc2ff1707c20240f2a056a870a2cb04"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testmethod_ReadUInt16_Vector_DataSetNotOpenException" ref="a3fc2ff1707c20240f2a056a870a2cb04" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testmethod_ReadUInt16_Vector_DataSetNotOpenException</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="af89a897af8a06b323867268d500b43f7"></a><!-- doxytag: member="DataSetTest_FStreamLoadEntireDataSet::testmethod_ReadUInt16_Raw_DataSetNotOpenException" ref="af89a897af8a06b323867268d500b43f7" args="()" --> void&nbsp;</td><td class="memItemRight" valign="bottom"><b>testmethod_ReadUInt16_Raw_DataSetNotOpenException</b> ()</td></tr> </table> <hr/><a name="_details"></a><h2>Detailed Description</h2> <p>Definition at line <a class="el" href="DataSetTest__FStreamLoadEntireDataSet_8h_source.html#l00035">35</a> of file <a class="el" href="DataSetTest__FStreamLoadEntireDataSet_8h_source.html">DataSetTest_FStreamLoadEntireDataSet.h</a>.</p> <hr/>The documentation for this class was generated from the following files:<ul> <li>calvin_files/data/test/<a class="el" href="DataSetTest__FStreamLoadEntireDataSet_8h_source.html">DataSetTest_FStreamLoadEntireDataSet.h</a></li> <li>calvin_files/data/test/<a class="el" href="DataSetTest__FStreamLoadEntireDataSet_8cpp_source.html">DataSetTest_FStreamLoadEntireDataSet.cpp</a></li> </ul> </div> <hr class="footer"/><address class="footer"><small>Generated on Fri Mar 20 2015 18:03:42 for Affymetrix Power Tools by&nbsp; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.1 </small></address> </body> </html>
lgpl-2.1
KDE/android-qt-mobility
tools/icheck/parser/src/libs/cplusplus/GenTemplateInstance.cpp
11481
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "GenTemplateInstance.h" #include "Overview.h" #include <CppControl.h> #include <Scope.h> #include <Names.h> #include <Symbols.h> #include <CoreTypes.h> #include <Literals.h> #include <QtCore/QVarLengthArray> #include <QtCore/QDebug> using namespace CPlusPlus; namespace { class ApplySubstitution { public: ApplySubstitution(const LookupContext &context, Symbol *symbol, const GenTemplateInstance::Substitution &substitution); ~ApplySubstitution(); Control *control() const { return context.control(); } FullySpecifiedType apply(const Name *name); FullySpecifiedType apply(const FullySpecifiedType &type); int findSubstitution(const Identifier *id) const; FullySpecifiedType applySubstitution(int index) const; private: class ApplyToType: protected TypeVisitor { public: ApplyToType(ApplySubstitution *q) : q(q) {} FullySpecifiedType operator()(const FullySpecifiedType &ty) { FullySpecifiedType previousType = switchType(ty); accept(ty.type()); return switchType(previousType); } protected: using TypeVisitor::visit; Control *control() const { return q->control(); } FullySpecifiedType switchType(const FullySpecifiedType &type) { FullySpecifiedType previousType = _type; _type = type; return previousType; } virtual void visit(VoidType *) { // nothing to do } virtual void visit(IntegerType *) { // nothing to do } virtual void visit(FloatType *) { // nothing to do } virtual void visit(PointerToMemberType *) { qDebug() << Q_FUNC_INFO; // ### TODO } virtual void visit(PointerType *ptrTy) { _type.setType(control()->pointerType(q->apply(ptrTy->elementType()))); } virtual void visit(ReferenceType *refTy) { _type.setType(control()->referenceType(q->apply(refTy->elementType()))); } virtual void visit(ArrayType *arrayTy) { _type.setType(control()->arrayType(q->apply(arrayTy->elementType()), arrayTy->size())); } virtual void visit(NamedType *ty) { FullySpecifiedType n = q->apply(ty->name()); _type.setType(n.type()); } virtual void visit(Function *funTy) { Function *fun = control()->newFunction(/*sourceLocation=*/ 0, funTy->name()); fun->setScope(funTy->scope()); fun->setConst(funTy->isConst()); fun->setVolatile(funTy->isVolatile()); fun->setVirtual(funTy->isVirtual()); fun->setAmbiguous(funTy->isAmbiguous()); fun->setVariadic(funTy->isVariadic()); fun->setReturnType(q->apply(funTy->returnType())); for (unsigned i = 0; i < funTy->argumentCount(); ++i) { Argument *originalArgument = funTy->argumentAt(i)->asArgument(); Argument *arg = control()->newArgument(/*sourceLocation*/ 0, originalArgument->name()); arg->setType(q->apply(originalArgument->type())); arg->setInitializer(originalArgument->initializer()); fun->arguments()->enterSymbol(arg); } _type.setType(fun); } virtual void visit(Namespace *) { qDebug() << Q_FUNC_INFO; } virtual void visit(Class *) { qDebug() << Q_FUNC_INFO; } virtual void visit(Enum *) { qDebug() << Q_FUNC_INFO; } virtual void visit(ForwardClassDeclaration *) { qDebug() << Q_FUNC_INFO; } virtual void visit(ObjCClass *) { qDebug() << Q_FUNC_INFO; } virtual void visit(ObjCProtocol *) { qDebug() << Q_FUNC_INFO; } virtual void visit(ObjCMethod *) { qDebug() << Q_FUNC_INFO; } virtual void visit(ObjCForwardClassDeclaration *) { qDebug() << Q_FUNC_INFO; } virtual void visit(ObjCForwardProtocolDeclaration *) { qDebug() << Q_FUNC_INFO; } private: ApplySubstitution *q; FullySpecifiedType _type; QHash<Symbol *, FullySpecifiedType> _processed; }; class ApplyToName: protected NameVisitor { public: ApplyToName(ApplySubstitution *q): q(q) {} FullySpecifiedType operator()(const Name *name) { FullySpecifiedType previousType = switchType(FullySpecifiedType()); accept(name); return switchType(previousType); } protected: Control *control() const { return q->control(); } int findSubstitution(const Identifier *id) const { return q->findSubstitution(id); } FullySpecifiedType applySubstitution(int index) const { return q->applySubstitution(index); } FullySpecifiedType switchType(const FullySpecifiedType &type) { FullySpecifiedType previousType = _type; _type = type; return previousType; } virtual void visit(const NameId *name) { int index = findSubstitution(name->identifier()); if (index != -1) _type = applySubstitution(index); else _type = control()->namedType(name); } virtual void visit(const TemplateNameId *name) { QVarLengthArray<FullySpecifiedType, 8> arguments(name->templateArgumentCount()); for (unsigned i = 0; i < name->templateArgumentCount(); ++i) { FullySpecifiedType argTy = name->templateArgumentAt(i); arguments[i] = q->apply(argTy); } const TemplateNameId *templId = control()->templateNameId(name->identifier(), arguments.data(), arguments.size()); _type = control()->namedType(templId); } virtual void visit(const QualifiedNameId *name) { QVarLengthArray<const Name *, 8> names(name->nameCount()); for (unsigned i = 0; i < name->nameCount(); ++i) { const Name *n = name->nameAt(i); if (const TemplateNameId *templId = n->asTemplateNameId()) { QVarLengthArray<FullySpecifiedType, 8> arguments(templId->templateArgumentCount()); for (unsigned templateArgIndex = 0; templateArgIndex < templId->templateArgumentCount(); ++templateArgIndex) { FullySpecifiedType argTy = templId->templateArgumentAt(templateArgIndex); arguments[templateArgIndex] = q->apply(argTy); } n = control()->templateNameId(templId->identifier(), arguments.data(), arguments.size()); } names[i] = n; } const QualifiedNameId *q = control()->qualifiedNameId(names.data(), names.size(), name->isGlobal()); _type = control()->namedType(q); } virtual void visit(const DestructorNameId *name) { Overview oo; qWarning() << "ignored name:" << oo(name); } virtual void visit(const OperatorNameId *name) { Overview oo; qWarning() << "ignored name:" << oo(name); } virtual void visit(const ConversionNameId *name) { Overview oo; qWarning() << "ignored name:" << oo(name); } virtual void visit(const SelectorNameId *name) { Overview oo; qWarning() << "ignored name:" << oo(name); } private: ApplySubstitution *q; FullySpecifiedType _type; }; public: // attributes LookupContext context; Symbol *symbol; GenTemplateInstance::Substitution substitution; ApplyToType applyToType; ApplyToName applyToName; }; ApplySubstitution::ApplySubstitution(const LookupContext &context, Symbol *symbol, const GenTemplateInstance::Substitution &substitution) : context(context), symbol(symbol), substitution(substitution), applyToType(this), applyToName(this) { } ApplySubstitution::~ApplySubstitution() { } FullySpecifiedType ApplySubstitution::apply(const Name *name) { FullySpecifiedType ty = applyToName(name); return ty; } FullySpecifiedType ApplySubstitution::apply(const FullySpecifiedType &type) { FullySpecifiedType ty = applyToType(type); return ty; } int ApplySubstitution::findSubstitution(const Identifier *id) const { Q_ASSERT(id != 0); for (int index = 0; index < substitution.size(); ++index) { QPair<const Identifier *, FullySpecifiedType> s = substitution.at(index); if (id->isEqualTo(s.first)) return index; } return -1; } FullySpecifiedType ApplySubstitution::applySubstitution(int index) const { Q_ASSERT(index != -1); Q_ASSERT(index < substitution.size()); return substitution.at(index).second; } } // end of anonymous namespace GenTemplateInstance::GenTemplateInstance(const LookupContext &context, const Substitution &substitution) : _symbol(0), _context(context), _substitution(substitution) { } FullySpecifiedType GenTemplateInstance::operator()(Symbol *symbol) { ApplySubstitution o(_context, symbol, _substitution); return o.apply(symbol->type()); } Control *GenTemplateInstance::control() const { return _context.control(); }
lgpl-2.1
SamyStyle/pywurfl
doc/api/toc-pywurfl.algorithms-module.html
2120
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>algorithms</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <h1 class="toc">Module algorithms</h1> <hr /> <h2 class="toc">Classes</h2> <div class="private"> <a target="mainFrame" href="pywurfl.algorithms.Algorithm-class.html" >Algorithm</a><br /> </div> <div class="private"> <a target="mainFrame" href="pywurfl.algorithms.JaroWinkler-class.html" >JaroWinkler</a><br /> </div> <div class="private"> <a target="mainFrame" href="pywurfl.algorithms.LevenshteinDistance-class.html" >LevenshteinDistance</a><br /> </div> <div class="private"> <a target="mainFrame" href="pywurfl.algorithms.Tokenizer-class.html" >Tokenizer</a><br /> </div> <div class="private"> <a target="mainFrame" href="pywurfl.algorithms.TwoStepAnalysis-class.html" >TwoStepAnalysis</a><br /> </div> <h2 class="toc">Variables</h2> <div class="private"> <a target="mainFrame" href="pywurfl.algorithms-module.html#__doc__" >__doc__</a><br /> </div> <div class="private"> <a target="mainFrame" href="pywurfl.algorithms-module.html#__package__" >__package__</a><br /> </div> <div class="private"> <a target="mainFrame" href="pywurfl.algorithms-module.html#__url__" >__url__</a><br /> </div> <hr /> <span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
lgpl-2.1
prefetchnta/questlab
bin/x64bin/python/37/Lib/tkinter/__init__.py
170982
"""Wrapper functions for Tcl/Tk. Tkinter provides classes which allow the display, positioning and control of widgets. Toplevel widgets are Tk and Toplevel. Other widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton, Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox LabelFrame and PanedWindow. Properties of the widgets are specified with keyword arguments. Keyword arguments have the same name as the corresponding resource under Tk. Widgets are positioned with one of the geometry managers Place, Pack or Grid. These managers can be called with methods place, pack, grid available in every Widget. Actions are bound to events by resources (e.g. keyword argument command) or with the method bind. Example (Hello, World): import tkinter from tkinter.constants import * tk = tkinter.Tk() frame = tkinter.Frame(tk, relief=RIDGE, borderwidth=2) frame.pack(fill=BOTH,expand=1) label = tkinter.Label(frame, text="Hello, World") label.pack(fill=X, expand=1) button = tkinter.Button(frame,text="Exit",command=tk.destroy) button.pack(side=BOTTOM) tk.mainloop() """ import enum import sys import _tkinter # If this fails your Python may not be configured for Tk TclError = _tkinter.TclError from tkinter.constants import * import re wantobjects = 1 TkVersion = float(_tkinter.TK_VERSION) TclVersion = float(_tkinter.TCL_VERSION) READABLE = _tkinter.READABLE WRITABLE = _tkinter.WRITABLE EXCEPTION = _tkinter.EXCEPTION _magic_re = re.compile(r'([\\{}])') _space_re = re.compile(r'([\s])', re.ASCII) def _join(value): """Internal function.""" return ' '.join(map(_stringify, value)) def _stringify(value): """Internal function.""" if isinstance(value, (list, tuple)): if len(value) == 1: value = _stringify(value[0]) if _magic_re.search(value): value = '{%s}' % value else: value = '{%s}' % _join(value) else: value = str(value) if not value: value = '{}' elif _magic_re.search(value): # add '\' before special characters and spaces value = _magic_re.sub(r'\\\1', value) value = value.replace('\n', r'\n') value = _space_re.sub(r'\\\1', value) if value[0] == '"': value = '\\' + value elif value[0] == '"' or _space_re.search(value): value = '{%s}' % value return value def _flatten(seq): """Internal function.""" res = () for item in seq: if isinstance(item, (tuple, list)): res = res + _flatten(item) elif item is not None: res = res + (item,) return res try: _flatten = _tkinter._flatten except AttributeError: pass def _cnfmerge(cnfs): """Internal function.""" if isinstance(cnfs, dict): return cnfs elif isinstance(cnfs, (type(None), str)): return cnfs else: cnf = {} for c in _flatten(cnfs): try: cnf.update(c) except (AttributeError, TypeError) as msg: print("_cnfmerge: fallback due to:", msg) for k, v in c.items(): cnf[k] = v return cnf try: _cnfmerge = _tkinter._cnfmerge except AttributeError: pass def _splitdict(tk, v, cut_minus=True, conv=None): """Return a properly formatted dict built from Tcl list pairs. If cut_minus is True, the supposed '-' prefix will be removed from keys. If conv is specified, it is used to convert values. Tcl list is expected to contain an even number of elements. """ t = tk.splitlist(v) if len(t) % 2: raise RuntimeError('Tcl list representing a dict is expected ' 'to contain an even number of elements') it = iter(t) dict = {} for key, value in zip(it, it): key = str(key) if cut_minus and key[0] == '-': key = key[1:] if conv: value = conv(value) dict[key] = value return dict class EventType(str, enum.Enum): KeyPress = '2' Key = KeyPress, KeyRelease = '3' ButtonPress = '4' Button = ButtonPress, ButtonRelease = '5' Motion = '6' Enter = '7' Leave = '8' FocusIn = '9' FocusOut = '10' Keymap = '11' # undocumented Expose = '12' GraphicsExpose = '13' # undocumented NoExpose = '14' # undocumented Visibility = '15' Create = '16' Destroy = '17' Unmap = '18' Map = '19' MapRequest = '20' Reparent = '21' Configure = '22' ConfigureRequest = '23' Gravity = '24' ResizeRequest = '25' Circulate = '26' CirculateRequest = '27' Property = '28' SelectionClear = '29' # undocumented SelectionRequest = '30' # undocumented Selection = '31' # undocumented Colormap = '32' ClientMessage = '33' # undocumented Mapping = '34' # undocumented VirtualEvent = '35', # undocumented Activate = '36', Deactivate = '37', MouseWheel = '38', def __str__(self): return self.name class Event: """Container for the properties of an event. Instances of this type are generated if one of the following events occurs: KeyPress, KeyRelease - for keyboard events ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate, Colormap, Gravity, Reparent, Property, Destroy, Activate, Deactivate - for window events. If a callback function for one of these events is registered using bind, bind_all, bind_class, or tag_bind, the callback is called with an Event as first argument. It will have the following attributes (in braces are the event types for which the attribute is valid): serial - serial number of event num - mouse button pressed (ButtonPress, ButtonRelease) focus - whether the window has the focus (Enter, Leave) height - height of the exposed window (Configure, Expose) width - width of the exposed window (Configure, Expose) keycode - keycode of the pressed key (KeyPress, KeyRelease) state - state of the event as a number (ButtonPress, ButtonRelease, Enter, KeyPress, KeyRelease, Leave, Motion) state - state as a string (Visibility) time - when the event occurred x - x-position of the mouse y - y-position of the mouse x_root - x-position of the mouse on the screen (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion) y_root - y-position of the mouse on the screen (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion) char - pressed character (KeyPress, KeyRelease) send_event - see X/Windows documentation keysym - keysym of the event as a string (KeyPress, KeyRelease) keysym_num - keysym of the event as a number (KeyPress, KeyRelease) type - type of the event as a number widget - widget in which the event occurred delta - delta of wheel movement (MouseWheel) """ def __repr__(self): attrs = {k: v for k, v in self.__dict__.items() if v != '??'} if not self.char: del attrs['char'] elif self.char != '??': attrs['char'] = repr(self.char) if not getattr(self, 'send_event', True): del attrs['send_event'] if self.state == 0: del attrs['state'] elif isinstance(self.state, int): state = self.state mods = ('Shift', 'Lock', 'Control', 'Mod1', 'Mod2', 'Mod3', 'Mod4', 'Mod5', 'Button1', 'Button2', 'Button3', 'Button4', 'Button5') s = [] for i, n in enumerate(mods): if state & (1 << i): s.append(n) state = state & ~((1<< len(mods)) - 1) if state or not s: s.append(hex(state)) attrs['state'] = '|'.join(s) if self.delta == 0: del attrs['delta'] # widget usually is known # serial and time are not very interesting # keysym_num duplicates keysym # x_root and y_root mostly duplicate x and y keys = ('send_event', 'state', 'keysym', 'keycode', 'char', 'num', 'delta', 'focus', 'x', 'y', 'width', 'height') return '<%s event%s>' % ( self.type, ''.join(' %s=%s' % (k, attrs[k]) for k in keys if k in attrs) ) _support_default_root = 1 _default_root = None def NoDefaultRoot(): """Inhibit setting of default root window. Call this function to inhibit that the first instance of Tk is used for windows without an explicit parent window. """ global _support_default_root _support_default_root = 0 global _default_root _default_root = None del _default_root def _tkerror(err): """Internal function.""" pass def _exit(code=0): """Internal function. Calling it will raise the exception SystemExit.""" try: code = int(code) except ValueError: pass raise SystemExit(code) _varnum = 0 class Variable: """Class to define value holders for e.g. buttons. Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations that constrain the type of the value returned from get().""" _default = "" _tk = None _tclCommands = None def __init__(self, master=None, value=None, name=None): """Construct a variable MASTER can be given as master widget. VALUE is an optional value (defaults to "") NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ # check for type of NAME parameter to override weird error message # raised from Modules/_tkinter.c:SetVar like: # TypeError: setvar() takes exactly 3 arguments (2 given) if name is not None and not isinstance(name, str): raise TypeError("name must be a string") global _varnum if not master: master = _default_root self._root = master._root() self._tk = master.tk if name: self._name = name else: self._name = 'PY_VAR' + repr(_varnum) _varnum += 1 if value is not None: self.initialize(value) elif not self._tk.getboolean(self._tk.call("info", "exists", self._name)): self.initialize(self._default) def __del__(self): """Unset the variable in Tcl.""" if self._tk is None: return if self._tk.getboolean(self._tk.call("info", "exists", self._name)): self._tk.globalunsetvar(self._name) if self._tclCommands is not None: for name in self._tclCommands: #print '- Tkinter: deleted command', name self._tk.deletecommand(name) self._tclCommands = None def __str__(self): """Return the name of the variable in Tcl.""" return self._name def set(self, value): """Set the variable to VALUE.""" return self._tk.globalsetvar(self._name, value) initialize = set def get(self): """Return value of variable.""" return self._tk.globalgetvar(self._name) def _register(self, callback): f = CallWrapper(callback, None, self._root).__call__ cbname = repr(id(f)) try: callback = callback.__func__ except AttributeError: pass try: cbname = cbname + callback.__name__ except AttributeError: pass self._tk.createcommand(cbname, f) if self._tclCommands is None: self._tclCommands = [] self._tclCommands.append(cbname) return cbname def trace_add(self, mode, callback): """Define a trace callback for the variable. Mode is one of "read", "write", "unset", or a list or tuple of such strings. Callback must be a function which is called when the variable is read, written or unset. Return the name of the callback. """ cbname = self._register(callback) self._tk.call('trace', 'add', 'variable', self._name, mode, (cbname,)) return cbname def trace_remove(self, mode, cbname): """Delete the trace callback for a variable. Mode is one of "read", "write", "unset" or a list or tuple of such strings. Must be same as were specified in trace_add(). cbname is the name of the callback returned from trace_add(). """ self._tk.call('trace', 'remove', 'variable', self._name, mode, cbname) for m, ca in self.trace_info(): if self._tk.splitlist(ca)[0] == cbname: break else: self._tk.deletecommand(cbname) try: self._tclCommands.remove(cbname) except ValueError: pass def trace_info(self): """Return all trace callback information.""" splitlist = self._tk.splitlist return [(splitlist(k), v) for k, v in map(splitlist, splitlist(self._tk.call('trace', 'info', 'variable', self._name)))] def trace_variable(self, mode, callback): """Define a trace callback for the variable. MODE is one of "r", "w", "u" for read, write, undefine. CALLBACK must be a function which is called when the variable is read, written or undefined. Return the name of the callback. This deprecated method wraps a deprecated Tcl method that will likely be removed in the future. Use trace_add() instead. """ # TODO: Add deprecation warning cbname = self._register(callback) self._tk.call("trace", "variable", self._name, mode, cbname) return cbname trace = trace_variable def trace_vdelete(self, mode, cbname): """Delete the trace callback for a variable. MODE is one of "r", "w", "u" for read, write, undefine. CBNAME is the name of the callback returned from trace_variable or trace. This deprecated method wraps a deprecated Tcl method that will likely be removed in the future. Use trace_remove() instead. """ # TODO: Add deprecation warning self._tk.call("trace", "vdelete", self._name, mode, cbname) cbname = self._tk.splitlist(cbname)[0] for m, ca in self.trace_info(): if self._tk.splitlist(ca)[0] == cbname: break else: self._tk.deletecommand(cbname) try: self._tclCommands.remove(cbname) except ValueError: pass def trace_vinfo(self): """Return all trace callback information. This deprecated method wraps a deprecated Tcl method that will likely be removed in the future. Use trace_info() instead. """ # TODO: Add deprecation warning return [self._tk.splitlist(x) for x in self._tk.splitlist( self._tk.call("trace", "vinfo", self._name))] def __eq__(self, other): """Comparison for equality (==). Note: if the Variable's master matters to behavior also compare self._master == other._master """ return self.__class__.__name__ == other.__class__.__name__ \ and self._name == other._name class StringVar(Variable): """Value holder for strings variables.""" _default = "" def __init__(self, master=None, value=None, name=None): """Construct a string variable. MASTER can be given as master widget. VALUE is an optional value (defaults to "") NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name) def get(self): """Return value of variable as string.""" value = self._tk.globalgetvar(self._name) if isinstance(value, str): return value return str(value) class IntVar(Variable): """Value holder for integer variables.""" _default = 0 def __init__(self, master=None, value=None, name=None): """Construct an integer variable. MASTER can be given as master widget. VALUE is an optional value (defaults to 0) NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name) def get(self): """Return the value of the variable as an integer.""" value = self._tk.globalgetvar(self._name) try: return self._tk.getint(value) except (TypeError, TclError): return int(self._tk.getdouble(value)) class DoubleVar(Variable): """Value holder for float variables.""" _default = 0.0 def __init__(self, master=None, value=None, name=None): """Construct a float variable. MASTER can be given as master widget. VALUE is an optional value (defaults to 0.0) NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name) def get(self): """Return the value of the variable as a float.""" return self._tk.getdouble(self._tk.globalgetvar(self._name)) class BooleanVar(Variable): """Value holder for boolean variables.""" _default = False def __init__(self, master=None, value=None, name=None): """Construct a boolean variable. MASTER can be given as master widget. VALUE is an optional value (defaults to False) NAME is an optional Tcl name (defaults to PY_VARnum). If NAME matches an existing variable and VALUE is omitted then the existing value is retained. """ Variable.__init__(self, master, value, name) def set(self, value): """Set the variable to VALUE.""" return self._tk.globalsetvar(self._name, self._tk.getboolean(value)) initialize = set def get(self): """Return the value of the variable as a bool.""" try: return self._tk.getboolean(self._tk.globalgetvar(self._name)) except TclError: raise ValueError("invalid literal for getboolean()") def mainloop(n=0): """Run the main loop of Tcl.""" _default_root.tk.mainloop(n) getint = int getdouble = float def getboolean(s): """Convert true and false to integer values 1 and 0.""" try: return _default_root.tk.getboolean(s) except TclError: raise ValueError("invalid literal for getboolean()") # Methods defined on both toplevel and interior widgets class Misc: """Internal class. Base class which defines methods common for interior widgets.""" # used for generating child widget names _last_child_ids = None # XXX font command? _tclCommands = None def destroy(self): """Internal function. Delete all Tcl commands created for this widget in the Tcl interpreter.""" if self._tclCommands is not None: for name in self._tclCommands: #print '- Tkinter: deleted command', name self.tk.deletecommand(name) self._tclCommands = None def deletecommand(self, name): """Internal function. Delete the Tcl command provided in NAME.""" #print '- Tkinter: deleted command', name self.tk.deletecommand(name) try: self._tclCommands.remove(name) except ValueError: pass def tk_strictMotif(self, boolean=None): """Set Tcl internal variable, whether the look and feel should adhere to Motif. A parameter of 1 means adhere to Motif (e.g. no color change if mouse passes over slider). Returns the set value.""" return self.tk.getboolean(self.tk.call( 'set', 'tk_strictMotif', boolean)) def tk_bisque(self): """Change the color scheme to light brown as used in Tk 3.6 and before.""" self.tk.call('tk_bisque') def tk_setPalette(self, *args, **kw): """Set a new color scheme for all widget elements. A single color as argument will cause that all colors of Tk widget elements are derived from this. Alternatively several keyword parameters and its associated colors can be given. The following keywords are valid: activeBackground, foreground, selectColor, activeForeground, highlightBackground, selectBackground, background, highlightColor, selectForeground, disabledForeground, insertBackground, troughColor.""" self.tk.call(('tk_setPalette',) + _flatten(args) + _flatten(list(kw.items()))) def wait_variable(self, name='PY_VAR'): """Wait until the variable is modified. A parameter of type IntVar, StringVar, DoubleVar or BooleanVar must be given.""" self.tk.call('tkwait', 'variable', name) waitvar = wait_variable # XXX b/w compat def wait_window(self, window=None): """Wait until a WIDGET is destroyed. If no parameter is given self is used.""" if window is None: window = self self.tk.call('tkwait', 'window', window._w) def wait_visibility(self, window=None): """Wait until the visibility of a WIDGET changes (e.g. it appears). If no parameter is given self is used.""" if window is None: window = self self.tk.call('tkwait', 'visibility', window._w) def setvar(self, name='PY_VAR', value='1'): """Set Tcl variable NAME to VALUE.""" self.tk.setvar(name, value) def getvar(self, name='PY_VAR'): """Return value of Tcl variable NAME.""" return self.tk.getvar(name) def getint(self, s): try: return self.tk.getint(s) except TclError as exc: raise ValueError(str(exc)) def getdouble(self, s): try: return self.tk.getdouble(s) except TclError as exc: raise ValueError(str(exc)) def getboolean(self, s): """Return a boolean value for Tcl boolean values true and false given as parameter.""" try: return self.tk.getboolean(s) except TclError: raise ValueError("invalid literal for getboolean()") def focus_set(self): """Direct input focus to this widget. If the application currently does not have the focus this widget will get the focus if the application gets the focus through the window manager.""" self.tk.call('focus', self._w) focus = focus_set # XXX b/w compat? def focus_force(self): """Direct input focus to this widget even if the application does not have the focus. Use with caution!""" self.tk.call('focus', '-force', self._w) def focus_get(self): """Return the widget which has currently the focus in the application. Use focus_displayof to allow working with several displays. Return None if application does not have the focus.""" name = self.tk.call('focus') if name == 'none' or not name: return None return self._nametowidget(name) def focus_displayof(self): """Return the widget which has currently the focus on the display where this widget is located. Return None if the application does not have the focus.""" name = self.tk.call('focus', '-displayof', self._w) if name == 'none' or not name: return None return self._nametowidget(name) def focus_lastfor(self): """Return the widget which would have the focus if top level for this widget gets the focus from the window manager.""" name = self.tk.call('focus', '-lastfor', self._w) if name == 'none' or not name: return None return self._nametowidget(name) def tk_focusFollowsMouse(self): """The widget under mouse will get automatically focus. Can not be disabled easily.""" self.tk.call('tk_focusFollowsMouse') def tk_focusNext(self): """Return the next widget in the focus order which follows widget which has currently the focus. The focus order first goes to the next child, then to the children of the child recursively and then to the next sibling which is higher in the stacking order. A widget is omitted if it has the takefocus resource set to 0.""" name = self.tk.call('tk_focusNext', self._w) if not name: return None return self._nametowidget(name) def tk_focusPrev(self): """Return previous widget in the focus order. See tk_focusNext for details.""" name = self.tk.call('tk_focusPrev', self._w) if not name: return None return self._nametowidget(name) def after(self, ms, func=None, *args): """Call function once after given time. MS specifies the time in milliseconds. FUNC gives the function which shall be called. Additional parameters are given as parameters to the function call. Return identifier to cancel scheduling with after_cancel.""" if not func: # I'd rather use time.sleep(ms*0.001) self.tk.call('after', ms) return None else: def callit(): try: func(*args) finally: try: self.deletecommand(name) except TclError: pass callit.__name__ = func.__name__ name = self._register(callit) return self.tk.call('after', ms, name) def after_idle(self, func, *args): """Call FUNC once if the Tcl main loop has no event to process. Return an identifier to cancel the scheduling with after_cancel.""" return self.after('idle', func, *args) def after_cancel(self, id): """Cancel scheduling of function identified with ID. Identifier returned by after or after_idle must be given as first parameter. """ if not id: raise ValueError('id must be a valid identifier returned from ' 'after or after_idle') try: data = self.tk.call('after', 'info', id) script = self.tk.splitlist(data)[0] self.deletecommand(script) except TclError: pass self.tk.call('after', 'cancel', id) def bell(self, displayof=0): """Ring a display's bell.""" self.tk.call(('bell',) + self._displayof(displayof)) # Clipboard handling: def clipboard_get(self, **kw): """Retrieve data from the clipboard on window's display. The window keyword defaults to the root window of the Tkinter application. The type keyword specifies the form in which the data is to be returned and should be an atom name such as STRING or FILE_NAME. Type defaults to STRING, except on X11, where the default is to try UTF8_STRING and fall back to STRING. This command is equivalent to: selection_get(CLIPBOARD) """ if 'type' not in kw and self._windowingsystem == 'x11': try: kw['type'] = 'UTF8_STRING' return self.tk.call(('clipboard', 'get') + self._options(kw)) except TclError: del kw['type'] return self.tk.call(('clipboard', 'get') + self._options(kw)) def clipboard_clear(self, **kw): """Clear the data in the Tk clipboard. A widget specified for the optional displayof keyword argument specifies the target display.""" if 'displayof' not in kw: kw['displayof'] = self._w self.tk.call(('clipboard', 'clear') + self._options(kw)) def clipboard_append(self, string, **kw): """Append STRING to the Tk clipboard. A widget specified at the optional displayof keyword argument specifies the target display. The clipboard can be retrieved with selection_get.""" if 'displayof' not in kw: kw['displayof'] = self._w self.tk.call(('clipboard', 'append') + self._options(kw) + ('--', string)) # XXX grab current w/o window argument def grab_current(self): """Return widget which has currently the grab in this application or None.""" name = self.tk.call('grab', 'current', self._w) if not name: return None return self._nametowidget(name) def grab_release(self): """Release grab for this widget if currently set.""" self.tk.call('grab', 'release', self._w) def grab_set(self): """Set grab for this widget. A grab directs all events to this and descendant widgets in the application.""" self.tk.call('grab', 'set', self._w) def grab_set_global(self): """Set global grab for this widget. A global grab directs all events to this and descendant widgets on the display. Use with caution - other applications do not get events anymore.""" self.tk.call('grab', 'set', '-global', self._w) def grab_status(self): """Return None, "local" or "global" if this widget has no, a local or a global grab.""" status = self.tk.call('grab', 'status', self._w) if status == 'none': status = None return status def option_add(self, pattern, value, priority = None): """Set a VALUE (second parameter) for an option PATTERN (first parameter). An optional third parameter gives the numeric priority (defaults to 80).""" self.tk.call('option', 'add', pattern, value, priority) def option_clear(self): """Clear the option database. It will be reloaded if option_add is called.""" self.tk.call('option', 'clear') def option_get(self, name, className): """Return the value for an option NAME for this widget with CLASSNAME. Values with higher priority override lower values.""" return self.tk.call('option', 'get', self._w, name, className) def option_readfile(self, fileName, priority = None): """Read file FILENAME into the option database. An optional second parameter gives the numeric priority.""" self.tk.call('option', 'readfile', fileName, priority) def selection_clear(self, **kw): """Clear the current X selection.""" if 'displayof' not in kw: kw['displayof'] = self._w self.tk.call(('selection', 'clear') + self._options(kw)) def selection_get(self, **kw): """Return the contents of the current X selection. A keyword parameter selection specifies the name of the selection and defaults to PRIMARY. A keyword parameter displayof specifies a widget on the display to use. A keyword parameter type specifies the form of data to be fetched, defaulting to STRING except on X11, where UTF8_STRING is tried before STRING.""" if 'displayof' not in kw: kw['displayof'] = self._w if 'type' not in kw and self._windowingsystem == 'x11': try: kw['type'] = 'UTF8_STRING' return self.tk.call(('selection', 'get') + self._options(kw)) except TclError: del kw['type'] return self.tk.call(('selection', 'get') + self._options(kw)) def selection_handle(self, command, **kw): """Specify a function COMMAND to call if the X selection owned by this widget is queried by another application. This function must return the contents of the selection. The function will be called with the arguments OFFSET and LENGTH which allows the chunking of very long selections. The following keyword parameters can be provided: selection - name of the selection (default PRIMARY), type - type of the selection (e.g. STRING, FILE_NAME).""" name = self._register(command) self.tk.call(('selection', 'handle') + self._options(kw) + (self._w, name)) def selection_own(self, **kw): """Become owner of X selection. A keyword parameter selection specifies the name of the selection (default PRIMARY).""" self.tk.call(('selection', 'own') + self._options(kw) + (self._w,)) def selection_own_get(self, **kw): """Return owner of X selection. The following keyword parameter can be provided: selection - name of the selection (default PRIMARY), type - type of the selection (e.g. STRING, FILE_NAME).""" if 'displayof' not in kw: kw['displayof'] = self._w name = self.tk.call(('selection', 'own') + self._options(kw)) if not name: return None return self._nametowidget(name) def send(self, interp, cmd, *args): """Send Tcl command CMD to different interpreter INTERP to be executed.""" return self.tk.call(('send', interp, cmd) + args) def lower(self, belowThis=None): """Lower this widget in the stacking order.""" self.tk.call('lower', self._w, belowThis) def tkraise(self, aboveThis=None): """Raise this widget in the stacking order.""" self.tk.call('raise', self._w, aboveThis) lift = tkraise def winfo_atom(self, name, displayof=0): """Return integer which represents atom NAME.""" args = ('winfo', 'atom') + self._displayof(displayof) + (name,) return self.tk.getint(self.tk.call(args)) def winfo_atomname(self, id, displayof=0): """Return name of atom with identifier ID.""" args = ('winfo', 'atomname') \ + self._displayof(displayof) + (id,) return self.tk.call(args) def winfo_cells(self): """Return number of cells in the colormap for this widget.""" return self.tk.getint( self.tk.call('winfo', 'cells', self._w)) def winfo_children(self): """Return a list of all widgets which are children of this widget.""" result = [] for child in self.tk.splitlist( self.tk.call('winfo', 'children', self._w)): try: # Tcl sometimes returns extra windows, e.g. for # menus; those need to be skipped result.append(self._nametowidget(child)) except KeyError: pass return result def winfo_class(self): """Return window class name of this widget.""" return self.tk.call('winfo', 'class', self._w) def winfo_colormapfull(self): """Return True if at the last color request the colormap was full.""" return self.tk.getboolean( self.tk.call('winfo', 'colormapfull', self._w)) def winfo_containing(self, rootX, rootY, displayof=0): """Return the widget which is at the root coordinates ROOTX, ROOTY.""" args = ('winfo', 'containing') \ + self._displayof(displayof) + (rootX, rootY) name = self.tk.call(args) if not name: return None return self._nametowidget(name) def winfo_depth(self): """Return the number of bits per pixel.""" return self.tk.getint(self.tk.call('winfo', 'depth', self._w)) def winfo_exists(self): """Return true if this widget exists.""" return self.tk.getint( self.tk.call('winfo', 'exists', self._w)) def winfo_fpixels(self, number): """Return the number of pixels for the given distance NUMBER (e.g. "3c") as float.""" return self.tk.getdouble(self.tk.call( 'winfo', 'fpixels', self._w, number)) def winfo_geometry(self): """Return geometry string for this widget in the form "widthxheight+X+Y".""" return self.tk.call('winfo', 'geometry', self._w) def winfo_height(self): """Return height of this widget.""" return self.tk.getint( self.tk.call('winfo', 'height', self._w)) def winfo_id(self): """Return identifier ID for this widget.""" return int(self.tk.call('winfo', 'id', self._w), 0) def winfo_interps(self, displayof=0): """Return the name of all Tcl interpreters for this display.""" args = ('winfo', 'interps') + self._displayof(displayof) return self.tk.splitlist(self.tk.call(args)) def winfo_ismapped(self): """Return true if this widget is mapped.""" return self.tk.getint( self.tk.call('winfo', 'ismapped', self._w)) def winfo_manager(self): """Return the window manager name for this widget.""" return self.tk.call('winfo', 'manager', self._w) def winfo_name(self): """Return the name of this widget.""" return self.tk.call('winfo', 'name', self._w) def winfo_parent(self): """Return the name of the parent of this widget.""" return self.tk.call('winfo', 'parent', self._w) def winfo_pathname(self, id, displayof=0): """Return the pathname of the widget given by ID.""" args = ('winfo', 'pathname') \ + self._displayof(displayof) + (id,) return self.tk.call(args) def winfo_pixels(self, number): """Rounded integer value of winfo_fpixels.""" return self.tk.getint( self.tk.call('winfo', 'pixels', self._w, number)) def winfo_pointerx(self): """Return the x coordinate of the pointer on the root window.""" return self.tk.getint( self.tk.call('winfo', 'pointerx', self._w)) def winfo_pointerxy(self): """Return a tuple of x and y coordinates of the pointer on the root window.""" return self._getints( self.tk.call('winfo', 'pointerxy', self._w)) def winfo_pointery(self): """Return the y coordinate of the pointer on the root window.""" return self.tk.getint( self.tk.call('winfo', 'pointery', self._w)) def winfo_reqheight(self): """Return requested height of this widget.""" return self.tk.getint( self.tk.call('winfo', 'reqheight', self._w)) def winfo_reqwidth(self): """Return requested width of this widget.""" return self.tk.getint( self.tk.call('winfo', 'reqwidth', self._w)) def winfo_rgb(self, color): """Return tuple of decimal values for red, green, blue for COLOR in this widget.""" return self._getints( self.tk.call('winfo', 'rgb', self._w, color)) def winfo_rootx(self): """Return x coordinate of upper left corner of this widget on the root window.""" return self.tk.getint( self.tk.call('winfo', 'rootx', self._w)) def winfo_rooty(self): """Return y coordinate of upper left corner of this widget on the root window.""" return self.tk.getint( self.tk.call('winfo', 'rooty', self._w)) def winfo_screen(self): """Return the screen name of this widget.""" return self.tk.call('winfo', 'screen', self._w) def winfo_screencells(self): """Return the number of the cells in the colormap of the screen of this widget.""" return self.tk.getint( self.tk.call('winfo', 'screencells', self._w)) def winfo_screendepth(self): """Return the number of bits per pixel of the root window of the screen of this widget.""" return self.tk.getint( self.tk.call('winfo', 'screendepth', self._w)) def winfo_screenheight(self): """Return the number of pixels of the height of the screen of this widget in pixel.""" return self.tk.getint( self.tk.call('winfo', 'screenheight', self._w)) def winfo_screenmmheight(self): """Return the number of pixels of the height of the screen of this widget in mm.""" return self.tk.getint( self.tk.call('winfo', 'screenmmheight', self._w)) def winfo_screenmmwidth(self): """Return the number of pixels of the width of the screen of this widget in mm.""" return self.tk.getint( self.tk.call('winfo', 'screenmmwidth', self._w)) def winfo_screenvisual(self): """Return one of the strings directcolor, grayscale, pseudocolor, staticcolor, staticgray, or truecolor for the default colormodel of this screen.""" return self.tk.call('winfo', 'screenvisual', self._w) def winfo_screenwidth(self): """Return the number of pixels of the width of the screen of this widget in pixel.""" return self.tk.getint( self.tk.call('winfo', 'screenwidth', self._w)) def winfo_server(self): """Return information of the X-Server of the screen of this widget in the form "XmajorRminor vendor vendorVersion".""" return self.tk.call('winfo', 'server', self._w) def winfo_toplevel(self): """Return the toplevel widget of this widget.""" return self._nametowidget(self.tk.call( 'winfo', 'toplevel', self._w)) def winfo_viewable(self): """Return true if the widget and all its higher ancestors are mapped.""" return self.tk.getint( self.tk.call('winfo', 'viewable', self._w)) def winfo_visual(self): """Return one of the strings directcolor, grayscale, pseudocolor, staticcolor, staticgray, or truecolor for the colormodel of this widget.""" return self.tk.call('winfo', 'visual', self._w) def winfo_visualid(self): """Return the X identifier for the visual for this widget.""" return self.tk.call('winfo', 'visualid', self._w) def winfo_visualsavailable(self, includeids=False): """Return a list of all visuals available for the screen of this widget. Each item in the list consists of a visual name (see winfo_visual), a depth and if includeids is true is given also the X identifier.""" data = self.tk.call('winfo', 'visualsavailable', self._w, 'includeids' if includeids else None) data = [self.tk.splitlist(x) for x in self.tk.splitlist(data)] return [self.__winfo_parseitem(x) for x in data] def __winfo_parseitem(self, t): """Internal function.""" return t[:1] + tuple(map(self.__winfo_getint, t[1:])) def __winfo_getint(self, x): """Internal function.""" return int(x, 0) def winfo_vrootheight(self): """Return the height of the virtual root window associated with this widget in pixels. If there is no virtual root window return the height of the screen.""" return self.tk.getint( self.tk.call('winfo', 'vrootheight', self._w)) def winfo_vrootwidth(self): """Return the width of the virtual root window associated with this widget in pixel. If there is no virtual root window return the width of the screen.""" return self.tk.getint( self.tk.call('winfo', 'vrootwidth', self._w)) def winfo_vrootx(self): """Return the x offset of the virtual root relative to the root window of the screen of this widget.""" return self.tk.getint( self.tk.call('winfo', 'vrootx', self._w)) def winfo_vrooty(self): """Return the y offset of the virtual root relative to the root window of the screen of this widget.""" return self.tk.getint( self.tk.call('winfo', 'vrooty', self._w)) def winfo_width(self): """Return the width of this widget.""" return self.tk.getint( self.tk.call('winfo', 'width', self._w)) def winfo_x(self): """Return the x coordinate of the upper left corner of this widget in the parent.""" return self.tk.getint( self.tk.call('winfo', 'x', self._w)) def winfo_y(self): """Return the y coordinate of the upper left corner of this widget in the parent.""" return self.tk.getint( self.tk.call('winfo', 'y', self._w)) def update(self): """Enter event loop until all pending events have been processed by Tcl.""" self.tk.call('update') def update_idletasks(self): """Enter event loop until all idle callbacks have been called. This will update the display of windows but not process events caused by the user.""" self.tk.call('update', 'idletasks') def bindtags(self, tagList=None): """Set or get the list of bindtags for this widget. With no argument return the list of all bindtags associated with this widget. With a list of strings as argument the bindtags are set to this list. The bindtags determine in which order events are processed (see bind).""" if tagList is None: return self.tk.splitlist( self.tk.call('bindtags', self._w)) else: self.tk.call('bindtags', self._w, tagList) def _bind(self, what, sequence, func, add, needcleanup=1): """Internal function.""" if isinstance(func, str): self.tk.call(what + (sequence, func)) elif func: funcid = self._register(func, self._substitute, needcleanup) cmd = ('%sif {"[%s %s]" == "break"} break\n' % (add and '+' or '', funcid, self._subst_format_str)) self.tk.call(what + (sequence, cmd)) return funcid elif sequence: return self.tk.call(what + (sequence,)) else: return self.tk.splitlist(self.tk.call(what)) def bind(self, sequence=None, func=None, add=None): """Bind to this widget at event SEQUENCE a call to function FUNC. SEQUENCE is a string of concatenated event patterns. An event pattern is of the form <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4, Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3, B3, Alt, Button4, B4, Double, Button5, B5 Triple, Mod1, M1. TYPE is one of Activate, Enter, Map, ButtonPress, Button, Expose, Motion, ButtonRelease FocusIn, MouseWheel, Circulate, FocusOut, Property, Colormap, Gravity Reparent, Configure, KeyPress, Key, Unmap, Deactivate, KeyRelease Visibility, Destroy, Leave and DETAIL is the button number for ButtonPress, ButtonRelease and DETAIL is the Keysym for KeyPress and KeyRelease. Examples are <Control-Button-1> for pressing Control and mouse button 1 or <Alt-A> for pressing A and the Alt key (KeyPress can be omitted). An event pattern can also be a virtual event of the form <<AString>> where AString can be arbitrary. This event can be generated by event_generate. If events are concatenated they must appear shortly after each other. FUNC will be called if the event sequence occurs with an instance of Event as argument. If the return value of FUNC is "break" no further bound function is invoked. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. Bind will return an identifier to allow deletion of the bound function with unbind without memory leak. If FUNC or SEQUENCE is omitted the bound function or list of bound events are returned.""" return self._bind(('bind', self._w), sequence, func, add) def unbind(self, sequence, funcid=None): """Unbind for this widget for event SEQUENCE the function identified with FUNCID.""" self.tk.call('bind', self._w, sequence, '') if funcid: self.deletecommand(funcid) def bind_all(self, sequence=None, func=None, add=None): """Bind to all widgets at an event SEQUENCE a call to function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.""" return self._bind(('bind', 'all'), sequence, func, add, 0) def unbind_all(self, sequence): """Unbind for all widgets for event SEQUENCE all functions.""" self.tk.call('bind', 'all' , sequence, '') def bind_class(self, className, sequence=None, func=None, add=None): """Bind to widgets with bindtag CLASSNAME at event SEQUENCE a call of function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.""" return self._bind(('bind', className), sequence, func, add, 0) def unbind_class(self, className, sequence): """Unbind for all widgets with bindtag CLASSNAME for event SEQUENCE all functions.""" self.tk.call('bind', className , sequence, '') def mainloop(self, n=0): """Call the mainloop of Tk.""" self.tk.mainloop(n) def quit(self): """Quit the Tcl interpreter. All widgets will be destroyed.""" self.tk.quit() def _getints(self, string): """Internal function.""" if string: return tuple(map(self.tk.getint, self.tk.splitlist(string))) def _getdoubles(self, string): """Internal function.""" if string: return tuple(map(self.tk.getdouble, self.tk.splitlist(string))) def _getboolean(self, string): """Internal function.""" if string: return self.tk.getboolean(string) def _displayof(self, displayof): """Internal function.""" if displayof: return ('-displayof', displayof) if displayof is None: return ('-displayof', self._w) return () @property def _windowingsystem(self): """Internal function.""" try: return self._root()._windowingsystem_cached except AttributeError: ws = self._root()._windowingsystem_cached = \ self.tk.call('tk', 'windowingsystem') return ws def _options(self, cnf, kw = None): """Internal function.""" if kw: cnf = _cnfmerge((cnf, kw)) else: cnf = _cnfmerge(cnf) res = () for k, v in cnf.items(): if v is not None: if k[-1] == '_': k = k[:-1] if callable(v): v = self._register(v) elif isinstance(v, (tuple, list)): nv = [] for item in v: if isinstance(item, int): nv.append(str(item)) elif isinstance(item, str): nv.append(_stringify(item)) else: break else: v = ' '.join(nv) res = res + ('-'+k, v) return res def nametowidget(self, name): """Return the Tkinter instance of a widget identified by its Tcl name NAME.""" name = str(name).split('.') w = self if not name[0]: w = w._root() name = name[1:] for n in name: if not n: break w = w.children[n] return w _nametowidget = nametowidget def _register(self, func, subst=None, needcleanup=1): """Return a newly created Tcl function. If this function is called, the Python function FUNC will be executed. An optional function SUBST can be given which will be executed before FUNC.""" f = CallWrapper(func, subst, self).__call__ name = repr(id(f)) try: func = func.__func__ except AttributeError: pass try: name = name + func.__name__ except AttributeError: pass self.tk.createcommand(name, f) if needcleanup: if self._tclCommands is None: self._tclCommands = [] self._tclCommands.append(name) return name register = _register def _root(self): """Internal function.""" w = self while w.master: w = w.master return w _subst_format = ('%#', '%b', '%f', '%h', '%k', '%s', '%t', '%w', '%x', '%y', '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D') _subst_format_str = " ".join(_subst_format) def _substitute(self, *args): """Internal function.""" if len(args) != len(self._subst_format): return args getboolean = self.tk.getboolean getint = self.tk.getint def getint_event(s): """Tk changed behavior in 8.4.2, returning "??" rather more often.""" try: return getint(s) except (ValueError, TclError): return s nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args # Missing: (a, c, d, m, o, v, B, R) e = Event() # serial field: valid for all events # number of button: ButtonPress and ButtonRelease events only # height field: Configure, ConfigureRequest, Create, # ResizeRequest, and Expose events only # keycode field: KeyPress and KeyRelease events only # time field: "valid for events that contain a time field" # width field: Configure, ConfigureRequest, Create, ResizeRequest, # and Expose events only # x field: "valid for events that contain an x field" # y field: "valid for events that contain a y field" # keysym as decimal: KeyPress and KeyRelease events only # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress, # KeyRelease, and Motion events e.serial = getint(nsign) e.num = getint_event(b) try: e.focus = getboolean(f) except TclError: pass e.height = getint_event(h) e.keycode = getint_event(k) e.state = getint_event(s) e.time = getint_event(t) e.width = getint_event(w) e.x = getint_event(x) e.y = getint_event(y) e.char = A try: e.send_event = getboolean(E) except TclError: pass e.keysym = K e.keysym_num = getint_event(N) try: e.type = EventType(T) except ValueError: e.type = T try: e.widget = self._nametowidget(W) except KeyError: e.widget = W e.x_root = getint_event(X) e.y_root = getint_event(Y) try: e.delta = getint(D) except (ValueError, TclError): e.delta = 0 return (e,) def _report_exception(self): """Internal function.""" exc, val, tb = sys.exc_info() root = self._root() root.report_callback_exception(exc, val, tb) def _getconfigure(self, *args): """Call Tcl configure command and return the result as a dict.""" cnf = {} for x in self.tk.splitlist(self.tk.call(*args)): x = self.tk.splitlist(x) cnf[x[0][1:]] = (x[0][1:],) + x[1:] return cnf def _getconfigure1(self, *args): x = self.tk.splitlist(self.tk.call(*args)) return (x[0][1:],) + x[1:] def _configure(self, cmd, cnf, kw): """Internal function.""" if kw: cnf = _cnfmerge((cnf, kw)) elif cnf: cnf = _cnfmerge(cnf) if cnf is None: return self._getconfigure(_flatten((self._w, cmd))) if isinstance(cnf, str): return self._getconfigure1(_flatten((self._w, cmd, '-'+cnf))) self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) # These used to be defined in Widget: def configure(self, cnf=None, **kw): """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method keys. """ return self._configure('configure', cnf, kw) config = configure def cget(self, key): """Return the resource value for a KEY given as string.""" return self.tk.call(self._w, 'cget', '-' + key) __getitem__ = cget def __setitem__(self, key, value): self.configure({key: value}) def keys(self): """Return a list of all resource names of this widget.""" splitlist = self.tk.splitlist return [splitlist(x)[0][1:] for x in splitlist(self.tk.call(self._w, 'configure'))] def __str__(self): """Return the window path name of this widget.""" return self._w def __repr__(self): return '<%s.%s object %s>' % ( self.__class__.__module__, self.__class__.__qualname__, self._w) # Pack methods that apply to the master _noarg_ = ['_noarg_'] def pack_propagate(self, flag=_noarg_): """Set or get the status for propagation of geometry information. A boolean argument specifies whether the geometry information of the slaves will determine the size of this widget. If no argument is given the current setting will be returned. """ if flag is Misc._noarg_: return self._getboolean(self.tk.call( 'pack', 'propagate', self._w)) else: self.tk.call('pack', 'propagate', self._w, flag) propagate = pack_propagate def pack_slaves(self): """Return a list of all slaves of this widget in its packing order.""" return [self._nametowidget(x) for x in self.tk.splitlist( self.tk.call('pack', 'slaves', self._w))] slaves = pack_slaves # Place method that applies to the master def place_slaves(self): """Return a list of all slaves of this widget in its packing order.""" return [self._nametowidget(x) for x in self.tk.splitlist( self.tk.call( 'place', 'slaves', self._w))] # Grid methods that apply to the master def grid_anchor(self, anchor=None): # new in Tk 8.5 """The anchor value controls how to place the grid within the master when no row/column has any weight. The default anchor is nw.""" self.tk.call('grid', 'anchor', self._w, anchor) anchor = grid_anchor def grid_bbox(self, column=None, row=None, col2=None, row2=None): """Return a tuple of integer coordinates for the bounding box of this widget controlled by the geometry manager grid. If COLUMN, ROW is given the bounding box applies from the cell with row and column 0 to the specified cell. If COL2 and ROW2 are given the bounding box starts at that cell. The returned integers specify the offset of the upper left corner in the master widget and the width and height. """ args = ('grid', 'bbox', self._w) if column is not None and row is not None: args = args + (column, row) if col2 is not None and row2 is not None: args = args + (col2, row2) return self._getints(self.tk.call(*args)) or None bbox = grid_bbox def _gridconvvalue(self, value): if isinstance(value, (str, _tkinter.Tcl_Obj)): try: svalue = str(value) if not svalue: return None elif '.' in svalue: return self.tk.getdouble(svalue) else: return self.tk.getint(svalue) except (ValueError, TclError): pass return value def _grid_configure(self, command, index, cnf, kw): """Internal function.""" if isinstance(cnf, str) and not kw: if cnf[-1:] == '_': cnf = cnf[:-1] if cnf[:1] != '-': cnf = '-'+cnf options = (cnf,) else: options = self._options(cnf, kw) if not options: return _splitdict( self.tk, self.tk.call('grid', command, self._w, index), conv=self._gridconvvalue) res = self.tk.call( ('grid', command, self._w, index) + options) if len(options) == 1: return self._gridconvvalue(res) def grid_columnconfigure(self, index, cnf={}, **kw): """Configure column INDEX of a grid. Valid resources are minsize (minimum size of the column), weight (how much does additional space propagate to this column) and pad (how much space to let additionally).""" return self._grid_configure('columnconfigure', index, cnf, kw) columnconfigure = grid_columnconfigure def grid_location(self, x, y): """Return a tuple of column and row which identify the cell at which the pixel at position X and Y inside the master widget is located.""" return self._getints( self.tk.call( 'grid', 'location', self._w, x, y)) or None def grid_propagate(self, flag=_noarg_): """Set or get the status for propagation of geometry information. A boolean argument specifies whether the geometry information of the slaves will determine the size of this widget. If no argument is given, the current setting will be returned. """ if flag is Misc._noarg_: return self._getboolean(self.tk.call( 'grid', 'propagate', self._w)) else: self.tk.call('grid', 'propagate', self._w, flag) def grid_rowconfigure(self, index, cnf={}, **kw): """Configure row INDEX of a grid. Valid resources are minsize (minimum size of the row), weight (how much does additional space propagate to this row) and pad (how much space to let additionally).""" return self._grid_configure('rowconfigure', index, cnf, kw) rowconfigure = grid_rowconfigure def grid_size(self): """Return a tuple of the number of column and rows in the grid.""" return self._getints( self.tk.call('grid', 'size', self._w)) or None size = grid_size def grid_slaves(self, row=None, column=None): """Return a list of all slaves of this widget in its packing order.""" args = () if row is not None: args = args + ('-row', row) if column is not None: args = args + ('-column', column) return [self._nametowidget(x) for x in self.tk.splitlist(self.tk.call( ('grid', 'slaves', self._w) + args))] # Support for the "event" command, new in Tk 4.2. # By Case Roole. def event_add(self, virtual, *sequences): """Bind a virtual event VIRTUAL (of the form <<Name>>) to an event SEQUENCE such that the virtual event is triggered whenever SEQUENCE occurs.""" args = ('event', 'add', virtual) + sequences self.tk.call(args) def event_delete(self, virtual, *sequences): """Unbind a virtual event VIRTUAL from SEQUENCE.""" args = ('event', 'delete', virtual) + sequences self.tk.call(args) def event_generate(self, sequence, **kw): """Generate an event SEQUENCE. Additional keyword arguments specify parameter of the event (e.g. x, y, rootx, rooty).""" args = ('event', 'generate', self._w, sequence) for k, v in kw.items(): args = args + ('-%s' % k, str(v)) self.tk.call(args) def event_info(self, virtual=None): """Return a list of all virtual events or the information about the SEQUENCE bound to the virtual event VIRTUAL.""" return self.tk.splitlist( self.tk.call('event', 'info', virtual)) # Image related commands def image_names(self): """Return a list of all existing image names.""" return self.tk.splitlist(self.tk.call('image', 'names')) def image_types(self): """Return a list of all available image types (e.g. photo bitmap).""" return self.tk.splitlist(self.tk.call('image', 'types')) class CallWrapper: """Internal class. Stores function to call when some user defined Tcl function is called e.g. after an event occurred.""" def __init__(self, func, subst, widget): """Store FUNC, SUBST and WIDGET as members.""" self.func = func self.subst = subst self.widget = widget def __call__(self, *args): """Apply first function SUBST to arguments, than FUNC.""" try: if self.subst: args = self.subst(*args) return self.func(*args) except SystemExit: raise except: self.widget._report_exception() class XView: """Mix-in class for querying and changing the horizontal position of a widget's window.""" def xview(self, *args): """Query and change the horizontal position of the view.""" res = self.tk.call(self._w, 'xview', *args) if not args: return self._getdoubles(res) def xview_moveto(self, fraction): """Adjusts the view in the window so that FRACTION of the total width of the canvas is off-screen to the left.""" self.tk.call(self._w, 'xview', 'moveto', fraction) def xview_scroll(self, number, what): """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT).""" self.tk.call(self._w, 'xview', 'scroll', number, what) class YView: """Mix-in class for querying and changing the vertical position of a widget's window.""" def yview(self, *args): """Query and change the vertical position of the view.""" res = self.tk.call(self._w, 'yview', *args) if not args: return self._getdoubles(res) def yview_moveto(self, fraction): """Adjusts the view in the window so that FRACTION of the total height of the canvas is off-screen to the top.""" self.tk.call(self._w, 'yview', 'moveto', fraction) def yview_scroll(self, number, what): """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT).""" self.tk.call(self._w, 'yview', 'scroll', number, what) class Wm: """Provides functions for the communication with the window manager.""" def wm_aspect(self, minNumer=None, minDenom=None, maxNumer=None, maxDenom=None): """Instruct the window manager to set the aspect ratio (width/height) of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple of the actual values if no argument is given.""" return self._getints( self.tk.call('wm', 'aspect', self._w, minNumer, minDenom, maxNumer, maxDenom)) aspect = wm_aspect def wm_attributes(self, *args): """This subcommand returns or sets platform specific attributes The first form returns a list of the platform specific flags and their values. The second form returns the value for the specific option. The third form sets one or more of the values. The values are as follows: On Windows, -disabled gets or sets whether the window is in a disabled state. -toolwindow gets or sets the style of the window to toolwindow (as defined in the MSDN). -topmost gets or sets whether this is a topmost window (displays above all other windows). On Macintosh, XXXXX On Unix, there are currently no special attribute values. """ args = ('wm', 'attributes', self._w) + args return self.tk.call(args) attributes=wm_attributes def wm_client(self, name=None): """Store NAME in WM_CLIENT_MACHINE property of this widget. Return current value.""" return self.tk.call('wm', 'client', self._w, name) client = wm_client def wm_colormapwindows(self, *wlist): """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property of this widget. This list contains windows whose colormaps differ from their parents. Return current list of widgets if WLIST is empty.""" if len(wlist) > 1: wlist = (wlist,) # Tk needs a list of windows here args = ('wm', 'colormapwindows', self._w) + wlist if wlist: self.tk.call(args) else: return [self._nametowidget(x) for x in self.tk.splitlist(self.tk.call(args))] colormapwindows = wm_colormapwindows def wm_command(self, value=None): """Store VALUE in WM_COMMAND property. It is the command which shall be used to invoke the application. Return current command if VALUE is None.""" return self.tk.call('wm', 'command', self._w, value) command = wm_command def wm_deiconify(self): """Deiconify this widget. If it was never mapped it will not be mapped. On Windows it will raise this widget and give it the focus.""" return self.tk.call('wm', 'deiconify', self._w) deiconify = wm_deiconify def wm_focusmodel(self, model=None): """Set focus model to MODEL. "active" means that this widget will claim the focus itself, "passive" means that the window manager shall give the focus. Return current focus model if MODEL is None.""" return self.tk.call('wm', 'focusmodel', self._w, model) focusmodel = wm_focusmodel def wm_forget(self, window): # new in Tk 8.5 """The window will be unmapped from the screen and will no longer be managed by wm. toplevel windows will be treated like frame windows once they are no longer managed by wm, however, the menu option configuration will be remembered and the menus will return once the widget is managed again.""" self.tk.call('wm', 'forget', window) forget = wm_forget def wm_frame(self): """Return identifier for decorative frame of this widget if present.""" return self.tk.call('wm', 'frame', self._w) frame = wm_frame def wm_geometry(self, newGeometry=None): """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return current value if None is given.""" return self.tk.call('wm', 'geometry', self._w, newGeometry) geometry = wm_geometry def wm_grid(self, baseWidth=None, baseHeight=None, widthInc=None, heightInc=None): """Instruct the window manager that this widget shall only be resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the number of grid units requested in Tk_GeometryRequest.""" return self._getints(self.tk.call( 'wm', 'grid', self._w, baseWidth, baseHeight, widthInc, heightInc)) grid = wm_grid def wm_group(self, pathName=None): """Set the group leader widgets for related widgets to PATHNAME. Return the group leader of this widget if None is given.""" return self.tk.call('wm', 'group', self._w, pathName) group = wm_group def wm_iconbitmap(self, bitmap=None, default=None): """Set bitmap for the iconified widget to BITMAP. Return the bitmap if None is given. Under Windows, the DEFAULT parameter can be used to set the icon for the widget and any descendents that don't have an icon set explicitly. DEFAULT can be the relative path to a .ico file (example: root.iconbitmap(default='myicon.ico') ). See Tk documentation for more information.""" if default: return self.tk.call('wm', 'iconbitmap', self._w, '-default', default) else: return self.tk.call('wm', 'iconbitmap', self._w, bitmap) iconbitmap = wm_iconbitmap def wm_iconify(self): """Display widget as icon.""" return self.tk.call('wm', 'iconify', self._w) iconify = wm_iconify def wm_iconmask(self, bitmap=None): """Set mask for the icon bitmap of this widget. Return the mask if None is given.""" return self.tk.call('wm', 'iconmask', self._w, bitmap) iconmask = wm_iconmask def wm_iconname(self, newName=None): """Set the name of the icon for this widget. Return the name if None is given.""" return self.tk.call('wm', 'iconname', self._w, newName) iconname = wm_iconname def wm_iconphoto(self, default=False, *args): # new in Tk 8.5 """Sets the titlebar icon for this window based on the named photo images passed through args. If default is True, this is applied to all future created toplevels as well. The data in the images is taken as a snapshot at the time of invocation. If the images are later changed, this is not reflected to the titlebar icons. Multiple images are accepted to allow different images sizes to be provided. The window manager may scale provided icons to an appropriate size. On Windows, the images are packed into a Windows icon structure. This will override an icon specified to wm_iconbitmap, and vice versa. On X, the images are arranged into the _NET_WM_ICON X property, which most modern window managers support. An icon specified by wm_iconbitmap may exist simultaneously. On Macintosh, this currently does nothing.""" if default: self.tk.call('wm', 'iconphoto', self._w, "-default", *args) else: self.tk.call('wm', 'iconphoto', self._w, *args) iconphoto = wm_iconphoto def wm_iconposition(self, x=None, y=None): """Set the position of the icon of this widget to X and Y. Return a tuple of the current values of X and X if None is given.""" return self._getints(self.tk.call( 'wm', 'iconposition', self._w, x, y)) iconposition = wm_iconposition def wm_iconwindow(self, pathName=None): """Set widget PATHNAME to be displayed instead of icon. Return the current value if None is given.""" return self.tk.call('wm', 'iconwindow', self._w, pathName) iconwindow = wm_iconwindow def wm_manage(self, widget): # new in Tk 8.5 """The widget specified will become a stand alone top-level window. The window will be decorated with the window managers title bar, etc.""" self.tk.call('wm', 'manage', widget) manage = wm_manage def wm_maxsize(self, width=None, height=None): """Set max WIDTH and HEIGHT for this widget. If the window is gridded the values are given in grid units. Return the current values if None is given.""" return self._getints(self.tk.call( 'wm', 'maxsize', self._w, width, height)) maxsize = wm_maxsize def wm_minsize(self, width=None, height=None): """Set min WIDTH and HEIGHT for this widget. If the window is gridded the values are given in grid units. Return the current values if None is given.""" return self._getints(self.tk.call( 'wm', 'minsize', self._w, width, height)) minsize = wm_minsize def wm_overrideredirect(self, boolean=None): """Instruct the window manager to ignore this widget if BOOLEAN is given with 1. Return the current value if None is given.""" return self._getboolean(self.tk.call( 'wm', 'overrideredirect', self._w, boolean)) overrideredirect = wm_overrideredirect def wm_positionfrom(self, who=None): """Instruct the window manager that the position of this widget shall be defined by the user if WHO is "user", and by its own policy if WHO is "program".""" return self.tk.call('wm', 'positionfrom', self._w, who) positionfrom = wm_positionfrom def wm_protocol(self, name=None, func=None): """Bind function FUNC to command NAME for this widget. Return the function bound to NAME if None is given. NAME could be e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW".""" if callable(func): command = self._register(func) else: command = func return self.tk.call( 'wm', 'protocol', self._w, name, command) protocol = wm_protocol def wm_resizable(self, width=None, height=None): """Instruct the window manager whether this width can be resized in WIDTH or HEIGHT. Both values are boolean values.""" return self.tk.call('wm', 'resizable', self._w, width, height) resizable = wm_resizable def wm_sizefrom(self, who=None): """Instruct the window manager that the size of this widget shall be defined by the user if WHO is "user", and by its own policy if WHO is "program".""" return self.tk.call('wm', 'sizefrom', self._w, who) sizefrom = wm_sizefrom def wm_state(self, newstate=None): """Query or set the state of this widget as one of normal, icon, iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only).""" return self.tk.call('wm', 'state', self._w, newstate) state = wm_state def wm_title(self, string=None): """Set the title of this widget.""" return self.tk.call('wm', 'title', self._w, string) title = wm_title def wm_transient(self, master=None): """Instruct the window manager that this widget is transient with regard to widget MASTER.""" return self.tk.call('wm', 'transient', self._w, master) transient = wm_transient def wm_withdraw(self): """Withdraw this widget from the screen such that it is unmapped and forgotten by the window manager. Re-draw it with wm_deiconify.""" return self.tk.call('wm', 'withdraw', self._w) withdraw = wm_withdraw class Tk(Misc, Wm): """Toplevel widget of Tk which represents mostly the main window of an application. It has an associated Tcl interpreter.""" _w = '.' def __init__(self, screenName=None, baseName=None, className='Tk', useTk=1, sync=0, use=None): """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will be created. BASENAME will be used for the identification of the profile file (see readprofile). It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME is the name of the widget class.""" self.master = None self.children = {} self._tkloaded = 0 # to avoid recursions in the getattr code in case of failure, we # ensure that self.tk is always _something_. self.tk = None if baseName is None: import os baseName = os.path.basename(sys.argv[0]) baseName, ext = os.path.splitext(baseName) if ext not in ('.py', '.pyc'): baseName = baseName + ext interactive = 0 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) if useTk: self._loadtk() if not sys.flags.ignore_environment: # Issue #16248: Honor the -E flag to avoid code injection. self.readprofile(baseName, className) def loadtk(self): if not self._tkloaded: self.tk.loadtk() self._loadtk() def _loadtk(self): self._tkloaded = 1 global _default_root # Version sanity checks tk_version = self.tk.getvar('tk_version') if tk_version != _tkinter.TK_VERSION: raise RuntimeError("tk.h version (%s) doesn't match libtk.a version (%s)" % (_tkinter.TK_VERSION, tk_version)) # Under unknown circumstances, tcl_version gets coerced to float tcl_version = str(self.tk.getvar('tcl_version')) if tcl_version != _tkinter.TCL_VERSION: raise RuntimeError("tcl.h version (%s) doesn't match libtcl.a version (%s)" \ % (_tkinter.TCL_VERSION, tcl_version)) # Create and register the tkerror and exit commands # We need to inline parts of _register here, _ register # would register differently-named commands. if self._tclCommands is None: self._tclCommands = [] self.tk.createcommand('tkerror', _tkerror) self.tk.createcommand('exit', _exit) self._tclCommands.append('tkerror') self._tclCommands.append('exit') if _support_default_root and not _default_root: _default_root = self self.protocol("WM_DELETE_WINDOW", self.destroy) def destroy(self): """Destroy this and all descendants widgets. This will end the application of this Tcl interpreter.""" for c in list(self.children.values()): c.destroy() self.tk.call('destroy', self._w) Misc.destroy(self) global _default_root if _support_default_root and _default_root is self: _default_root = None def readprofile(self, baseName, className): """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into the Tcl Interpreter and calls exec on the contents of BASENAME.py and CLASSNAME.py if such a file exists in the home directory.""" import os if 'HOME' in os.environ: home = os.environ['HOME'] else: home = os.curdir class_tcl = os.path.join(home, '.%s.tcl' % className) class_py = os.path.join(home, '.%s.py' % className) base_tcl = os.path.join(home, '.%s.tcl' % baseName) base_py = os.path.join(home, '.%s.py' % baseName) dir = {'self': self} exec('from tkinter import *', dir) if os.path.isfile(class_tcl): self.tk.call('source', class_tcl) if os.path.isfile(class_py): exec(open(class_py).read(), dir) if os.path.isfile(base_tcl): self.tk.call('source', base_tcl) if os.path.isfile(base_py): exec(open(base_py).read(), dir) def report_callback_exception(self, exc, val, tb): """Report callback exception on sys.stderr. Applications may want to override this internal function, and should when sys.stderr is None.""" import traceback print("Exception in Tkinter callback", file=sys.stderr) sys.last_type = exc sys.last_value = val sys.last_traceback = tb traceback.print_exception(exc, val, tb) def __getattr__(self, attr): "Delegate attribute access to the interpreter object" return getattr(self.tk, attr) # Ideally, the classes Pack, Place and Grid disappear, the # pack/place/grid methods are defined on the Widget class, and # everybody uses w.pack_whatever(...) instead of Pack.whatever(w, # ...), with pack(), place() and grid() being short for # pack_configure(), place_configure() and grid_columnconfigure(), and # forget() being short for pack_forget(). As a practical matter, I'm # afraid that there is too much code out there that may be using the # Pack, Place or Grid class, so I leave them intact -- but only as # backwards compatibility features. Also note that those methods that # take a master as argument (e.g. pack_propagate) have been moved to # the Misc class (which now incorporates all methods common between # toplevel and interior widgets). Again, for compatibility, these are # copied into the Pack, Place or Grid class. def Tcl(screenName=None, baseName=None, className='Tk', useTk=0): return Tk(screenName, baseName, className, useTk) class Pack: """Geometry manager Pack. Base class to use the methods pack_* in every widget.""" def pack_configure(self, cnf={}, **kw): """Pack a widget in the parent widget. Use as options: after=widget - pack it after you have packed widget anchor=NSEW (or subset) - position widget according to given direction before=widget - pack it before you will pack widget expand=bool - expand widget if parent size grows fill=NONE or X or Y or BOTH - fill widget if widget grows in=master - use master to contain this widget in_=master - see 'in' option description ipadx=amount - add internal padding in x direction ipady=amount - add internal padding in y direction padx=amount - add padding in x direction pady=amount - add padding in y direction side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget. """ self.tk.call( ('pack', 'configure', self._w) + self._options(cnf, kw)) pack = configure = config = pack_configure def pack_forget(self): """Unmap this widget and do not use it for the packing order.""" self.tk.call('pack', 'forget', self._w) forget = pack_forget def pack_info(self): """Return information about the packing options for this widget.""" d = _splitdict(self.tk, self.tk.call('pack', 'info', self._w)) if 'in' in d: d['in'] = self.nametowidget(d['in']) return d info = pack_info propagate = pack_propagate = Misc.pack_propagate slaves = pack_slaves = Misc.pack_slaves class Place: """Geometry manager Place. Base class to use the methods place_* in every widget.""" def place_configure(self, cnf={}, **kw): """Place a widget in the parent widget. Use as options: in=master - master relative to which the widget is placed in_=master - see 'in' option description x=amount - locate anchor of this widget at position x of master y=amount - locate anchor of this widget at position y of master relx=amount - locate anchor of this widget between 0.0 and 1.0 relative to width of master (1.0 is right edge) rely=amount - locate anchor of this widget between 0.0 and 1.0 relative to height of master (1.0 is bottom edge) anchor=NSEW (or subset) - position anchor according to given direction width=amount - width of this widget in pixel height=amount - height of this widget in pixel relwidth=amount - width of this widget between 0.0 and 1.0 relative to width of master (1.0 is the same width as the master) relheight=amount - height of this widget between 0.0 and 1.0 relative to height of master (1.0 is the same height as the master) bordermode="inside" or "outside" - whether to take border width of master widget into account """ self.tk.call( ('place', 'configure', self._w) + self._options(cnf, kw)) place = configure = config = place_configure def place_forget(self): """Unmap this widget.""" self.tk.call('place', 'forget', self._w) forget = place_forget def place_info(self): """Return information about the placing options for this widget.""" d = _splitdict(self.tk, self.tk.call('place', 'info', self._w)) if 'in' in d: d['in'] = self.nametowidget(d['in']) return d info = place_info slaves = place_slaves = Misc.place_slaves class Grid: """Geometry manager Grid. Base class to use the methods grid_* in every widget.""" # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu) def grid_configure(self, cnf={}, **kw): """Position a widget in the parent widget in a grid. Use as options: column=number - use cell identified with given column (starting with 0) columnspan=number - this widget will span several columns in=master - use master to contain this widget in_=master - see 'in' option description ipadx=amount - add internal padding in x direction ipady=amount - add internal padding in y direction padx=amount - add padding in x direction pady=amount - add padding in y direction row=number - use cell identified with given row (starting with 0) rowspan=number - this widget will span several rows sticky=NSEW - if cell is larger on which sides will this widget stick to the cell boundary """ self.tk.call( ('grid', 'configure', self._w) + self._options(cnf, kw)) grid = configure = config = grid_configure bbox = grid_bbox = Misc.grid_bbox columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure def grid_forget(self): """Unmap this widget.""" self.tk.call('grid', 'forget', self._w) forget = grid_forget def grid_remove(self): """Unmap this widget but remember the grid options.""" self.tk.call('grid', 'remove', self._w) def grid_info(self): """Return information about the options for positioning this widget in a grid.""" d = _splitdict(self.tk, self.tk.call('grid', 'info', self._w)) if 'in' in d: d['in'] = self.nametowidget(d['in']) return d info = grid_info location = grid_location = Misc.grid_location propagate = grid_propagate = Misc.grid_propagate rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure size = grid_size = Misc.grid_size slaves = grid_slaves = Misc.grid_slaves class BaseWidget(Misc): """Internal class.""" def _setup(self, master, cnf): """Internal function. Sets up information about children.""" if _support_default_root: global _default_root if not master: if not _default_root: _default_root = Tk() master = _default_root self.master = master self.tk = master.tk name = None if 'name' in cnf: name = cnf['name'] del cnf['name'] if not name: name = self.__class__.__name__.lower() if master._last_child_ids is None: master._last_child_ids = {} count = master._last_child_ids.get(name, 0) + 1 master._last_child_ids[name] = count if count == 1: name = '!%s' % (name,) else: name = '!%s%d' % (name, count) self._name = name if master._w=='.': self._w = '.' + name else: self._w = master._w + '.' + name self.children = {} if self._name in self.master.children: self.master.children[self._name].destroy() self.master.children[self._name] = self def __init__(self, master, widgetName, cnf={}, kw={}, extra=()): """Construct a widget with the parent widget MASTER, a name WIDGETNAME and appropriate options.""" if kw: cnf = _cnfmerge((cnf, kw)) self.widgetName = widgetName BaseWidget._setup(self, master, cnf) if self._tclCommands is None: self._tclCommands = [] classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)] for k, v in classes: del cnf[k] self.tk.call( (widgetName, self._w) + extra + self._options(cnf)) for k, v in classes: k.configure(self, v) def destroy(self): """Destroy this and all descendants widgets.""" for c in list(self.children.values()): c.destroy() self.tk.call('destroy', self._w) if self._name in self.master.children: del self.master.children[self._name] Misc.destroy(self) def _do(self, name, args=()): # XXX Obsolete -- better use self.tk.call directly! return self.tk.call((self._w, name) + args) class Widget(BaseWidget, Pack, Place, Grid): """Internal class. Base class for a widget which can be positioned with the geometry managers Pack, Place or Grid.""" pass class Toplevel(BaseWidget, Wm): """Toplevel widget, e.g. for dialogs.""" def __init__(self, master=None, cnf={}, **kw): """Construct a toplevel widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, class, colormap, container, cursor, height, highlightbackground, highlightcolor, highlightthickness, menu, relief, screen, takefocus, use, visual, width.""" if kw: cnf = _cnfmerge((cnf, kw)) extra = () for wmkey in ['screen', 'class_', 'class', 'visual', 'colormap']: if wmkey in cnf: val = cnf[wmkey] # TBD: a hack needed because some keys # are not valid as keyword arguments if wmkey[-1] == '_': opt = '-'+wmkey[:-1] else: opt = '-'+wmkey extra = extra + (opt, val) del cnf[wmkey] BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra) root = self._root() self.iconname(root.iconname()) self.title(root.title()) self.protocol("WM_DELETE_WINDOW", self.destroy) class Button(Widget): """Button widget.""" def __init__(self, master=None, cnf={}, **kw): """Construct a button widget with the parent MASTER. STANDARD OPTIONS activebackground, activeforeground, anchor, background, bitmap, borderwidth, cursor, disabledforeground, font, foreground highlightbackground, highlightcolor, highlightthickness, image, justify, padx, pady, relief, repeatdelay, repeatinterval, takefocus, text, textvariable, underline, wraplength WIDGET-SPECIFIC OPTIONS command, compound, default, height, overrelief, state, width """ Widget.__init__(self, master, 'button', cnf, kw) def flash(self): """Flash the button. This is accomplished by redisplaying the button several times, alternating between active and normal colors. At the end of the flash the button is left in the same normal/active state as when the command was invoked. This command is ignored if the button's state is disabled. """ self.tk.call(self._w, 'flash') def invoke(self): """Invoke the command associated with the button. The return value is the return value from the command, or an empty string if there is no command associated with the button. This command is ignored if the button's state is disabled. """ return self.tk.call(self._w, 'invoke') class Canvas(Widget, XView, YView): """Canvas widget to display graphical elements like lines or text.""" def __init__(self, master=None, cnf={}, **kw): """Construct a canvas widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, closeenough, confine, cursor, height, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, offset, relief, scrollregion, selectbackground, selectborderwidth, selectforeground, state, takefocus, width, xscrollcommand, xscrollincrement, yscrollcommand, yscrollincrement.""" Widget.__init__(self, master, 'canvas', cnf, kw) def addtag(self, *args): """Internal function.""" self.tk.call((self._w, 'addtag') + args) def addtag_above(self, newtag, tagOrId): """Add tag NEWTAG to all items above TAGORID.""" self.addtag(newtag, 'above', tagOrId) def addtag_all(self, newtag): """Add tag NEWTAG to all items.""" self.addtag(newtag, 'all') def addtag_below(self, newtag, tagOrId): """Add tag NEWTAG to all items below TAGORID.""" self.addtag(newtag, 'below', tagOrId) def addtag_closest(self, newtag, x, y, halo=None, start=None): """Add tag NEWTAG to item which is closest to pixel at X, Y. If several match take the top-most. All items closer than HALO are considered overlapping (all are closests). If START is specified the next below this tag is taken.""" self.addtag(newtag, 'closest', x, y, halo, start) def addtag_enclosed(self, newtag, x1, y1, x2, y2): """Add tag NEWTAG to all items in the rectangle defined by X1,Y1,X2,Y2.""" self.addtag(newtag, 'enclosed', x1, y1, x2, y2) def addtag_overlapping(self, newtag, x1, y1, x2, y2): """Add tag NEWTAG to all items which overlap the rectangle defined by X1,Y1,X2,Y2.""" self.addtag(newtag, 'overlapping', x1, y1, x2, y2) def addtag_withtag(self, newtag, tagOrId): """Add tag NEWTAG to all items with TAGORID.""" self.addtag(newtag, 'withtag', tagOrId) def bbox(self, *args): """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle which encloses all items with tags specified as arguments.""" return self._getints( self.tk.call((self._w, 'bbox') + args)) or None def tag_unbind(self, tagOrId, sequence, funcid=None): """Unbind for all items with TAGORID for event SEQUENCE the function identified with FUNCID.""" self.tk.call(self._w, 'bind', tagOrId, sequence, '') if funcid: self.deletecommand(funcid) def tag_bind(self, tagOrId, sequence=None, func=None, add=None): """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.""" return self._bind((self._w, 'bind', tagOrId), sequence, func, add) def canvasx(self, screenx, gridspacing=None): """Return the canvas x coordinate of pixel position SCREENX rounded to nearest multiple of GRIDSPACING units.""" return self.tk.getdouble(self.tk.call( self._w, 'canvasx', screenx, gridspacing)) def canvasy(self, screeny, gridspacing=None): """Return the canvas y coordinate of pixel position SCREENY rounded to nearest multiple of GRIDSPACING units.""" return self.tk.getdouble(self.tk.call( self._w, 'canvasy', screeny, gridspacing)) def coords(self, *args): """Return a list of coordinates for the item given in ARGS.""" # XXX Should use _flatten on args return [self.tk.getdouble(x) for x in self.tk.splitlist( self.tk.call((self._w, 'coords') + args))] def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={}) """Internal function.""" args = _flatten(args) cnf = args[-1] if isinstance(cnf, (dict, tuple)): args = args[:-1] else: cnf = {} return self.tk.getint(self.tk.call( self._w, 'create', itemType, *(args + self._options(cnf, kw)))) def create_arc(self, *args, **kw): """Create arc shaped region with coordinates x1,y1,x2,y2.""" return self._create('arc', args, kw) def create_bitmap(self, *args, **kw): """Create bitmap with coordinates x1,y1.""" return self._create('bitmap', args, kw) def create_image(self, *args, **kw): """Create image item with coordinates x1,y1.""" return self._create('image', args, kw) def create_line(self, *args, **kw): """Create line with coordinates x1,y1,...,xn,yn.""" return self._create('line', args, kw) def create_oval(self, *args, **kw): """Create oval with coordinates x1,y1,x2,y2.""" return self._create('oval', args, kw) def create_polygon(self, *args, **kw): """Create polygon with coordinates x1,y1,...,xn,yn.""" return self._create('polygon', args, kw) def create_rectangle(self, *args, **kw): """Create rectangle with coordinates x1,y1,x2,y2.""" return self._create('rectangle', args, kw) def create_text(self, *args, **kw): """Create text with coordinates x1,y1.""" return self._create('text', args, kw) def create_window(self, *args, **kw): """Create window with coordinates x1,y1,x2,y2.""" return self._create('window', args, kw) def dchars(self, *args): """Delete characters of text items identified by tag or id in ARGS (possibly several times) from FIRST to LAST character (including).""" self.tk.call((self._w, 'dchars') + args) def delete(self, *args): """Delete items identified by all tag or ids contained in ARGS.""" self.tk.call((self._w, 'delete') + args) def dtag(self, *args): """Delete tag or id given as last arguments in ARGS from items identified by first argument in ARGS.""" self.tk.call((self._w, 'dtag') + args) def find(self, *args): """Internal function.""" return self._getints( self.tk.call((self._w, 'find') + args)) or () def find_above(self, tagOrId): """Return items above TAGORID.""" return self.find('above', tagOrId) def find_all(self): """Return all items.""" return self.find('all') def find_below(self, tagOrId): """Return all items below TAGORID.""" return self.find('below', tagOrId) def find_closest(self, x, y, halo=None, start=None): """Return item which is closest to pixel at X, Y. If several match take the top-most. All items closer than HALO are considered overlapping (all are closest). If START is specified the next below this tag is taken.""" return self.find('closest', x, y, halo, start) def find_enclosed(self, x1, y1, x2, y2): """Return all items in rectangle defined by X1,Y1,X2,Y2.""" return self.find('enclosed', x1, y1, x2, y2) def find_overlapping(self, x1, y1, x2, y2): """Return all items which overlap the rectangle defined by X1,Y1,X2,Y2.""" return self.find('overlapping', x1, y1, x2, y2) def find_withtag(self, tagOrId): """Return all items with TAGORID.""" return self.find('withtag', tagOrId) def focus(self, *args): """Set focus to the first item specified in ARGS.""" return self.tk.call((self._w, 'focus') + args) def gettags(self, *args): """Return tags associated with the first item specified in ARGS.""" return self.tk.splitlist( self.tk.call((self._w, 'gettags') + args)) def icursor(self, *args): """Set cursor at position POS in the item identified by TAGORID. In ARGS TAGORID must be first.""" self.tk.call((self._w, 'icursor') + args) def index(self, *args): """Return position of cursor as integer in item specified in ARGS.""" return self.tk.getint(self.tk.call((self._w, 'index') + args)) def insert(self, *args): """Insert TEXT in item TAGORID at position POS. ARGS must be TAGORID POS TEXT.""" self.tk.call((self._w, 'insert') + args) def itemcget(self, tagOrId, option): """Return the resource value for an OPTION for item TAGORID.""" return self.tk.call( (self._w, 'itemcget') + (tagOrId, '-'+option)) def itemconfigure(self, tagOrId, cnf=None, **kw): """Configure resources of an item TAGORID. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method without arguments. """ return self._configure(('itemconfigure', tagOrId), cnf, kw) itemconfig = itemconfigure # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift, # so the preferred name for them is tag_lower, tag_raise # (similar to tag_bind, and similar to the Text widget); # unfortunately can't delete the old ones yet (maybe in 1.6) def tag_lower(self, *args): """Lower an item TAGORID given in ARGS (optional below another item).""" self.tk.call((self._w, 'lower') + args) lower = tag_lower def move(self, *args): """Move an item TAGORID given in ARGS.""" self.tk.call((self._w, 'move') + args) def postscript(self, cnf={}, **kw): """Print the contents of the canvas to a postscript file. Valid options: colormap, colormode, file, fontmap, height, pageanchor, pageheight, pagewidth, pagex, pagey, rotate, width, x, y.""" return self.tk.call((self._w, 'postscript') + self._options(cnf, kw)) def tag_raise(self, *args): """Raise an item TAGORID given in ARGS (optional above another item).""" self.tk.call((self._w, 'raise') + args) lift = tkraise = tag_raise def scale(self, *args): """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE.""" self.tk.call((self._w, 'scale') + args) def scan_mark(self, x, y): """Remember the current X, Y coordinates.""" self.tk.call(self._w, 'scan', 'mark', x, y) def scan_dragto(self, x, y, gain=10): """Adjust the view of the canvas to GAIN times the difference between X and Y and the coordinates given in scan_mark.""" self.tk.call(self._w, 'scan', 'dragto', x, y, gain) def select_adjust(self, tagOrId, index): """Adjust the end of the selection near the cursor of an item TAGORID to index.""" self.tk.call(self._w, 'select', 'adjust', tagOrId, index) def select_clear(self): """Clear the selection if it is in this widget.""" self.tk.call(self._w, 'select', 'clear') def select_from(self, tagOrId, index): """Set the fixed end of a selection in item TAGORID to INDEX.""" self.tk.call(self._w, 'select', 'from', tagOrId, index) def select_item(self): """Return the item which has the selection.""" return self.tk.call(self._w, 'select', 'item') or None def select_to(self, tagOrId, index): """Set the variable end of a selection in item TAGORID to INDEX.""" self.tk.call(self._w, 'select', 'to', tagOrId, index) def type(self, tagOrId): """Return the type of the item TAGORID.""" return self.tk.call(self._w, 'type', tagOrId) or None class Checkbutton(Widget): """Checkbutton widget which is either in on- or off-state.""" def __init__(self, master=None, cnf={}, **kw): """Construct a checkbutton widget with the parent MASTER. Valid resource names: activebackground, activeforeground, anchor, background, bd, bg, bitmap, borderwidth, command, cursor, disabledforeground, fg, font, foreground, height, highlightbackground, highlightcolor, highlightthickness, image, indicatoron, justify, offvalue, onvalue, padx, pady, relief, selectcolor, selectimage, state, takefocus, text, textvariable, underline, variable, width, wraplength.""" Widget.__init__(self, master, 'checkbutton', cnf, kw) def deselect(self): """Put the button in off-state.""" self.tk.call(self._w, 'deselect') def flash(self): """Flash the button.""" self.tk.call(self._w, 'flash') def invoke(self): """Toggle the button and invoke a command if given as resource.""" return self.tk.call(self._w, 'invoke') def select(self): """Put the button in on-state.""" self.tk.call(self._w, 'select') def toggle(self): """Toggle the button.""" self.tk.call(self._w, 'toggle') class Entry(Widget, XView): """Entry widget which allows displaying simple text.""" def __init__(self, master=None, cnf={}, **kw): """Construct an entry widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, cursor, exportselection, fg, font, foreground, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, invalidcommand, invcmd, justify, relief, selectbackground, selectborderwidth, selectforeground, show, state, takefocus, textvariable, validate, validatecommand, vcmd, width, xscrollcommand.""" Widget.__init__(self, master, 'entry', cnf, kw) def delete(self, first, last=None): """Delete text from FIRST to LAST (not included).""" self.tk.call(self._w, 'delete', first, last) def get(self): """Return the text.""" return self.tk.call(self._w, 'get') def icursor(self, index): """Insert cursor at INDEX.""" self.tk.call(self._w, 'icursor', index) def index(self, index): """Return position of cursor.""" return self.tk.getint(self.tk.call( self._w, 'index', index)) def insert(self, index, string): """Insert STRING at INDEX.""" self.tk.call(self._w, 'insert', index, string) def scan_mark(self, x): """Remember the current X, Y coordinates.""" self.tk.call(self._w, 'scan', 'mark', x) def scan_dragto(self, x): """Adjust the view of the canvas to 10 times the difference between X and Y and the coordinates given in scan_mark.""" self.tk.call(self._w, 'scan', 'dragto', x) def selection_adjust(self, index): """Adjust the end of the selection near the cursor to INDEX.""" self.tk.call(self._w, 'selection', 'adjust', index) select_adjust = selection_adjust def selection_clear(self): """Clear the selection if it is in this widget.""" self.tk.call(self._w, 'selection', 'clear') select_clear = selection_clear def selection_from(self, index): """Set the fixed end of a selection to INDEX.""" self.tk.call(self._w, 'selection', 'from', index) select_from = selection_from def selection_present(self): """Return True if there are characters selected in the entry, False otherwise.""" return self.tk.getboolean( self.tk.call(self._w, 'selection', 'present')) select_present = selection_present def selection_range(self, start, end): """Set the selection from START to END (not included).""" self.tk.call(self._w, 'selection', 'range', start, end) select_range = selection_range def selection_to(self, index): """Set the variable end of a selection to INDEX.""" self.tk.call(self._w, 'selection', 'to', index) select_to = selection_to class Frame(Widget): """Frame widget which may contain other widgets and can have a 3D border.""" def __init__(self, master=None, cnf={}, **kw): """Construct a frame widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, class, colormap, container, cursor, height, highlightbackground, highlightcolor, highlightthickness, relief, takefocus, visual, width.""" cnf = _cnfmerge((cnf, kw)) extra = () if 'class_' in cnf: extra = ('-class', cnf['class_']) del cnf['class_'] elif 'class' in cnf: extra = ('-class', cnf['class']) del cnf['class'] Widget.__init__(self, master, 'frame', cnf, {}, extra) class Label(Widget): """Label widget which can display text and bitmaps.""" def __init__(self, master=None, cnf={}, **kw): """Construct a label widget with the parent MASTER. STANDARD OPTIONS activebackground, activeforeground, anchor, background, bitmap, borderwidth, cursor, disabledforeground, font, foreground, highlightbackground, highlightcolor, highlightthickness, image, justify, padx, pady, relief, takefocus, text, textvariable, underline, wraplength WIDGET-SPECIFIC OPTIONS height, state, width """ Widget.__init__(self, master, 'label', cnf, kw) class Listbox(Widget, XView, YView): """Listbox widget which can display a list of strings.""" def __init__(self, master=None, cnf={}, **kw): """Construct a listbox widget with the parent MASTER. Valid resource names: background, bd, bg, borderwidth, cursor, exportselection, fg, font, foreground, height, highlightbackground, highlightcolor, highlightthickness, relief, selectbackground, selectborderwidth, selectforeground, selectmode, setgrid, takefocus, width, xscrollcommand, yscrollcommand, listvariable.""" Widget.__init__(self, master, 'listbox', cnf, kw) def activate(self, index): """Activate item identified by INDEX.""" self.tk.call(self._w, 'activate', index) def bbox(self, index): """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle which encloses the item identified by the given index.""" return self._getints(self.tk.call(self._w, 'bbox', index)) or None def curselection(self): """Return the indices of currently selected item.""" return self._getints(self.tk.call(self._w, 'curselection')) or () def delete(self, first, last=None): """Delete items from FIRST to LAST (included).""" self.tk.call(self._w, 'delete', first, last) def get(self, first, last=None): """Get list of items from FIRST to LAST (included).""" if last is not None: return self.tk.splitlist(self.tk.call( self._w, 'get', first, last)) else: return self.tk.call(self._w, 'get', first) def index(self, index): """Return index of item identified with INDEX.""" i = self.tk.call(self._w, 'index', index) if i == 'none': return None return self.tk.getint(i) def insert(self, index, *elements): """Insert ELEMENTS at INDEX.""" self.tk.call((self._w, 'insert', index) + elements) def nearest(self, y): """Get index of item which is nearest to y coordinate Y.""" return self.tk.getint(self.tk.call( self._w, 'nearest', y)) def scan_mark(self, x, y): """Remember the current X, Y coordinates.""" self.tk.call(self._w, 'scan', 'mark', x, y) def scan_dragto(self, x, y): """Adjust the view of the listbox to 10 times the difference between X and Y and the coordinates given in scan_mark.""" self.tk.call(self._w, 'scan', 'dragto', x, y) def see(self, index): """Scroll such that INDEX is visible.""" self.tk.call(self._w, 'see', index) def selection_anchor(self, index): """Set the fixed end oft the selection to INDEX.""" self.tk.call(self._w, 'selection', 'anchor', index) select_anchor = selection_anchor def selection_clear(self, first, last=None): """Clear the selection from FIRST to LAST (included).""" self.tk.call(self._w, 'selection', 'clear', first, last) select_clear = selection_clear def selection_includes(self, index): """Return True if INDEX is part of the selection.""" return self.tk.getboolean(self.tk.call( self._w, 'selection', 'includes', index)) select_includes = selection_includes def selection_set(self, first, last=None): """Set the selection from FIRST to LAST (included) without changing the currently selected elements.""" self.tk.call(self._w, 'selection', 'set', first, last) select_set = selection_set def size(self): """Return the number of elements in the listbox.""" return self.tk.getint(self.tk.call(self._w, 'size')) def itemcget(self, index, option): """Return the resource value for an ITEM and an OPTION.""" return self.tk.call( (self._w, 'itemcget') + (index, '-'+option)) def itemconfigure(self, index, cnf=None, **kw): """Configure resources of an ITEM. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method without arguments. Valid resource names: background, bg, foreground, fg, selectbackground, selectforeground.""" return self._configure(('itemconfigure', index), cnf, kw) itemconfig = itemconfigure class Menu(Widget): """Menu widget which allows displaying menu bars, pull-down menus and pop-up menus.""" def __init__(self, master=None, cnf={}, **kw): """Construct menu widget with the parent MASTER. Valid resource names: activebackground, activeborderwidth, activeforeground, background, bd, bg, borderwidth, cursor, disabledforeground, fg, font, foreground, postcommand, relief, selectcolor, takefocus, tearoff, tearoffcommand, title, type.""" Widget.__init__(self, master, 'menu', cnf, kw) def tk_popup(self, x, y, entry=""): """Post the menu at position X,Y with entry ENTRY.""" self.tk.call('tk_popup', self._w, x, y, entry) def activate(self, index): """Activate entry at INDEX.""" self.tk.call(self._w, 'activate', index) def add(self, itemType, cnf={}, **kw): """Internal function.""" self.tk.call((self._w, 'add', itemType) + self._options(cnf, kw)) def add_cascade(self, cnf={}, **kw): """Add hierarchical menu item.""" self.add('cascade', cnf or kw) def add_checkbutton(self, cnf={}, **kw): """Add checkbutton menu item.""" self.add('checkbutton', cnf or kw) def add_command(self, cnf={}, **kw): """Add command menu item.""" self.add('command', cnf or kw) def add_radiobutton(self, cnf={}, **kw): """Addd radio menu item.""" self.add('radiobutton', cnf or kw) def add_separator(self, cnf={}, **kw): """Add separator.""" self.add('separator', cnf or kw) def insert(self, index, itemType, cnf={}, **kw): """Internal function.""" self.tk.call((self._w, 'insert', index, itemType) + self._options(cnf, kw)) def insert_cascade(self, index, cnf={}, **kw): """Add hierarchical menu item at INDEX.""" self.insert(index, 'cascade', cnf or kw) def insert_checkbutton(self, index, cnf={}, **kw): """Add checkbutton menu item at INDEX.""" self.insert(index, 'checkbutton', cnf or kw) def insert_command(self, index, cnf={}, **kw): """Add command menu item at INDEX.""" self.insert(index, 'command', cnf or kw) def insert_radiobutton(self, index, cnf={}, **kw): """Addd radio menu item at INDEX.""" self.insert(index, 'radiobutton', cnf or kw) def insert_separator(self, index, cnf={}, **kw): """Add separator at INDEX.""" self.insert(index, 'separator', cnf or kw) def delete(self, index1, index2=None): """Delete menu items between INDEX1 and INDEX2 (included).""" if index2 is None: index2 = index1 num_index1, num_index2 = self.index(index1), self.index(index2) if (num_index1 is None) or (num_index2 is None): num_index1, num_index2 = 0, -1 for i in range(num_index1, num_index2 + 1): if 'command' in self.entryconfig(i): c = str(self.entrycget(i, 'command')) if c: self.deletecommand(c) self.tk.call(self._w, 'delete', index1, index2) def entrycget(self, index, option): """Return the resource value of a menu item for OPTION at INDEX.""" return self.tk.call(self._w, 'entrycget', index, '-' + option) def entryconfigure(self, index, cnf=None, **kw): """Configure a menu item at INDEX.""" return self._configure(('entryconfigure', index), cnf, kw) entryconfig = entryconfigure def index(self, index): """Return the index of a menu item identified by INDEX.""" i = self.tk.call(self._w, 'index', index) if i == 'none': return None return self.tk.getint(i) def invoke(self, index): """Invoke a menu item identified by INDEX and execute the associated command.""" return self.tk.call(self._w, 'invoke', index) def post(self, x, y): """Display a menu at position X,Y.""" self.tk.call(self._w, 'post', x, y) def type(self, index): """Return the type of the menu item at INDEX.""" return self.tk.call(self._w, 'type', index) def unpost(self): """Unmap a menu.""" self.tk.call(self._w, 'unpost') def xposition(self, index): # new in Tk 8.5 """Return the x-position of the leftmost pixel of the menu item at INDEX.""" return self.tk.getint(self.tk.call(self._w, 'xposition', index)) def yposition(self, index): """Return the y-position of the topmost pixel of the menu item at INDEX.""" return self.tk.getint(self.tk.call( self._w, 'yposition', index)) class Menubutton(Widget): """Menubutton widget, obsolete since Tk8.0.""" def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, 'menubutton', cnf, kw) class Message(Widget): """Message widget to display multiline text. Obsolete since Label does it too.""" def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, 'message', cnf, kw) class Radiobutton(Widget): """Radiobutton widget which shows only one of several buttons in on-state.""" def __init__(self, master=None, cnf={}, **kw): """Construct a radiobutton widget with the parent MASTER. Valid resource names: activebackground, activeforeground, anchor, background, bd, bg, bitmap, borderwidth, command, cursor, disabledforeground, fg, font, foreground, height, highlightbackground, highlightcolor, highlightthickness, image, indicatoron, justify, padx, pady, relief, selectcolor, selectimage, state, takefocus, text, textvariable, underline, value, variable, width, wraplength.""" Widget.__init__(self, master, 'radiobutton', cnf, kw) def deselect(self): """Put the button in off-state.""" self.tk.call(self._w, 'deselect') def flash(self): """Flash the button.""" self.tk.call(self._w, 'flash') def invoke(self): """Toggle the button and invoke a command if given as resource.""" return self.tk.call(self._w, 'invoke') def select(self): """Put the button in on-state.""" self.tk.call(self._w, 'select') class Scale(Widget): """Scale widget which can display a numerical scale.""" def __init__(self, master=None, cnf={}, **kw): """Construct a scale widget with the parent MASTER. Valid resource names: activebackground, background, bigincrement, bd, bg, borderwidth, command, cursor, digits, fg, font, foreground, from, highlightbackground, highlightcolor, highlightthickness, label, length, orient, relief, repeatdelay, repeatinterval, resolution, showvalue, sliderlength, sliderrelief, state, takefocus, tickinterval, to, troughcolor, variable, width.""" Widget.__init__(self, master, 'scale', cnf, kw) def get(self): """Get the current value as integer or float.""" value = self.tk.call(self._w, 'get') try: return self.tk.getint(value) except (ValueError, TypeError, TclError): return self.tk.getdouble(value) def set(self, value): """Set the value to VALUE.""" self.tk.call(self._w, 'set', value) def coords(self, value=None): """Return a tuple (X,Y) of the point along the centerline of the trough that corresponds to VALUE or the current value if None is given.""" return self._getints(self.tk.call(self._w, 'coords', value)) def identify(self, x, y): """Return where the point X,Y lies. Valid return values are "slider", "though1" and "though2".""" return self.tk.call(self._w, 'identify', x, y) class Scrollbar(Widget): """Scrollbar widget which displays a slider at a certain position.""" def __init__(self, master=None, cnf={}, **kw): """Construct a scrollbar widget with the parent MASTER. Valid resource names: activebackground, activerelief, background, bd, bg, borderwidth, command, cursor, elementborderwidth, highlightbackground, highlightcolor, highlightthickness, jump, orient, relief, repeatdelay, repeatinterval, takefocus, troughcolor, width.""" Widget.__init__(self, master, 'scrollbar', cnf, kw) def activate(self, index=None): """Marks the element indicated by index as active. The only index values understood by this method are "arrow1", "slider", or "arrow2". If any other value is specified then no element of the scrollbar will be active. If index is not specified, the method returns the name of the element that is currently active, or None if no element is active.""" return self.tk.call(self._w, 'activate', index) or None def delta(self, deltax, deltay): """Return the fractional change of the scrollbar setting if it would be moved by DELTAX or DELTAY pixels.""" return self.tk.getdouble( self.tk.call(self._w, 'delta', deltax, deltay)) def fraction(self, x, y): """Return the fractional value which corresponds to a slider position of X,Y.""" return self.tk.getdouble(self.tk.call(self._w, 'fraction', x, y)) def identify(self, x, y): """Return the element under position X,Y as one of "arrow1","slider","arrow2" or "".""" return self.tk.call(self._w, 'identify', x, y) def get(self): """Return the current fractional values (upper and lower end) of the slider position.""" return self._getdoubles(self.tk.call(self._w, 'get')) def set(self, first, last): """Set the fractional values of the slider position (upper and lower ends as value between 0 and 1).""" self.tk.call(self._w, 'set', first, last) class Text(Widget, XView, YView): """Text widget which can display text in various forms.""" def __init__(self, master=None, cnf={}, **kw): """Construct a text widget with the parent MASTER. STANDARD OPTIONS background, borderwidth, cursor, exportselection, font, foreground, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, padx, pady, relief, selectbackground, selectborderwidth, selectforeground, setgrid, takefocus, xscrollcommand, yscrollcommand, WIDGET-SPECIFIC OPTIONS autoseparators, height, maxundo, spacing1, spacing2, spacing3, state, tabs, undo, width, wrap, """ Widget.__init__(self, master, 'text', cnf, kw) def bbox(self, index): """Return a tuple of (x,y,width,height) which gives the bounding box of the visible part of the character at the given index.""" return self._getints( self.tk.call(self._w, 'bbox', index)) or None def compare(self, index1, op, index2): """Return whether between index INDEX1 and index INDEX2 the relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=.""" return self.tk.getboolean(self.tk.call( self._w, 'compare', index1, op, index2)) def count(self, index1, index2, *args): # new in Tk 8.5 """Counts the number of relevant things between the two indices. If index1 is after index2, the result will be a negative number (and this holds for each of the possible options). The actual items which are counted depends on the options given by args. The result is a list of integers, one for the result of each counting option given. Valid counting options are "chars", "displaychars", "displayindices", "displaylines", "indices", "lines", "xpixels" and "ypixels". There is an additional possible option "update", which if given then all subsequent options ensure that any possible out of date information is recalculated.""" args = ['-%s' % arg for arg in args if not arg.startswith('-')] args += [index1, index2] res = self.tk.call(self._w, 'count', *args) or None if res is not None and len(args) <= 3: return (res, ) else: return res def debug(self, boolean=None): """Turn on the internal consistency checks of the B-Tree inside the text widget according to BOOLEAN.""" if boolean is None: return self.tk.getboolean(self.tk.call(self._w, 'debug')) self.tk.call(self._w, 'debug', boolean) def delete(self, index1, index2=None): """Delete the characters between INDEX1 and INDEX2 (not included).""" self.tk.call(self._w, 'delete', index1, index2) def dlineinfo(self, index): """Return tuple (x,y,width,height,baseline) giving the bounding box and baseline position of the visible part of the line containing the character at INDEX.""" return self._getints(self.tk.call(self._w, 'dlineinfo', index)) def dump(self, index1, index2=None, command=None, **kw): """Return the contents of the widget between index1 and index2. The type of contents returned in filtered based on the keyword parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are given and true, then the corresponding items are returned. The result is a list of triples of the form (key, value, index). If none of the keywords are true then 'all' is used by default. If the 'command' argument is given, it is called once for each element of the list of triples, with the values of each triple serving as the arguments to the function. In this case the list is not returned.""" args = [] func_name = None result = None if not command: # Never call the dump command without the -command flag, since the # output could involve Tcl quoting and would be a pain to parse # right. Instead just set the command to build a list of triples # as if we had done the parsing. result = [] def append_triple(key, value, index, result=result): result.append((key, value, index)) command = append_triple try: if not isinstance(command, str): func_name = command = self._register(command) args += ["-command", command] for key in kw: if kw[key]: args.append("-" + key) args.append(index1) if index2: args.append(index2) self.tk.call(self._w, "dump", *args) return result finally: if func_name: self.deletecommand(func_name) ## new in tk8.4 def edit(self, *args): """Internal method This method controls the undo mechanism and the modified flag. The exact behavior of the command depends on the option argument that follows the edit argument. The following forms of the command are currently supported: edit_modified, edit_redo, edit_reset, edit_separator and edit_undo """ return self.tk.call(self._w, 'edit', *args) def edit_modified(self, arg=None): """Get or Set the modified flag If arg is not specified, returns the modified flag of the widget. The insert, delete, edit undo and edit redo commands or the user can set or clear the modified flag. If boolean is specified, sets the modified flag of the widget to arg. """ return self.edit("modified", arg) def edit_redo(self): """Redo the last undone edit When the undo option is true, reapplies the last undone edits provided no other edits were done since then. Generates an error when the redo stack is empty. Does nothing when the undo option is false. """ return self.edit("redo") def edit_reset(self): """Clears the undo and redo stacks """ return self.edit("reset") def edit_separator(self): """Inserts a separator (boundary) on the undo stack. Does nothing when the undo option is false """ return self.edit("separator") def edit_undo(self): """Undoes the last edit action If the undo option is true. An edit action is defined as all the insert and delete commands that are recorded on the undo stack in between two separators. Generates an error when the undo stack is empty. Does nothing when the undo option is false """ return self.edit("undo") def get(self, index1, index2=None): """Return the text from INDEX1 to INDEX2 (not included).""" return self.tk.call(self._w, 'get', index1, index2) # (Image commands are new in 8.0) def image_cget(self, index, option): """Return the value of OPTION of an embedded image at INDEX.""" if option[:1] != "-": option = "-" + option if option[-1:] == "_": option = option[:-1] return self.tk.call(self._w, "image", "cget", index, option) def image_configure(self, index, cnf=None, **kw): """Configure an embedded image at INDEX.""" return self._configure(('image', 'configure', index), cnf, kw) def image_create(self, index, cnf={}, **kw): """Create an embedded image at INDEX.""" return self.tk.call( self._w, "image", "create", index, *self._options(cnf, kw)) def image_names(self): """Return all names of embedded images in this widget.""" return self.tk.call(self._w, "image", "names") def index(self, index): """Return the index in the form line.char for INDEX.""" return str(self.tk.call(self._w, 'index', index)) def insert(self, index, chars, *args): """Insert CHARS before the characters at INDEX. An additional tag can be given in ARGS. Additional CHARS and tags can follow in ARGS.""" self.tk.call((self._w, 'insert', index, chars) + args) def mark_gravity(self, markName, direction=None): """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT). Return the current value if None is given for DIRECTION.""" return self.tk.call( (self._w, 'mark', 'gravity', markName, direction)) def mark_names(self): """Return all mark names.""" return self.tk.splitlist(self.tk.call( self._w, 'mark', 'names')) def mark_set(self, markName, index): """Set mark MARKNAME before the character at INDEX.""" self.tk.call(self._w, 'mark', 'set', markName, index) def mark_unset(self, *markNames): """Delete all marks in MARKNAMES.""" self.tk.call((self._w, 'mark', 'unset') + markNames) def mark_next(self, index): """Return the name of the next mark after INDEX.""" return self.tk.call(self._w, 'mark', 'next', index) or None def mark_previous(self, index): """Return the name of the previous mark before INDEX.""" return self.tk.call(self._w, 'mark', 'previous', index) or None def peer_create(self, newPathName, cnf={}, **kw): # new in Tk 8.5 """Creates a peer text widget with the given newPathName, and any optional standard configuration options. By default the peer will have the same start and end line as the parent widget, but these can be overridden with the standard configuration options.""" self.tk.call(self._w, 'peer', 'create', newPathName, *self._options(cnf, kw)) def peer_names(self): # new in Tk 8.5 """Returns a list of peers of this widget (this does not include the widget itself).""" return self.tk.splitlist(self.tk.call(self._w, 'peer', 'names')) def replace(self, index1, index2, chars, *args): # new in Tk 8.5 """Replaces the range of characters between index1 and index2 with the given characters and tags specified by args. See the method insert for some more information about args, and the method delete for information about the indices.""" self.tk.call(self._w, 'replace', index1, index2, chars, *args) def scan_mark(self, x, y): """Remember the current X, Y coordinates.""" self.tk.call(self._w, 'scan', 'mark', x, y) def scan_dragto(self, x, y): """Adjust the view of the text to 10 times the difference between X and Y and the coordinates given in scan_mark.""" self.tk.call(self._w, 'scan', 'dragto', x, y) def search(self, pattern, index, stopindex=None, forwards=None, backwards=None, exact=None, regexp=None, nocase=None, count=None, elide=None): """Search PATTERN beginning from INDEX until STOPINDEX. Return the index of the first character of a match or an empty string.""" args = [self._w, 'search'] if forwards: args.append('-forwards') if backwards: args.append('-backwards') if exact: args.append('-exact') if regexp: args.append('-regexp') if nocase: args.append('-nocase') if elide: args.append('-elide') if count: args.append('-count'); args.append(count) if pattern and pattern[0] == '-': args.append('--') args.append(pattern) args.append(index) if stopindex: args.append(stopindex) return str(self.tk.call(tuple(args))) def see(self, index): """Scroll such that the character at INDEX is visible.""" self.tk.call(self._w, 'see', index) def tag_add(self, tagName, index1, *args): """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS. Additional pairs of indices may follow in ARGS.""" self.tk.call( (self._w, 'tag', 'add', tagName, index1) + args) def tag_unbind(self, tagName, sequence, funcid=None): """Unbind for all characters with TAGNAME for event SEQUENCE the function identified with FUNCID.""" self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '') if funcid: self.deletecommand(funcid) def tag_bind(self, tagName, sequence, func, add=None): """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC. An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.""" return self._bind((self._w, 'tag', 'bind', tagName), sequence, func, add) def tag_cget(self, tagName, option): """Return the value of OPTION for tag TAGNAME.""" if option[:1] != '-': option = '-' + option if option[-1:] == '_': option = option[:-1] return self.tk.call(self._w, 'tag', 'cget', tagName, option) def tag_configure(self, tagName, cnf=None, **kw): """Configure a tag TAGNAME.""" return self._configure(('tag', 'configure', tagName), cnf, kw) tag_config = tag_configure def tag_delete(self, *tagNames): """Delete all tags in TAGNAMES.""" self.tk.call((self._w, 'tag', 'delete') + tagNames) def tag_lower(self, tagName, belowThis=None): """Change the priority of tag TAGNAME such that it is lower than the priority of BELOWTHIS.""" self.tk.call(self._w, 'tag', 'lower', tagName, belowThis) def tag_names(self, index=None): """Return a list of all tag names.""" return self.tk.splitlist( self.tk.call(self._w, 'tag', 'names', index)) def tag_nextrange(self, tagName, index1, index2=None): """Return a list of start and end index for the first sequence of characters between INDEX1 and INDEX2 which all have tag TAGNAME. The text is searched forward from INDEX1.""" return self.tk.splitlist(self.tk.call( self._w, 'tag', 'nextrange', tagName, index1, index2)) def tag_prevrange(self, tagName, index1, index2=None): """Return a list of start and end index for the first sequence of characters between INDEX1 and INDEX2 which all have tag TAGNAME. The text is searched backwards from INDEX1.""" return self.tk.splitlist(self.tk.call( self._w, 'tag', 'prevrange', tagName, index1, index2)) def tag_raise(self, tagName, aboveThis=None): """Change the priority of tag TAGNAME such that it is higher than the priority of ABOVETHIS.""" self.tk.call( self._w, 'tag', 'raise', tagName, aboveThis) def tag_ranges(self, tagName): """Return a list of ranges of text which have tag TAGNAME.""" return self.tk.splitlist(self.tk.call( self._w, 'tag', 'ranges', tagName)) def tag_remove(self, tagName, index1, index2=None): """Remove tag TAGNAME from all characters between INDEX1 and INDEX2.""" self.tk.call( self._w, 'tag', 'remove', tagName, index1, index2) def window_cget(self, index, option): """Return the value of OPTION of an embedded window at INDEX.""" if option[:1] != '-': option = '-' + option if option[-1:] == '_': option = option[:-1] return self.tk.call(self._w, 'window', 'cget', index, option) def window_configure(self, index, cnf=None, **kw): """Configure an embedded window at INDEX.""" return self._configure(('window', 'configure', index), cnf, kw) window_config = window_configure def window_create(self, index, cnf={}, **kw): """Create a window at INDEX.""" self.tk.call( (self._w, 'window', 'create', index) + self._options(cnf, kw)) def window_names(self): """Return all names of embedded windows in this widget.""" return self.tk.splitlist( self.tk.call(self._w, 'window', 'names')) def yview_pickplace(self, *what): """Obsolete function, use see.""" self.tk.call((self._w, 'yview', '-pickplace') + what) class _setit: """Internal class. It wraps the command in the widget OptionMenu.""" def __init__(self, var, value, callback=None): self.__value = value self.__var = var self.__callback = callback def __call__(self, *args): self.__var.set(self.__value) if self.__callback: self.__callback(self.__value, *args) class OptionMenu(Menubutton): """OptionMenu which allows the user to select a value from a menu.""" def __init__(self, master, variable, value, *values, **kwargs): """Construct an optionmenu widget with the parent MASTER, with the resource textvariable set to VARIABLE, the initially selected value VALUE, the other menu values VALUES and an additional keyword argument command.""" kw = {"borderwidth": 2, "textvariable": variable, "indicatoron": 1, "relief": RAISED, "anchor": "c", "highlightthickness": 2} Widget.__init__(self, master, "menubutton", kw) self.widgetName = 'tk_optionMenu' menu = self.__menu = Menu(self, name="menu", tearoff=0) self.menuname = menu._w # 'command' is the only supported keyword callback = kwargs.get('command') if 'command' in kwargs: del kwargs['command'] if kwargs: raise TclError('unknown option -'+kwargs.keys()[0]) menu.add_command(label=value, command=_setit(variable, value, callback)) for v in values: menu.add_command(label=v, command=_setit(variable, v, callback)) self["menu"] = menu def __getitem__(self, name): if name == 'menu': return self.__menu return Widget.__getitem__(self, name) def destroy(self): """Destroy this widget and the associated menu.""" Menubutton.destroy(self) self.__menu = None class Image: """Base class for images.""" _last_id = 0 def __init__(self, imgtype, name=None, cnf={}, master=None, **kw): self.name = None if not master: master = _default_root if not master: raise RuntimeError('Too early to create image') self.tk = getattr(master, 'tk', master) if not name: Image._last_id += 1 name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x> if kw and cnf: cnf = _cnfmerge((cnf, kw)) elif kw: cnf = kw options = () for k, v in cnf.items(): if callable(v): v = self._register(v) options = options + ('-'+k, v) self.tk.call(('image', 'create', imgtype, name,) + options) self.name = name def __str__(self): return self.name def __del__(self): if self.name: try: self.tk.call('image', 'delete', self.name) except TclError: # May happen if the root was destroyed pass def __setitem__(self, key, value): self.tk.call(self.name, 'configure', '-'+key, value) def __getitem__(self, key): return self.tk.call(self.name, 'configure', '-'+key) def configure(self, **kw): """Configure the image.""" res = () for k, v in _cnfmerge(kw).items(): if v is not None: if k[-1] == '_': k = k[:-1] if callable(v): v = self._register(v) res = res + ('-'+k, v) self.tk.call((self.name, 'config') + res) config = configure def height(self): """Return the height of the image.""" return self.tk.getint( self.tk.call('image', 'height', self.name)) def type(self): """Return the type of the image, e.g. "photo" or "bitmap".""" return self.tk.call('image', 'type', self.name) def width(self): """Return the width of the image.""" return self.tk.getint( self.tk.call('image', 'width', self.name)) class PhotoImage(Image): """Widget which can display images in PGM, PPM, GIF, PNG format.""" def __init__(self, name=None, cnf={}, master=None, **kw): """Create an image with NAME. Valid resource names: data, format, file, gamma, height, palette, width.""" Image.__init__(self, 'photo', name, cnf, master, **kw) def blank(self): """Display a transparent image.""" self.tk.call(self.name, 'blank') def cget(self, option): """Return the value of OPTION.""" return self.tk.call(self.name, 'cget', '-' + option) # XXX config def __getitem__(self, key): return self.tk.call(self.name, 'cget', '-' + key) # XXX copy -from, -to, ...? def copy(self): """Return a new PhotoImage with the same image as this widget.""" destImage = PhotoImage(master=self.tk) self.tk.call(destImage, 'copy', self.name) return destImage def zoom(self, x, y=''): """Return a new PhotoImage with the same image as this widget but zoom it with a factor of x in the X direction and y in the Y direction. If y is not given, the default value is the same as x. """ destImage = PhotoImage(master=self.tk) if y=='': y=x self.tk.call(destImage, 'copy', self.name, '-zoom',x,y) return destImage def subsample(self, x, y=''): """Return a new PhotoImage based on the same image as this widget but use only every Xth or Yth pixel. If y is not given, the default value is the same as x. """ destImage = PhotoImage(master=self.tk) if y=='': y=x self.tk.call(destImage, 'copy', self.name, '-subsample',x,y) return destImage def get(self, x, y): """Return the color (red, green, blue) of the pixel at X,Y.""" return self.tk.call(self.name, 'get', x, y) def put(self, data, to=None): """Put row formatted colors to image starting from position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))""" args = (self.name, 'put', data) if to: if to[0] == '-to': to = to[1:] args = args + ('-to',) + tuple(to) self.tk.call(args) # XXX read def write(self, filename, format=None, from_coords=None): """Write image to file FILENAME in FORMAT starting from position FROM_COORDS.""" args = (self.name, 'write', filename) if format: args = args + ('-format', format) if from_coords: args = args + ('-from',) + tuple(from_coords) self.tk.call(args) class BitmapImage(Image): """Widget which can display images in XBM format.""" def __init__(self, name=None, cnf={}, master=None, **kw): """Create a bitmap with NAME. Valid resource names: background, data, file, foreground, maskdata, maskfile.""" Image.__init__(self, 'bitmap', name, cnf, master, **kw) def image_names(): return _default_root.tk.splitlist(_default_root.tk.call('image', 'names')) def image_types(): return _default_root.tk.splitlist(_default_root.tk.call('image', 'types')) class Spinbox(Widget, XView): """spinbox widget.""" def __init__(self, master=None, cnf={}, **kw): """Construct a spinbox widget with the parent MASTER. STANDARD OPTIONS activebackground, background, borderwidth, cursor, exportselection, font, foreground, highlightbackground, highlightcolor, highlightthickness, insertbackground, insertborderwidth, insertofftime, insertontime, insertwidth, justify, relief, repeatdelay, repeatinterval, selectbackground, selectborderwidth selectforeground, takefocus, textvariable xscrollcommand. WIDGET-SPECIFIC OPTIONS buttonbackground, buttoncursor, buttondownrelief, buttonuprelief, command, disabledbackground, disabledforeground, format, from, invalidcommand, increment, readonlybackground, state, to, validate, validatecommand values, width, wrap, """ Widget.__init__(self, master, 'spinbox', cnf, kw) def bbox(self, index): """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle which encloses the character given by index. The first two elements of the list give the x and y coordinates of the upper-left corner of the screen area covered by the character (in pixels relative to the widget) and the last two elements give the width and height of the character, in pixels. The bounding box may refer to a region outside the visible area of the window. """ return self._getints(self.tk.call(self._w, 'bbox', index)) or None def delete(self, first, last=None): """Delete one or more elements of the spinbox. First is the index of the first character to delete, and last is the index of the character just after the last one to delete. If last isn't specified it defaults to first+1, i.e. a single character is deleted. This command returns an empty string. """ return self.tk.call(self._w, 'delete', first, last) def get(self): """Returns the spinbox's string""" return self.tk.call(self._w, 'get') def icursor(self, index): """Alter the position of the insertion cursor. The insertion cursor will be displayed just before the character given by index. Returns an empty string """ return self.tk.call(self._w, 'icursor', index) def identify(self, x, y): """Returns the name of the widget at position x, y Return value is one of: none, buttondown, buttonup, entry """ return self.tk.call(self._w, 'identify', x, y) def index(self, index): """Returns the numerical index corresponding to index """ return self.tk.call(self._w, 'index', index) def insert(self, index, s): """Insert string s at index Returns an empty string. """ return self.tk.call(self._w, 'insert', index, s) def invoke(self, element): """Causes the specified element to be invoked The element could be buttondown or buttonup triggering the action associated with it. """ return self.tk.call(self._w, 'invoke', element) def scan(self, *args): """Internal function.""" return self._getints( self.tk.call((self._w, 'scan') + args)) or () def scan_mark(self, x): """Records x and the current view in the spinbox window; used in conjunction with later scan dragto commands. Typically this command is associated with a mouse button press in the widget. It returns an empty string. """ return self.scan("mark", x) def scan_dragto(self, x): """Compute the difference between the given x argument and the x argument to the last scan mark command It then adjusts the view left or right by 10 times the difference in x-coordinates. This command is typically associated with mouse motion events in the widget, to produce the effect of dragging the spinbox at high speed through the window. The return value is an empty string. """ return self.scan("dragto", x) def selection(self, *args): """Internal function.""" return self._getints( self.tk.call((self._w, 'selection') + args)) or () def selection_adjust(self, index): """Locate the end of the selection nearest to the character given by index, Then adjust that end of the selection to be at index (i.e including but not going beyond index). The other end of the selection is made the anchor point for future select to commands. If the selection isn't currently in the spinbox, then a new selection is created to include the characters between index and the most recent selection anchor point, inclusive. """ return self.selection("adjust", index) def selection_clear(self): """Clear the selection If the selection isn't in this widget then the command has no effect. """ return self.selection("clear") def selection_element(self, element=None): """Sets or gets the currently selected element. If a spinbutton element is specified, it will be displayed depressed. """ return self.tk.call(self._w, 'selection', 'element', element) ########################################################################### class LabelFrame(Widget): """labelframe widget.""" def __init__(self, master=None, cnf={}, **kw): """Construct a labelframe widget with the parent MASTER. STANDARD OPTIONS borderwidth, cursor, font, foreground, highlightbackground, highlightcolor, highlightthickness, padx, pady, relief, takefocus, text WIDGET-SPECIFIC OPTIONS background, class, colormap, container, height, labelanchor, labelwidget, visual, width """ Widget.__init__(self, master, 'labelframe', cnf, kw) ######################################################################## class PanedWindow(Widget): """panedwindow widget.""" def __init__(self, master=None, cnf={}, **kw): """Construct a panedwindow widget with the parent MASTER. STANDARD OPTIONS background, borderwidth, cursor, height, orient, relief, width WIDGET-SPECIFIC OPTIONS handlepad, handlesize, opaqueresize, sashcursor, sashpad, sashrelief, sashwidth, showhandle, """ Widget.__init__(self, master, 'panedwindow', cnf, kw) def add(self, child, **kw): """Add a child widget to the panedwindow in a new pane. The child argument is the name of the child widget followed by pairs of arguments that specify how to manage the windows. The possible options and values are the ones accepted by the paneconfigure method. """ self.tk.call((self._w, 'add', child) + self._options(kw)) def remove(self, child): """Remove the pane containing child from the panedwindow All geometry management options for child will be forgotten. """ self.tk.call(self._w, 'forget', child) forget=remove def identify(self, x, y): """Identify the panedwindow component at point x, y If the point is over a sash or a sash handle, the result is a two element list containing the index of the sash or handle, and a word indicating whether it is over a sash or a handle, such as {0 sash} or {2 handle}. If the point is over any other part of the panedwindow, the result is an empty list. """ return self.tk.call(self._w, 'identify', x, y) def proxy(self, *args): """Internal function.""" return self._getints( self.tk.call((self._w, 'proxy') + args)) or () def proxy_coord(self): """Return the x and y pair of the most recent proxy location """ return self.proxy("coord") def proxy_forget(self): """Remove the proxy from the display. """ return self.proxy("forget") def proxy_place(self, x, y): """Place the proxy at the given x and y coordinates. """ return self.proxy("place", x, y) def sash(self, *args): """Internal function.""" return self._getints( self.tk.call((self._w, 'sash') + args)) or () def sash_coord(self, index): """Return the current x and y pair for the sash given by index. Index must be an integer between 0 and 1 less than the number of panes in the panedwindow. The coordinates given are those of the top left corner of the region containing the sash. pathName sash dragto index x y This command computes the difference between the given coordinates and the coordinates given to the last sash coord command for the given sash. It then moves that sash the computed difference. The return value is the empty string. """ return self.sash("coord", index) def sash_mark(self, index): """Records x and y for the sash given by index; Used in conjunction with later dragto commands to move the sash. """ return self.sash("mark", index) def sash_place(self, index, x, y): """Place the sash given by index at the given coordinates """ return self.sash("place", index, x, y) def panecget(self, child, option): """Query a management option for window. Option may be any value allowed by the paneconfigure subcommand """ return self.tk.call( (self._w, 'panecget') + (child, '-'+option)) def paneconfigure(self, tagOrId, cnf=None, **kw): """Query or modify the management options for window. If no option is specified, returns a list describing all of the available options for pathName. If option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. The following options are supported: after window Insert the window after the window specified. window should be the name of a window already managed by pathName. before window Insert the window before the window specified. window should be the name of a window already managed by pathName. height size Specify a height for the window. The height will be the outer dimension of the window including its border, if any. If size is an empty string, or if -height is not specified, then the height requested internally by the window will be used initially; the height may later be adjusted by the movement of sashes in the panedwindow. Size may be any value accepted by Tk_GetPixels. minsize n Specifies that the size of the window cannot be made less than n. This constraint only affects the size of the widget in the paned dimension -- the x dimension for horizontal panedwindows, the y dimension for vertical panedwindows. May be any value accepted by Tk_GetPixels. padx n Specifies a non-negative value indicating how much extra space to leave on each side of the window in the X-direction. The value may have any of the forms accepted by Tk_GetPixels. pady n Specifies a non-negative value indicating how much extra space to leave on each side of the window in the Y-direction. The value may have any of the forms accepted by Tk_GetPixels. sticky style If a window's pane is larger than the requested dimensions of the window, this option may be used to position (or stretch) the window within its pane. Style is a string that contains zero or more of the characters n, s, e or w. The string can optionally contains spaces or commas, but they are ignored. Each letter refers to a side (north, south, east, or west) that the window will "stick" to. If both n and s (or e and w) are specified, the window will be stretched to fill the entire height (or width) of its cavity. width size Specify a width for the window. The width will be the outer dimension of the window including its border, if any. If size is an empty string, or if -width is not specified, then the width requested internally by the window will be used initially; the width may later be adjusted by the movement of sashes in the panedwindow. Size may be any value accepted by Tk_GetPixels. """ if cnf is None and not kw: return self._getconfigure(self._w, 'paneconfigure', tagOrId) if isinstance(cnf, str) and not kw: return self._getconfigure1( self._w, 'paneconfigure', tagOrId, '-'+cnf) self.tk.call((self._w, 'paneconfigure', tagOrId) + self._options(cnf, kw)) paneconfig = paneconfigure def panes(self): """Returns an ordered list of the child panes.""" return self.tk.splitlist(self.tk.call(self._w, 'panes')) # Test: def _test(): root = Tk() text = "This is Tcl/Tk version %s" % TclVersion text += "\nThis should be a cedilla: \xe7" label = Label(root, text=text) label.pack() test = Button(root, text="Click me!", command=lambda root=root: root.test.configure( text="[%s]" % root.test['text'])) test.pack() root.test = test quit = Button(root, text="QUIT", command=root.destroy) quit.pack() # The following three commands are needed so the window pops # up on top on Windows... root.iconify() root.update() root.deiconify() root.mainloop() if __name__ == '__main__': _test()
lgpl-2.1
ACS-Community/ACS
LGPL/CommonSoftware/cdb_rdb/src/alma/acs/tmcdb/helper/BL_FEDelayOp.java
803
package alma.acs.tmcdb; /** * This class has been automatically generated from the 'HwConfigMonitoring' TMCDB table model, * and represents the 'BL_FEDelayOp' CHECK constraint defined for the 'Operation' column of the 'BL_FEDelay' table. * * <p>This is automatic generated code, so don't try to change it by yourself! */ public enum BL_FEDelayOp { I("I"), U("U"), D("D"); private String _stringValue; BL_FEDelayOp(String value) { _stringValue = value; } public String toString() { return _stringValue; } public static BL_FEDelayOp valueOfForEnum(String value) { if( value.equals("I") ) return I; if( value.equals("U") ) return U; if( value.equals("D") ) return D; else throw new RuntimeException("Invalid value for BL_FEDelayOp enumeration: " + value); } }
lgpl-2.1
Metaswitch/jitsi
src/net/java/sip/communicator/impl/keybindings/KeybindingsServiceImpl.java
15260
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.keybindings; import java.awt.*; import java.io.*; import java.text.*; import java.util.*; import java.util.List; import javax.swing.*; import net.java.sip.communicator.service.keybindings.*; import net.java.sip.communicator.util.*; import org.jitsi.service.configuration.*; import org.jitsi.service.fileaccess.*; import org.osgi.framework.*; //disambiguation /** * Service that concerns keybinding mappings used by various parts of the UI. * Persistence is handled as follows when started: * <ol> * <li>Load default bindings from relative directory</li> * <li>Attempt to load custom bindings and resolve any duplicates</li> * <li>If merged bindings differ from the custom bindings then this attempts to * save the merged version</li> * </ol> * Custom bindings attempt to be written again whenever they're changed if the * service is running. Each category of keybindings are stored in its own file. * * @author Damian Johnson */ class KeybindingsServiceImpl implements KeybindingsService, Observer { /** * The <tt>Logger</tt> instance used by the * <tt>KeybindingsServiceImpl</tt> class and its instances for logging * output. */ private static final Logger logger = Logger.getLogger(KeybindingsServiceImpl.class); /** * Name of the relative directory that holds default bindings. */ private static final String DEFAULT_KEYBINDING_DIR = "/resources/config/defaultkeybindings"; /** * Name of the directory that holds custom bindings. */ private static final String CUSTOM_KEYBINDING_DIR = "keybindings"; /** * Path where to store the global shortcuts. */ private final static String CONFIGURATION_PATH = "net.java.sip.communicator.impl.keybinding.global"; /** * Path where to store the global shortcuts defaults values. */ private final static String DEFAULTS_VALUES_PATH = "impl.keybinding.global"; /** * Flag indicating if service is running. */ private boolean isRunning = false; /** * Loaded keybinding mappings, maps to null if defaults failed to be loaded. */ private final HashMap<KeybindingSet.Category, KeybindingSetImpl> bindings = new HashMap<KeybindingSet.Category, KeybindingSetImpl>(); /** * Loaded global keybinding mappings. */ private GlobalKeybindingSet globalBindings = null; /** * Starts the KeybindingService, for each keybinding category retrieving the * default bindings then overwriting them with any custom bindings that can * be retrieved. This writes the merged copy back if it differs from the * custom bindings. This is a no-op if the service has already been started. * * @param bc the currently valid OSGI bundle context. */ synchronized void start(BundleContext bc) { if (this.isRunning) return; for (KeybindingSet.Category category : KeybindingSet.Category.values()) { // Retrieves default bindings Persistence format = category.getFormat(); LinkedHashMap<KeyStroke, String> defaultBindings; try { String defaultPath = DEFAULT_KEYBINDING_DIR + "/" + category.getResource(); InputStream in = getClass().getResourceAsStream(defaultPath); defaultBindings = format.load(in); } catch (IOException exc) { logger.error("default bindings set missing: " + category.getResource(), exc); this.bindings.put(category, null); continue; } catch (ParseException exc) { logger.error("unable to parse default bindings set: " + category.getResource(), exc); this.bindings.put(category, null); continue; } // Attempts to retrieve custom bindings String customPath = CUSTOM_KEYBINDING_DIR + "/" + category.getResource(); File customFile; try { ServiceReference faServiceReference = bc.getServiceReference(FileAccessService.class.getName()); FileAccessService faService = (FileAccessService) bc.getService(faServiceReference); // Makes directory for custom bindings if it doesn't exist File customDir = faService .getPrivatePersistentDirectory(CUSTOM_KEYBINDING_DIR); if (!customDir.exists()) customDir.mkdir(); // Gets file access service to reference persistent storage // of the user customFile = faService.getPrivatePersistentFile(customPath); } catch (Exception exc) { String msg = "unable to secure file for custom bindings (" + customPath + "), using defaults but won't be able to save changes"; logger.error(msg, exc); KeybindingSetImpl newSet = new KeybindingSetImpl(defaultBindings, category, null); this.bindings.put(category, newSet); newSet.addObserver(this); continue; } LinkedHashMap<KeyStroke, String> customBindings = null; if (customFile.exists()) { try { FileInputStream in = new FileInputStream(customFile); customBindings = format.load(in); in.close(); } catch (Exception exc) { // If either an IO or ParseException occur then we skip // loading custom bindings } } // Merges custom bindings LinkedHashMap<KeyStroke, String> merged = new LinkedHashMap<KeyStroke, String>(); if (customBindings != null) { Map<KeyStroke, String> customTmp = new LinkedHashMap<KeyStroke, String>(customBindings); for (Map.Entry<KeyStroke, String> shortcut2action : defaultBindings.entrySet()) { String action = shortcut2action.getValue(); if (customTmp.containsValue(action)) { KeyStroke custom = null; for(Map.Entry<KeyStroke, String> customShortcut2action : customTmp.entrySet()) { if (customShortcut2action.getValue().equals(action)) { custom = customShortcut2action.getKey(); break; } } assert custom != null; customTmp.remove(custom); merged.put(custom, action); } else { merged.put(shortcut2action.getKey(), action); } } } else { merged = defaultBindings; } // Writes merged result if (!merged.equals(customBindings)) { try { FileOutputStream out = new FileOutputStream(customFile); format.save(out, merged); out.close(); } catch (IOException exc) { logger.error("unable to write to: " + customFile.getAbsolutePath(), exc); } } KeybindingSetImpl newSet = new KeybindingSetImpl(merged, category, customFile); this.bindings.put(category, newSet); newSet.addObserver(this); } // global shortcut initialization globalBindings = new GlobalKeybindingSetImpl(); globalBindings.setBindings(getGlobalShortcutFromConfiguration()); this.isRunning = true; } /** * Invalidates references to custom bindings, preventing further writes. */ synchronized void stop() { if (!this.isRunning) return; for (KeybindingSetImpl bindingSet : this.bindings.values()) { bindingSet.invalidate(); } this.bindings.clear(); this.saveGlobalShortcutFromConfiguration(); this.isRunning = false; } /** * Provides the bindings associated with a given category. This may be null * if the default bindings failed to be loaded. * * @param category segment of the UI for which bindings should be retrieved * @return mappings of keystrokes to the string representation of their * actions * @throws UnsupportedOperationException if the service isn't running */ public synchronized KeybindingSet getBindings( KeybindingSet.Category category) { if (!this.isRunning) throw new UnsupportedOperationException(); // Started services should have all categories assert this.bindings.containsKey(category); return this.bindings.get(category); } /** * Listens for changes in binding sets so changes can be written. */ public void update(Observable obs, Object arg) { if (obs instanceof KeybindingSetImpl) { KeybindingSetImpl changedBindings = (KeybindingSetImpl) obs; // Attempts to avoid lock if unwritable (this works since bindings // can't become re-writable) if (changedBindings.isWritable()) { synchronized (this) { if (changedBindings.isWritable()) { // Writes new bindings to custom file File customFile = changedBindings.getCustomFile(); try { FileOutputStream out = new FileOutputStream(customFile); Persistence format = changedBindings.getCategory().getFormat(); format.save(out, changedBindings.getBindings()); out.close(); } catch (IOException exc) { logger.error("unable to write to: " + customFile.getAbsolutePath(), exc); } } } } } } /** * Returns list of global shortcuts from the configuration file. * * @return list of global shortcuts. */ public Map<String, List<AWTKeyStroke>> getGlobalShortcutFromConfiguration() { Map<String, List<AWTKeyStroke>> gBindings = new LinkedHashMap<String, List<AWTKeyStroke>>(); ConfigurationService configService = KeybindingsActivator.getConfigService(); String shortcut = null; String shortcut2 = null; String propName = null; String propName2 = null; String names[] = new String[]{"answer", "hangup", "answer_hangup", "contactlist", "mute", "push_to_talk"}; Object configured = configService.getProperty( "net.java.sip.communicator.impl.keybinding.global.configured"); if(configured == null) { // default keystrokes for(String name : names) { List<AWTKeyStroke> kss = new ArrayList<AWTKeyStroke>(); propName = DEFAULTS_VALUES_PATH + "." + name + ".1"; shortcut = propName != null ? KeybindingsActivator.getResourceService().getSettingsString( propName) : null; if(shortcut != null) { kss.add(AWTKeyStroke.getAWTKeyStroke(shortcut)); } gBindings.put(name, kss); } configService.setProperty( "net.java.sip.communicator.impl.keybinding.global.configured", "true"); return gBindings; } for(String name : names) { List<AWTKeyStroke> kss = new ArrayList<AWTKeyStroke>(); propName = CONFIGURATION_PATH + "." + name + ".1"; propName2 = CONFIGURATION_PATH + "." + name + ".2"; shortcut = propName != null ? (String)configService.getProperty(propName) : null; shortcut2 = propName2 != null ? (String)configService.getProperty(propName2) : null; if(shortcut != null) { kss.add(AWTKeyStroke.getAWTKeyStroke(shortcut)); } // second shortcut is always "special" if(shortcut2 != null) { //16367 is the combination of all possible modifiers //(shift ctrl meta alt altGraph button1 button2 button3 pressed) //it is used to distinguish special key (headset) and others int nb = Integer.parseInt(shortcut2); kss.add(AWTKeyStroke.getAWTKeyStroke(nb, 16367)); } gBindings.put(name, kss); } return gBindings; } /** * Save the configuration file. */ public void saveGlobalShortcutFromConfiguration() { ConfigurationService configService = KeybindingsActivator.getConfigService(); String shortcut = null; String shortcut2 = null; for(Map.Entry<String, List<AWTKeyStroke>> entry : globalBindings.getBindings().entrySet()) { String key = entry.getKey(); List<AWTKeyStroke> kss = entry.getValue(); String path = CONFIGURATION_PATH; path += "." + key; shortcut = path + ".1"; shortcut2 = path + ".2"; configService.setProperty(shortcut, kss.size() > 0 ? kss.get(0) : null); // second shortcut is special configService.setProperty(shortcut2, (kss.size() > 1 && kss.get(1) != null) ? kss.get(1).getKeyCode() : null); } } /** * Provides the bindings associated with the global category. * * @return global keybinding set */ public GlobalKeybindingSet getGlobalBindings() { return globalBindings; } }
lgpl-2.1
neiljay/RIOT
tests/pthread_rwlock/Makefile
674
include ../Makefile.tests_common BOARD_BLACKLIST := arduino-mega2560 waspmote-pro arduino-uno arduino-duemilanove \ jiminy-mega256rfr2 mega-xplained # arduino mega2560 uno duemilanove : unknown type name: clockid_t # jiminy-mega256rfr2: unknown type name: clockid_t # mega-xplained: unknown type name: clockid_t USEMODULE += pthread USEMODULE += xtimer USEMODULE += random BOARD_INSUFFICIENT_MEMORY += chronos msb-430 msb-430h nucleo-f031k6 \ nucleo-f042k6 nucleo-l031k6 nucleo-f030r8 \ nucleo-f334r8 nucleo-l053r8 stm32f0discovery include $(RIOTBASE)/Makefile.include test: tests/01-run.py
lgpl-2.1
roystgnr/libmesh
include/reduced_basis/rb_parameters.h
5046
// rbOOmit: An implementation of the Certified Reduced Basis method. // Copyright (C) 2009, 2010 David J. Knezevic // This file is part of rbOOmit. // rbOOmit 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. // rbOOmit 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 #ifndef LIBMESH_RB_PARAMETERS_H #define LIBMESH_RB_PARAMETERS_H // libMesh includes #include "libmesh/libmesh_common.h" // C++ includes #include <string> #include <map> #include <set> namespace libMesh { /** * This class is part of the rbOOmit framework. * * This class defines a set of parameters index by strings. * * \author David J. Knezevic * \date 2012 */ class RBParameters { public: /** * The special functions can be defaulted for this class, as it * does not manage any memory itself. */ RBParameters () = default; RBParameters (RBParameters &&) = default; RBParameters (const RBParameters &) = default; RBParameters & operator= (const RBParameters &) = default; RBParameters & operator= (RBParameters &&) = default; ~RBParameters() = default; /** * Constructor. Set parameters based on the std::map \p parameter_map. */ RBParameters(const std::map<std::string, Real> & parameter_map); // Define a constant iterator for this class typedef std::map<std::string, Real>::const_iterator const_iterator; /** * Clear this object. */ void clear(); /** * Get a const reference to the map that stores all of the values. */ const std::map<std::string, Real> & get_parameters_map() const; /** * Get a const reference to the map that stores all of the "extra" values. */ const std::map<std::string, Real> & get_extra_parameters_map() const; /** * Get the value of the specific parameter. */ Real get_value(const std::string & param_name) const; /** * Set the value of the specified parameter. If param_name * doesn't already exist, it is added to the RBParameters object. */ void set_value(const std::string & param_name, Real value); /** * Get the value of the specific extra parameter. */ Real get_extra_value(const std::string & param_name) const; /** * Set the value of the specified extra parameter. If param_name * doesn't already exist, it is added to the extra parameters. */ void set_extra_value(const std::string & param_name, Real value); /** * Get the number of parameters that have been added. */ unsigned int n_parameters() const; /** * Fill \p param_names with the names of the parameters. * * \deprecated to avoid making it too easy to create copies that in * most circumstances aren't needed. If this functionality really * is required, call get_parameters_map() and loop over the keys * directly. */ void get_parameter_names(std::set<std::string> & param_names) const; /** * Fill \p param_names with the names of the extra parameters. * * \deprecated to avoid making it too easy to create copies that in * most circumstances aren't needed. If this functionality really * is required, call get_parameters_map() and loop over the keys * directly. */ void get_extra_parameter_names(std::set<std::string> & param_names) const; /** * Get const_iterator access to the parameters stored in this RBParameters object. */ const_iterator begin() const; const_iterator end() const; /** * Get const_iterator access to the extra parameters stored in this RBParameters object. */ const_iterator extra_begin() const; const_iterator extra_end() const; /** * Two RBParameters are equal if they have the same _parameters map. */ bool operator== (const RBParameters & rhs) const; /** * \returns !(*this == rhs). */ bool operator!= (const RBParameters & node) const; /** * Get a string that specifies the contents of this RBParameters object. * \p precision specifies the number of digits of precision we use * in scientific notation in the string. */ std::string get_string(unsigned int precision=6) const; /** * Print the parameters. */ void print() const; private: /** * The map that stores the actual parameters, indexed by names. */ std::map<std::string, Real> _parameters; /** * The map that stores extra parameters not used for RB training, indexed by names. */ std::map<std::string, Real> _extra_parameters; }; } // namespace libMesh #endif // LIBMESH_RB_PARAMETERS_H
lgpl-2.1
GNOME/glib
gio/gnetworking.c
2493
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */ /* GIO - GLib Input, Output and Streaming Library * * Copyright (C) 2011 Red Hat, Inc. * * 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 "gnetworking.h" /** * SECTION:gnetworking * @title: gnetworking.h * @short_description: System networking includes * @include: gio/gnetworking.h * * The `<gio/gnetworking.h>` header can be included to get * various low-level networking-related system headers, automatically * taking care of certain portability issues for you. * * This can be used, for example, if you want to call setsockopt() * on a #GSocket. * * Note that while WinSock has many of the same APIs as the * traditional UNIX socket API, most of them behave at least slightly * differently (particularly with respect to error handling). If you * want your code to work under both UNIX and Windows, you will need * to take these differences into account. * * Also, under GNU libc, certain non-portable functions are only visible * in the headers if you define %_GNU_SOURCE before including them. Note * that this symbol must be defined before including any headers, or it * may not take effect. */ /** * g_networking_init: * * Initializes the platform networking libraries (eg, on Windows, this * calls WSAStartup()). GLib will call this itself if it is needed, so * you only need to call it if you directly call system networking * functions (without calling any GLib networking functions first). * * Since: 2.36 */ void g_networking_init (void) { #ifdef G_OS_WIN32 static gsize inited = 0; if (g_once_init_enter (&inited)) { WSADATA wsadata; if (WSAStartup (MAKEWORD (2, 0), &wsadata) != 0) g_error ("Windows Sockets could not be initialized"); g_once_init_leave (&inited, 1); } #endif }
lgpl-2.1
pranavrc/example-gluon
core/tests/testgluoncore.h
1921
/****************************************************************************** * This file is part of the Gluon Development Platform * * Copyright (c) 2010 Clark Gaebel <cg.wowus.cg@gmail.com> * Copyright (c) 2011 Laszlo Papp <djszapi@archlinux.us> * * 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 */ #ifndef TEST_GLUON_CORE_H #define TEST_GLUON_CORE_H #include <core/gluonobject.h> #include <core/gdlhandler.h> #include <QtTest/QTest> #include <QtCore/QList> class TestGluonCore : public QObject { Q_OBJECT public: explicit TestGluonCore(); virtual ~TestGluonCore(); private: static bool compareTrees( const QList<GluonCore::GluonObject*>& t1, const QList<GluonCore::GluonObject*>& t2 ); template <typename T> static QList<const T*> constListFromNonConst( const QList<T*>& x ) { QList<const T*> r; foreach( T * e, x ) r.push_back( e ); return r; } // Returns true if the passed GDL has (parsed -> serialized -> parsed) == parsed static bool ensureReversible( const QString& gdl ); private slots: void doxygenSample(); void invadersSample(); }; #endif
lgpl-2.1
robsoncouto/badge
main.c
8120
#define F_CPU 8000000UL #include<avr/io.h> #include <avr/wdt.h> #include<util/delay.h> #include <string.h> #include<stdlib.h> #include"sprites.h" #include"pic.h" #include "hardware.h" #include "ST7565-T3/c/stlcd.h" #include "ST7565-T3/c/glcd.h" //This is the buffer used to transfer data to the LCD uint8_t buffer[128*64/8]; typedef struct { uint8_t isJumping; uint8_t x; uint8_t y; uint8_t w; uint8_t h; const uint8_t* sprite; uint8_t steps; uint8_t hasChanged; }dino; typedef struct { uint8_t x; uint8_t y; uint8_t w; uint8_t h; const uint8_t* sprite; uint8_t alive; }cacti; struct ground { uint8_t x; int8_t y; uint8_t w; uint8_t h; const uint8_t* sprite; }; //Points used for the rex jump const char points[]={38,31,28,25,23,22,20,19,18,17,16,15,14,14,13,12,12,11,11,10,10,10,9,9,9,8,8,8,8,8,8}; void draw_ground(void){ static uint8_t i=0; drawbitmap(buffer, 0, 56, gnd+i, 128-i, 8, 1); drawbitmap(buffer, 128-i, 56, gnd, i, 8, 1); i++; if(i==128)i=0; } uint8_t draw_cactus(cacti cactus,uint8_t color){ return drawbitmap2(buffer, cactus.x, cactus.y, cactus.sprite, cactus.w, cactus.h, color); } uint8_t draw_dino(dino rex, uint8_t color){ return drawbitmap2(buffer, rex.x, rex.y, rex.sprite, 20, 24, color); } void Rex2screen(dino rex, uint8_t color){ draw_dino(rex,color); write_part(buffer,rex.x,rex.y,rex.w,rex.h); } void updateJump(dino* rex){ static uint8_t index=0; if(rex->isJumping){ if(rex->isJumping>31){ if(points[index]!=rex->y){ rex->hasChanged=1; Rex2screen(*rex, 0); } rex->y=points[index]; rex->isJumping--; index++; }else{ index--; if(points[index]!=rex->y){ rex->hasChanged=1; Rex2screen(*rex, 0); } rex->y=points[index]; rex->isJumping--; if(rex->isJumping==0)rex->y=40; } }else{ rex->y=40; } } void updateWalk(dino* rex){ if(!(rex->isJumping)){ rex->steps++; if(rex->steps==20){ if (rex->sprite==dino3) { rex->sprite=dino4; rex->hasChanged=1; Rex2screen(*rex, 0); }else{ rex->sprite=dino3; rex->hasChanged=1; Rex2screen(*rex, 0); } rex->steps=0; } } } const uint8_t* cactsmall[6]; const uint8_t* cactbig[6]; void create_cactus(cacti* cactus){ cactus->x=127;// Fixed (It cant be more than 127) cactus->alive=0xFF; if(get_rand(2)%2==0){//gets the type of the cactus(big or small) cactus->y=48; cactus->w=8; cactus->h=16; cactus->sprite=cactsmall[get_rand(5)]; }else{ cactus->y=40; cactus->w=12; cactus->h=24; cactus->sprite=cactbig[get_rand(5)]; } } void kill_cactus(cacti* cactus){ cactus->alive=0; } void create_dino(dino* rex){ rex->x = 20; rex->y = 40; rex->w = 20; rex->h = 24; rex->sprite=dino3; rex->isJumping=0; rex->steps=0; rex->hasChanged=1; } void draw_score(uint16_t score){ char s[5]; itoa(score,s,10); drawstring(buffer, 112, 0,s); write_part(buffer,112,0,15,8); } void draw_highscore(uint16_t high){ //FIXME char s[5]; itoa(high,s,10); drawstring(buffer, 92, 0,s); write_part(buffer,92,0,15,8); } #define MAX_CAC 3 void create_cactus(cacti* cactus); int main(void){ init_hardware(); //low level atmega stuff (PORTS, ACD, etc) clear_screen(); drawbitmap(buffer, 0, 0, picture,50,64,1); drawstring(buffer,51,0,"ROBSON COUTO"); drawstring(buffer,51,2,"Eng Eletrica"); drawstring(buffer,51,4,"UFC"); drawstring(buffer,51,6,"github:"); drawstring(buffer,51,7,"@robsoncouto"); write_buffer(buffer); while(1){ if(button_pressed()){ while (1) { for(int i=0;i<164;i=i+4){ clear_buffer(buffer); drawbitmap(buffer, 0, 0, dragao+i,128,8,1); drawbitmap(buffer, 0, 8, dragao+1*292+i,128,8,1);//FIXME ugliest hack ever, not proud drawbitmap(buffer, 0, 16, dragao+2*292+i,128,8,1); drawbitmap(buffer, 0, 24, dragao+3*292+i,128,8,1); drawbitmap(buffer, 0, 32, dragao+4*292+i,128,8,1); drawbitmap(buffer, 0, 40, dragao+5*292+i,128,8,1); drawbitmap(buffer, 0, 48, dragao+6*292+i,128,8,1); drawbitmap(buffer, 0, 56, dragao+7*292+i,128,8,1); write_buffer(buffer); _delay_ms(300); if(button_pressed()){ goto game; } } } } } game: //Initise the arrays that keep the sprite addresses //One of these values in gotten randomly at cacti creation cactsmall[0]=cacts1; cactsmall[1]=cacts2; cactsmall[2]=cacts3; cactsmall[3]=cacts4; cactsmall[4]=cacts5; cactsmall[5]=cacts6; cactbig[0]=cactusb1; cactbig[1]=cactusb2; cactbig[2]=cactusb3; cactbig[3]=cactusb4; cactbig[4]=cactusb5; cactbig[5]=cactusb6; dino Rex; create_dino(&Rex); cacti cac[MAX_CAC]; uint8_t nof_cacti=0; //current number of cacti on screen uint8_t tail=0;//the position of the new cactus on the ring uint8_t frames2nxtCac=0; //frames to next cactus. This is a delay to the creation of //the next cactus. So the Rex has some space to land uint16_t highscore=0,score=0; //init_hardware(); //low level atmega stuff (PORTS, ACD, etc) highscore=get_score();//FIXME make the score zero when first time (Not used memory=0xFF) uint8_t bump=0; //collision between dino and catus kept here clear_screen(); clear_buffer(buffer); for(int j=0;j<MAX_CAC;j++){ kill_cactus(&cac[j]); } draw_highscore(highscore);//only time this is written to the screen draw_score(score); while(1){ bump=0; clear_buffer(buffer);//The memory is cleared, but not the LCD if(button_pressed()){ if(!(Rex.isJumping)){ Rex.isJumping=2*sizeof(points);//The array points has the positions for the jump (2x because is back an forth ) } } updateWalk(&Rex); //Updates dino sprite (which leg touches the ground) updateJump(&Rex); //Update the dinos position draw_dino(Rex,1); if(nof_cacti<=MAX_CAC){ //Checks if there are MAX_CAC cacti on screen already if((!cac[tail].alive)&(frames2nxtCac==0)){ if(get_rand(16)==0){//"1 in 16 chance" No, I know //If the previous conditions are met, create a new cactus and delay creation of new cacti create_cactus(&cac[tail]); tail++; nof_cacti++; frames2nxtCac=60;//can be changed } } if (tail==MAX_CAC){ tail=0; } } //Only writes the dino to the LCD when it has changed position or sprite if(Rex.hasChanged){ write_part(buffer,Rex.x,Rex.y,Rex.w,Rex.h); Rex.hasChanged=0; } //Draw cacti to the buffer, checks collision, and write them to the LCD for(int j=0;j<MAX_CAC;j++){ if(cac[j].alive){ if(cac[j].x<1){ kill_cactus(&cac[j]); score++; nof_cacti--; draw_cactus(cac[j],0); draw_score(score);//The score is also drawn to the LCD only when changed }else{ cac[j].x--; bump|=draw_cactus(cac[j],1);//draw the cati to the buffer and gets a possible collision } write_part(buffer,cac[j].x,cac[j].y,cac[j].w,cac[j].h);//draw the cati to the LCD } } draw_ground();//draww ground to buffer write_part(buffer,0,56,128,8);//draw gnd from buffer to LCD _delay_ms(5);//FIXME needs a interrupt/timer scheme to keep fixed fps if (bump) { drawstring(buffer,18,4,"G A M E O V E R"); write_part(buffer,18,32,100,8);//FIXME put in the center if(score>highscore)update_score(score); //writes new score to EEPROM` while (1) { if(button_pressed()){ reset();//see hardware.c for implementation } } } if(frames2nxtCac)frames2nxtCac--;//Each frame decreases delay for new catcus //Erase cacti from LCD screen for(int j=0;j<MAX_CAC;j++){ if(cac[j].alive){ draw_cactus(cac[j],0); write_part(buffer,cac[j].x,cac[j].y,cac[j].w,cac[j].h); } } } }
lgpl-2.1
cureos/accord
Sources/Accord.Statistics/Accord.MachineLearning/Learning/IParallel.cs
1980
// Accord Statistics Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2016 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace Accord.MachineLearning { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; /// <summary> /// Common interface for parallel algorithms. /// </summary> /// public interface IParallel : ISupportsCancellation { /// <summary> /// Gets or sets the parallelization options for this algorithm. /// </summary> /// ParallelOptions ParallelOptions { get; set; } } /// <summary> /// Common interface for algorithms that can be canceled /// in the middle of execution. /// </summary> /// public interface ISupportsCancellation { /// <summary> /// Gets or sets a cancellation token that can be used /// to cancel the algorithm while it is running. /// </summary> /// CancellationToken Token { get; set; } } }
lgpl-2.1
dobkeratops/rustfind
rf_common.rs
184
// Commmon use's pub use collections::HashMap; pub use std::str; pub use std::num; pub use timer::Profiler; use std::strbuf::StrBuf; use std::strbuf; use std::vec::Vec; use std::vec;
lgpl-2.1
Copix/Copix3
www/js/FCKeditor/fckconfig.js
13198
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2007 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Editor configuration settings. * * Follow this link for more information: * http://wiki.fckeditor.net/Developer%27s_Guide/Configuration/Configurations_Settings */ FCKConfig.CustomConfigurationsPath = '' ; FCKConfig.EditorAreaCSS = FCKConfig.BasePath + 'css/fck_editorarea.css' ; FCKConfig.EditorAreaStyles = '' ; FCKConfig.ToolbarComboPreviewCSS = '' ; FCKConfig.DocType = '' ; FCKConfig.BaseHref = '' ; FCKConfig.FullPage = false ; // The following option determines whether the "Show Blocks" feature is enabled or not at startup. FCKConfig.StartupShowBlocks = false ; FCKConfig.Debug = false ; FCKConfig.AllowQueryStringDebug = true ; FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/default/' ; FCKConfig.PreloadImages = [ FCKConfig.SkinPath + 'images/toolbar.start.gif', FCKConfig.SkinPath + 'images/toolbar.buttonarrow.gif' ] ; FCKConfig.PluginsPath = FCKConfig.BasePath + 'plugins/' ; // FCKConfig.Plugins.Add( 'autogrow' ) ; // FCKConfig.Plugins.Add( 'dragresizetable' ); FCKConfig.AutoGrowMax = 400 ; // FCKConfig.ProtectedSource.Add( /<%[\s\S]*?%>/g ) ; // ASP style server side code <%...%> // FCKConfig.ProtectedSource.Add( /<\?[\s\S]*?\?>/g ) ; // PHP style server side code // FCKConfig.ProtectedSource.Add( /(<asp:[^\>]+>[\s|\S]*?<\/asp:[^\>]+>)|(<asp:[^\>]+\/>)/gi ) ; // ASP.Net style tags <asp:control> FCKConfig.AutoDetectLanguage = true ; FCKConfig.DefaultLanguage = 'en' ; FCKConfig.ContentLangDirection = 'ltr' ; FCKConfig.ProcessHTMLEntities = true ; FCKConfig.IncludeLatinEntities = true ; FCKConfig.IncludeGreekEntities = true ; FCKConfig.ProcessNumericEntities = false ; FCKConfig.AdditionalNumericEntities = '' ; // Single Quote: "'" FCKConfig.FillEmptyBlocks = true ; FCKConfig.FormatSource = true ; FCKConfig.FormatOutput = true ; FCKConfig.FormatIndentator = ' ' ; FCKConfig.GeckoUseSPAN = false ; FCKConfig.StartupFocus = false ; FCKConfig.ForcePasteAsPlainText = false ; FCKConfig.AutoDetectPasteFromWord = true ; // IE only. FCKConfig.ShowDropDialog = true ; FCKConfig.ForceSimpleAmpersand = false ; FCKConfig.TabSpaces = 0 ; FCKConfig.ShowBorders = true ; FCKConfig.SourcePopup = false ; FCKConfig.ToolbarStartExpanded = true ; FCKConfig.ToolbarCanCollapse = true ; FCKConfig.IgnoreEmptyParagraphValue = true ; FCKConfig.PreserveSessionOnFileBrowser = false ; FCKConfig.FloatingPanelsZIndex = 10000 ; FCKConfig.HtmlEncodeOutput = false ; FCKConfig.TemplateReplaceAll = true ; FCKConfig.TemplateReplaceCheckbox = true ; FCKConfig.ToolbarLocation = 'In' ; FCKConfig.ToolbarSets["Default"] = [ ['Source','DocProps','-','Save','NewPage','Preview','-','Templates'], ['Cut','Copy','Paste','PasteText','PasteWord','-','Print','SpellCheck'], ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'], ['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'], '/', ['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'], ['OrderedList','UnorderedList','-','Outdent','Indent','Blockquote'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'], ['Link','Unlink','Anchor'], ['Image','Flash','Table','Rule','Smiley','SpecialChar','PageBreak'], '/', ['Style','FontFormat','FontName','FontSize'], ['TextColor','BGColor'], ['FitWindow','ShowBlocks','-','About'] // No comma for the last row. ] ; FCKConfig.ToolbarSets["Basic"] = [ ['Bold','Italic','-','OrderedList','UnorderedList','-','Link','Unlink','-','About'] ] ; FCKConfig.ToolbarSets["Copix"] = [ ['Source'], ['Cut','Copy','Paste','PasteText','PasteWord'], ['Undo','Redo','-','Find','Replace'], ['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'], ['OrderedList','UnorderedList','-','Outdent','Indent'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'], ['Link','Unlink','Anchor'], ['Image','Rule','SpecialChar','Smiley'] //['Style', 'mailto'],//, 'phototheque','document','cmslink','cmslinkpopup'],'/', //['Table','-','TableInsertRow','TableDeleteRows','TableInsertColumn','TableDeleteColumns','TableInsertCell','TableDeleteCells','TableMergeCells','TableSplitCell'] ] ; FCKConfig.EnterMode = 'p' ; // p | div | br FCKConfig.ShiftEnterMode = 'br' ; // p | div | br FCKConfig.Keystrokes = [ [ CTRL + 65 /*A*/, true ], [ CTRL + 67 /*C*/, true ], [ CTRL + 70 /*F*/, true ], [ CTRL + 83 /*S*/, true ], [ CTRL + 88 /*X*/, true ], [ CTRL + 86 /*V*/, 'Paste' ], [ SHIFT + 45 /*INS*/, 'Paste' ], [ CTRL + 88 /*X*/, 'Cut' ], [ SHIFT + 46 /*DEL*/, 'Cut' ], [ CTRL + 90 /*Z*/, 'Undo' ], [ CTRL + 89 /*Y*/, 'Redo' ], [ CTRL + SHIFT + 90 /*Z*/, 'Redo' ], [ CTRL + 76 /*L*/, 'Link' ], [ CTRL + 66 /*B*/, 'Bold' ], [ CTRL + 73 /*I*/, 'Italic' ], [ CTRL + 85 /*U*/, 'Underline' ], [ CTRL + SHIFT + 83 /*S*/, 'Save' ], [ CTRL + ALT + 13 /*ENTER*/, 'FitWindow' ], [ CTRL + 9 /*TAB*/, 'Source' ] ] ; FCKConfig.ContextMenu = ['Generic','Link','Anchor','Image','Flash','Select','Textarea','Checkbox','Radio','TextField','HiddenField','ImageButton','Button','BulletedList','NumberedList','Table','Form'] ; FCKConfig.BrowserContextMenuOnCtrl = false ; FCKConfig.EnableMoreFontColors = true ; FCKConfig.FontColors = '000000,993300,333300,003300,003366,000080,333399,333333,800000,FF6600,808000,808080,008080,0000FF,666699,808080,FF0000,FF9900,99CC00,339966,33CCCC,3366FF,800080,999999,FF00FF,FFCC00,FFFF00,00FF00,00FFFF,00CCFF,993366,C0C0C0,FF99CC,FFCC99,FFFF99,CCFFCC,CCFFFF,99CCFF,CC99FF,FFFFFF' ; FCKConfig.FontFormats = 'p;div;pre;address;h1;h2;h3;h4;h5;h6' ; FCKConfig.FontNames = 'Arial;Comic Sans MS;Courier New;Tahoma;Times New Roman;Verdana' ; FCKConfig.FontSizes = 'smaller;larger;xx-small;x-small;small;medium;large;x-large;xx-large' ; FCKConfig.StylesXmlPath = FCKConfig.EditorPath + 'fckstyles.xml' ; FCKConfig.TemplatesXmlPath = FCKConfig.EditorPath + 'fcktemplates.xml' ; FCKConfig.SpellChecker = 'ieSpell' ; // 'ieSpell' | 'SpellerPages' FCKConfig.IeSpellDownloadUrl = 'http://www.iespell.com/download.php' ; FCKConfig.SpellerPagesServerScript = 'server-scripts/spellchecker.php' ; // Available extension: .php .cfm .pl FCKConfig.FirefoxSpellChecker = false ; FCKConfig.MaxUndoLevels = 15 ; FCKConfig.DisableObjectResizing = false ; FCKConfig.DisableFFTableHandles = true ; FCKConfig.LinkDlgHideTarget = false ; FCKConfig.LinkDlgHideAdvanced = false ; FCKConfig.ImageDlgHideLink = false ; FCKConfig.ImageDlgHideAdvanced = false ; FCKConfig.FlashDlgHideAdvanced = false ; FCKConfig.ProtectedTags = '' ; // This will be applied to the body element of the editor FCKConfig.BodyId = '' ; FCKConfig.BodyClass = '' ; FCKConfig.DefaultStyleLabel = '' ; FCKConfig.DefaultFontFormatLabel = '' ; FCKConfig.DefaultFontLabel = '' ; FCKConfig.DefaultFontSizeLabel = '' ; FCKConfig.DefaultLinkTarget = '' ; // The option switches between trying to keep the html structure or do the changes so the content looks like it was in Word FCKConfig.CleanWordKeepsStructure = false ; // Only inline elements are valid. FCKConfig.RemoveFormatTags = 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var' ; FCKConfig.CustomStyles = { 'Red Title' : { Element : 'h3', Styles : { 'color' : 'Red' } } }; // Do not add, rename or remove styles here. Only apply definition changes. FCKConfig.CoreStyles = { // Basic Inline Styles. 'Bold' : { Element : 'b', Overrides : 'strong' }, 'Italic' : { Element : 'i', Overrides : 'em' }, 'Underline' : { Element : 'u' }, 'StrikeThrough' : { Element : 'strike' }, 'Subscript' : { Element : 'sub' }, 'Superscript' : { Element : 'sup' }, // Basic Block Styles (Font Format Combo). 'p' : { Element : 'p' }, 'div' : { Element : 'div' }, 'pre' : { Element : 'pre' }, 'address' : { Element : 'address' }, 'h1' : { Element : 'h1' }, 'h2' : { Element : 'h2' }, 'h3' : { Element : 'h3' }, 'h4' : { Element : 'h4' }, 'h5' : { Element : 'h5' }, 'h6' : { Element : 'h6' }, // Other formatting features. 'FontFace' : { Element : 'span', Styles : { 'font-family' : '#("Font")' }, Overrides : [ { Element : 'font', Attributes : { 'face' : null } } ] }, 'Size' : { Element : 'span', Styles : { 'font-size' : '#("Size","fontSize")' }, Overrides : [ { Element : 'font', Attributes : { 'size' : null } } ] }, 'Color' : { Element : 'span', Styles : { 'color' : '#("Color","color")' }, Overrides : [ { Element : 'font', Attributes : { 'color' : null } } ] }, 'BackColor' : { Element : 'span', Styles : { 'background-color' : '#("Color","color")' } } }; // The distance of an indentation step. FCKConfig.IndentLength = 40 ; FCKConfig.IndentUnit = 'px' ; // Alternatively, FCKeditor allows the use of CSS classes for block indentation. // This overrides the IndentLength/IndentUnit settings. FCKConfig.IndentClasses = [] ; // [ Left, Center, Right, Justified ] FCKConfig.JustifyClasses = [] ; // The following value defines which File Browser connector and Quick Upload // "uploader" to use. It is valid for the default implementaion and it is here // just to make this configuration file cleaner. // It is not possible to change this value using an external file or even // inline when creating the editor instance. In that cases you must set the // values of LinkBrowserURL, ImageBrowserURL and so on. // Custom implementations should just ignore it. var _FileBrowserLanguage = 'php' ; // asp | aspx | cfm | lasso | perl | php | py var _QuickUploadLanguage = 'php' ; // asp | aspx | cfm | lasso | perl | php | py // Don't care about the following line. It just calculates the correct connector // extension to use for the default File Browser (Perl uses "cgi"). var _FileBrowserExtension = _FileBrowserLanguage == 'perl' ? 'cgi' : _FileBrowserLanguage ; FCKConfig.LinkBrowser = true ; FCKConfig.LinkBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Connector=../../connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ; FCKConfig.LinkBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70% FCKConfig.LinkBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70% FCKConfig.ImageBrowser = true ; FCKConfig.ImageBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Image&Connector=../../connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ; FCKConfig.ImageBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70% ; FCKConfig.ImageBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70% ; FCKConfig.FlashBrowser = true ; FCKConfig.FlashBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Flash&Connector=../../connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ; FCKConfig.FlashBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; //70% ; FCKConfig.FlashBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; //70% ; FCKConfig.LinkUpload = true ; FCKConfig.LinkUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadLanguage ; FCKConfig.LinkUploadAllowedExtensions = "" ; // empty for all FCKConfig.LinkUploadDeniedExtensions = ".(html|htm|php|php2|php3|php4|php5|phtml|pwml|inc|asp|aspx|ascx|jsp|cfm|cfc|pl|bat|exe|com|dll|vbs|js|reg|cgi|htaccess|asis|sh|shtml|shtm|phtm)$" ; // empty for no one FCKConfig.ImageUpload = true ; FCKConfig.ImageUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadLanguage + '?Type=Image' ; FCKConfig.ImageUploadAllowedExtensions = ".(jpg|gif|jpeg|png|bmp)$" ; // empty for all FCKConfig.ImageUploadDeniedExtensions = "" ; // empty for no one FCKConfig.FlashUpload = true ; FCKConfig.FlashUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadLanguage + '?Type=Flash' ; FCKConfig.FlashUploadAllowedExtensions = ".(swf|fla)$" ; // empty for all FCKConfig.FlashUploadDeniedExtensions = "" ; // empty for no one FCKConfig.SmileyPath = FCKConfig.BasePath + 'images/smiley/msn/' ; FCKConfig.SmileyImages = ['regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','confused_smile.gif','tounge_smile.gif','embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angry_smile.gif','angel_smile.gif','shades_smile.gif','devil_smile.gif','cry_smile.gif','lightbulb.gif','thumbs_down.gif','thumbs_up.gif','heart.gif','broken_heart.gif','kiss.gif','envelope.gif'] ; FCKConfig.SmileyColumns = 8 ; FCKConfig.SmileyWindowWidth = 320 ; FCKConfig.SmileyWindowHeight = 240 ;
lgpl-2.1
enachb/freetel-code
src/wxWidgets-2.9.4/samples/controls/controls.cpp
68101
///////////////////////////////////////////////////////////////////////////// // Name: controls.cpp // Purpose: Controls wxWidgets sample // Author: Robert Roebling // Modified by: // RCS-ID: $Id$ // Copyright: (c) Robert Roebling, Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "wx/spinbutt.h" #include "wx/tglbtn.h" #include "wx/bookctrl.h" #include "wx/imaglist.h" #include "wx/artprov.h" #include "wx/cshelp.h" #include "wx/gbsizer.h" #if wxUSE_TOOLTIPS #include "wx/tooltip.h" #ifdef __WXMSW__ #include "wx/numdlg.h" #endif // __WXMSW__ #endif // wxUSE_TOOLTIPS #ifndef __WXMSW__ #include "icons/choice.xpm" #include "icons/combo.xpm" #include "icons/list.xpm" #include "icons/radio.xpm" #include "icons/text.xpm" #include "icons/gauge.xpm" #endif #ifndef wxUSE_SPINBTN #define wxUSE_SPINBTN 1 #endif #include "wx/progdlg.h" #if wxUSE_SPINCTRL #include "wx/spinctrl.h" #endif // wxUSE_SPINCTRL #if !wxUSE_TOGGLEBTN #define wxToggleButton wxCheckBox #define EVT_TOGGLEBUTTON EVT_CHECKBOX #endif #ifndef wxHAS_IMAGES_IN_RESOURCES #include "../sample.xpm" #endif //---------------------------------------------------------------------- // class definitions //---------------------------------------------------------------------- class MyApp: public wxApp { public: bool OnInit(); }; class MyPanel: public wxPanel { public: MyPanel(wxFrame *frame, int x, int y, int w, int h); virtual ~MyPanel(); #if wxUSE_TOOLTIPS void SetAllToolTips(); #endif // wxUSE_TOOLTIPS void OnIdle( wxIdleEvent &event ); void OnListBox( wxCommandEvent &event ); void OnListBoxDoubleClick( wxCommandEvent &event ); void OnListBoxButtons( wxCommandEvent &event ); #if wxUSE_CHOICE void OnChoice( wxCommandEvent &event ); void OnChoiceButtons( wxCommandEvent &event ); #endif void OnCombo( wxCommandEvent &event ); void OnComboTextChanged( wxCommandEvent &event ); void OnComboTextEnter( wxCommandEvent &event ); void OnComboButtons( wxCommandEvent &event ); void OnRadio( wxCommandEvent &event ); void OnRadioButtons( wxCommandEvent &event ); void OnRadioButton1( wxCommandEvent &event ); void OnRadioButton2( wxCommandEvent &event ); void OnSetFont( wxCommandEvent &event ); void OnPageChanged( wxBookCtrlEvent &event ); void OnPageChanging( wxBookCtrlEvent &event ); void OnSliderUpdate( wxCommandEvent &event ); void OnUpdateLabel( wxCommandEvent &event ); #if wxUSE_SPINBTN void OnSpinUp( wxSpinEvent &event ); void OnSpinDown( wxSpinEvent &event ); void OnSpinUpdate( wxSpinEvent &event ); #if wxUSE_PROGRESSDLG void OnUpdateShowProgress( wxUpdateUIEvent& event ); void OnShowProgress( wxCommandEvent &event ); #endif // wxUSE_PROGRESSDLG #endif // wxUSE_SPINBTN void OnNewText( wxCommandEvent &event ); #if wxUSE_SPINCTRL void OnSpinCtrl(wxSpinEvent& event); void OnSpinCtrlUp(wxSpinEvent& event); void OnSpinCtrlDown(wxSpinEvent& event); void OnSpinCtrlText(wxCommandEvent& event); #endif // wxUSE_SPINCTRL void OnEnableAll(wxCommandEvent& event); void OnChangeColour(wxCommandEvent& event); void OnTestButton(wxCommandEvent& event); void OnBmpButton(wxCommandEvent& event); void OnBmpButtonToggle(wxCommandEvent& event); void OnSizerCheck (wxCommandEvent &event); wxListBox *m_listbox, *m_listboxSorted; #if wxUSE_CHOICE wxChoice *m_choice, *m_choiceSorted; #endif // wxUSE_CHOICE wxComboBox *m_combo; wxRadioBox *m_radio; #if wxUSE_GAUGE wxGauge *m_gauge, *m_gaugeVert; #endif // wxUSE_GAUGE #if wxUSE_SLIDER wxSlider *m_slider; #endif // wxUSE_SLIDER wxButton *m_fontButton; wxButton *m_lbSelectNum; wxButton *m_lbSelectThis; #if wxUSE_SPINBTN wxSpinButton *m_spinbutton; #if wxUSE_PROGRESSDLG wxButton *m_btnProgress; #endif // wxUSE_PROGRESSDLG #endif // wxUSE_SPINBTN wxStaticText *m_wrappingText; wxStaticText *m_nonWrappingText; #if wxUSE_SPINCTRL wxSpinCtrl *m_spinctrl; #endif // wxUSE_SPINCTRL wxTextCtrl *m_spintext; wxCheckBox *m_checkbox; wxTextCtrl *m_text; wxBookCtrl *m_book; wxStaticText *m_label; wxBoxSizer *m_buttonSizer; wxButton *m_sizerBtn1; wxButton *m_sizerBtn2; wxButton *m_sizerBtn3; wxButton *m_sizerBtn4; wxBoxSizer *m_hsizer; wxButton *m_bigBtn; private: wxLog *m_logTargetOld; DECLARE_EVENT_TABLE() }; class MyFrame: public wxFrame { public: MyFrame(const wxChar *title, int x, int y); void OnQuit(wxCommandEvent& event); void OnAbout(wxCommandEvent& event); void OnClearLog(wxCommandEvent& event); #if wxUSE_TOOLTIPS void OnSetTooltipDelay(wxCommandEvent& event); void OnToggleTooltips(wxCommandEvent& event); #ifdef __WXMSW__ void OnSetMaxTooltipWidth(wxCommandEvent& event); #endif // __WXMSW__ #endif // wxUSE_TOOLTIPS void OnEnableAll(wxCommandEvent& event); void OnHideAll(wxCommandEvent& event); void OnHideList(wxCommandEvent& event); void OnContextHelp(wxCommandEvent& event); void OnIdle( wxIdleEvent& event ); void OnIconized( wxIconizeEvent& event ); void OnMaximized( wxMaximizeEvent& event ); void OnSize( wxSizeEvent& event ); void OnMove( wxMoveEvent& event ); MyPanel *GetPanel() const { return m_panel; } private: #if wxUSE_STATUSBAR void UpdateStatusBar(const wxPoint& pos, const wxSize& size) { if ( m_frameStatusBar ) { wxString msg; wxSize sizeAll = GetSize(), sizeCl = GetClientSize(); msg.Printf(_("pos=(%d, %d), size=%dx%d or %dx%d (client=%dx%d)"), pos.x, pos.y, size.x, size.y, sizeAll.x, sizeAll.y, sizeCl.x, sizeCl.y); SetStatusText(msg, 1); } } #endif // wxUSE_STATUSBAR MyPanel *m_panel; DECLARE_EVENT_TABLE() }; // a button which intercepts double clicks (for testing...) class MyButton : public wxButton { public: MyButton(wxWindow *parent, wxWindowID id, const wxString& label = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize) : wxButton(parent, id, label, pos, size) { } void OnDClick(wxMouseEvent& event) { wxLogMessage(wxT("MyButton::OnDClick")); event.Skip(); } private: DECLARE_EVENT_TABLE() }; // a combo which intercepts chars (to test Windows behaviour) class MyComboBox : public wxComboBox { public: MyComboBox(wxWindow *parent, wxWindowID id, const wxString& value = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, int n = 0, const wxString choices[] = NULL, long style = 0, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxComboBoxNameStr) : wxComboBox(parent, id, value, pos, size, n, choices, style, validator, name) { } protected: void OnChar(wxKeyEvent& event); void OnKeyDown(wxKeyEvent& event); void OnKeyUp(wxKeyEvent& event); void OnFocusGot(wxFocusEvent& event) { wxLogMessage(wxT("MyComboBox::OnFocusGot")); event.Skip(); } private: DECLARE_EVENT_TABLE() }; // a radiobox which handles focus set/kill (for testing) class MyRadioBox : public wxRadioBox { public: MyRadioBox(wxWindow *parent, wxWindowID id, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, int n = 0, const wxString choices[] = NULL, int majorDim = 1, long style = wxRA_SPECIFY_COLS, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxRadioBoxNameStr) : wxRadioBox(parent, id, title, pos, size, n, choices, majorDim, style, validator, name) { } protected: void OnFocusGot(wxFocusEvent& event) { wxLogMessage(wxT("MyRadioBox::OnFocusGot")); event.Skip(); } void OnFocusLost(wxFocusEvent& event) { wxLogMessage(wxT("MyRadioBox::OnFocusLost")); event.Skip(); } private: DECLARE_EVENT_TABLE() }; // a choice which handles focus set/kill (for testing) class MyChoice : public wxChoice { public: MyChoice(wxWindow *parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, int n = 0, const wxString choices[] = NULL, long style = 0, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxChoiceNameStr ) : wxChoice(parent, id, pos, size, n, choices, style, validator, name) { } protected: void OnFocusGot(wxFocusEvent& event) { wxLogMessage(wxT("MyChoice::OnFocusGot")); event.Skip(); } void OnFocusLost(wxFocusEvent& event) { wxLogMessage(wxT("MyChoice::OnFocusLost")); event.Skip(); } private: DECLARE_EVENT_TABLE() }; //---------------------------------------------------------------------- // other //---------------------------------------------------------------------- static void SetListboxClientData(const wxChar *name, wxListBox *control); #if wxUSE_CHOICE static void SetChoiceClientData(const wxChar *name, wxChoice *control); #endif // wxUSE_CHOICE IMPLEMENT_APP(MyApp) //---------------------------------------------------------------------- // MyApp //---------------------------------------------------------------------- enum { CONTROLS_QUIT = wxID_EXIT, CONTROLS_ABOUT = wxID_ABOUT, CONTROLS_TEXT = 100, CONTROLS_CLEAR_LOG, // tooltip menu CONTROLS_SET_TOOLTIP_DELAY = 200, CONTROLS_ENABLE_TOOLTIPS, CONTROLS_SET_TOOLTIPS_MAX_WIDTH, // panel menu CONTROLS_ENABLE_ALL, CONTROLS_HIDE_ALL, CONTROLS_HIDE_LIST, CONTROLS_CONTEXT_HELP }; bool MyApp::OnInit() { // use standard command line handling: if ( !wxApp::OnInit() ) return false; // parse the cmd line int x = 50, y = 50; if ( argc == 3 ) { wxSscanf(wxString(argv[1]), wxT("%d"), &x); wxSscanf(wxString(argv[2]), wxT("%d"), &y); } #if wxUSE_HELP wxHelpProvider::Set( new wxSimpleHelpProvider ); #endif // wxUSE_HELP // Create the main frame window MyFrame *frame = new MyFrame(wxT("Controls wxWidgets App"), x, y); frame->Show(true); return true; } //---------------------------------------------------------------------- // MyPanel //---------------------------------------------------------------------- const int ID_BOOK = 1000; const int ID_LISTBOX = 130; const int ID_LISTBOX_SEL_NUM = 131; const int ID_LISTBOX_SEL_STR = 132; const int ID_LISTBOX_CLEAR = 133; const int ID_LISTBOX_APPEND = 134; const int ID_LISTBOX_DELETE = 135; const int ID_LISTBOX_FONT = 136; const int ID_LISTBOX_ENABLE = 137; const int ID_LISTBOX_SORTED = 138; const int ID_CHOICE = 120; const int ID_CHOICE_SEL_NUM = 121; const int ID_CHOICE_SEL_STR = 122; const int ID_CHOICE_CLEAR = 123; const int ID_CHOICE_APPEND = 124; const int ID_CHOICE_DELETE = 125; const int ID_CHOICE_FONT = 126; const int ID_CHOICE_ENABLE = 127; const int ID_CHOICE_SORTED = 128; const int ID_COMBO = 140; const int ID_COMBO_SEL_NUM = 141; const int ID_COMBO_SEL_STR = 142; const int ID_COMBO_CLEAR = 143; const int ID_COMBO_APPEND = 144; const int ID_COMBO_DELETE = 145; const int ID_COMBO_FONT = 146; const int ID_COMBO_ENABLE = 147; const int ID_COMBO_SET_TEXT = 148; const int ID_RADIOBOX = 160; const int ID_RADIOBOX_SEL_NUM = 161; const int ID_RADIOBOX_SEL_STR = 162; const int ID_RADIOBOX_FONT = 163; const int ID_RADIOBOX_ENABLE = 164; const int ID_RADIOBOX2 = 165; const int ID_RADIOBUTTON_1 = 166; const int ID_RADIOBUTTON_2 = 167; const int ID_SET_FONT = 170; #if wxUSE_GAUGE const int ID_GAUGE = 180; #endif // wxUSE_GAUGE #if wxUSE_SLIDER const int ID_SLIDER = 181; #endif // wxUSE_SLIDER const int ID_SPIN = 182; #if wxUSE_PROGRESSDLG const int ID_BTNPROGRESS = 183; #endif // wxUSE_PROGRESSDLG const int ID_BUTTON_LABEL = 184; const int ID_SPINCTRL = 185; const int ID_BTNNEWTEXT = 186; const int ID_BUTTON_TEST1 = 190; const int ID_BUTTON_TEST2 = 191; const int ID_BITMAP_BTN = 192; const int ID_BITMAP_BTN_ENABLE = 193; const int ID_CHANGE_COLOUR = 200; const int ID_SIZER_CHECK1 = 201; const int ID_SIZER_CHECK2 = 202; const int ID_SIZER_CHECK3 = 203; const int ID_SIZER_CHECK4 = 204; const int ID_SIZER_CHECK14 = 205; const int ID_SIZER_CHECKBIG = 206; const int ID_HYPERLINK = 300; BEGIN_EVENT_TABLE(MyPanel, wxPanel) EVT_IDLE ( MyPanel::OnIdle) EVT_BOOKCTRL_PAGE_CHANGING(ID_BOOK, MyPanel::OnPageChanging) EVT_BOOKCTRL_PAGE_CHANGED(ID_BOOK, MyPanel::OnPageChanged) EVT_LISTBOX (ID_LISTBOX, MyPanel::OnListBox) EVT_LISTBOX (ID_LISTBOX_SORTED, MyPanel::OnListBox) EVT_LISTBOX_DCLICK(ID_LISTBOX, MyPanel::OnListBoxDoubleClick) EVT_BUTTON (ID_LISTBOX_SEL_NUM, MyPanel::OnListBoxButtons) EVT_BUTTON (ID_LISTBOX_SEL_STR, MyPanel::OnListBoxButtons) EVT_BUTTON (ID_LISTBOX_CLEAR, MyPanel::OnListBoxButtons) EVT_BUTTON (ID_LISTBOX_APPEND, MyPanel::OnListBoxButtons) EVT_BUTTON (ID_LISTBOX_DELETE, MyPanel::OnListBoxButtons) EVT_BUTTON (ID_LISTBOX_FONT, MyPanel::OnListBoxButtons) EVT_CHECKBOX (ID_LISTBOX_ENABLE, MyPanel::OnListBoxButtons) #if wxUSE_CHOICE EVT_CHOICE (ID_CHOICE, MyPanel::OnChoice) EVT_CHOICE (ID_CHOICE_SORTED, MyPanel::OnChoice) EVT_BUTTON (ID_CHOICE_SEL_NUM, MyPanel::OnChoiceButtons) EVT_BUTTON (ID_CHOICE_SEL_STR, MyPanel::OnChoiceButtons) EVT_BUTTON (ID_CHOICE_CLEAR, MyPanel::OnChoiceButtons) EVT_BUTTON (ID_CHOICE_APPEND, MyPanel::OnChoiceButtons) EVT_BUTTON (ID_CHOICE_DELETE, MyPanel::OnChoiceButtons) EVT_BUTTON (ID_CHOICE_FONT, MyPanel::OnChoiceButtons) EVT_CHECKBOX (ID_CHOICE_ENABLE, MyPanel::OnChoiceButtons) #endif EVT_COMBOBOX (ID_COMBO, MyPanel::OnCombo) EVT_TEXT (ID_COMBO, MyPanel::OnComboTextChanged) EVT_TEXT_ENTER(ID_COMBO, MyPanel::OnComboTextEnter) EVT_BUTTON (ID_COMBO_SEL_NUM, MyPanel::OnComboButtons) EVT_BUTTON (ID_COMBO_SEL_STR, MyPanel::OnComboButtons) EVT_BUTTON (ID_COMBO_CLEAR, MyPanel::OnComboButtons) EVT_BUTTON (ID_COMBO_APPEND, MyPanel::OnComboButtons) EVT_BUTTON (ID_COMBO_DELETE, MyPanel::OnComboButtons) EVT_BUTTON (ID_COMBO_FONT, MyPanel::OnComboButtons) EVT_BUTTON (ID_COMBO_SET_TEXT, MyPanel::OnComboButtons) EVT_CHECKBOX (ID_COMBO_ENABLE, MyPanel::OnComboButtons) EVT_RADIOBOX (ID_RADIOBOX, MyPanel::OnRadio) EVT_RADIOBOX (ID_RADIOBOX2, MyPanel::OnRadio) EVT_BUTTON (ID_RADIOBOX_SEL_NUM, MyPanel::OnRadioButtons) EVT_BUTTON (ID_RADIOBOX_SEL_STR, MyPanel::OnRadioButtons) EVT_BUTTON (ID_RADIOBOX_FONT, MyPanel::OnRadioButtons) EVT_CHECKBOX (ID_RADIOBOX_ENABLE, MyPanel::OnRadioButtons) EVT_RADIOBUTTON(ID_RADIOBUTTON_1, MyPanel::OnRadioButton1) EVT_RADIOBUTTON(ID_RADIOBUTTON_2, MyPanel::OnRadioButton2) EVT_BUTTON (ID_SET_FONT, MyPanel::OnSetFont) #if wxUSE_SLIDER EVT_SLIDER (ID_SLIDER, MyPanel::OnSliderUpdate) #endif // wxUSE_SLIDER #if wxUSE_SPINBTN EVT_SPIN (ID_SPIN, MyPanel::OnSpinUpdate) EVT_SPIN_UP (ID_SPIN, MyPanel::OnSpinUp) EVT_SPIN_DOWN (ID_SPIN, MyPanel::OnSpinDown) #if wxUSE_PROGRESSDLG EVT_UPDATE_UI (ID_BTNPROGRESS, MyPanel::OnUpdateShowProgress) EVT_BUTTON (ID_BTNPROGRESS, MyPanel::OnShowProgress) #endif // wxUSE_PROGRESSDLG #endif // wxUSE_SPINBTN #if wxUSE_SPINCTRL EVT_SPINCTRL (ID_SPINCTRL, MyPanel::OnSpinCtrl) EVT_SPIN_UP (ID_SPINCTRL, MyPanel::OnSpinCtrlUp) EVT_SPIN_DOWN (ID_SPINCTRL, MyPanel::OnSpinCtrlDown) EVT_TEXT (ID_SPINCTRL, MyPanel::OnSpinCtrlText) #endif // wxUSE_SPINCTRL EVT_BUTTON (ID_BTNNEWTEXT, MyPanel::OnNewText) EVT_TOGGLEBUTTON(ID_BUTTON_LABEL, MyPanel::OnUpdateLabel) EVT_CHECKBOX (ID_CHANGE_COLOUR, MyPanel::OnChangeColour) EVT_BUTTON (ID_BUTTON_TEST1, MyPanel::OnTestButton) EVT_BUTTON (ID_BUTTON_TEST2, MyPanel::OnTestButton) EVT_BUTTON (ID_BITMAP_BTN, MyPanel::OnBmpButton) EVT_TOGGLEBUTTON(ID_BITMAP_BTN_ENABLE, MyPanel::OnBmpButtonToggle) EVT_CHECKBOX (ID_SIZER_CHECK1, MyPanel::OnSizerCheck) EVT_CHECKBOX (ID_SIZER_CHECK2, MyPanel::OnSizerCheck) EVT_CHECKBOX (ID_SIZER_CHECK3, MyPanel::OnSizerCheck) EVT_CHECKBOX (ID_SIZER_CHECK4, MyPanel::OnSizerCheck) EVT_CHECKBOX (ID_SIZER_CHECK14, MyPanel::OnSizerCheck) EVT_CHECKBOX (ID_SIZER_CHECKBIG, MyPanel::OnSizerCheck) END_EVENT_TABLE() BEGIN_EVENT_TABLE(MyButton, wxButton) EVT_LEFT_DCLICK(MyButton::OnDClick) END_EVENT_TABLE() BEGIN_EVENT_TABLE(MyComboBox, wxComboBox) EVT_CHAR(MyComboBox::OnChar) EVT_KEY_DOWN(MyComboBox::OnKeyDown) EVT_KEY_UP(MyComboBox::OnKeyUp) EVT_SET_FOCUS(MyComboBox::OnFocusGot) END_EVENT_TABLE() BEGIN_EVENT_TABLE(MyRadioBox, wxRadioBox) EVT_SET_FOCUS(MyRadioBox::OnFocusGot) EVT_KILL_FOCUS(MyRadioBox::OnFocusLost) END_EVENT_TABLE() BEGIN_EVENT_TABLE(MyChoice, wxChoice) EVT_SET_FOCUS(MyChoice::OnFocusGot) EVT_KILL_FOCUS(MyChoice::OnFocusLost) END_EVENT_TABLE() // ============================================================================ // implementation // ============================================================================ MyPanel::MyPanel( wxFrame *frame, int x, int y, int w, int h ) : wxPanel( frame, wxID_ANY, wxPoint(x, y), wxSize(w, h) ) { m_listbox = NULL; m_listboxSorted = NULL; #if wxUSE_CHOICE m_choice = NULL; m_choiceSorted = NULL; #endif // wxUSE_CHOICE m_combo = NULL; m_radio = NULL; #if wxUSE_GAUGE m_gauge = NULL; m_gaugeVert = NULL; #endif // wxUSE_GAUGE #if wxUSE_SLIDER m_slider = NULL; #endif // wxUSE_SLIDER m_fontButton = NULL; m_lbSelectNum = NULL; m_lbSelectThis = NULL; #if wxUSE_SPINBTN m_spinbutton = NULL; #if wxUSE_PROGRESSDLG m_btnProgress = NULL; #endif // wxUSE_PROGRESSDLG #endif // wxUSE_SPINBTN #if wxUSE_SPINCTRL m_spinctrl = NULL; #endif // wxUSE_SPINCTRL m_spintext = NULL; m_checkbox = NULL; m_text = NULL; m_book = NULL; m_label = NULL; m_text = new wxTextCtrl(this, wxID_ANY, wxT("This is the log window.\n"), wxPoint(0, 250), wxSize(100, 50), wxTE_MULTILINE); m_logTargetOld = wxLog::SetActiveTarget(new wxLogTextCtrl(m_text)); m_book = new wxBookCtrl(this, ID_BOOK); wxString choices[] = { wxT("This"), wxT("is"), wxT("one of my long and"), wxT("wonderful"), wxT("examples.") }; #ifndef __WXMSW__ // image ids enum { Image_List, Image_Choice, Image_Combo, Image_Text, Image_Radio, #if wxUSE_GAUGE Image_Gauge, #endif // wxUSE_GAUGE Image_Max }; // fill the image list wxBitmap bmp(list_xpm); wxImageList *imagelist = new wxImageList(bmp.GetWidth(), bmp.GetHeight()); imagelist-> Add( bmp ); imagelist-> Add( wxBitmap( choice_xpm )); imagelist-> Add( wxBitmap( combo_xpm )); imagelist-> Add( wxBitmap( text_xpm )); imagelist-> Add( wxBitmap( radio_xpm )); #if wxUSE_GAUGE imagelist-> Add( wxBitmap( gauge_xpm )); #endif // wxUSE_GAUGE m_book->SetImageList(imagelist); #else // load images from resources enum { Image_List, Image_Choice, Image_Combo, Image_Text, Image_Radio, #if wxUSE_GAUGE Image_Gauge, #endif // wxUSE_GAUGE Image_Max }; wxImageList *imagelist = new wxImageList(16, 16, false, Image_Max); static const wxChar *s_iconNames[Image_Max] = { wxT("list") , wxT("choice") , wxT("combo") , wxT("text") , wxT("radio") #if wxUSE_GAUGE , wxT("gauge") #endif // wxUSE_GAUGE }; for ( size_t n = 0; n < Image_Max; n++ ) { wxBitmap bmp(s_iconNames[n]); if ( !bmp.IsOk() || (imagelist->Add(bmp) == -1) ) { wxLogWarning(wxT("Couldn't load the image '%s' for the book control page %d."), s_iconNames[n], n); } } m_book->SetImageList(imagelist); #endif // ------------------------------------------------------------------------ // listbox page // ------------------------------------------------------------------------ wxPanel *panel = new wxPanel(m_book); m_listbox = new wxListBox( panel, ID_LISTBOX, wxPoint(10,10), wxSize(120,70), 5, choices, wxLB_MULTIPLE | wxLB_ALWAYS_SB | wxHSCROLL ); m_listboxSorted = new wxListBox( panel, ID_LISTBOX_SORTED, wxPoint(10,90), wxSize(120,70), 3, choices, wxLB_SORT ); SetListboxClientData(wxT("listbox"), m_listbox); SetListboxClientData(wxT("listbox"), m_listboxSorted); m_listbox->SetCursor(*wxCROSS_CURSOR); m_lbSelectNum = new wxButton( panel, ID_LISTBOX_SEL_NUM, wxT("Select #&2"), wxPoint(180,30), wxSize(140,30) ); m_lbSelectThis = new wxButton( panel, ID_LISTBOX_SEL_STR, wxT("&Select 'This'"), wxPoint(340,30), wxSize(140,30) ); (void)new wxButton( panel, ID_LISTBOX_CLEAR, wxT("&Clear"), wxPoint(180,80), wxSize(140,30) ); (void)new MyButton( panel, ID_LISTBOX_APPEND, wxT("&Append 'Hi!'"), wxPoint(340,80), wxSize(140,30) ); (void)new wxButton( panel, ID_LISTBOX_DELETE, wxT("D&elete selected item"), wxPoint(180,130), wxSize(140,30) ); wxButton *button = new MyButton( panel, ID_LISTBOX_FONT, wxT("Set &Italic font"), wxPoint(340,130), wxSize(140,30) ); button->SetDefault(); m_checkbox = new wxCheckBox( panel, ID_LISTBOX_ENABLE, wxT("&Disable"), wxPoint(20,170) ); m_checkbox->SetValue(false); button->MoveAfterInTabOrder(m_checkbox); (void)new wxCheckBox( panel, ID_CHANGE_COLOUR, wxT("&Toggle colour"), wxPoint(110,170) ); panel->SetCursor(wxCursor(wxCURSOR_HAND)); m_book->AddPage(panel, wxT("wxListBox"), true, Image_List); // ------------------------------------------------------------------------ // choice page // ------------------------------------------------------------------------ #if wxUSE_CHOICE panel = new wxPanel(m_book); m_choice = new MyChoice( panel, ID_CHOICE, wxPoint(10,10), wxSize(120,wxDefaultCoord), 5, choices ); m_choiceSorted = new MyChoice( panel, ID_CHOICE_SORTED, wxPoint(10,70), wxSize(120,wxDefaultCoord), 5, choices, wxCB_SORT ); SetChoiceClientData(wxT("choice"), m_choice); SetChoiceClientData(wxT("choice"), m_choiceSorted); m_choice->SetSelection(2); (void)new wxButton( panel, ID_CHOICE_SEL_NUM, wxT("Select #&2"), wxPoint(180,30), wxSize(140,30) ); (void)new wxButton( panel, ID_CHOICE_SEL_STR, wxT("&Select 'This'"), wxPoint(340,30), wxSize(140,30) ); (void)new wxButton( panel, ID_CHOICE_CLEAR, wxT("&Clear"), wxPoint(180,80), wxSize(140,30) ); (void)new wxButton( panel, ID_CHOICE_APPEND, wxT("&Append 'Hi!'"), wxPoint(340,80), wxSize(140,30) ); (void)new wxButton( panel, ID_CHOICE_DELETE, wxT("D&elete selected item"), wxPoint(180,130), wxSize(140,30) ); (void)new wxButton( panel, ID_CHOICE_FONT, wxT("Set &Italic font"), wxPoint(340,130), wxSize(140,30) ); (void)new wxCheckBox( panel, ID_CHOICE_ENABLE, wxT("&Disable"), wxPoint(20,130), wxSize(140,30) ); m_book->AddPage(panel, wxT("wxChoice"), false, Image_Choice); #endif // wxUSE_CHOICE // ------------------------------------------------------------------------ // combo page // ------------------------------------------------------------------------ panel = new wxPanel(m_book); (void)new wxStaticBox( panel, wxID_ANY, wxT("&Box around combobox"), wxPoint(5, 5), wxSize(150, 100)); m_combo = new MyComboBox( panel, ID_COMBO, wxT("This"), wxPoint(20,25), wxSize(120, wxDefaultCoord), 5, choices, wxTE_PROCESS_ENTER); (void)new wxButton( panel, ID_COMBO_SEL_NUM, wxT("Select #&2"), wxPoint(180,30), wxSize(140,30) ); (void)new wxButton( panel, ID_COMBO_SEL_STR, wxT("&Select 'This'"), wxPoint(340,30), wxSize(140,30) ); (void)new wxButton( panel, ID_COMBO_CLEAR, wxT("&Clear"), wxPoint(180,80), wxSize(140,30) ); (void)new wxButton( panel, ID_COMBO_APPEND, wxT("&Append 'Hi!'"), wxPoint(340,80), wxSize(140,30) ); (void)new wxButton( panel, ID_COMBO_DELETE, wxT("D&elete selected item"), wxPoint(180,130), wxSize(140,30) ); (void)new wxButton( panel, ID_COMBO_FONT, wxT("Set &Italic font"), wxPoint(340,130), wxSize(140,30) ); (void)new wxButton( panel, ID_COMBO_SET_TEXT, wxT("Set 'Hi!' at #2"), wxPoint(340,180), wxSize(140,30) ); (void)new wxCheckBox( panel, ID_COMBO_ENABLE, wxT("&Disable"), wxPoint(20,130), wxSize(140,30) ); m_book->AddPage(panel, wxT("wxComboBox"), false, Image_Combo); // ------------------------------------------------------------------------ // radio box // ------------------------------------------------------------------------ wxString choices2[] = { wxT("First"), wxT("Second"), /* "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Nineth", "Tenth" */ }; panel = new wxPanel(m_book); wxGridBagSizer* radio_page_sizer = new wxGridBagSizer(5, 5); m_radio = new wxRadioBox(panel, ID_RADIOBOX, wxT("T&his"), wxPoint(10,10), wxDefaultSize, WXSIZEOF(choices), choices, 1, wxRA_SPECIFY_COLS ); MyRadioBox* mybox = new MyRadioBox(panel, ID_RADIOBOX2, wxT("&That"), wxPoint(10,160), wxDefaultSize, WXSIZEOF(choices2), choices2, 1, wxRA_SPECIFY_ROWS ); radio_page_sizer->Add( m_radio, wxGBPosition(0,0), wxGBSpan(2,1) ); radio_page_sizer->Add( mybox, wxGBPosition(2,0), wxGBSpan(2,1) ); #if wxUSE_HELP for (unsigned int item = 0; item < WXSIZEOF(choices); ++item) m_radio->SetItemHelpText( item, wxString::Format( wxT("Help text for \"%s\""), choices[item].c_str() ) ); // erase help text for the second item m_radio->SetItemHelpText( 1, wxT("") ); // set default help text for control m_radio->SetHelpText( wxT("Default helptext for wxRadioBox") ); #endif // wxUSE_HELP wxButton* select_two = new wxButton ( panel, ID_RADIOBOX_SEL_NUM, wxT("Select #&2") ); wxButton* select_this = new wxButton ( panel, ID_RADIOBOX_SEL_STR, wxT("&Select 'This'") ); m_fontButton = new wxButton ( panel, ID_SET_FONT, wxT("Set &more Italic font") ); wxButton* set_italic = new wxButton ( panel, ID_RADIOBOX_FONT, wxT("Set &Italic font") ); wxCheckBox* disable_cb = new wxCheckBox( panel, ID_RADIOBOX_ENABLE, wxT("&Disable") ); wxRadioButton *rb = new wxRadioButton( panel, ID_RADIOBUTTON_1, wxT("Radiobutton1"), wxDefaultPosition, wxDefaultSize, wxRB_GROUP ); wxRadioButton *rb2 = new wxRadioButton( panel, ID_RADIOBUTTON_2, wxT("&Radiobutton2"), wxDefaultPosition, wxDefaultSize ); rb->SetValue( false ); radio_page_sizer->Add( select_two, wxGBPosition(0, 1), wxDefaultSpan, wxALL , 10 ); radio_page_sizer->Add( select_this, wxGBPosition(1, 1), wxDefaultSpan, wxALL , 10 ); radio_page_sizer->Add( m_fontButton, wxGBPosition(0, 2), wxDefaultSpan, wxALL , 10 ); radio_page_sizer->Add( set_italic, wxGBPosition(1, 2), wxDefaultSpan, wxALL , 10 ); radio_page_sizer->Add( disable_cb, wxGBPosition(2, 2), wxDefaultSpan, wxLEFT | wxRIGHT, 10 ); radio_page_sizer->Add( rb, wxGBPosition(3, 1), wxDefaultSpan, wxLEFT | wxRIGHT, 10 ); radio_page_sizer->Add( rb2, wxGBPosition(3, 2), wxDefaultSpan, wxLEFT | wxRIGHT, 10 ); panel->SetSizer( radio_page_sizer ); m_book->AddPage(panel, wxT("wxRadioBox"), false, Image_Radio); // ------------------------------------------------------------------------ // gauge and slider // ------------------------------------------------------------------------ #if wxUSE_SLIDER && wxUSE_GAUGE panel = new wxPanel(m_book); wxBoxSizer *gauge_page_vsizer = new wxBoxSizer( wxVERTICAL ); wxBoxSizer *gauge_page_first_row_sizer = new wxBoxSizer( wxHORIZONTAL ); wxStaticBoxSizer *gauge_sizer = new wxStaticBoxSizer( wxHORIZONTAL, panel, wxT("&wxGauge and wxSlider") ); gauge_page_first_row_sizer->Add( gauge_sizer, 0, wxALL, 5 ); wxBoxSizer *sz = new wxBoxSizer( wxVERTICAL ); gauge_sizer->Add( sz ); m_gauge = new wxGauge( panel, wxID_ANY, 200, wxDefaultPosition, wxSize(155, 30), wxGA_HORIZONTAL|wxNO_BORDER ); sz->Add( m_gauge, 0, wxALL, 10 ); m_slider = new wxSlider( panel, ID_SLIDER, 0, 0, 200, wxDefaultPosition, wxSize(155,wxDefaultCoord), wxSL_AUTOTICKS | wxSL_LABELS); m_slider->SetTickFreq(40); sz->Add( m_slider, 0, wxALL, 10 ); m_gaugeVert = new wxGauge( panel, wxID_ANY, 100, wxDefaultPosition, wxSize(wxDefaultCoord, 90), wxGA_VERTICAL | wxGA_SMOOTH | wxNO_BORDER ); gauge_sizer->Add( m_gaugeVert, 0, wxALL, 10 ); wxStaticBox *sb = new wxStaticBox( panel, wxID_ANY, wxT("&Explanation"), wxDefaultPosition, wxDefaultSize ); //, wxALIGN_CENTER ); wxStaticBoxSizer *wrapping_sizer = new wxStaticBoxSizer( sb, wxVERTICAL ); gauge_page_first_row_sizer->Add( wrapping_sizer, 0, wxALL, 5 ); #ifdef __WXMOTIF__ // No wrapping text in wxStaticText yet :-( m_wrappingText = new wxStaticText( panel, wxID_ANY, wxT("Drag the slider!"), wxPoint(250,30), wxSize(240, wxDefaultCoord) ); #else m_wrappingText = new wxStaticText( panel, wxID_ANY, wxT("In order see the gauge (aka progress bar) ") wxT("control do something you have to drag the ") wxT("handle of the slider to the right.") wxT("\n\n") wxT("This is also supposed to demonstrate how ") wxT("to use static controls with line wrapping."), wxDefaultPosition, wxSize(240, wxDefaultCoord) ); #endif wrapping_sizer->Add( m_wrappingText ); wxStaticBoxSizer *non_wrapping_sizer = new wxStaticBoxSizer( wxVERTICAL, panel, wxT("Non-wrapping") ); gauge_page_first_row_sizer->Add( non_wrapping_sizer, 0, wxALL, 5 ); m_nonWrappingText = new wxStaticText( panel, wxID_ANY, wxT("This static text has two lines.\nThey do not wrap."), wxDefaultPosition, wxDefaultSize ); non_wrapping_sizer->Add( m_nonWrappingText ); gauge_page_vsizer->Add( gauge_page_first_row_sizer, 1 ); wxBoxSizer *gauge_page_second_row_sizer = new wxBoxSizer( wxHORIZONTAL ); int initialSpinValue = -5; wxString s; s << initialSpinValue; m_spintext = new wxTextCtrl( panel, wxID_ANY, s ); gauge_page_second_row_sizer->Add( m_spintext, 0, wxALL, 5 ); #if wxUSE_SPINBTN m_spinbutton = new wxSpinButton( panel, ID_SPIN ); m_spinbutton->SetRange(-40,30); m_spinbutton->SetValue(initialSpinValue); gauge_page_second_row_sizer->Add( m_spinbutton, 0, wxALL, 5 ); #endif // wxUSE_SPINBTN #if wxUSE_SPINCTRL m_spinctrl = new wxSpinCtrl( panel, ID_SPINCTRL, wxEmptyString ); m_spinctrl->SetRange(-10,30); m_spinctrl->SetValue(15); gauge_page_second_row_sizer->Add( m_spinctrl, 0, wxALL, 5 ); #endif // wxUSE_SPINCTRL #if wxUSE_SPINBTN #if wxUSE_PROGRESSDLG m_btnProgress = new wxButton( panel, ID_BTNPROGRESS, wxT("&Show progress dialog") ); gauge_page_second_row_sizer->Add( m_btnProgress, 0, wxALL, 5 ); #endif // wxUSE_PROGRESSDLG #endif // wxUSE_SPINBTN wxButton* newTextButton = new wxButton( panel, ID_BTNNEWTEXT, wxT("New text")); gauge_page_second_row_sizer->Add( newTextButton, 0, wxALL, 5 ); gauge_page_vsizer->Add(gauge_page_second_row_sizer, 1); panel->SetSizer( gauge_page_vsizer ); m_book->AddPage(panel, wxT("wxGauge"), false, Image_Gauge); #endif // wxUSE_SLIDER && wxUSE_GAUGE // ------------------------------------------------------------------------ // wxBitmapXXX // ------------------------------------------------------------------------ panel = new wxPanel(m_book); #if !defined(__WXMOTIF__) // wxStaticBitmap not working under Motif yet. wxIcon icon = wxArtProvider::GetIcon(wxART_INFORMATION); (void) new wxStaticBitmap( panel, wxID_ANY, icon, wxPoint(10, 10) ); // VZ: don't leak memory // bmpStatic = new wxStaticBitmap(panel, wxID_ANY, wxNullIcon, wxPoint(50, 10)); // bmpStatic->SetIcon(wxArtProvider::GetIcon(wxART_QUESTION)); #endif // !Motif wxBitmap bitmap( 100, 100 ); wxMemoryDC dc; dc.SelectObject( bitmap ); dc.SetBackground(*wxGREEN); dc.SetPen(*wxRED_PEN); dc.Clear(); dc.DrawEllipse(5, 5, 90, 90); dc.DrawText(wxT("Bitmap"), 30, 40); dc.SelectObject( wxNullBitmap ); wxPanel *panel2 = new wxPanel(panel, -1, wxPoint(100, 0), wxSize(100, 200)); (void)new wxBitmapButton(panel2, ID_BITMAP_BTN, bitmap, wxPoint(0, 20)); (void)new wxToggleButton(panel2, ID_BITMAP_BTN_ENABLE, wxT("Enable/disable &bitmap"), wxPoint(0, 140)); #if defined(__WXMSW__) || defined(__WXMOTIF__) // test for masked bitmap display bitmap = wxBitmap(wxT("test2.bmp"), wxBITMAP_TYPE_BMP); if (bitmap.IsOk()) { bitmap.SetMask(new wxMask(bitmap, *wxBLUE)); (void)new wxStaticBitmap(panel, wxID_ANY, bitmap, wxPoint(300, 120)); } #endif wxBitmap bmp1(wxArtProvider::GetBitmap(wxART_INFORMATION)), bmp2(wxArtProvider::GetBitmap(wxART_WARNING)), bmp3(wxArtProvider::GetBitmap(wxART_QUESTION)); wxBitmapButton *bmpBtn = new wxBitmapButton ( panel, wxID_ANY, bmp1, wxPoint(30, 70) ); bmpBtn->SetBitmapSelected(bmp2); bmpBtn->SetBitmapFocus(bmp3); (void)new wxToggleButton(panel, ID_BUTTON_LABEL, wxT("&Toggle label"), wxPoint(250, 20)); m_label = new wxStaticText(panel, wxID_ANY, wxT("Label with some long text"), wxPoint(250, 60), wxDefaultSize, wxALIGN_RIGHT /*| wxST_NO_AUTORESIZE*/); m_label->SetForegroundColour( *wxBLUE ); m_book->AddPage(panel, wxT("wxBitmapXXX")); // ------------------------------------------------------------------------ // sizer page // ------------------------------------------------------------------------ panel = new wxPanel(m_book); wxBoxSizer *sizer = new wxBoxSizer( wxVERTICAL ); wxStaticBoxSizer *csizer = new wxStaticBoxSizer (new wxStaticBox (panel, wxID_ANY, wxT("Show Buttons")), wxHORIZONTAL ); wxCheckBox *check1, *check2, *check3, *check4, *check14, *checkBig; check1 = new wxCheckBox (panel, ID_SIZER_CHECK1, wxT("1")); check1->SetValue (true); csizer->Add (check1); check2 = new wxCheckBox (panel, ID_SIZER_CHECK2, wxT("2")); check2->SetValue (true); csizer->Add (check2); check3 = new wxCheckBox (panel, ID_SIZER_CHECK3, wxT("3")); check3->SetValue (true); csizer->Add (check3); check4 = new wxCheckBox (panel, ID_SIZER_CHECK4, wxT("4")); check4->SetValue (true); csizer->Add (check4); check14 = new wxCheckBox (panel, ID_SIZER_CHECK14, wxT("1-4")); check14->SetValue (true); csizer->Add (check14); checkBig = new wxCheckBox (panel, ID_SIZER_CHECKBIG, wxT("Big")); checkBig->SetValue (true); csizer->Add (checkBig); sizer->Add (csizer); m_hsizer = new wxBoxSizer( wxHORIZONTAL ); m_buttonSizer = new wxBoxSizer (wxVERTICAL); m_sizerBtn1 = new wxButton(panel, wxID_ANY, wxT("Test Button &1 (tab order 1)") ); m_buttonSizer->Add( m_sizerBtn1, 0, wxALL, 10 ); m_sizerBtn2 = new wxButton(panel, wxID_ANY, wxT("Test Button &2 (tab order 3)") ); m_buttonSizer->Add( m_sizerBtn2, 0, wxALL, 10 ); m_sizerBtn3 = new wxButton(panel, wxID_ANY, wxT("Test Button &3 (tab order 2)") ); m_buttonSizer->Add( m_sizerBtn3, 0, wxALL, 10 ); m_sizerBtn4 = new wxButton(panel, wxID_ANY, wxT("Test Button &4 (tab order 4)") ); m_buttonSizer->Add( m_sizerBtn4, 0, wxALL, 10 ); m_sizerBtn3->MoveBeforeInTabOrder(m_sizerBtn2); m_hsizer->Add (m_buttonSizer); m_hsizer->Add( 20,20, 1 ); m_bigBtn = new wxButton(panel, wxID_ANY, wxT("Multiline\nbutton") ); m_hsizer->Add( m_bigBtn , 3, wxGROW|wxALL, 10 ); sizer->Add (m_hsizer, 1, wxGROW); panel->SetSizer( sizer ); m_book->AddPage(panel, wxT("wxSizer")); // set the sizer for the panel itself sizer = new wxBoxSizer(wxVERTICAL); sizer->Add(m_book, wxSizerFlags().Border().Expand()); sizer->Add(m_text, wxSizerFlags(1).Border().Expand()); SetSizer(sizer); #if wxUSE_TOOLTIPS SetAllToolTips(); #endif // wxUSE_TOOLTIPS } #if wxUSE_TOOLTIPS namespace { void ResetToolTip(wxWindow *win, const char *tip) { wxCHECK_RET( win, "NULL window?" ); win->UnsetToolTip(); win->SetToolTip(tip); } } void MyPanel::SetAllToolTips() { ResetToolTip(FindWindow(ID_LISTBOX_FONT), "Press here to set italic font"); ResetToolTip(m_checkbox, "Click here to disable the listbox"); ResetToolTip(m_listbox, "This is a list box"); ResetToolTip(m_combo, "This is a natural\ncombobox - can you believe me?"); ResetToolTip(m_slider, "This is a sliding slider"); ResetToolTip(FindWindow(ID_RADIOBOX2), "Ever seen a radiobox?"); //ResetToolTip(m_radio, "Tooltip for the entire radiobox"); for ( unsigned int nb = 0; nb < m_radio->GetCount(); nb++ ) { m_radio->SetItemToolTip(nb, ""); m_radio->SetItemToolTip(nb, "tooltip for\n" + m_radio->GetString(nb)); } // remove the tooltip for one of the items m_radio->SetItemToolTip(2, ""); } #endif // wxUSE_TOOLTIPS void MyPanel::OnIdle(wxIdleEvent& event) { static const int INVALID_SELECTION = -2; static int s_selCombo = INVALID_SELECTION; if (!m_combo || !m_choice) { event.Skip(); return; } int sel = m_combo->GetSelection(); if ( sel != s_selCombo ) { if ( s_selCombo != INVALID_SELECTION ) { wxLogMessage(wxT("EVT_IDLE: combobox selection changed from %d to %d"), s_selCombo, sel); } s_selCombo = sel; } static int s_selChoice = INVALID_SELECTION; sel = m_choice->GetSelection(); if ( sel != s_selChoice ) { if ( s_selChoice != INVALID_SELECTION ) { wxLogMessage(wxT("EVT_IDLE: choice selection changed from %d to %d"), s_selChoice, sel); } s_selChoice = sel; } event.Skip(); } void MyPanel::OnPageChanging( wxBookCtrlEvent &event ) { int selOld = event.GetOldSelection(); if ( selOld == 2 ) { if ( wxMessageBox(wxT("This demonstrates how a program may prevent the\n") wxT("page change from taking place - if you select\n") wxT("[No] the current page will stay the third one\n"), wxT("Control sample"), wxICON_QUESTION | wxYES_NO, this) != wxYES ) { event.Veto(); return; } } *m_text << wxT("Book selection is being changed from ") << selOld << wxT(" to ") << event.GetSelection() << wxT(" (current page from book is ") << m_book->GetSelection() << wxT(")\n"); } void MyPanel::OnPageChanged( wxBookCtrlEvent &event ) { *m_text << wxT("Book selection is now ") << event.GetSelection() << wxT(" (from book: ") << m_book->GetSelection() << wxT(")\n"); } void MyPanel::OnTestButton(wxCommandEvent& event) { wxLogMessage(wxT("Button %c clicked."), event.GetId() == ID_BUTTON_TEST1 ? wxT('1') : wxT('2')); } void MyPanel::OnBmpButton(wxCommandEvent& WXUNUSED(event)) { wxLogMessage(wxT("Bitmap button clicked.")); } void MyPanel::OnBmpButtonToggle(wxCommandEvent& event) { FindWindow(ID_BITMAP_BTN)->Enable(!event.IsChecked()); } void MyPanel::OnChangeColour(wxCommandEvent& WXUNUSED(event)) { static wxColour s_colOld; SetThemeEnabled(false); // test panel colour changing and propagation to the subcontrols if ( s_colOld.IsOk() ) { SetBackgroundColour(s_colOld); s_colOld = wxNullColour; m_lbSelectThis->SetForegroundColour(wxNullColour); m_lbSelectThis->SetBackgroundColour(wxNullColour); } else { s_colOld = wxColour(wxT("red")); SetBackgroundColour(wxT("white")); m_lbSelectThis->SetForegroundColour(wxT("white")); m_lbSelectThis->SetBackgroundColour(wxT("red")); } m_lbSelectThis->Refresh(); Refresh(); } void MyPanel::OnListBox( wxCommandEvent &event ) { wxListBox *listbox = event.GetId() == ID_LISTBOX ? m_listbox : m_listboxSorted; bool deselect = false; if (listbox->HasFlag(wxLB_MULTIPLE) || listbox->HasFlag(wxLB_EXTENDED)) { deselect = !event.IsSelection(); if (deselect) m_text->AppendText( wxT("ListBox deselection event\n") ); } m_text->AppendText( wxT("ListBox event selection string is: '") ); m_text->AppendText( event.GetString() ); m_text->AppendText( wxT("'\n") ); // can't use GetStringSelection() with multiple selections, there could be // more than one of them if ( !listbox->HasFlag(wxLB_MULTIPLE) && !listbox->HasFlag(wxLB_EXTENDED) ) { m_text->AppendText( wxT("ListBox control selection string is: '") ); m_text->AppendText( listbox->GetStringSelection() ); m_text->AppendText( wxT("'\n") ); } wxStringClientData *obj = ((wxStringClientData *)event.GetClientObject()); m_text->AppendText( wxT("ListBox event client data string is: '") ); if (obj) // BC++ doesn't like use of '? .. : .. ' in this context m_text->AppendText( obj->GetData() ); else m_text->AppendText( wxString(wxT("none")) ); m_text->AppendText( wxT("'\n") ); m_text->AppendText( wxT("ListBox control client data string is: '") ); obj = (wxStringClientData *)listbox->GetClientObject(event.GetInt()); if (obj) m_text->AppendText( obj->GetData() ); else m_text->AppendText( wxString(wxT("none")) ); m_text->AppendText( wxT("'\n") ); } void MyPanel::OnListBoxDoubleClick( wxCommandEvent &event ) { m_text->AppendText( wxT("ListBox double click string is: ") ); m_text->AppendText( event.GetString() ); m_text->AppendText( wxT("\n") ); } void MyPanel::OnListBoxButtons( wxCommandEvent &event ) { switch (event.GetId()) { case ID_LISTBOX_ENABLE: { m_text->AppendText(wxT("Checkbox clicked.\n")); #if wxUSE_TOOLTIPS wxCheckBox *cb = (wxCheckBox*)event.GetEventObject(); if (event.GetInt()) cb->SetToolTip( wxT("Click to enable listbox") ); else cb->SetToolTip( wxT("Click to disable listbox") ); #endif // wxUSE_TOOLTIPS m_listbox->Enable( event.GetInt() == 0 ); m_lbSelectThis->Enable( event.GetInt() == 0 ); m_lbSelectNum->Enable( event.GetInt() == 0 ); m_listboxSorted->Enable( event.GetInt() == 0 ); FindWindow(ID_CHANGE_COLOUR)->Enable( event.GetInt() == 0 ); break; } case ID_LISTBOX_SEL_NUM: { if (m_listbox->GetCount() > 2) m_listbox->SetSelection( 2 ); if (m_listboxSorted->GetCount() > 2) m_listboxSorted->SetSelection( 2 ); m_lbSelectThis->WarpPointer( 40, 14 ); break; } case ID_LISTBOX_SEL_STR: { if (m_listbox->FindString(wxT("This")) != wxNOT_FOUND) m_listbox->SetStringSelection( wxT("This") ); if (m_listboxSorted->FindString(wxT("This")) != wxNOT_FOUND) m_listboxSorted->SetStringSelection( wxT("This") ); m_lbSelectNum->WarpPointer( 40, 14 ); break; } case ID_LISTBOX_CLEAR: { m_listbox->Clear(); m_listboxSorted->Clear(); break; } case ID_LISTBOX_APPEND: { m_listbox->Append( wxT("Hi kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk!") ); m_listboxSorted->Append( wxT("Hi hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh!") ); break; } case ID_LISTBOX_DELETE: { int idx; idx = m_listbox->GetSelection(); if ( idx != wxNOT_FOUND ) m_listbox->Delete( idx ); idx = m_listboxSorted->GetSelection(); if ( idx != wxNOT_FOUND ) m_listboxSorted->Delete( idx ); break; } case ID_LISTBOX_FONT: { m_listbox->SetFont( *wxITALIC_FONT ); m_listboxSorted->SetFont( *wxITALIC_FONT ); m_checkbox->SetFont( *wxITALIC_FONT ); break; } } } #if wxUSE_CHOICE static wxString GetDataString(wxClientData *data) { return data ? static_cast<wxStringClientData *>(data)->GetData() : wxString("none"); } void MyPanel::OnChoice( wxCommandEvent &event ) { wxChoice *choice = event.GetId() == ID_CHOICE ? m_choice : m_choiceSorted; const int sel = choice->GetSelection(); wxClientData *dataEvt = event.GetClientObject(), *dataCtrl = choice->GetClientObject(sel); wxLogMessage(wxT("EVT_CHOICE: item %d/%d (event/control), ") wxT("string \"%s\"/\"%s\", ") wxT("data \"%s\"/\"%s\""), (int)event.GetInt(), sel, event.GetString(), choice->GetStringSelection(), GetDataString(dataEvt), GetDataString(dataCtrl)); } void MyPanel::OnChoiceButtons( wxCommandEvent &event ) { switch (event.GetId()) { case ID_CHOICE_ENABLE: { m_choice->Enable( event.GetInt() == 0 ); m_choiceSorted->Enable( event.GetInt() == 0 ); break; } case ID_CHOICE_SEL_NUM: { m_choice->SetSelection( 2 ); m_choiceSorted->SetSelection( 2 ); break; } case ID_CHOICE_SEL_STR: { m_choice->SetStringSelection( wxT("This") ); m_choiceSorted->SetStringSelection( wxT("This") ); break; } case ID_CHOICE_CLEAR: { m_choice->Clear(); m_choiceSorted->Clear(); break; } case ID_CHOICE_APPEND: { m_choice->Append( wxT("Hi!") ); m_choiceSorted->Append( wxT("Hi!") ); break; } case ID_CHOICE_DELETE: { int idx = m_choice->GetSelection(); if ( idx != wxNOT_FOUND ) m_choice->Delete( idx ); idx = m_choiceSorted->GetSelection(); if ( idx != wxNOT_FOUND ) m_choiceSorted->Delete( idx ); break; } case ID_CHOICE_FONT: { m_choice->SetFont( *wxITALIC_FONT ); m_choiceSorted->SetFont( *wxITALIC_FONT ); break; } } } #endif // wxUSE_CHOICE void MyPanel::OnCombo( wxCommandEvent &event ) { if (!m_combo) return; wxLogMessage(wxT("EVT_COMBOBOX: item %d/%d (event/control), string \"%s\"/\"%s\""), (int)event.GetInt(), m_combo->GetSelection(), event.GetString().c_str(), m_combo->GetStringSelection().c_str()); } void MyPanel::OnComboTextChanged(wxCommandEvent& event) { if (m_combo) { wxLogMessage(wxT("EVT_TEXT for the combobox: \"%s\" (event) or \"%s\" (control)."), event.GetString().c_str(), m_combo->GetValue().c_str()); } } void MyPanel::OnComboTextEnter(wxCommandEvent& WXUNUSED(event)) { if (m_combo) { wxLogMessage(wxT("Enter pressed in the combobox: value is '%s'."), m_combo->GetValue().c_str()); } } void MyPanel::OnComboButtons( wxCommandEvent &event ) { switch (event.GetId()) { case ID_COMBO_ENABLE: { m_combo->Enable( event.GetInt() == 0 ); break; } case ID_COMBO_SEL_NUM: { m_combo->SetSelection( 2 ); break; } case ID_COMBO_SEL_STR: { m_combo->SetStringSelection( wxT("This") ); break; } case ID_COMBO_CLEAR: { m_combo->Clear(); break; } case ID_COMBO_APPEND: { m_combo->Append( wxT("Hi!") ); break; } case ID_COMBO_DELETE: { int idx = m_combo->GetSelection(); m_combo->Delete( idx ); break; } case ID_COMBO_FONT: { m_combo->SetFont( *wxITALIC_FONT ); break; } case ID_COMBO_SET_TEXT: { m_combo->SetString( 2, wxT("Hi!") ); break; } } } void MyPanel::OnRadio( wxCommandEvent &event ) { m_text->AppendText( wxT("RadioBox selection string is: ") ); m_text->AppendText( event.GetString() ); m_text->AppendText( wxT("\n") ); } void MyPanel::OnRadioButton1( wxCommandEvent & WXUNUSED(event) ) { wxMessageBox(wxT("First wxRadioButton selected."), wxT("wxControl sample")); } void MyPanel::OnRadioButton2( wxCommandEvent & WXUNUSED(event) ) { m_text->AppendText(wxT("Second wxRadioButton selected.\n")); } void MyPanel::OnRadioButtons( wxCommandEvent &event ) { switch (event.GetId()) { case ID_RADIOBOX_ENABLE: m_radio->Enable( event.GetInt() == 0 ); break; case ID_RADIOBOX_SEL_NUM: m_radio->SetSelection( 2 ); break; case ID_RADIOBOX_SEL_STR: m_radio->SetStringSelection( wxT("This") ); break; case ID_RADIOBOX_FONT: m_radio->SetFont( *wxITALIC_FONT ); break; } } void MyPanel::OnSetFont( wxCommandEvent &WXUNUSED(event) ) { m_fontButton->SetFont( *wxITALIC_FONT ); m_text->SetFont( *wxITALIC_FONT ); } void MyPanel::OnUpdateLabel( wxCommandEvent &event ) { m_label->SetLabel(event.GetInt() ? wxT("Very very very very very long text.") : wxT("Shorter text.")); } #if wxUSE_SLIDER void MyPanel::OnSliderUpdate( wxCommandEvent &WXUNUSED(event) ) { #if wxUSE_GAUGE m_gauge->SetValue( m_slider->GetValue() ); m_gaugeVert->SetValue( m_slider->GetValue() / 2 ); #endif // wxUSE_GAUGE } #endif // wxUSE_SLIDER #if wxUSE_SPINCTRL void MyPanel::OnSpinCtrlText(wxCommandEvent& event) { if ( m_spinctrl ) { wxString s; s.Printf( wxT("Spin ctrl text changed: now %d (from event: %s)\n"), m_spinctrl->GetValue(), event.GetString().c_str() ); m_text->AppendText(s); } } void MyPanel::OnSpinCtrl(wxSpinEvent& event) { if ( m_spinctrl ) { wxString s; s.Printf( wxT("Spin ctrl changed: now %d (from event: %d)\n"), m_spinctrl->GetValue(), event.GetInt() ); m_text->AppendText(s); } } void MyPanel::OnSpinCtrlUp(wxSpinEvent& event) { if ( m_spinctrl ) { m_text->AppendText( wxString::Format( wxT("Spin up: %d (from event: %d)\n"), m_spinctrl->GetValue(), event.GetInt() ) ); } } void MyPanel::OnSpinCtrlDown(wxSpinEvent& event) { if ( m_spinctrl ) { m_text->AppendText( wxString::Format( wxT("Spin down: %d (from event: %d)\n"), m_spinctrl->GetValue(), event.GetInt() ) ); } } #endif // wxUSE_SPINCTRL #if wxUSE_SPINBTN void MyPanel::OnSpinUp( wxSpinEvent &event ) { wxString value; value.Printf( wxT("Spin control up: current = %d\n"), m_spinbutton->GetValue()); if ( event.GetPosition() > 17 ) { value += wxT("Preventing the spin button from going above 17.\n"); event.Veto(); } m_text->AppendText(value); } void MyPanel::OnSpinDown( wxSpinEvent &event ) { wxString value; value.Printf( wxT("Spin control down: current = %d\n"), m_spinbutton->GetValue()); if ( event.GetPosition() < -17 ) { value += wxT("Preventing the spin button from going below -17.\n"); event.Veto(); } m_text->AppendText(value); } void MyPanel::OnSpinUpdate( wxSpinEvent &event ) { wxString value; value.Printf( wxT("%d"), event.GetPosition() ); m_spintext->SetValue( value ); value.Printf( wxT("Spin control range: (%d, %d), current = %d\n"), m_spinbutton->GetMin(), m_spinbutton->GetMax(), m_spinbutton->GetValue()); m_text->AppendText(value); } void MyPanel::OnNewText( wxCommandEvent& /* event */) { m_nonWrappingText->SetLabel( wxT("This text is short\nbut still spans\nover three lines.") ); m_wrappingText->SetLabel( wxT("This text is short but will still be wrapped if it is too long.") ); m_wrappingText->GetParent()->Layout(); } #if wxUSE_PROGRESSDLG void MyPanel::OnUpdateShowProgress( wxUpdateUIEvent& event ) { event.Enable( m_spinbutton->GetValue() > 0 ); } void MyPanel::OnShowProgress( wxCommandEvent& WXUNUSED(event) ) { int max = m_spinbutton->GetValue(); if ( max <= 0 ) { wxLogError(wxT("You must set positive range!")); return; } wxProgressDialog dialog(wxT("Progress dialog example"), wxT("An informative message"), max, // range this, // parent wxPD_CAN_ABORT | wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME); bool cont = true; for ( int i = 0; i <= max && cont; i++ ) { wxSleep(1); if ( i == max ) { cont = dialog.Update(i, wxT("That's all, folks!")); } else if ( i == max / 2 ) { cont = dialog.Update(i, wxT("Only a half left (very long message)!")); } else { cont = dialog.Update(i); } } if ( !cont ) { *m_text << wxT("Progress dialog aborted!\n"); } else { *m_text << wxT("Countdown from ") << max << wxT(" finished.\n"); } } #endif // wxUSE_PROGRESSDLG #endif // wxUSE_SPINBTN void MyPanel::OnSizerCheck( wxCommandEvent &event) { switch (event.GetId ()) { case ID_SIZER_CHECK1: m_buttonSizer->Show (m_sizerBtn1, event.IsChecked ()); m_buttonSizer->Layout (); break; case ID_SIZER_CHECK2: m_buttonSizer->Show (m_sizerBtn2, event.IsChecked ()); m_buttonSizer->Layout (); break; case ID_SIZER_CHECK3: m_buttonSizer->Show (m_sizerBtn3, event.IsChecked ()); m_buttonSizer->Layout (); break; case ID_SIZER_CHECK4: m_buttonSizer->Show (m_sizerBtn4, event.IsChecked ()); m_buttonSizer->Layout (); break; case ID_SIZER_CHECK14: m_hsizer->Show (m_buttonSizer, event.IsChecked ()); m_hsizer->Layout (); break; case ID_SIZER_CHECKBIG: m_hsizer->Show (m_bigBtn, event.IsChecked ()); m_hsizer->Layout (); break; } } MyPanel::~MyPanel() { //wxLog::RemoveTraceMask(wxT("focus")); delete wxLog::SetActiveTarget(m_logTargetOld); delete m_book->GetImageList(); } //---------------------------------------------------------------------- // MyFrame //---------------------------------------------------------------------- BEGIN_EVENT_TABLE(MyFrame, wxFrame) EVT_MENU(CONTROLS_QUIT, MyFrame::OnQuit) EVT_MENU(CONTROLS_ABOUT, MyFrame::OnAbout) EVT_MENU(CONTROLS_CLEAR_LOG, MyFrame::OnClearLog) #if wxUSE_TOOLTIPS EVT_MENU(CONTROLS_SET_TOOLTIP_DELAY, MyFrame::OnSetTooltipDelay) EVT_MENU(CONTROLS_ENABLE_TOOLTIPS, MyFrame::OnToggleTooltips) #ifdef __WXMSW__ EVT_MENU(CONTROLS_SET_TOOLTIPS_MAX_WIDTH, MyFrame::OnSetMaxTooltipWidth) #endif // __WXMSW__ #endif // wxUSE_TOOLTIPS EVT_MENU(CONTROLS_ENABLE_ALL, MyFrame::OnEnableAll) EVT_MENU(CONTROLS_HIDE_ALL, MyFrame::OnHideAll) EVT_MENU(CONTROLS_HIDE_LIST, MyFrame::OnHideList) EVT_MENU(CONTROLS_CONTEXT_HELP, MyFrame::OnContextHelp) EVT_ICONIZE(MyFrame::OnIconized) EVT_MAXIMIZE(MyFrame::OnMaximized) EVT_SIZE(MyFrame::OnSize) EVT_MOVE(MyFrame::OnMove) EVT_IDLE(MyFrame::OnIdle) END_EVENT_TABLE() MyFrame::MyFrame(const wxChar *title, int x, int y) : wxFrame(NULL, wxID_ANY, title, wxPoint(x, y), wxSize(700, 450)) { SetHelpText( wxT("Controls sample demonstrating various widgets") ); // Give it an icon // The wxICON() macros loads an icon from a resource under Windows // and uses an #included XPM image under GTK+ and Motif SetIcon( wxICON(sample) ); wxMenu *file_menu = new wxMenu; file_menu->Append(CONTROLS_CLEAR_LOG, wxT("&Clear log\tCtrl-L")); file_menu->AppendSeparator(); file_menu->Append(CONTROLS_ABOUT, wxT("&About\tF1")); file_menu->AppendSeparator(); file_menu->Append(CONTROLS_QUIT, wxT("E&xit\tAlt-X"), wxT("Quit controls sample")); wxMenuBar *menu_bar = new wxMenuBar; menu_bar->Append(file_menu, wxT("&File")); #if wxUSE_TOOLTIPS wxMenu *tooltip_menu = new wxMenu; tooltip_menu->Append(CONTROLS_SET_TOOLTIP_DELAY, wxT("Set &delay\tCtrl-D")); tooltip_menu->AppendSeparator(); tooltip_menu->Append(CONTROLS_ENABLE_TOOLTIPS, wxT("&Toggle tooltips\tCtrl-T"), wxT("enable/disable tooltips"), true); tooltip_menu->Check(CONTROLS_ENABLE_TOOLTIPS, true); #ifdef __WXMSW__ tooltip_menu->Append(CONTROLS_SET_TOOLTIPS_MAX_WIDTH, "Set maximal &width"); #endif // __WXMSW__ menu_bar->Append(tooltip_menu, wxT("&Tooltips")); #endif // wxUSE_TOOLTIPS wxMenu *panel_menu = new wxMenu; panel_menu->Append(CONTROLS_ENABLE_ALL, wxT("&Disable all\tCtrl-E"), wxT("Enable/disable all panel controls"), true); panel_menu->Append(CONTROLS_HIDE_ALL, wxT("&Hide all\tCtrl-I"), wxT("Show/hide thoe whole panel controls"), true); panel_menu->Append(CONTROLS_HIDE_LIST, wxT("Hide &list ctrl\tCtrl-S"), wxT("Enable/disable all panel controls"), true); panel_menu->Append(CONTROLS_CONTEXT_HELP, wxT("&Context help...\tCtrl-H"), wxT("Get context help for a control")); menu_bar->Append(panel_menu, wxT("&Panel")); SetMenuBar(menu_bar); #if wxUSE_STATUSBAR CreateStatusBar(2); #endif // wxUSE_STATUSBAR m_panel = new MyPanel( this, 10, 10, 300, 100 ); } void MyFrame::OnQuit (wxCommandEvent& WXUNUSED(event) ) { Close(true); } void MyFrame::OnAbout( wxCommandEvent& WXUNUSED(event) ) { wxBusyCursor bc; wxMessageDialog dialog(this, wxT("This is a control sample"), wxT("About Controls"), wxOK ); dialog.ShowModal(); } void MyFrame::OnClearLog(wxCommandEvent& WXUNUSED(event)) { m_panel->m_text->Clear(); } #if wxUSE_TOOLTIPS void MyFrame::OnSetTooltipDelay(wxCommandEvent& WXUNUSED(event)) { static long s_delay = 5000; wxString delay; delay.Printf( wxT("%ld"), s_delay); delay = wxGetTextFromUser(wxT("Enter delay (in milliseconds)"), wxT("Set tooltip delay"), delay, this); if ( !delay ) return; // cancelled wxSscanf(delay, wxT("%ld"), &s_delay); wxToolTip::SetDelay(s_delay); wxLogStatus(this, wxT("Tooltip delay set to %ld milliseconds"), s_delay); } void MyFrame::OnToggleTooltips(wxCommandEvent& WXUNUSED(event)) { static bool s_enabled = true; s_enabled = !s_enabled; wxToolTip::Enable(s_enabled); wxLogStatus(this, wxT("Tooltips %sabled"), s_enabled ? wxT("en") : wxT("dis") ); } #ifdef __WXMSW__ void MyFrame::OnSetMaxTooltipWidth(wxCommandEvent& WXUNUSED(event)) { static int s_maxWidth = 0; wxNumberEntryDialog dlg ( this, "Change maximal tooltip width", "&Width in pixels:", GetTitle(), s_maxWidth, -1, 600 ); if ( dlg.ShowModal() == wxID_CANCEL ) return; s_maxWidth = dlg.GetValue(); wxToolTip::SetMaxWidth(s_maxWidth); // we need to set the tooltip again to test the new width m_panel->SetAllToolTips(); } #endif // __WXMSW__ #endif // wxUSE_TOOLTIPS void MyFrame::OnEnableAll(wxCommandEvent& WXUNUSED(event)) { static bool s_enable = true; s_enable = !s_enable; m_panel->Enable(s_enable); static bool s_enableCheckbox = true; if ( !s_enable ) { // this is a test for correct behaviour of either enabling or disabling // a child when its parent is disabled: the checkbox should have the // correct state when the parent is enabled back m_panel->m_checkbox->Enable(s_enableCheckbox); s_enableCheckbox = !s_enableCheckbox; } } void MyFrame::OnHideAll(wxCommandEvent& WXUNUSED(event)) { static bool s_show = true; s_show = !s_show; m_panel->Show(s_show); } void MyFrame::OnHideList(wxCommandEvent& WXUNUSED(event)) { static bool s_show = true; s_show = !s_show; m_panel->m_listbox->Show(s_show); } void MyFrame::OnContextHelp(wxCommandEvent& WXUNUSED(event)) { // starts a local event loop wxContextHelp chelp(this); } void MyFrame::OnMove( wxMoveEvent& event ) { #if wxUSE_STATUSBAR UpdateStatusBar(event.GetPosition(), GetSize()); #endif // wxUSE_STATUSBAR event.Skip(); } void MyFrame::OnIconized( wxIconizeEvent& event ) { wxLogMessage(wxT("Frame %s"), event.IsIconized() ? wxT("iconized") : wxT("restored")); event.Skip(); } void MyFrame::OnMaximized( wxMaximizeEvent& WXUNUSED(event) ) { wxLogMessage(wxT("Frame maximized")); } void MyFrame::OnSize( wxSizeEvent& event ) { #if wxUSE_STATUSBAR UpdateStatusBar(GetPosition(), event.GetSize()); #endif // wxUSE_STATUSBAR event.Skip(); } void MyFrame::OnIdle( wxIdleEvent& WXUNUSED(event) ) { // track the window which has the focus in the status bar static wxWindow *s_windowFocus = NULL; wxWindow *focus = wxWindow::FindFocus(); if ( focus != s_windowFocus ) { s_windowFocus = focus; wxString msg; if ( focus ) { msg.Printf( "Focus: %s" #ifdef __WXMSW__ ", HWND = %08x" #endif , s_windowFocus->GetName().c_str() #ifdef __WXMSW__ , (unsigned int) s_windowFocus->GetHWND() #endif ); } else { msg = wxT("No focus"); } #if wxUSE_STATUSBAR SetStatusText(msg); #endif // wxUSE_STATUSBAR } } void MyComboBox::OnChar(wxKeyEvent& event) { wxLogMessage(wxT("MyComboBox::OnChar")); if ( event.GetKeyCode() == 'w' ) { wxLogMessage(wxT("MyComboBox: 'w' will be ignored.")); } else { event.Skip(); } } void MyComboBox::OnKeyDown(wxKeyEvent& event) { wxLogMessage(wxT("MyComboBox::OnKeyDown")); if ( event.GetKeyCode() == 'w' ) { wxLogMessage(wxT("MyComboBox: 'w' will be ignored.")); } else { event.Skip(); } } void MyComboBox::OnKeyUp(wxKeyEvent& event) { wxLogMessage(wxT("MyComboBox::OnKeyUp")); event.Skip(); } static void SetListboxClientData(const wxChar *name, wxListBox *control) { size_t count = control->GetCount(); for ( size_t n = 0; n < count; n++ ) { wxString s; s.Printf(wxT("%s client data for '%s'"), name, control->GetString(n).c_str()); control->SetClientObject(n, new wxStringClientData(s)); } } #if wxUSE_CHOICE static void SetChoiceClientData(const wxChar *name, wxChoice *control) { size_t count = control->GetCount(); for ( size_t n = 0; n < count; n++ ) { wxString s; s.Printf(wxT("%s client data for '%s'"), name, control->GetString(n).c_str()); control->SetClientObject(n, new wxStringClientData(s)); } } #endif // wxUSE_CHOICE
lgpl-2.1
mono/linux-packaging-monodevelop
src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/CodeAnalysisRunner.cs
4774
// // CodeAnalysisRunner.cs // // Author: // Mike Krüger <mkrueger@xamarin.com> // // Copyright (c) 2012 Xamarin Inc. (http://xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //#define PROFILE using System; using System.Linq; using MonoDevelop.AnalysisCore; using System.Collections.Generic; using MonoDevelop.AnalysisCore.Fixes; using ICSharpCode.NRefactory.CSharp; using MonoDevelop.Core; using MonoDevelop.Ide.Gui; using MonoDevelop.Refactoring; using System.Threading; using System.Threading.Tasks; using System.Collections.Concurrent; using MonoDevelop.SourceEditor.QuickTasks; using ICSharpCode.NRefactory.TypeSystem; using MonoDevelop.CodeIssues; using Mono.TextEditor; using ICSharpCode.NRefactory.Refactoring; using MonoDevelop.CodeActions; using System.Diagnostics; using MonoDevelop.Ide.TypeSystem; namespace MonoDevelop.CodeIssues { public static class CodeAnalysisRunner { static IEnumerable<BaseCodeIssueProvider> EnumerateProvider (CodeIssueProvider p) { if (p.HasSubIssues) return p.SubIssues; return new BaseCodeIssueProvider[] { p }; } public static IEnumerable<Result> Check (Document input, ParsedDocument parsedDocument, CancellationToken cancellationToken) { if (!QuickTaskStrip.EnableFancyFeatures || input.Project == null || !input.IsCompileableInProject) return Enumerable.Empty<Result> (); #if PROFILE var runList = new List<Tuple<long, string>> (); #endif var editor = input.Editor; if (editor == null) return Enumerable.Empty<Result> (); var loc = editor.Caret.Location; var result = new BlockingCollection<Result> (); var codeIssueProvider = RefactoringService.GetInspectors (editor.Document.MimeType).ToArray (); var context = parsedDocument.CreateRefactoringContext != null ? parsedDocument.CreateRefactoringContext (input, cancellationToken) : null; Parallel.ForEach (codeIssueProvider, (parentProvider) => { try { #if PROFILE var clock = new Stopwatch(); clock.Start (); #endif foreach (var provider in EnumerateProvider (parentProvider)) { cancellationToken.ThrowIfCancellationRequested (); var severity = provider.GetSeverity (); if (severity == Severity.None || !provider.GetIsEnabled ()) continue; foreach (var r in provider.GetIssues (context, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested (); var fixes = r.Actions == null ? new List<GenericFix> () : new List<GenericFix> (r.Actions.Where (a => a != null).Select (a => { Action batchAction = null; if (a.SupportsBatchRunning) batchAction = () => a.BatchRun (input, loc); return new GenericFix ( a.Title, () => { using (var script = context.CreateScript ()) { a.Run (context, script); } }, batchAction) { DocumentRegion = new DocumentRegion (r.Region.Begin, r.Region.End), IdString = a.IdString }; })); result.Add (new InspectorResults ( provider, r.Region, r.Description, severity, r.IssueMarker, fixes.ToArray () )); } } #if PROFILE clock.Stop (); lock (runList) { runList.Add (Tuple.Create (clock.ElapsedMilliseconds, parentProvider.Title)); } #endif } catch (OperationCanceledException) { //ignore } catch (Exception e) { LoggingService.LogError ("CodeAnalysis: Got exception in inspector '" + parentProvider + "'", e); } }); #if PROFILE runList.Sort (); foreach (var item in runList) { Console.WriteLine (item.Item1 +"ms\t: " + item.Item2); } #endif return result; } } }
lgpl-2.1
martyone/sailfish-qtcreator
src/plugins/qtsupport/qtoptionspage.cpp
34775
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qtoptionspage.h" #include "qtconfigwidget.h" #include "ui_showbuildlog.h" #include "ui_qtversionmanager.h" #include "ui_qtversioninfo.h" #include "ui_debugginghelper.h" #include "qtsupportconstants.h" #include "qtversionmanager.h" #include "qtversionfactory.h" #include "qmldumptool.h" #include <coreplugin/progressmanager/progressmanager.h> #include <coreplugin/coreconstants.h> #include <coreplugin/variablechooser.h> #include <projectexplorer/toolchain.h> #include <projectexplorer/toolchainmanager.h> #include <projectexplorer/projectexplorerconstants.h> #include <utils/hostosinfo.h> #include <utils/pathchooser.h> #include <utils/qtcassert.h> #include <utils/runextensions.h> #include <utils/algorithm.h> #include <QDir> #include <QMessageBox> #include <QFileDialog> #include <QTextBrowser> #include <QDesktopServices> using namespace ProjectExplorer; using namespace Utils; namespace QtSupport { namespace Internal { enum ModelRoles { VersionIdRole = Qt::UserRole, ToolChainIdRole, BuildLogRole, BuildRunningRole}; /// // QtOptionsPage /// QtOptionsPage::QtOptionsPage() : m_widget(0) { setId(Constants::QTVERSION_SETTINGS_PAGE_ID); setDisplayName(QCoreApplication::translate("Qt4ProjectManager", Constants::QTVERSION_SETTINGS_PAGE_NAME)); setCategory(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY); setDisplayCategory(QCoreApplication::translate("ProjectExplorer", ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_TR_CATEGORY)); setCategoryIcon(QLatin1String(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY_ICON)); } QWidget *QtOptionsPage::widget() { if (!m_widget) m_widget = new QtOptionsPageWidget; return m_widget; } void QtOptionsPage::apply() { if (!m_widget) // page was never shown return; m_widget->apply(); } void QtOptionsPage::finish() { delete m_widget; } //----------------------------------------------------- QtOptionsPageWidget::QtOptionsPageWidget(QWidget *parent) : QWidget(parent) , m_specifyNameString(tr("<specify a name>")) , m_ui(new Internal::Ui::QtVersionManager()) , m_versionUi(new Internal::Ui::QtVersionInfo()) , m_debuggingHelperUi(new Internal::Ui::DebuggingHelper()) , m_infoBrowser(new QTextBrowser) , m_invalidVersionIcon(QLatin1String(Core::Constants::ICON_ERROR)) , m_warningVersionIcon(QLatin1String(Core::Constants::ICON_WARNING)) , m_configurationWidget(0) , m_autoItem(0) , m_manualItem(0) { QWidget *versionInfoWidget = new QWidget(); m_versionUi->setupUi(versionInfoWidget); m_versionUi->editPathPushButton->setText(PathChooser::browseButtonLabel()); QWidget *debuggingHelperDetailsWidget = new QWidget(); m_debuggingHelperUi->setupUi(debuggingHelperDetailsWidget); m_ui->setupUi(this); m_infoBrowser->setOpenLinks(false); m_infoBrowser->setTextInteractionFlags(Qt::TextBrowserInteraction); connect(m_infoBrowser, &QTextBrowser::anchorClicked, this, &QtOptionsPageWidget::infoAnchorClicked); m_ui->infoWidget->setWidget(m_infoBrowser); connect(m_ui->infoWidget, &DetailsWidget::expanded, this, &QtOptionsPageWidget::setInfoWidgetVisibility); m_ui->versionInfoWidget->setWidget(versionInfoWidget); m_ui->versionInfoWidget->setState(DetailsWidget::NoSummary); m_ui->debuggingHelperWidget->setWidget(debuggingHelperDetailsWidget); connect(m_ui->debuggingHelperWidget, &DetailsWidget::expanded, this, &QtOptionsPageWidget::setInfoWidgetVisibility); // setup parent items for auto-detected and manual versions m_ui->qtdirList->header()->setStretchLastSection(false); m_ui->qtdirList->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); m_ui->qtdirList->header()->setSectionResizeMode(1, QHeaderView::Stretch); m_ui->qtdirList->setTextElideMode(Qt::ElideNone); m_autoItem = new QTreeWidgetItem(m_ui->qtdirList); m_autoItem->setText(0, tr("Auto-detected")); m_autoItem->setFirstColumnSpanned(true); m_autoItem->setFlags(Qt::ItemIsEnabled); m_manualItem = new QTreeWidgetItem(m_ui->qtdirList); m_manualItem->setText(0, tr("Manual")); m_manualItem->setFirstColumnSpanned(true); m_manualItem->setFlags(Qt::ItemIsEnabled); QList<int> additions = transform(QtVersionManager::versions(), &BaseQtVersion::uniqueId); updateQtVersions(additions, QList<int>(), QList<int>()); m_ui->qtdirList->expandAll(); connect(m_versionUi->nameEdit, &QLineEdit::textEdited, this, &QtOptionsPageWidget::updateCurrentQtName); connect(m_versionUi->editPathPushButton, &QAbstractButton::clicked, this, &QtOptionsPageWidget::editPath); connect(m_ui->addButton, &QAbstractButton::clicked, this, &QtOptionsPageWidget::addQtDir); connect(m_ui->delButton, &QAbstractButton::clicked, this, &QtOptionsPageWidget::removeQtDir); connect(m_ui->qtdirList, &QTreeWidget::currentItemChanged, this, &QtOptionsPageWidget::versionChanged); connect(m_debuggingHelperUi->rebuildButton, &QAbstractButton::clicked, this, [this]() { buildDebuggingHelper(); }); connect(m_debuggingHelperUi->qmlDumpBuildButton, &QAbstractButton::clicked, this, &QtOptionsPageWidget::buildQmlDump); connect(m_debuggingHelperUi->showLogButton, &QAbstractButton::clicked, this, &QtOptionsPageWidget::slotShowDebuggingBuildLog); connect(m_debuggingHelperUi->toolChainComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated), this, &QtOptionsPageWidget::selectedToolChainChanged); connect(m_ui->cleanUpButton, &QAbstractButton::clicked, this, &QtOptionsPageWidget::cleanUpQtVersions); userChangedCurrentVersion(); updateCleanUpButton(); connect(QtVersionManager::instance(), &QtVersionManager::dumpUpdatedFor, this, &QtOptionsPageWidget::qtVersionsDumpUpdated); connect(QtVersionManager::instance(), &QtVersionManager::qtVersionsChanged, this, &QtOptionsPageWidget::updateQtVersions); connect(ProjectExplorer::ToolChainManager::instance(), &ToolChainManager::toolChainsChanged, this, &QtOptionsPageWidget::toolChainsUpdated); auto chooser = new Core::VariableChooser(this); chooser->addSupportedWidget(m_versionUi->nameEdit, "Qt:Name"); chooser->addMacroExpanderProvider( [this]() -> Utils::MacroExpander * { BaseQtVersion *version = currentVersion(); return version ? version->macroExpander() : 0; }); } int QtOptionsPageWidget::currentIndex() const { if (QTreeWidgetItem *currentItem = m_ui->qtdirList->currentItem()) return indexForTreeItem(currentItem); return -1; } BaseQtVersion *QtOptionsPageWidget::currentVersion() const { const int currentItemIndex = currentIndex(); if (currentItemIndex >= 0 && currentItemIndex < m_versions.size()) return m_versions.at(currentItemIndex); return 0; } static inline int findVersionById(const QList<BaseQtVersion *> &l, int id) { const int size = l.size(); for (int i = 0; i < size; i++) if (l.at(i)->uniqueId() == id) return i; return -1; } // Update with results of terminated helper build void QtOptionsPageWidget::debuggingHelperBuildFinished(int qtVersionId, const QString &output, DebuggingHelperBuildTask::Tools tools) { const int index = findVersionById(m_versions, qtVersionId); if (index == -1) return; // Oops, somebody managed to delete the version BaseQtVersion *version = m_versions.at(index); // Update item view QTreeWidgetItem *item = treeItemForIndex(index); QTC_ASSERT(item, return); DebuggingHelperBuildTask::Tools buildFlags = item->data(0, BuildRunningRole).value<DebuggingHelperBuildTask::Tools>(); buildFlags &= ~tools; item->setData(0, BuildRunningRole, QVariant::fromValue(buildFlags)); item->setData(0, BuildLogRole, output); bool success = true; if (tools & DebuggingHelperBuildTask::QmlDump) success &= version->hasQmlDump(); if (!success) showDebuggingBuildLog(item); updateDebuggingHelperUi(); } void QtOptionsPageWidget::cleanUpQtVersions() { QStringList toRemove; foreach (const BaseQtVersion *v, m_versions) { if (!v->isValid()) toRemove.append(v->displayName()); } if (toRemove.isEmpty()) return; if (QMessageBox::warning(0, tr("Remove Invalid Qt Versions"), tr("Do you want to remove all invalid Qt Versions?<br>" "<ul><li>%1</li></ul><br>" "will be removed.").arg(toRemove.join(QLatin1String("</li><li>"))), QMessageBox::Yes, QMessageBox::No) == QMessageBox::No) return; for (int i = m_versions.count() - 1; i >= 0; --i) { if (!m_versions.at(i)->isValid()) { QTreeWidgetItem *item = treeItemForIndex(i); delete item; delete m_versions.at(i); m_versions.removeAt(i); } } updateCleanUpButton(); } void QtOptionsPageWidget::toolChainsUpdated() { for (int i = 0; i < m_versions.count(); ++i) { QTreeWidgetItem *item = treeItemForIndex(i); if (item == m_ui->qtdirList->currentItem()) { updateDescriptionLabel(); updateDebuggingHelperUi(); } else { updateVersionItem(m_versions.at(i)); } } } void QtOptionsPageWidget::selectedToolChainChanged(int comboIndex) { const int index = currentIndex(); if (index < 0) return; QTreeWidgetItem *item = treeItemForIndex(index); QTC_ASSERT(item, return); QString toolChainId = m_debuggingHelperUi->toolChainComboBox->itemData(comboIndex).toString(); item->setData(0, ToolChainIdRole, toolChainId); } void QtOptionsPageWidget::qtVersionsDumpUpdated(const FileName &qmakeCommand) { foreach (BaseQtVersion *version, m_versions) { if (version->qmakeCommand() == qmakeCommand) version->recheckDumper(); } if (currentVersion() && currentVersion()->qmakeCommand() == qmakeCommand) { updateWidgets(); updateDescriptionLabel(); updateDebuggingHelperUi(); } } void QtOptionsPageWidget::setInfoWidgetVisibility() { m_ui->versionInfoWidget->setVisible((m_ui->infoWidget->state() == DetailsWidget::Collapsed) && (m_ui->debuggingHelperWidget->state() == DetailsWidget::Collapsed)); m_ui->infoWidget->setVisible(m_ui->debuggingHelperWidget->state() == DetailsWidget::Collapsed); m_ui->debuggingHelperWidget->setVisible(m_ui->infoWidget->state() == DetailsWidget::Collapsed); } void QtOptionsPageWidget::infoAnchorClicked(const QUrl &url) { QDesktopServices::openUrl(url); } QtOptionsPageWidget::ValidityInfo QtOptionsPageWidget::validInformation(const BaseQtVersion *version) { ValidityInfo info; info.icon = m_validVersionIcon; if (!version) return info; info.description = tr("Qt version %1 for %2").arg(version->qtVersionString(), version->description()); if (!version->isValid()) { info.icon = m_invalidVersionIcon; info.message = version->invalidReason(); return info; } // Do we have tool chain issues? QStringList missingToolChains; int abiCount = 0; foreach (const Abi &abi, version->qtAbis()) { if (ToolChainManager::findToolChains(abi).isEmpty()) missingToolChains.append(abi.toString()); ++abiCount; } bool useable = true; QStringList warnings; if (!isNameUnique(version)) warnings << tr("Display Name is not unique."); if (!missingToolChains.isEmpty()) { if (missingToolChains.count() == abiCount) { // Yes, this Qt version can't be used at all! info.message = tr("No compiler can produce code for this Qt version. Please define one or more compilers."); info.icon = m_invalidVersionIcon; useable = false; } else { // Yes, some ABIs are unsupported warnings << tr("Not all possible target environments can be supported due to missing compilers."); info.toolTip = tr("The following ABIs are currently not supported:<ul><li>%1</li></ul>") .arg(missingToolChains.join(QLatin1String("</li><li>"))); info.icon = m_warningVersionIcon; } } if (useable) { warnings += version->warningReason(); if (!warnings.isEmpty()) { info.message = warnings.join(QLatin1Char('\n')); info.icon = m_warningVersionIcon; } } return info; } QList<ToolChain*> QtOptionsPageWidget::toolChains(const BaseQtVersion *version) { QList<ToolChain*> toolChains; if (!version) return toolChains; QSet<QString> ids; foreach (const Abi &a, version->qtAbis()) { foreach (ToolChain *tc, ToolChainManager::findToolChains(a)) { if (ids.contains(tc->id())) continue; ids.insert(tc->id()); toolChains.append(tc); } } return toolChains; } QString QtOptionsPageWidget::defaultToolChainId(const BaseQtVersion *version) { QList<ToolChain*> possibleToolChains = toolChains(version); if (!possibleToolChains.isEmpty()) return possibleToolChains.first()->id(); return QString(); } bool QtOptionsPageWidget::isNameUnique(const BaseQtVersion *version) { const QString name = version->displayName().trimmed(); foreach (const BaseQtVersion *i, m_versions) { if (i == version) continue; if (i->displayName().trimmed() == name) return false; } return true; } void QtOptionsPageWidget::updateVersionItem(BaseQtVersion *version) { const ValidityInfo info = validInformation(version); QTreeWidgetItem *item = treeItemForIndex(m_versions.indexOf(version)); item->setText(0, version->displayName()); item->setText(1, version->qmakeCommand().toUserOutput()); item->setIcon(0, info.icon); } void QtOptionsPageWidget::buildDebuggingHelper(DebuggingHelperBuildTask::Tools tools) { const int index = currentIndex(); if (index < 0) return; // remove tools that cannot be build tools &= DebuggingHelperBuildTask::availableTools(currentVersion()); QTreeWidgetItem *item = treeItemForIndex(index); QTC_ASSERT(item, return); DebuggingHelperBuildTask::Tools buildFlags = item->data(0, BuildRunningRole).value<DebuggingHelperBuildTask::Tools>(); buildFlags |= tools; item->setData(0, BuildRunningRole, QVariant::fromValue(buildFlags)); BaseQtVersion *version = m_versions.at(index); if (!version) return; updateDebuggingHelperUi(); // Run a debugging helper build task in the background. QString toolChainId = m_debuggingHelperUi->toolChainComboBox->itemData( m_debuggingHelperUi->toolChainComboBox->currentIndex()).toString(); ToolChain *toolChain = ToolChainManager::findToolChain(toolChainId); if (!toolChain) return; DebuggingHelperBuildTask *buildTask = new DebuggingHelperBuildTask(version, toolChain, tools); // Don't open General Messages pane with errors buildTask->showOutputOnError(false); connect(buildTask, SIGNAL(finished(int,QString,DebuggingHelperBuildTask::Tools)), this, SLOT(debuggingHelperBuildFinished(int,QString,DebuggingHelperBuildTask::Tools)), Qt::QueuedConnection); QFuture<void> task = QtConcurrent::run(&DebuggingHelperBuildTask::run, buildTask); const QString taskName = tr("Building Helpers"); Core::ProgressManager::addTask(task, taskName, "QmakeProjectManager::BuildHelpers"); } void QtOptionsPageWidget::buildQmlDump() { buildDebuggingHelper(DebuggingHelperBuildTask::QmlDump); } // Non-modal dialog class BuildLogDialog : public QDialog { public: explicit BuildLogDialog(QWidget *parent = 0); void setText(const QString &text); private: Ui_ShowBuildLog m_ui; }; BuildLogDialog::BuildLogDialog(QWidget *parent) : QDialog(parent) { m_ui.setupUi(this); setAttribute(Qt::WA_DeleteOnClose, true); } void BuildLogDialog::setText(const QString &text) { m_ui.log->setPlainText(text); // Show and scroll to bottom m_ui.log->moveCursor(QTextCursor::End); m_ui.log->ensureCursorVisible(); } void QtOptionsPageWidget::slotShowDebuggingBuildLog() { if (const QTreeWidgetItem *currentItem = m_ui->qtdirList->currentItem()) showDebuggingBuildLog(currentItem); } void QtOptionsPageWidget::showDebuggingBuildLog(const QTreeWidgetItem *currentItem) { const int currentItemIndex = indexForTreeItem(currentItem); if (currentItemIndex < 0) return; BuildLogDialog *dialog = new BuildLogDialog(this->window()); dialog->setWindowTitle(tr("Debugging Helper Build Log for \"%1\"").arg(currentItem->text(0))); dialog->setText(currentItem->data(0, BuildLogRole).toString()); dialog->show(); } void QtOptionsPageWidget::updateQtVersions(const QList<int> &additions, const QList<int> &removals, const QList<int> &changes) { QList<QTreeWidgetItem *> toRemove; QList<int> toAdd = additions; // Generate list of all existing items: QList<QTreeWidgetItem *> itemList; for (int i = 0; i < m_autoItem->childCount(); ++i) itemList.append(m_autoItem->child(i)); for (int i = 0; i < m_manualItem->childCount(); ++i) itemList.append(m_manualItem->child(i)); // Find existing items to remove/change: foreach (QTreeWidgetItem *item, itemList) { int id = item->data(0, VersionIdRole).toInt(); if (removals.contains(id)) { toRemove.append(item); continue; } if (changes.contains(id)) { toAdd.append(id); toRemove.append(item); continue; } } // Remove changed/removed items: foreach (QTreeWidgetItem *item, toRemove) { int index = indexForTreeItem(item); delete m_versions.at(index); m_versions.removeAt(index); delete item; } // Add changed/added items: foreach (int a, toAdd) { BaseQtVersion *version = QtVersionManager::version(a)->clone(); m_versions.append(version); QTreeWidgetItem *item = new QTreeWidgetItem; item->setData(0, VersionIdRole, version->uniqueId()); item->setData(0, ToolChainIdRole, defaultToolChainId(version)); // Insert in the right place: QTreeWidgetItem *parent = version->isAutodetected()? m_autoItem : m_manualItem; for (int i = 0; i < parent->childCount(); ++i) { BaseQtVersion *currentVersion = m_versions.at(indexForTreeItem(parent->child(i))); if (currentVersion->qtVersion() > version->qtVersion()) continue; parent->insertChild(i, item); parent = 0; break; } if (parent) parent->addChild(item); } // Only set the icon after all versions are there to make sure all names are known: foreach (BaseQtVersion *i, m_versions) updateVersionItem(i); } QtOptionsPageWidget::~QtOptionsPageWidget() { delete m_ui; delete m_versionUi; delete m_debuggingHelperUi; delete m_configurationWidget; qDeleteAll(m_versions); } void QtOptionsPageWidget::addQtDir() { FileName qtVersion = FileName::fromString( QFileDialog::getOpenFileName(this, tr("Select a qmake Executable"), QString(), BuildableHelperLibrary::filterForQmakeFileDialog(), 0, QFileDialog::DontResolveSymlinks)); if (qtVersion.isNull()) return; QFileInfo fi(qtVersion.toString()); // should add all qt versions here ? if (BuildableHelperLibrary::isQtChooser(fi)) qtVersion = FileName::fromString(BuildableHelperLibrary::qtChooserToQmakePath(fi.symLinkTarget())); BaseQtVersion *version = Utils::findOrDefault(m_versions, Utils::equal(&BaseQtVersion::qmakeCommand, qtVersion)); if (version) { // Already exist QMessageBox::warning(this, tr("Qt Version Already Known"), tr("This Qt version was already registered as \"%1\".") .arg(version->displayName())); return; } QString error; version = QtVersionFactory::createQtVersionFromQMakePath(qtVersion, false, QString(), &error); if (version) { m_versions.append(version); QTreeWidgetItem *item = new QTreeWidgetItem(m_ui->qtdirList->topLevelItem(1)); item->setText(0, version->displayName()); item->setText(1, version->qmakeCommand().toUserOutput()); item->setData(0, VersionIdRole, version->uniqueId()); item->setData(0, ToolChainIdRole, defaultToolChainId(version)); item->setIcon(0, version->isValid()? m_validVersionIcon : m_invalidVersionIcon); m_ui->qtdirList->setCurrentItem(item); // should update the rest of the ui m_versionUi->nameEdit->setFocus(); m_versionUi->nameEdit->selectAll(); } else { QMessageBox::warning(this, tr("Qmake Not Executable"), tr("The qmake executable %1 could not be added: %2").arg(qtVersion.toUserOutput()).arg(error)); return; } updateCleanUpButton(); } void QtOptionsPageWidget::removeQtDir() { QTreeWidgetItem *item = m_ui->qtdirList->currentItem(); int index = indexForTreeItem(item); if (index < 0) return; delete item; BaseQtVersion *version = m_versions.at(index); m_versions.removeAt(index); delete version; updateCleanUpButton(); } void QtOptionsPageWidget::editPath() { BaseQtVersion *current = currentVersion(); QString dir = currentVersion()->qmakeCommand().toFileInfo().absolutePath(); FileName qtVersion = FileName::fromString( QFileDialog::getOpenFileName(this, tr("Select a qmake Executable"), dir, BuildableHelperLibrary::filterForQmakeFileDialog(), 0, QFileDialog::DontResolveSymlinks)); if (qtVersion.isNull()) return; BaseQtVersion *version = QtVersionFactory::createQtVersionFromQMakePath(qtVersion); if (!version) return; // Same type? then replace! if (current->type() != version->type()) { // not the same type, error out QMessageBox::critical(this, tr("Incompatible Qt Versions"), tr("The Qt version selected must match the device type."), QMessageBox::Ok); delete version; return; } // same type, replace version->setId(current->uniqueId()); if (current->unexpandedDisplayName() != current->defaultUnexpandedDisplayName(current->qmakeCommand())) version->setUnexpandedDisplayName(current->displayName()); m_versions.replace(m_versions.indexOf(current), version); delete current; // Update ui userChangedCurrentVersion(); QTreeWidgetItem *item = m_ui->qtdirList->currentItem(); item->setText(0, version->displayName()); item->setText(1, version->qmakeCommand().toUserOutput()); item->setData(0, VersionIdRole, version->uniqueId()); item->setData(0, ToolChainIdRole, defaultToolChainId(version)); item->setIcon(0, version->isValid()? m_validVersionIcon : m_invalidVersionIcon); } void QtOptionsPageWidget::updateDebuggingHelperUi() { BaseQtVersion *version = currentVersion(); const QTreeWidgetItem *currentItem = m_ui->qtdirList->currentItem(); QList<ToolChain*> toolchains = toolChains(currentVersion()); if (!version || !version->isValid() || toolchains.isEmpty()) { m_ui->debuggingHelperWidget->setVisible(false); } else { const DebuggingHelperBuildTask::Tools availableTools = DebuggingHelperBuildTask::availableTools(version); const bool canBuildQmlDumper = availableTools & DebuggingHelperBuildTask::QmlDump; const bool hasQmlDumper = version->hasQmlDump(); const bool needsQmlDumper = version->needsQmlDump(); bool isBuildingQmlDumper = false; if (currentItem) { DebuggingHelperBuildTask::Tools buildingTools = currentItem->data(0, BuildRunningRole).value<DebuggingHelperBuildTask::Tools>(); isBuildingQmlDumper = buildingTools & DebuggingHelperBuildTask::QmlDump; } // get names of tools from labels QStringList helperNames; const QChar colon = QLatin1Char(':'); if (hasQmlDumper) helperNames << m_debuggingHelperUi->qmlDumpLabel->text().remove(colon); QString status; if (helperNames.isEmpty()) { status = tr("Helpers: None available"); } else { //: %1 is list of tool names. status = tr("Helpers: %1.").arg(helperNames.join(QLatin1String(", "))); } m_ui->debuggingHelperWidget->setSummaryText(status); QString qmlDumpStatusText, qmlDumpStatusToolTip; Qt::TextInteractionFlags qmlDumpStatusTextFlags = Qt::NoTextInteraction; if (hasQmlDumper) { qmlDumpStatusText = QDir::toNativeSeparators(version->qmlDumpTool(false)); const QString debugQmlDumpPath = QDir::toNativeSeparators(version->qmlDumpTool(true)); if (qmlDumpStatusText != debugQmlDumpPath) { if (!qmlDumpStatusText.isEmpty() && !debugQmlDumpPath.isEmpty()) qmlDumpStatusText += QLatin1String("\n"); qmlDumpStatusText += debugQmlDumpPath; } qmlDumpStatusTextFlags = Qt::TextSelectableByMouse; } else { if (!needsQmlDumper) { qmlDumpStatusText = tr("<i>Not needed.</i>"); } else if (canBuildQmlDumper) { qmlDumpStatusText = tr("<i>Not yet built.</i>"); } else { qmlDumpStatusText = tr("<i>Cannot be compiled.</i>"); QmlDumpTool::canBuild(version, &qmlDumpStatusToolTip); } } m_debuggingHelperUi->qmlDumpStatus->setText(qmlDumpStatusText); m_debuggingHelperUi->qmlDumpStatus->setTextInteractionFlags(qmlDumpStatusTextFlags); m_debuggingHelperUi->qmlDumpStatus->setToolTip(qmlDumpStatusToolTip); m_debuggingHelperUi->qmlDumpBuildButton->setEnabled(canBuildQmlDumper & !isBuildingQmlDumper); QList<ToolChain*> toolchains = toolChains(currentVersion()); QString selectedToolChainId = currentItem->data(0, ToolChainIdRole).toString(); m_debuggingHelperUi->toolChainComboBox->clear(); for (int i = 0; i < toolchains.size(); ++i) { if (!toolchains.at(i)->isValid()) continue; if (i >= m_debuggingHelperUi->toolChainComboBox->count()) { m_debuggingHelperUi->toolChainComboBox->insertItem(i, toolchains.at(i)->displayName(), toolchains.at(i)->id()); } if (toolchains.at(i)->id() == selectedToolChainId) m_debuggingHelperUi->toolChainComboBox->setCurrentIndex(i); } const bool hasLog = currentItem && !currentItem->data(0, BuildLogRole).toString().isEmpty(); m_debuggingHelperUi->showLogButton->setEnabled(hasLog); const bool canBuild = canBuildQmlDumper; const bool isBuilding = isBuildingQmlDumper; m_debuggingHelperUi->rebuildButton->setEnabled(canBuild && !isBuilding); m_debuggingHelperUi->toolChainComboBox->setEnabled(canBuild && !isBuilding); setInfoWidgetVisibility(); } } // To be called if a Qt version was removed or added void QtOptionsPageWidget::updateCleanUpButton() { bool hasInvalidVersion = false; for (int i = 0; i < m_versions.count(); ++i) { if (!m_versions.at(i)->isValid()) { hasInvalidVersion = true; break; } } m_ui->cleanUpButton->setEnabled(hasInvalidVersion); } void QtOptionsPageWidget::userChangedCurrentVersion() { updateWidgets(); updateDescriptionLabel(); updateDebuggingHelperUi(); } void QtOptionsPageWidget::qtVersionChanged() { updateDescriptionLabel(); updateDebuggingHelperUi(); } void QtOptionsPageWidget::updateDescriptionLabel() { QTreeWidgetItem *item = m_ui->qtdirList->currentItem(); const BaseQtVersion *version = currentVersion(); const ValidityInfo info = validInformation(version); if (info.message.isEmpty()) { m_versionUi->errorLabel->setVisible(false); } else { m_versionUi->errorLabel->setVisible(true); m_versionUi->errorLabel->setText(info.message); m_versionUi->errorLabel->setToolTip(info.toolTip); } m_ui->infoWidget->setSummaryText(info.description); if (item) item->setIcon(0, info.icon); if (version) { m_infoBrowser->setHtml(version->toHtml(true)); setInfoWidgetVisibility(); } else { m_infoBrowser->clear(); m_ui->versionInfoWidget->setVisible(false); m_ui->infoWidget->setVisible(false); m_ui->debuggingHelperWidget->setVisible(false); } } int QtOptionsPageWidget::indexForTreeItem(const QTreeWidgetItem *item) const { if (!item || !item->parent()) return -1; const int uniqueId = item->data(0, VersionIdRole).toInt(); for (int index = 0; index < m_versions.size(); ++index) { if (m_versions.at(index)->uniqueId() == uniqueId) return index; } return -1; } QTreeWidgetItem *QtOptionsPageWidget::treeItemForIndex(int index) const { const int uniqueId = m_versions.at(index)->uniqueId(); for (int i = 0; i < m_ui->qtdirList->topLevelItemCount(); ++i) { QTreeWidgetItem *toplevelItem = m_ui->qtdirList->topLevelItem(i); for (int j = 0; j < toplevelItem->childCount(); ++j) { QTreeWidgetItem *item = toplevelItem->child(j); if (item->data(0, VersionIdRole).toInt() == uniqueId) return item; } } return 0; } void QtOptionsPageWidget::versionChanged(QTreeWidgetItem *newItem, QTreeWidgetItem *old) { Q_UNUSED(newItem); Q_UNUSED(old); userChangedCurrentVersion(); } void QtOptionsPageWidget::updateWidgets() { delete m_configurationWidget; m_configurationWidget = 0; BaseQtVersion *version = currentVersion(); if (version) { m_versionUi->nameEdit->setText(version->unexpandedDisplayName()); m_versionUi->qmakePath->setText(version->qmakeCommand().toUserOutput()); m_configurationWidget = version->createConfigurationWidget(); if (m_configurationWidget) { m_versionUi->formLayout->addRow(m_configurationWidget); m_configurationWidget->setEnabled(!version->isAutodetected()); connect(m_configurationWidget, SIGNAL(changed()), this, SLOT(qtVersionChanged())); } } else { m_versionUi->nameEdit->clear(); m_versionUi->qmakePath->clear(); } const bool enabled = version != 0; const bool isAutodetected = enabled && version->isAutodetected(); m_ui->delButton->setEnabled(enabled && !isAutodetected); m_versionUi->nameEdit->setEnabled(enabled); m_versionUi->editPathPushButton->setEnabled(enabled && !isAutodetected); } void QtOptionsPageWidget::updateCurrentQtName() { QTreeWidgetItem *currentItem = m_ui->qtdirList->currentItem(); Q_ASSERT(currentItem); int currentItemIndex = indexForTreeItem(currentItem); if (currentItemIndex < 0) return; BaseQtVersion *version = m_versions[currentItemIndex]; version->setUnexpandedDisplayName(m_versionUi->nameEdit->text()); updateDescriptionLabel(); foreach (BaseQtVersion *i, m_versions) updateVersionItem(i); } void QtOptionsPageWidget::apply() { disconnect(QtVersionManager::instance(), &QtVersionManager::qtVersionsChanged, this, &QtOptionsPageWidget::updateQtVersions); QtVersionManager::setNewQtVersions(versions()); connect(QtVersionManager::instance(), &QtVersionManager::qtVersionsChanged, this, &QtOptionsPageWidget::updateQtVersions); } QList<BaseQtVersion *> QtOptionsPageWidget::versions() const { QList<BaseQtVersion *> result; for (int i = 0; i < m_versions.count(); ++i) result.append(m_versions.at(i)->clone()); return result; } } // namespace Internal } // namespace QtSupport
lgpl-2.1
cdmdotnet/CQRS
wiki/docs/4.2/coverage-report/Cqrs/Services/EventService.cs.gcov.html
15112
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>LCOV - doc-coverage.info - Cqrs/Services/EventService.cs</title> <link rel="stylesheet" type="text/css" href="../../gcov.css"> </head> <body> <table width="100%" border=0 cellspacing=0 cellpadding=0> <tr><td class="title">Documentation Coverage Report</td></tr> <tr><td class="ruler"><img src="../../glass.png" width=3 height=3 alt=""></td></tr> <tr> <td width="100%"> <table cellpadding=1 border=0 width="100%"> <tr> <td width="10%" class="headerItem">Current view:</td> <td width="35%" class="headerValue"><a href="../../index.html">top level</a> - <a href="index.html">Cqrs/Services</a> - EventService.cs</td> <td width="5%"></td> <td width="15%"></td> <td width="10%" class="headerCovTableHead">Hit</td> <td width="10%" class="headerCovTableHead">Total</td> <td width="15%" class="headerCovTableHead">Coverage</td> </tr> <tr> <td class="headerItem">Version:</td> <td class="headerValue">4.0</td> <td></td> <td class="headerItem">Artefacts:</td> <td class="headerCovTableEntry">6</td> <td class="headerCovTableEntry">6</td> <td class="headerCovTableEntryHi">100.0 %</td> </tr> <tr> <td class="headerItem">Date:</td> <td class="headerValue">2020-09-17 19:32:03</td> <td></td> </tr> <tr><td><img src="../../glass.png" width=3 height=3 alt=""></td></tr> </table> </td> </tr> <tr><td class="ruler"><img src="../../glass.png" width=3 height=3 alt=""></td></tr> </table> <table cellpadding=0 cellspacing=0 border=0> <tr> <td><br></td> </tr> <tr> <td> <pre class="sourceHeading"> Line data Source code</pre> <pre class="source"> <span class="lineNum"> 1 </span> : #region Copyright <span class="lineNum"> 2 </span> : // // ----------------------------------------------------------------------- <span class="lineNum"> 3 </span> : // // &lt;copyright company=&quot;Chinchilla Software Limited&quot;&gt; <span class="lineNum"> 4 </span> : // // Copyright Chinchilla Software Limited. All rights reserved. <span class="lineNum"> 5 </span> : // // &lt;/copyright&gt; <span class="lineNum"> 6 </span> : // // ----------------------------------------------------------------------- <span class="lineNum"> 7 </span> : #endregion <span class="lineNum"> 8 </span> : <span class="lineNum"> 9 </span> : using System; <span class="lineNum"> 10 </span> : using System.Collections.Generic; <span class="lineNum"> 11 </span> : using System.ServiceModel; <span class="lineNum"> 12 </span> : using Chinchilla.Logging; <span class="lineNum"> 13 </span> : using Cqrs.Authentication; <span class="lineNum"> 14 </span> : using Cqrs.Events; <span class="lineNum"> 15 </span> : using Cqrs.Messages; <span class="lineNum"> 16 </span> : <span class="lineNum"> 17 </span> : namespace Cqrs.Services <span class="lineNum"> 18 </span> : { <span class="lineNum"> 19 </span> : /// &lt;summary&gt; <span class="lineNum"> 20 </span> : /// A WCF &lt;see cref=&quot;ServiceContractAttribute&quot;&gt;ServiceContract&lt;/see&gt; that provides read-only access to &lt;see cref=&quot;IEventStore{TAuthenticationToken}&quot;/&gt; &lt;see cref=&quot;IEvent{TAuthenticationToken}&quot;&gt;events&lt;/see&gt; <span class="lineNum"> 21 </span> : /// raised with the same &lt;see cref=&quot;IMessage.CorrelationId&quot;/&gt;. <span class="lineNum"> 22 </span> : /// &lt;/summary&gt; <span class="lineNum"> 23 </span> : /// &lt;typeparam name=&quot;TAuthenticationToken&quot;&gt;The &lt;see cref=&quot;Type&quot;/&gt; of authentication token.&lt;/typeparam&gt; <span class="lineNum"> 24 </span> : public abstract class EventService&lt;TAuthenticationToken&gt; : IEventService&lt;TAuthenticationToken&gt; <span class="lineNum"> 25 </span><span class="lineCov"> 1 : {</span> <span class="lineNum"> 26 </span> : /// &lt;summary&gt; <span class="lineNum"> 27 </span> : /// Instantiates a new instance of &lt;see cref=&quot;EventService{TAuthenticationToken}&quot;/&gt;. <span class="lineNum"> 28 </span> : /// &lt;/summary&gt; <span class="lineNum"> 29 </span><span class="lineCov"> 1 : protected EventService(IEventStore&lt;TAuthenticationToken&gt; eventStore, ILogger logger, ICorrelationIdHelper correlationIdHelper, IAuthenticationTokenHelper&lt;TAuthenticationToken&gt; authenticationTokenHelper)</span> <span class="lineNum"> 30 </span> : { <span class="lineNum"> 31 </span> : EventStore = eventStore; <span class="lineNum"> 32 </span> : Logger = logger; <span class="lineNum"> 33 </span> : CorrelationIdHelper = correlationIdHelper; <span class="lineNum"> 34 </span> : AuthenticationTokenHelper = authenticationTokenHelper; <span class="lineNum"> 35 </span> : } <span class="lineNum"> 36 </span> : <span class="lineNum"> 37 </span> : /// &lt;summary&gt; <span class="lineNum"> 38 </span> : /// Gets or sets the &lt;see cref=&quot;IEventStore{TAuthenticationToken}&quot;/&gt;. <span class="lineNum"> 39 </span> : /// &lt;/summary&gt; <span class="lineNum"> 40 </span> : protected virtual IEventStore&lt;TAuthenticationToken&gt; EventStore { get; private set; } <span class="lineNum"> 41 </span> : <span class="lineNum"> 42 </span> : /// &lt;summary&gt; <span class="lineNum"> 43 </span> : /// Gets or sets the &lt;see cref=&quot;IAuthenticationTokenHelper{TAuthenticationToken}&quot;/&gt;. <span class="lineNum"> 44 </span> : /// &lt;/summary&gt; <span class="lineNum"> 45 </span> : protected IAuthenticationTokenHelper&lt;TAuthenticationToken&gt; AuthenticationTokenHelper { get; private set; } <span class="lineNum"> 46 </span> : <span class="lineNum"> 47 </span> : /// &lt;summary&gt; <span class="lineNum"> 48 </span> : /// Gets or sets the &lt;see cref=&quot;ILogger&quot;/&gt;. <span class="lineNum"> 49 </span> : /// &lt;/summary&gt; <span class="lineNum"> 50 </span> : protected ICorrelationIdHelper CorrelationIdHelper { get; private set; } <span class="lineNum"> 51 </span> : <span class="lineNum"> 52 </span> : /// &lt;summary&gt; <span class="lineNum"> 53 </span> : /// Gets or sets the &lt;see cref=&quot;ILogger&quot;/&gt;. <span class="lineNum"> 54 </span> : /// &lt;/summary&gt; <span class="lineNum"> 55 </span> : protected ILogger Logger { get; private set; } <span class="lineNum"> 56 </span> : <span class="lineNum"> 57 </span> : /// &lt;summary&gt; <span class="lineNum"> 58 </span> : /// Get all &lt;see cref=&quot;IEvent{TAuthenticationToken}&quot;&gt;events&lt;/see&gt; <span class="lineNum"> 59 </span> : /// raised with the same &lt;see cref=&quot;IMessage.CorrelationId&quot;/&gt;. <span class="lineNum"> 60 </span> : /// &lt;/summary&gt; <span class="lineNum"> 61 </span> : /// &lt;param name=&quot;serviceRequest&quot;&gt;The &lt;see cref=&quot;IMessage.CorrelationId&quot;/&gt; of the &lt;see cref=&quot;IEvent{TAuthenticationToken}&quot;&gt;events&lt;/see&gt; to find.&lt;/param&gt; <span class="lineNum"> 62 </span><span class="lineCov"> 1 : public virtual IServiceResponseWithResultData&lt;IEnumerable&lt;EventData&gt;&gt; GetEventData(IServiceRequestWithData&lt;TAuthenticationToken, Guid&gt; serviceRequest)</span> <span class="lineNum"> 63 </span> : { <span class="lineNum"> 64 </span> : AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken); <span class="lineNum"> 65 </span> : CorrelationIdHelper.SetCorrelationId(serviceRequest.CorrelationId); <span class="lineNum"> 66 </span> : <span class="lineNum"> 67 </span> : OnGetEventData(serviceRequest); <span class="lineNum"> 68 </span> : IEnumerable&lt;EventData&gt; results = EventStore.Get(serviceRequest.Data); <span class="lineNum"> 69 </span> : results = OnGotEventData(serviceRequest, results); <span class="lineNum"> 70 </span> : <span class="lineNum"> 71 </span> : return CompleteResponse <span class="lineNum"> 72 </span> : ( <span class="lineNum"> 73 </span> : new ServiceResponseWithResultData&lt;IEnumerable&lt;EventData&gt;&gt; <span class="lineNum"> 74 </span> : { <span class="lineNum"> 75 </span> : State = ServiceResponseStateType.Succeeded, <span class="lineNum"> 76 </span> : ResultData = results, <span class="lineNum"> 77 </span> : } <span class="lineNum"> 78 </span> : ); <span class="lineNum"> 79 </span> : } <span class="lineNum"> 80 </span> : <span class="lineNum"> 81 </span> : /// &lt;summary&gt; <span class="lineNum"> 82 </span> : /// Executed before calling the &lt;see cref=&quot;IEventStore{TAuthenticationToken}.Get(System.Type,System.Guid,bool,int)&quot;/&gt; method on &lt;see cref=&quot;EventStore&quot;/&gt; <span class="lineNum"> 83 </span> : /// in &lt;see cref=&quot;GetEventData&quot;/&gt;. <span class="lineNum"> 84 </span> : /// &lt;/summary&gt; <span class="lineNum"> 85 </span> : /// &lt;param name=&quot;serviceRequest&quot;&gt;The original &lt;see cref=&quot;IServiceRequestWithData{TAuthenticationToken,Guid}&quot;/&gt;.&lt;/param&gt; <span class="lineNum"> 86 </span><span class="lineCov"> 1 : protected virtual void OnGetEventData(IServiceRequestWithData&lt;TAuthenticationToken, Guid&gt; serviceRequest) { }</span> <span class="lineNum"> 87 </span> : <span class="lineNum"> 88 </span> : /// &lt;summary&gt; <span class="lineNum"> 89 </span> : /// Executed after calling the &lt;see cref=&quot;IEventStore{TAuthenticationToken}.Get(System.Type,System.Guid,bool,int)&quot;/&gt; method on &lt;see cref=&quot;EventStore&quot;/&gt; <span class="lineNum"> 90 </span> : /// in &lt;see cref=&quot;GetEventData&quot;/&gt;. <span class="lineNum"> 91 </span> : /// &lt;/summary&gt; <span class="lineNum"> 92 </span> : /// &lt;param name=&quot;serviceRequest&quot;&gt;The original &lt;see cref=&quot;IServiceRequestWithData{TAuthenticationToken,Guid}&quot;/&gt;.&lt;/param&gt; <span class="lineNum"> 93 </span> : /// &lt;param name=&quot;results&quot;&gt;The collection of &lt;see cref=&quot;IEvent{TAuthenticationToken}&quot;&gt;events&lt;/see&gt; from the &lt;see cref=&quot;EventStore&quot;/&gt;.&lt;/param&gt; <span class="lineNum"> 94 </span><span class="lineCov"> 1 : protected virtual IEnumerable&lt;EventData&gt; OnGotEventData(IServiceRequestWithData&lt;TAuthenticationToken, Guid&gt; serviceRequest, IEnumerable&lt;EventData&gt; results)</span> <span class="lineNum"> 95 </span> : { <span class="lineNum"> 96 </span> : return results; <span class="lineNum"> 97 </span> : } <span class="lineNum"> 98 </span> : <span class="lineNum"> 99 </span> : /// &lt;summary&gt; <span class="lineNum"> 100 </span> : /// Sets the &lt;see cref=&quot;IServiceResponse.CorrelationId&quot;/&gt; on the provided &lt;paramref name=&quot;serviceResponse&quot;/&gt;. <span class="lineNum"> 101 </span> : /// &lt;/summary&gt; <span class="lineNum"> 102 </span><span class="lineCov"> 1 : protected virtual TServiceResponse CompleteResponse&lt;TServiceResponse&gt;(TServiceResponse serviceResponse)</span> <span class="lineNum"> 103 </span> : where TServiceResponse : IServiceResponse <span class="lineNum"> 104 </span> : { <span class="lineNum"> 105 </span> : serviceResponse.CorrelationId = CorrelationIdHelper.GetCorrelationId(); <span class="lineNum"> 106 </span> : return serviceResponse; <span class="lineNum"> 107 </span> : } <span class="lineNum"> 108 </span> : } <span class="lineNum"> 109 </span> : } </pre> </td> </tr> </table> <br> <table width="100%" border=0 cellspacing=0 cellpadding=0> <tr><td class="ruler"><img src="../../glass.png" width=3 height=3 alt=""></td></tr> <tr><td class="versionInfo">Generated by: <a href="http://ltp.sourceforge.net/coverage/lcov.php" target="_parent">LCOV version 1.13</a></td></tr> </table> <br> </body> </html>
lgpl-2.1
PureBilling/dbal
lib/Doctrine/DBAL/Schema/SchemaConfig.php
2923
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\DBAL\Schema; /** * Configuration for a Schema * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @link www.doctrine-project.org * @since 2.0 * @author Benjamin Eberlei <kontakt@beberlei.de> */ class SchemaConfig { /** * @var bool */ protected $hasExplicitForeignKeyIndexes = false; /** * @var int */ protected $maxIdentifierLength = 63; /** * @var string */ protected $name; /** * @var array */ protected $defaultTableOptions = array(); /** * @return bool */ public function hasExplicitForeignKeyIndexes() { return $this->hasExplicitForeignKeyIndexes; } /** * @param bool $flag */ public function setExplicitForeignKeyIndexes($flag) { $this->hasExplicitForeignKeyIndexes = (bool)$flag; } /** * @param int $length */ public function setMaxIdentifierLength($length) { $this->maxIdentifierLength = (int)$length; } /** * @return int */ public function getMaxIdentifierLength() { return $this->maxIdentifierLength; } /** * Get default namespace of schema objects. * * @return string */ public function getName() { return $this->name; } /** * set default namespace name of schema objects. * * @param string $name the value to set. */ public function setName($name) { $this->name = $name; } /** * Get the default options that are passed to Table instances created with * Schema#createTable(). * * @return array */ public function getDefaultTableOptions() { return $this->defaultTableOptions; } public function setDefaultTableOptions(array $defaultTableOptions) { $this->defaultTableOptions = $defaultTableOptions; } }
lgpl-2.1
KnightSwarm/WebKitTi
Source/WebCore/svg/SVGTextContentElement.cpp
10922
/* * Copyright (C) 2004, 2005, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org> * Copyright (C) 2004, 2005, 2006, 2007, 2008 Rob Buis <buis@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #if ENABLE(SVG) #include "SVGTextContentElement.h" #include "CSSPropertyNames.h" #include "CSSValueKeywords.h" #include "Frame.h" #include "FrameSelection.h" #include "RenderObject.h" #include "RenderSVGResource.h" #include "RenderSVGText.h" #include "SVGDocumentExtensions.h" #include "SVGElementInstance.h" #include "SVGNames.h" #include "SVGTextQuery.h" #include "XMLNames.h" namespace WebCore { // Define custom animated property 'textLength'. const SVGPropertyInfo* SVGTextContentElement::textLengthPropertyInfo() { static const SVGPropertyInfo* s_propertyInfo = 0; if (!s_propertyInfo) { s_propertyInfo = new SVGPropertyInfo(AnimatedLength, PropertyIsReadWrite, SVGNames::textLengthAttr, SVGNames::textLengthAttr.localName(), &SVGTextContentElement::synchronizeTextLength, &SVGTextContentElement::lookupOrCreateTextLengthWrapper); } return s_propertyInfo; } // Animated property definitions DEFINE_ANIMATED_ENUMERATION(SVGTextContentElement, SVGNames::lengthAdjustAttr, LengthAdjust, lengthAdjust, SVGLengthAdjustType) DEFINE_ANIMATED_BOOLEAN(SVGTextContentElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired) BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGTextContentElement) REGISTER_LOCAL_ANIMATED_PROPERTY(textLength) REGISTER_LOCAL_ANIMATED_PROPERTY(lengthAdjust) REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired) REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement) END_REGISTER_ANIMATED_PROPERTIES SVGTextContentElement::SVGTextContentElement(const QualifiedName& tagName, Document* document) : SVGGraphicsElement(tagName, document) , m_textLength(LengthModeOther) , m_specifiedTextLength(LengthModeOther) , m_lengthAdjust(SVGLengthAdjustSpacing) { registerAnimatedPropertiesForSVGTextContentElement(); } void SVGTextContentElement::synchronizeTextLength(SVGElement* contextElement) { ASSERT(contextElement); SVGTextContentElement* ownerType = toSVGTextContentElement(contextElement); if (!ownerType->m_textLength.shouldSynchronize) return; AtomicString value(SVGPropertyTraits<SVGLength>::toString(ownerType->m_specifiedTextLength)); ownerType->m_textLength.synchronize(ownerType, textLengthPropertyInfo()->attributeName, value); } PassRefPtr<SVGAnimatedProperty> SVGTextContentElement::lookupOrCreateTextLengthWrapper(SVGElement* contextElement) { ASSERT(contextElement); SVGTextContentElement* ownerType = toSVGTextContentElement(contextElement); return SVGAnimatedProperty::lookupOrCreateWrapper<SVGTextContentElement, SVGAnimatedLength, SVGLength> (ownerType, textLengthPropertyInfo(), ownerType->m_textLength.value); } PassRefPtr<SVGAnimatedLength> SVGTextContentElement::textLengthAnimated() { DEFINE_STATIC_LOCAL(SVGLength, defaultTextLength, (LengthModeOther)); if (m_specifiedTextLength == defaultTextLength) m_textLength.value.newValueSpecifiedUnits(LengthTypeNumber, getComputedTextLength(), ASSERT_NO_EXCEPTION); m_textLength.shouldSynchronize = true; return static_pointer_cast<SVGAnimatedLength>(lookupOrCreateTextLengthWrapper(this)); } unsigned SVGTextContentElement::getNumberOfChars() { document()->updateLayoutIgnorePendingStylesheets(); return SVGTextQuery(renderer()).numberOfCharacters(); } float SVGTextContentElement::getComputedTextLength() { document()->updateLayoutIgnorePendingStylesheets(); return SVGTextQuery(renderer()).textLength(); } float SVGTextContentElement::getSubStringLength(unsigned charnum, unsigned nchars, ExceptionCode& ec) { document()->updateLayoutIgnorePendingStylesheets(); unsigned numberOfChars = getNumberOfChars(); if (charnum >= numberOfChars) { ec = INDEX_SIZE_ERR; return 0.0f; } return SVGTextQuery(renderer()).subStringLength(charnum, nchars); } SVGPoint SVGTextContentElement::getStartPositionOfChar(unsigned charnum, ExceptionCode& ec) { document()->updateLayoutIgnorePendingStylesheets(); if (charnum > getNumberOfChars()) { ec = INDEX_SIZE_ERR; return SVGPoint(); } return SVGTextQuery(renderer()).startPositionOfCharacter(charnum); } SVGPoint SVGTextContentElement::getEndPositionOfChar(unsigned charnum, ExceptionCode& ec) { document()->updateLayoutIgnorePendingStylesheets(); if (charnum > getNumberOfChars()) { ec = INDEX_SIZE_ERR; return SVGPoint(); } return SVGTextQuery(renderer()).endPositionOfCharacter(charnum); } FloatRect SVGTextContentElement::getExtentOfChar(unsigned charnum, ExceptionCode& ec) { document()->updateLayoutIgnorePendingStylesheets(); if (charnum > getNumberOfChars()) { ec = INDEX_SIZE_ERR; return FloatRect(); } return SVGTextQuery(renderer()).extentOfCharacter(charnum); } float SVGTextContentElement::getRotationOfChar(unsigned charnum, ExceptionCode& ec) { document()->updateLayoutIgnorePendingStylesheets(); if (charnum > getNumberOfChars()) { ec = INDEX_SIZE_ERR; return 0.0f; } return SVGTextQuery(renderer()).rotationOfCharacter(charnum); } int SVGTextContentElement::getCharNumAtPosition(const SVGPoint& point) { document()->updateLayoutIgnorePendingStylesheets(); return SVGTextQuery(renderer()).characterNumberAtPosition(point); } void SVGTextContentElement::selectSubString(unsigned charnum, unsigned nchars, ExceptionCode& ec) { unsigned numberOfChars = getNumberOfChars(); if (charnum >= numberOfChars) { ec = INDEX_SIZE_ERR; return; } if (nchars > numberOfChars - charnum) nchars = numberOfChars - charnum; ASSERT(document()); ASSERT(document()->frame()); FrameSelection& selection = document()->frame()->selection(); // Find selection start VisiblePosition start(firstPositionInNode(const_cast<SVGTextContentElement*>(this))); for (unsigned i = 0; i < charnum; ++i) start = start.next(); // Find selection end VisiblePosition end(start); for (unsigned i = 0; i < nchars; ++i) end = end.next(); selection.setSelection(VisibleSelection(start, end)); } bool SVGTextContentElement::isSupportedAttribute(const QualifiedName& attrName) { DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ()); if (supportedAttributes.isEmpty()) { SVGLangSpace::addSupportedAttributes(supportedAttributes); SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes); supportedAttributes.add(SVGNames::lengthAdjustAttr); supportedAttributes.add(SVGNames::textLengthAttr); } return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName); } bool SVGTextContentElement::isPresentationAttribute(const QualifiedName& name) const { if (name.matches(XMLNames::spaceAttr)) return true; return SVGGraphicsElement::isPresentationAttribute(name); } void SVGTextContentElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style) { if (!isSupportedAttribute(name)) SVGGraphicsElement::collectStyleForPresentationAttribute(name, value, style); else if (name.matches(XMLNames::spaceAttr)) { DEFINE_STATIC_LOCAL(const AtomicString, preserveString, ("preserve", AtomicString::ConstructFromLiteral)); if (value == preserveString) addPropertyToPresentationAttributeStyle(style, CSSPropertyWhiteSpace, CSSValuePre); else addPropertyToPresentationAttributeStyle(style, CSSPropertyWhiteSpace, CSSValueNowrap); } } void SVGTextContentElement::parseAttribute(const QualifiedName& name, const AtomicString& value) { SVGParsingError parseError = NoError; if (!isSupportedAttribute(name)) SVGGraphicsElement::parseAttribute(name, value); else if (name == SVGNames::lengthAdjustAttr) { SVGLengthAdjustType propertyValue = SVGPropertyTraits<SVGLengthAdjustType>::fromString(value); if (propertyValue > 0) setLengthAdjustBaseValue(propertyValue); } else if (name == SVGNames::textLengthAttr) { m_textLength.value = SVGLength::construct(LengthModeOther, value, parseError, ForbidNegativeLengths); } else if (SVGExternalResourcesRequired::parseAttribute(name, value)) { } else if (SVGLangSpace::parseAttribute(name, value)) { } else ASSERT_NOT_REACHED(); reportAttributeParsingError(parseError, name, value); } void SVGTextContentElement::svgAttributeChanged(const QualifiedName& attrName) { if (!isSupportedAttribute(attrName)) { SVGGraphicsElement::svgAttributeChanged(attrName); return; } SVGElementInstance::InvalidationGuard invalidationGuard(this); if (attrName == SVGNames::textLengthAttr) m_specifiedTextLength = m_textLength.value; if (RenderObject* renderer = this->renderer()) RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer); } bool SVGTextContentElement::selfHasRelativeLengths() const { // Any element of the <text> subtree is advertized as using relative lengths. // On any window size change, we have to relayout the text subtree, as the // effective 'on-screen' font size may change. return true; } SVGTextContentElement* SVGTextContentElement::elementFromRenderer(RenderObject* renderer) { if (!renderer) return 0; if (!renderer->isSVGText() && !renderer->isSVGInline()) return 0; SVGElement* element = toSVGElement(renderer->node()); ASSERT(element); if (!element->isTextContent()) return 0; return toSVGTextContentElement(element); } } #endif // ENABLE(SVG)
lgpl-2.1
MichaelRiss/FTSPlot
Interval.h
1407
/* FTSPlot - fast time series dataset plotter Copyright (C) 2013 Michael Riss <Michael.Riss@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef INTERVAL_H #define INTERVAL_H #include <QtCore> namespace FTSPlot { class Interval { public: Interval ( quint64 begin = 0, quint64 end = 1 ); quint64 begin; quint64 end; bool operator< ( const Interval & other ) const; bool operator> ( const Interval & other ) const; bool operator== ( const Interval & other ) const; bool operator!= ( const Interval & other ) const; }; QDebug& operator<< ( QDebug& debug, const Interval& b ); } #endif // INTERVAL_H // kate: indent-mode cstyle; space-indent on; indent-width 4;
lgpl-2.1
xmirror/m17n-lib
src/m17n-gui.c
23939
/* m17n-gui.c -- body of the GUI API. Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 National Institute of Advanced Industrial Science and Technology (AIST) Registration Number H15PRO112 This file is part of the m17n library. The m17n 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 m17n 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 m17n library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 02111-1307, USA. */ /***en @addtogroup m17nGUI @brief GUI support for a window system. This section defines the m17n GUI API concerning M-text drawing and inputting under a window system. All the definitions here are independent of window systems. An actual library file, however, can depend on a specific window system. For instance, the library file m17n-X.so is an example of implementation of the m17n GUI API for the X Window System. Actually the GUI API is mainly for toolkit libraries or to implement XOM, not for direct use from application programs. */ /***ja @addtogroup m17nGUI @brief ¥¦¥£¥ó¥É¥¦¥·¥¹¥Æ¥à¾å¤Î GUI ¥µ¥Ý¡¼¥È. ¤³¤Î¥»¥¯¥·¥ç¥ó¤Ï¥¦¥£¥ó¥É¥¦¥·¥¹¥Æ¥à¤Î¤â¤È¤Ç¤Î M-text ¤Îɽ¼¨¤ÈÆþÎϤˤ«¤«¤ï¤ë m17n GUI API ¤òÄêµÁ¤¹¤ë¡£ ¤³¤³¤Ç¤Î¤¹¤Ù¤Æ¤ÎÄêµÁ¤Ï¥¦¥£¥ó¥É¥¦¥·¥¹¥Æ¥à¤È¤ÏÆÈΩ¤Ç¤¢¤ë¡£ ¤·¤«¤·¡¢¼ÂºÝ¤Î¥é¥¤¥Ö¥é¥ê¥Õ¥¡¥¤¥ë¤Ï¸ÄÊ̤Υ¦¥£¥ó¥É¥¦¥·¥¹¥Æ¥à¤Ë°Í¸¤¹¤ë¾ì¹ç¤¬¤¢¤ë¡£ ¤¿¤È¤¨¤Ð¥é¥¤¥Ö¥é¥ê¥Õ¥¡¥¤¥ë m17n-X.so ¤Ï¡¢m17n GUI API ¤Î X ¥¦¥£¥ó¥É¥¦ÍѤμÂÁõÎã¤Ç¤¢¤ë¡£ ¸½¼Â¤Ë¤Ï¡¢GUI API ¤Ï¼ç¤Ë¥Ä¡¼¥ë¥­¥Ã¥È¥é¥¤¥Ö¥é¥ê¸þ¤±¤Ç¤¢¤ë¤«¡¢¤Þ¤¿¤Ï XOM ¤ò¼ÂÁõ¤¹¤ë¤¿¤á¤ËÍѤ¤¤é¤ì¤Æ¤ª¤ê¡¢¥¢¥×¥ê¥±¡¼¥·¥ç¥ó¥×¥í¥°¥é¥à¤«¤é¤ÎľÀܤÎÍøÍѤòǰƬ¤Ë¤ª¤¤¤¿¤â¤Î¤Ç¤Ï¤Ê¤¤¡£ */ /*=*/ #if !defined (FOR_DOXYGEN) || defined (DOXYGEN_INTERNAL_MODULE) /*** @addtogroup m17nInternal @{ */ #include "config.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include "config.h" #ifdef HAVE_DLFCN_H #include <dlfcn.h> #endif #include "m17n-gui.h" #include "m17n-misc.h" #include "internal.h" #include "plist.h" #include "internal-gui.h" #include "font.h" #include "fontset.h" #include "face.h" #ifndef DLOPEN_SHLIB_EXT #define DLOPEN_SHLIB_EXT ".so" #endif /** Information about a dynamic library supporting a specific graphic device. */ typedef struct { /** Name of the dynamic library (e.g. "libm17n-X.so"). */ char *library; /** Handle of the dynamic library. */ void *handle; /** Function to call just after loading the library. */ int (*init) (); /** Function to call to open a frame on the graphic device. */ int (*open) (MFrame *frame, MPlist *param); /** Function to call just before unloading the library. */ int (*fini) (); } MDeviceLibraryInterface; /** Plist of device symbol vs MDeviceLibraryInterface. */ static MPlist *device_library_list; /** Close MFrame and free it. */ static void free_frame (void *object) { MFrame *frame = (MFrame *) object; (*frame->driver->close) (frame); M17N_OBJECT_UNREF (frame->face); M17N_OBJECT_UNREF (frame->font_driver_list); free (object); } /** Register a dynamic library of name LIB by a key NAME. */ static int register_device_library (MSymbol name, char *lib) { MDeviceLibraryInterface *interface; MSTRUCT_CALLOC (interface, MERROR_WIN); interface->library = malloc (strlen (M17N_MODULE_DIR) + 1 + strlen (lib) + strlen (DLOPEN_SHLIB_EXT) + 1); sprintf (interface->library, "%s/%s%s", M17N_MODULE_DIR, lib, DLOPEN_SHLIB_EXT); if (! device_library_list) device_library_list = mplist (); mplist_add (device_library_list, name, interface); return 0; } #ifdef HAVE_FREETYPE /** Null device support. */ static struct { MPlist *realized_fontset_list; MPlist *realized_font_list; MPlist *realized_face_list; } null_device; static void null_device_close (MFrame *frame) { } static void * null_device_get_prop (MFrame *frame, MSymbol key) { return NULL; } static void null_device_realize_face (MRealizedFace *rface) { rface->info = NULL; } static void null_device_free_realized_face (MRealizedFace *rface) { } static MDeviceDriver null_driver = { null_device_close, null_device_get_prop, null_device_realize_face, null_device_free_realized_face }; static int null_device_init () { null_device.realized_fontset_list = mplist (); null_device.realized_font_list = mplist (); null_device.realized_face_list = mplist (); return 0; } static int null_device_fini () { MPlist *plist; MPLIST_DO (plist, null_device.realized_fontset_list) mfont__free_realized_fontset ((MRealizedFontset *) MPLIST_VAL (plist)); M17N_OBJECT_UNREF (null_device.realized_fontset_list); MPLIST_DO (plist, null_device.realized_face_list) mface__free_realized ((MRealizedFace *) MPLIST_VAL (plist)); M17N_OBJECT_UNREF (null_device.realized_face_list); if (MPLIST_VAL (null_device.realized_font_list)) mfont__free_realized (MPLIST_VAL (null_device.realized_font_list)); M17N_OBJECT_UNREF (null_device.realized_font_list); return 0; } static int null_device_open (MFrame *frame, MPlist *param) { MFace *face; frame->device = NULL; frame->device_type = 0; frame->dpi = (int) mplist_get (param, Mresolution); if (frame->dpi == 0) frame->dpi = 100; frame->driver = &null_driver; frame->font_driver_list = mplist (); mplist_add (frame->font_driver_list, Mfreetype, &mfont__ft_driver); frame->realized_font_list = null_device.realized_font_list; frame->realized_face_list = null_device.realized_face_list; frame->realized_fontset_list = null_device.realized_fontset_list; face = mface_copy (mface__default); mplist_push (param, Mface, face); M17N_OBJECT_UNREF (face); return 0; } static MDeviceLibraryInterface null_interface = { NULL, NULL, null_device_init, null_device_open, null_device_fini }; #endif /* Internal API */ /* External API */ void m17n_init_win (void) { int mdebug_flag = MDEBUG_INIT; merror_code = MERROR_NONE; if (m17n__gui_initialized++) return; m17n_init (); m17n_init_flt (); if (merror_code != MERROR_NONE) { m17n__gui_initialized--; return; } MDEBUG_PUSH_TIME (); Mgd = msymbol ("gd"); Mfont = msymbol ("font"); Mfont_width = msymbol ("font-width"); Mfont_ascent = msymbol ("font-ascent"); Mfont_descent = msymbol ("font-descent"); Mdevice = msymbol ("device"); Mdisplay = msymbol ("display"); Mscreen = msymbol ("screen"); Mdrawable = msymbol ("drawable"); Mdepth = msymbol ("depth"); Mwidget = msymbol ("widget"); Mcolormap = msymbol ("colormap"); MDEBUG_PUSH_TIME (); if (mfont__init () < 0) goto err; MDEBUG_PRINT_TIME ("INIT", (mdebug__output, " to initialize font module.")); if (mfont__fontset_init () < 0) goto err; MDEBUG_PRINT_TIME ("INIT", (mdebug__output, " to initialize fontset module.")); if (mface__init () < 0) goto err; MDEBUG_PRINT_TIME ("INIT", (mdebug__output, " to initialize face module.")); if (mdraw__init () < 0) goto err; MDEBUG_PRINT_TIME ("INIT", (mdebug__output, " to initialize draw module.")); if (minput__win_init () < 0) goto err; MDEBUG_PRINT_TIME ("INIT", (mdebug__output, " to initialize input-win module.")); mframe_default = NULL; register_device_library (Mx, "libm17n-X"); register_device_library (Mgd, "libm17n-gd"); return; err: MDEBUG_POP_TIME (); MDEBUG_PRINT_TIME ("INIT", (mdebug__output, " to initialize the m17n GUI module.")); MDEBUG_POP_TIME (); } void m17n_fini_win (void) { int mdebug_flag = MDEBUG_FINI; MPlist *plist; if (m17n__gui_initialized == 0 || --m17n__gui_initialized > 0) return; MDEBUG_PUSH_TIME (); MDEBUG_PUSH_TIME (); MDEBUG_PRINT_TIME ("FINI", (mdebug__output, " to finalize device modules.")); MPLIST_DO (plist, device_library_list) { MDeviceLibraryInterface *interface = MPLIST_VAL (plist); if (interface->handle && interface->fini) { (*interface->fini) (); dlclose (interface->handle); } free (interface->library); free (interface); } #ifdef HAVE_FREETYPE if (null_interface.handle) { (*null_interface.fini) (); null_interface.handle = NULL; } #endif /* not HAVE_FREETYPE */ M17N_OBJECT_UNREF (device_library_list); minput__win_fini (); MDEBUG_PRINT_TIME ("FINI", (mdebug__output, " to finalize input-gui module.")); mdraw__fini (); MDEBUG_PRINT_TIME ("FINI", (mdebug__output, " to finalize draw module.")); mface__fini (); MDEBUG_PRINT_TIME ("FINI", (mdebug__output, " to finalize face module.")); mfont__fontset_fini (); MDEBUG_PRINT_TIME ("FINI", (mdebug__output, " to finalize fontset module.")); mfont__fini (); MDEBUG_PRINT_TIME ("FINI", (mdebug__output, " to finalize font module.")); mframe_default = NULL; MDEBUG_POP_TIME (); MDEBUG_PRINT_TIME ("FINI", (mdebug__output, " to finalize the gui modules.")); MDEBUG_POP_TIME (); m17n_fini_flt (); m17n_fini (); } /*** @} */ #endif /* !FOR_DOXYGEN || DOXYGEN_INTERNAL_MODULE */ /*** @addtogroup m17nFrame */ /***en @brief A @e frame is an object corresponding to the graphic device. A @e frame is an object of the type #MFrame to hold various information about each display/input device. Almost all m17n GUI functions require a pointer to a frame as an argument. */ /***ja @brief @e ¥Õ¥ì¡¼¥à ¤È¤Ï¥°¥é¥Õ¥£¥Ã¥¯¥Ç¥Ð¥¤¥¹¤ËÂбþ¤¹¤ë¥ª¥Ö¥¸¥§¥¯¥È¤Ç¤¢¤ë. @e ¥Õ¥ì¡¼¥à ¤È¤Ï #MFrame ·¿¤Î¥ª¥Ö¥¸¥§¥¯¥È¤Ç¤¢¤ê¡¢¸Ä¡¹¤Îɽ¼¨¡¿ÆþÎϥǥХ¤¥¹¤Î¾ðÊó¤ò³ÊǼ¤¹¤ë¤¿¤á¤ËÍѤ¤¤é¤ì¤ë¡£ ¤Û¤È¤ó¤É¤¹¤Ù¤Æ¤Î m17n GUI´Ø¿ô¤Ï¡¢°ú¿ô¤È¤·¤Æ¥Õ¥ì¡¼¥à¤Ø¤Î¥Ý¥¤¥ó¥¿¤òÍ׵᤹¤ë¡£ */ /*** @{ */ /*=*/ /***en @name Variables: Keys of frame parameter These are the symbols to use in a parameter to create a frame. See the function mframe () for details. @b Mdevice, @b Mdisplay, @b Mscreen, @b Mdrawable, @b Mdepth, and @b Mcolormap are also keys of a frame property. */ /***ja @name ÊÑ¿ô¡§ ¥Õ¥ì¡¼¥à¥Ñ¥é¥á¡¼¥¿ÍÑ¥­¡¼ ¥Õ¥ì¡¼¥à¤òÀ¸À®¤¹¤ëºÝ¤Î¥Ñ¥é¥á¡¼¥¿¤ËÍѤ¤¤ë¥·¥ó¥Ü¥ë¡£¾Ü¤·¤¯¤Ï´Ø¿ô mframe () ¤ÎÀâÌÀ»²¾È¡£ @b Mdevice¡¢ @b Mdisplay¡¢ @b Mscreen¡¢ @b Mdrawable¡¢ @b Mdepth¡¢ @b Mcolormap ¤Ï¥Õ¥ì¡¼¥à¥×¥í¥Ñ¥Æ¥£¤Î¥­¡¼¤Ç¤â¤¢¤ë¡£ */ /*=*/ MSymbol Mdevice, Mdisplay, Mscreen, Mdrawable, Mdepth, Mcolormap, Mwidget; MSymbol Mgd; /*=*/ /***en @name Variables: Keys of frame property These are the symbols to use as an argument to the function mframe_get_prop (). */ /***ja @name ÊÑ¿ô¡§ ¥Õ¥ì¡¼¥à¥×¥í¥Ñ¥Æ¥£¤Î¥­¡¼ ´Ø¿ô mframe_get_prop () ¤Î°ú¿ô¤ËÍѤ¤¤é¤ì¤ë¥·¥ó¥Ü¥ë¡£ */ /*** @{ */ /*=*/ MSymbol Mfont; MSymbol Mfont_width; MSymbol Mfont_ascent; MSymbol Mfont_descent; /*=*/ /*** @} */ /*=*/ /***en @brief Create a new frame. The mframe () function creates a new frame with parameters listed in $PLIST which may be @c NULL. The recognized keys in $PLIST are window system dependent. The following key is always recognized. <ul> <li> @b Mdevice, the value must be one of #Mx, @b Mgd, and #Mnil. If the value is #Mx, the frame is for X Window System. The argument #MDrawWindow specified together with the frame must be of type @c Window. The frame is both readable and writable, thus all GUI functions can be used. If the value is @b Mgd, the frame is for an image object of GD library. The argument #MDrawWindow specified together with the frame must be of type @c gdImagePtr. The frame is writable only, thus functions minput_XXX can't be used for the frame. If the value is #Mnil, the frame is for a null device. The frame is not writable nor readable, thus functions mdraw_XXX that require the argument #MDrawWindow and functions minput_XXX can't be used for the frame. <li> #Mface, the value must be a pointer to #MFace. The value is used as the default face of the frame. </ul> In addition, if the value of the key @b Mdevice is #Mx, the following keys are recognized. They are to specify the root window and the depth of drawables that can be used with the frame. <ul> <li> @b Mdrawable, the value type must be <tt>Drawable</tt>. A parameter of key @b Mdisplay must also be specified. The created frame can be used for drawables whose root window and depth are the same as those of the specified drawable on the specified display. When this parameter is specified, the parameter of key @b Mscreen is ignored. <li> @b Mwidget, the value type must be <tt>Widget</tt>. The created frame can be used for drawables whose root window and depth are the same as those of the specified widget. If a parameter of key #Mface is not specified, the default face is created from the resources of the widget. When this parameter is specified, the parameters of key @b Mdisplay, @b Mscreen, @b Mdrawable, @b Mdepth are ignored. <li> @b Mdepth, the value type must be <tt>unsigned</tt>. The created frame can be used for drawables of the specified depth. <li> @b Mscreen, the value type must be <tt>(Screen *)</tt>. The created frame can be used for drawables whose root window is the same as the root window of the specified screen, and depth is the same at the default depth of the screen. When this parameter is specified, parameter of key @b Mdisplay is ignored. <li> @b Mdisplay, the value type must be <tt>(Display *)</tt>. The created frame can be used for drawables whose root window is the same as the root window for the default screen of the display, and depth is the same as the default depth of the screen. <li> @b Mcolormap, the value type must be <tt>(Colormap)</tt>. The created frame uses the specified colormap. <li> @b Mfont, the value must be #Mx, #Mfreetype, or #Mxft. The created frame uses the specified font backend. The value #Mx instructs to use X core fonts, #Mfreetype to use local fonts supported by FreeType fonts, and #Mxft to use local fonts via Xft library. You can specify this parameter more than once with different values if you want to use multiple font backends. This is ignored if the specified font backend is not supported on the device. When this parameter is not specified, all font backend supported on the device are used. </ul> @return If the operation was successful, mframe () returns a pointer to a newly created frame. Otherwise, it returns @c NULL. */ /***ja @brief ¿·¤·¤¤¥Õ¥ì¡¼¥à¤òºî¤ë. ´Ø¿ô mframe () ¤Ï $PLIST Ãæ¤Î¥Ñ¥é¥á¡¼¥¿¤ò»ý¤Ä¿·¤·¤¤¥Õ¥ì¡¼¥à¤òºî¤ë¡£ $PLIST ¤Ï @c NULL ¤Ç¤âÎɤ¤¡£ $PLIST ¤Ë¸½¤ï¤ì¤ë¥­¡¼¤Î¤¦¤Á¤É¤ì¤¬Ç§¼±¤µ¤ì¤ë¤«¤Ï¥¦¥£¥ó¥É¥¦¥·¥¹¥Æ¥à¤Ë°Í¸¤¹¤ë¡£ °Ê²¼¤Î¥­¡¼¤Ï¾ï¤Ëǧ¼±¤µ¤ì¤ë¡£ <ul> <li> @b Mdevice. ÃÍ¤Ï #Mx, @b Mgd, #Mnil ¤Î¤¤¤º¤ì¤«¤Ç¤Ê¤¯¤Æ¤Ï¤Ê¤é¤Ê¤¤¡£ Ãͤ¬ #Mx ¤Ê¤é¤Ð¡¢¿·¤·¤¤¥Õ¥ì¡¼¥à¤Ï X ¥¦¥£¥ó¥É¥¦¥·¥¹¥Æ¥àÍѤǤ¢¤ë¡£ ¤³¤Î¥Õ¥ì¡¼¥à¤È¶¦¤Ë»ØÄꤵ¤ì¤¿°ú¿ô #MDrawWindow ¤Ï¡¢ @c Window ·¿¤Ç¤Ê¤¯¤Æ¤Ï¤Ê¤é¤Ê¤¤¡£¥Õ¥ì¡¼¥à¤ÏÆÉ¤ß½ñ¤­¤È¤â¤Ë²Äǽ¤Ç¤¢¤ê¡¢¤¹¤Ù¤Æ¤ÎGUI ´Ø¿ô¤¬»ÈÍѤǤ­¤ë¡£ Ãͤ¬ @b Mgd ¤Ê¤é¤Ð¡¢¿·¤·¤¤¥Õ¥ì¡¼¥à¤Ï GD ¥é¥¤¥Ö¥é¥ê¤Î¥¤¥á¡¼¥¸¥ª¥Ö¥¸¥§¥¯¥ÈÍѤǤ¢¤ë¡£¤³¤Î¥Õ¥ì¡¼¥à¤È¶¦¤Ë»ØÄꤵ¤ì¤¿°ú¿ô #MDrawWindow ¤Ï¡¢ @c gdImagePtr ·¿¤Ç¤Ê¤¯¤Æ¤Ï¤Ê¤é¤Ê¤¤¡£¥Õ¥ì¡¼¥à¤Ï½ñ¤­½Ð¤·ÀìÍѤǤ¢¤ê¡¢ minput_ ¤Ç»Ï¤Þ¤ë̾Á°¤Î´Ø¿ô¤Ï»ÈÍѤǤ­¤Ê¤¤¡£ Ãͤ¬ #Mnil ¤Ê¤é¤Ð¡¢¿·¤·¤¤¥Õ¥ì¡¼¥à¤Ï, null ¥Ç¥Ð¥¤¥¹ÍѤǤ¢¤ë¡£¤³¤Î¥Õ¥ì¡¼¥à¤ÏÆÉ¤ß½ñ¤­¤Ç¤­¤Ê¤¤¤Î¤Ç¡¢°ú¿ô #MDrawWindow ¤òɬÍפȤ¹¤ëmdraw_ ¤Ç»Ï¤Þ¤ë̾Á°¤Î´Ø¿ô¤ä¡¢minput_ ¤Ç»Ï¤Þ¤ë̾Á°¤Î´Ø¿ô¤Ï»ÈÍѤǤ­¤Ê¤¤¡£ <li> #Mface. ÃÍ¤Ï #MFace ¤Ø¤Î¥Ý¥¤¥ó¥¿¤Ç¤Ê¤¯¤Æ¤Ï¤Ê¤é¤Ê¤¤¡£ ¤³¤ÎÃͤϥե졼¥à¤Î¥Ç¥Õ¥©¥ë¥È¤Î¥Õ¥§¡¼¥¹¤È¤·¤ÆÍѤ¤¤é¤ì¤ë¡£ </ul> ¤³¤ì¤é¤Î¥­¡¼¤Ë²Ã¤¨¡¢@b Mdevice ¤Î¥­¡¼¤¬ #Mx ¤Ç¤¢¤ë¾ì¹ç¤Ë¸Â¤ê°Ê²¼¤Î¥­¡¼¤âǧ¼±¤µ¤ì¤ë¡£°Ê²¼¤Î¥­¡¼¤Ï¥ë¡¼¥È¥¦¥£¥ó¥É¥¦¤È¡¢¥Õ¥ì¡¼¥à¤ÇÍøÍѤǤ­¤ë drawable ¤Î¿¼¤µ¤ò»ØÄꤹ¤ë¡£ <ul> <li> @b Mdrawable. ÃÍ¤Ï <tt>Drawable</tt> ·¿¤Ç¤Ê¤¯¤Æ¤Ï¤Ê¤é¤Ê¤¤¡£ ¥­¡¼ @b Mdisplay ¤ò»ý¤Ä¥Ñ¥é¥á¡¼¥¿¤â»ØÄꤵ¤ì¤Æ¤¤¤ëɬÍפ¬¤¢¤ë¡£ À¸À®¤µ¤ì¤¿¥Õ¥ì¡¼¥à¤Ï¡¢»ØÄꤵ¤ì¤¿¥Ç¥£¥¹¥×¥ì¥¤¾å¤Î»ØÄꤵ¤ì¤¿ drawable ¤ÈƱ¤¸¥ë¡¼¥È¥¦¥£¥ó¥É¥¦¤È¿¼¤µ¤ò»ý¤Ä drawable ¤ËÍѤ¤¤é¤ì¤ë¡£ ¤³¤Î¥Ñ¥é¥á¡¼¥¿¤¬¤¢¤ë¾ì¹ç¤Ë¤Ï¡¢@b Mscreen ¤ò¥­¡¼¤È¤¹¤ë¥Ñ¥é¥á¡¼¥¿¤Ï̵»ë¤µ¤ì¤ë¡£ <li> @b Mwidget. ÃÍ¤Ï <tt>Widget</tt> ·¿¤Ç¤Ê¤¯¤Æ¤Ï¤Ê¤é¤Ê¤¤¡£ À¸À®¤µ¤ì¤¿¥Õ¥ì¡¼¥à¤Ï¡¢»ØÄꤷ¤¿¥¦¥£¥¸¥§¥Ã¥È¤ÈƱ¤¸¥ë¡¼¥È¥¦¥£¥ó¥É¥¦¤È¿¼¤µ¤ò»ý¤Ä drawable ¤ËÍѤ¤¤é¤ì¤ë¡£ ¥­¡¼ #Mface ¤ò»ý¤Ä¥Ñ¥é¥á¡¼¥¿¤¬¤Ê¤±¤ì¤Ð¡¢¥Ç¥Õ¥©¥ë¥È¤Î¥Õ¥§¡¼¥¹¤Ï¤³¤Î ¥¦¥£¥¸¥§¥Ã¥È¤Î¥ê¥½¡¼¥¹¤«¤éºî¤é¤ì¤ë¡£ ¤³¤Î¥Ñ¥é¥á¡¼¥¿¤¬¤¢¤ë¾ì¹ç¤Ë¤Ï¡¢@b Mdisplay, @b Mscreen, @b Mdrawable, @b Mdepth ¤ò¥­¡¼¤È¤¹¤ë¥Ñ¥é¥á¡¼¥¿¤Ï̵»ë¤µ¤ì¤ë¡£ <li> @b Mdepth. ÃÍ¤Ï <tt>unsigned</tt> ·¿¤Ç¤Ê¤¯¤Æ¤Ï¤Ê¤é¤Ê¤¤¡£ À¸À®¤µ¤ì¤¿¥Õ¥ì¡¼¥à¤Ï¡¢»ØÄꤷ¤¿¿¼¤µ¤Î drawable ¤ËÍѤ¤¤é¤ì¤ë¡£ <li> @b Mscreen. ÃÍ¤Ï <tt>(Screen *)</tt> ·¿¤Ç¤Ê¤¯¤Æ¤Ï¤Ê¤é¤Ê¤¤¡£ À¸À®¤·¤¿¥Õ¥ì¡¼¥à¤Ï¡¢»ØÄꤷ¤¿¥¹¥¯¥ê¡¼¥ó¤ÈƱ¤¸¥ë¡¼¥È¥¦¥£¥ó¥É¥¦¤ò»ý¤Á¡¢¥¹¥¯¥ê¡¼¥ó¤Î¥Ç¥Õ¥©¥ë¥È¤Î¿¼¤µ¤ÈƱ¤¸¿¼¤µ¤ò»ý¤Ä drawable ¤ËÍѤ¤¤é¤ì¤ë¡£ ¤³¤Î¥Ñ¥é¥á¡¼¥¿¤¬¤¢¤ë¾ì¹ç¤Ë¤Ï¡¢@b Mdisplay ¤ò¥­¡¼¤È¤¹¤ë¥Ñ¥é¥á¡¼¥¿¤Ï̵»ë¤µ¤ì¤ë¡£ <li> @b Mdisplay. ÃÍ¤Ï <tt>(Display *)</tt> ·¿¤Ç¤Ê¤¯¤Æ¤Ï¤Ê¤é¤Ê¤¤¡£ À¸À®¤µ¤ì¤¿¥Õ¥ì¡¼¥à¤Ï¡¢»ØÄꤷ¤¿¥Ç¥£¥¹¥×¥ì¥¤¤Î¥Ç¥Õ¥©¥ë¥È¥¹¥¯¥ê¡¼¥ó¤ÈƱ¤¸¥ë¡¼¥È¥¦¥£¥ó¥É¥¦¤ÈƱ¤¸¿¼¤µ¤ò»ý¤Ädrawables ¤ËÍѤ¤¤é¤ì¤ë¡£ <li> @b Mcolormap. ÃÍ¤Ï <tt>(Colormap)</tt> ·¿¤Ç¤Ê¤¯¤Æ¤Ï¤Ê¤é¤Ê¤¤¡£ À¸À®¤µ¤ì¤¿¥Õ¥ì¡¼¥à¤Ï¡¢»ØÄꤷ¤¿¥«¥é¡¼¥Þ¥Ã¥×¤ò»ÈÍѤ¹¤ë¡£ <li> #Mfont. Ãͤϡ¢#Mx, #Mfreetype, #Mxft ¤Î¤¤¤º¤ì¤«¡£ À¸À®¤µ¤ì¤¿¥Õ¥ì¡¼¥à¤Ï»ØÄꤷ¤¿¥Õ¥©¥ó¥È¥Ð¥Ã¥¯¥¨¥ó¥É¤ò»ÈÍѤ¹¤ë¡£Ãͤ¬ #Mx ¤Ç¤¢¤ì¤Ð X ¤Î¥³¥¢¥Õ¥©¥ó¥È¡¢#Mfreetype ¤Ç¤¢¤ì¤Ð FreeType ¤Ç¥µ¥Ý¡¼¥È¤µ¤ì¤Æ¤¤¤ë¥í¡¼¥«¥ë¥Õ¥©¥ó¥È¡¢#Mxft ¤Ç¤¢¤ì¤Ð Xft ¥é¥¤¥Ö¥é¥ê·Ðͳ¤ÇÍѤ¤¤ë¥í¡¼¥«¥ë¥Õ¥©¥ó¥È¤ò»ÈÍѤ¹¤ë¡£ Ê£¿ô¤Î¥Õ¥©¥ó¥È¥Ð¥Ã¥¯¥¨¥ó¥É¤ò»ÈÍѤ·¤¿¤¤¾ì¹ç¤Ë¤Ï¡¢¤³¤Î¥Ñ¥é¥á¡¼¥¿¤òÊ£¿ô²ó¡¢°Û¤Ê¤ëÃͤǻØÄꤹ¤ë¤³¤È¤¬¤Ç¤­¤ë¡£ »ØÄꤷ¤¿¥Ð¥Ã¥¯¥¨¥ó¥É¤¬¥µ¥Ý¡¼¥È¤µ¤ì¤Æ¤¤¤Ê¤¤¥Ç¥Ð¥¤¥¹¤Ç¤Ï¡¢¤³¤Î¥Ñ¥é¥á¡¼¥¿¤Ï̵»ë¤µ¤ì¤ë¡£ ¤³¤Î¥Ñ¥é¥á¡¼¥¿¤¬Ìµ¤¤¾ì¹ç¤Ë¤Ï¡¢¥Ç¥Ð¥¤¥¹¤Ç¥µ¥Ý¡¼¥È¤µ¤ì¤Æ¤¤¤ë¤¹¤Ù¤Æ¤Î¥Õ¥©¥ó¥È¥Ð¥Ã¥¯¥¨¥ó¥É¤òÍøÍѤ¹¤ë¡£ </ul> @return À®¸ù¤¹¤ì¤Ð mframe() ¤Ï¿·¤·¤¤¥Õ¥ì¡¼¥à¤Ø¤Î¥Ý¥¤¥ó¥¿¤òÊÖ¤¹¡£¤½¤¦¤Ç¤Ê¤±¤ì¤Ð @c NULL ¤òÊÖ¤¹¡£ */ MFrame * mframe (MPlist *plist) { MFrame *frame; int plist_created = 0; MPlist *pl; MSymbol device; MDeviceLibraryInterface *interface; if (plist) { pl = mplist_find_by_key (plist, Mdevice); if (pl) device = MPLIST_VAL (pl); else device = Mx; } else { plist = mplist (); plist_created = 1; device = Mx; } if (device == Mnil) { #ifdef HAVE_FREETYPE interface = &null_interface; if (! interface->handle) { (*interface->init) (); interface->handle = (void *) 1; } #else /* not HAVE_FREETYPE */ MERROR (MERROR_WIN, NULL); #endif /* not HAVE_FREETYPE */ } else { interface = mplist_get (device_library_list, device); if (! interface) MERROR (MERROR_WIN, NULL); if (! interface->handle) { if (! (interface->handle = dlopen (interface->library, RTLD_NOW)) || ! (interface->init = (int (*) ()) dlsym (interface->handle, "device_init")) || ! (interface->open = (int (*) (MFrame *, MPlist *)) dlsym (interface->handle, "device_open")) || ! (interface->fini = (int (*) ()) dlsym (interface->handle, "device_fini")) || (*interface->init) () < 0) { fprintf (stderr, "%s\n", (char *) dlerror ()); if (interface->handle) dlclose (interface->handle); MERROR (MERROR_WIN, NULL); } } } M17N_OBJECT (frame, free_frame, MERROR_FRAME); if ((*interface->open) (frame, plist) < 0) { free (frame); MERROR (MERROR_WIN, NULL); } if (! mframe_default) mframe_default = frame; frame->face = mface (); MPLIST_DO (pl, plist) if (MPLIST_KEY (pl) == Mface) mface_merge (frame->face, (MFace *) MPLIST_VAL (pl)); mface__update_frame_face (frame); frame->font = frame->rface->rfont ? (MFont *) frame->rface->rfont : NULL; if (plist_created) M17N_OBJECT_UNREF (plist); return frame; } /*=*/ /***en @brief Return property value of frame. The mframe_get_prop () function returns a value of property $KEY of frame $FRAME. The valid keys and the corresponding return values are as follows. @verbatim key type of value meaning of value --- ------------- ---------------- Mface MFace * The default face. Mfont MFont * The default font. Mfont_width int Width of the default font. Mfont_ascent int Ascent of the default font. Mfont_descent int Descent of the default font. @endverbatim In the m17n-X library, the followings are also accepted. @verbatim key type of value meaning of value --- ------------- ---------------- Mdisplay Display * Display associated with the frame. Mscreen int Screen number of a screen associated with the frame. Mcolormap Colormap Colormap of the frame. Mdepth unsigned Depth of the frame. @endverbatim */ /***ja @brief ¥Õ¥ì¡¼¥à¤Î¥×¥í¥Ñ¥Æ¥£¤ÎÃͤòÊÖ¤¹. ´Ø¿ô mframe_get_prop () ¤Ï¥Õ¥ì¡¼¥à $FRAME ¤Î¥­¡¼ $KEY ¤ò»ý¤Ä¥×¥í¥Ñ¥Æ¥£¤ÎÃͤòÊÖ¤¹¡£Í­¸ú¤Ê¥­¡¼¤È¤½¤ÎÃͤϰʲ¼¤ÎÄ̤ꡣ @verbatim ¥­¡¼ Ãͤη¿ ÃͤΰÕÌ£ --- ------------- ---------------- Mface MFace * ¥Ç¥Õ¥©¥ë¥È¤Î¥Õ¥§¡¼¥¹ Mfont MFont * ¥Ç¥Õ¥©¥ë¥È¤Î¥Õ¥©¥ó¥È Mfont_width int ¥Ç¥Õ¥©¥ë¥È¤Î¥Õ¥©¥ó¥È¤ÎÉý Mfont_ascent int ¥Ç¥Õ¥©¥ë¥È¤Î¥Õ¥©¥ó¥È¤Î ascent Mfont_descent int ¥Ç¥Õ¥©¥ë¥È¤Î¥Õ¥©¥ó¥È¤Î descent @endverbatim m17n-X ¥é¥¤¥Ö¥é¥ê¤Ç¤Ï¡¢°Ê²¼¤Î¥­¡¼¤â»ÈÍѤǤ­¤ë¡£ @verbatim ¥­¡¼ Ãͤη¿ ÃͤΰÕÌ£ --- ------------- ---------------- Mdisplay Display * ¥Õ¥ì¡¼¥à¤È´ØÏ¢ÉÕ¤±¤é¤ì¤¿¥Ç¥£¥¹¥×¥ì¥¤ Mscreen int ¥Õ¥ì¡¼¥à¤È´ØÏ¢ÉÕ¤±¤é¤ì¤¿¥¹¥¯¥ê¡¼¥ó ¤Î¥¹¥¯¥ê¡¼¥ó¥Ê¥ó¥Ð Mcolormap Colormap ¥Õ¥ì¡¼¥à¤Î¥«¥é¡¼¥Þ¥Ã¥× Mdepth unsigned ¥Õ¥ì¡¼¥à¤Î¿¼¤µ @endverbatim */ void * mframe_get_prop (MFrame *frame, MSymbol key) { if (key == Mface) return frame->face; if (key == Mfont) return frame->font; if (key == Mfont_width) return (void *) (frame->average_width); if (key == Mfont_ascent) return (void *) (frame->ascent); if (key == Mfont_descent) return (void *) (frame->descent); return (*frame->driver->get_prop) (frame, key); } /*=*/ /***en @brief The default frame. The external variable #mframe_default contains a pointer to the default frame that is created by the first call of mframe (). */ /***ja @brief ¥Ç¥Õ¥©¥ë¥È¤Î¥Õ¥ì¡¼¥à. ³°ÉôÊÑ¿ô #mframe_default ¤Ï¡¢¥Ç¥Õ¥©¥ë¥È¤Î¥Õ¥ì¡¼¥à¤Ø¤Î¥Ý¥¤¥ó¥¿¤ò»ý¤Ä¡£ ¥Ç¥Õ¥©¥ë¥È¤Î¥Õ¥ì¡¼¥à¤Ï¡¢ºÇ½é¤Ë mframe () ¤¬¸Æ¤Ó½Ð¤µ¤ì¤¿¤È¤­¤Ëºî¤é¤ì¤ë¡£ */ MFrame *mframe_default; /*** @} */ /* Local Variables: coding: euc-japan End: */
lgpl-2.1
GRM-dev/Narutocraft-PL_Mod
src/main/java/pl/grmdev/narutocraft/items/weapons/SmokeBomb.java
318
package pl.grmdev.narutocraft.items.weapons; import net.minecraft.item.Item; import pl.grmdev.narutocraft.NarutoCraft; public class SmokeBomb extends Item { public SmokeBomb(){ this.setUnlocalizedName("SmokeBomb"); this.setCreativeTab(NarutoCraft.mTabNarutoCraft); this.maxStackSize = 64; } }
lgpl-2.1
prowritingaid/openoffice-extension
src/main/java/com/prowritingaid/client/TagAnalysisResponse.java
261
package com.prowritingaid.client; public class TagAnalysisResponse { public String url; public int wordCount; public DocTag[] tags; public int numReports; public long requestId ; public String onreportsidebar; }
lgpl-2.1
nfinit-gaming/BetterAgriculture
src/main/java/betteragriculture/client/render/mobs/RenderEntityMobPig8.java
815
package betteragriculture.client.render.mobs; import betteragriculture.entity.entitymob.EntityMobPig8; import net.minecraft.client.model.ModelPig; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.renderer.entity.layers.LayerHeldItem; import net.minecraft.util.ResourceLocation; public class RenderEntityMobPig8 extends RenderLiving<EntityMobPig8> { private final ResourceLocation textures = new ResourceLocation("betteragriculture:textures/models/pig8.png"); public RenderEntityMobPig8(RenderManager renderManager) { super(renderManager, new ModelPig(), 0); this.addLayer(new LayerHeldItem(this)); } @Override protected ResourceLocation getEntityTexture(EntityMobPig8 entity) { return textures; } }
lgpl-2.1
giaf/hpmpc
kernel/avx/kernel_dsymv_avx_lib4.c
34535
/************************************************************************************************** * * * This file is part of HPMPC. * * * * HPMPC -- Library for High-Performance implementation of solvers for MPC. * * Copyright (C) 2014-2015 by Technical University of Denmark. All rights reserved. * * * * HPMPC 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. * * * * HPMPC 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 HPMPC; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * * * Author: Gianluca Frison, giaf (at) dtu.dk * * * **************************************************************************************************/ #include <mmintrin.h> #include <xmmintrin.h> // SSE #include <emmintrin.h> // SSE2 #include <pmmintrin.h> // SSE3 #include <smmintrin.h> // SSE4 #include <immintrin.h> // AVX #if ! defined(BLASFEO) // it moves vertically across blocks void kernel_dsymv_6_lib4(int kmax, double *A, int sda, double *x_n, double *y_n, double *z_n, double *x_t, double *y_t, double *z_t, int tri, int alg_n, int alg_t) { if(kmax<=0) return; const int bs = 4; __builtin_prefetch( A + bs*0 ); __builtin_prefetch( A + bs*2 ); __builtin_prefetch( A + bs*4 ); int k; double k_left; static double d_mask[4] = {0.5, 1.5, 2.5, 3.5}; __m256d v_mask, zeros, temp, a_00, x_n_0, x_n_1, x_n_2, x_n_3, x_n_4, x_n_5, y_n_0, x_t_0, y_t_0, y_t_1, y_t_2, y_t_4, y_t_5, y_t_3; __m256i i_mask; zeros = _mm256_setzero_pd(); x_n_0 = _mm256_broadcast_sd( &x_n[0] ); x_n_1 = _mm256_broadcast_sd( &x_n[1] ); x_n_2 = _mm256_broadcast_sd( &x_n[2] ); x_n_3 = _mm256_broadcast_sd( &x_n[3] ); x_n_4 = _mm256_broadcast_sd( &x_n[4] ); x_n_5 = _mm256_broadcast_sd( &x_n[5] ); if(alg_n==-1) { x_n_0 = _mm256_sub_pd( zeros, x_n_0 ); x_n_1 = _mm256_sub_pd( zeros, x_n_1 ); x_n_2 = _mm256_sub_pd( zeros, x_n_2 ); x_n_3 = _mm256_sub_pd( zeros, x_n_3 ); x_n_4 = _mm256_sub_pd( zeros, x_n_4 ); x_n_5 = _mm256_sub_pd( zeros, x_n_5 ); } y_t_0 = _mm256_setzero_pd(); y_t_1 = _mm256_setzero_pd(); y_t_2 = _mm256_setzero_pd(); y_t_3 = _mm256_setzero_pd(); y_t_4 = _mm256_setzero_pd(); y_t_5 = _mm256_setzero_pd(); k=0; // corner if(tri>0) { if(tri==1) // starting from the top of a panel { __builtin_prefetch( A + sda*bs +bs*0 ); __builtin_prefetch( A + sda*bs +bs*2 ); __builtin_prefetch( A + sda*bs +bs*4 ); y_n_0 = _mm256_loadu_pd( &y_n[0] ); x_t_0 = _mm256_loadu_pd( &x_t[0] ); a_00 = _mm256_load_pd( &A[0+bs*0] ); temp = _mm256_mul_pd( a_00, x_n_0 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); a_00 = _mm256_blend_pd( a_00, zeros, 0x1 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_0 = _mm256_add_pd( temp, y_t_0 ); a_00 = _mm256_load_pd( &A[0+bs*1] ); a_00 = _mm256_blend_pd( a_00, zeros, 0x1 ); temp = _mm256_mul_pd( a_00, x_n_1 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); a_00 = _mm256_blend_pd( a_00, zeros, 0x3 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_1 = _mm256_add_pd( temp, y_t_1 ); a_00 = _mm256_load_pd( &A[0+bs*2] ); a_00 = _mm256_blend_pd( a_00, zeros, 0x3 ); temp = _mm256_mul_pd( a_00, x_n_2 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); a_00 = _mm256_blend_pd( a_00, zeros, 0x7 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_2 = _mm256_add_pd( temp, y_t_2 ); a_00 = _mm256_load_pd( &A[0+bs*3] ); a_00 = _mm256_blend_pd( a_00, zeros, 0x7 ); temp = _mm256_mul_pd( a_00, x_n_3 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); _mm256_storeu_pd( &z_n[0], y_n_0 ); A += sda*bs; y_n += 4; z_n += 4; x_t += 4; __builtin_prefetch( A + sda*bs +bs*0 ); __builtin_prefetch( A + sda*bs +bs*2 ); __builtin_prefetch( A + sda*bs +bs*4 ); y_n_0 = _mm256_loadu_pd( &y_n[0] ); x_t_0 = _mm256_loadu_pd( &x_t[0] ); a_00 = _mm256_load_pd( &A[0+bs*0] ); temp = _mm256_mul_pd( a_00, x_n_0 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_0 = _mm256_add_pd( temp, y_t_0 ); a_00 = _mm256_load_pd( &A[0+bs*1] ); temp = _mm256_mul_pd( a_00, x_n_1 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_1 = _mm256_add_pd( temp, y_t_1 ); a_00 = _mm256_load_pd( &A[0+bs*2] ); temp = _mm256_mul_pd( a_00, x_n_2 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_2 = _mm256_add_pd( temp, y_t_2 ); a_00 = _mm256_load_pd( &A[0+bs*3] ); temp = _mm256_mul_pd( a_00, x_n_3 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_3 = _mm256_add_pd( temp, y_t_3 ); a_00 = _mm256_load_pd( &A[0+bs*4] ); temp = _mm256_mul_pd( a_00, x_n_4 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); a_00 = _mm256_blend_pd( a_00, zeros, 0x1 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_4 = _mm256_add_pd( temp, y_t_4 ); a_00 = _mm256_load_pd( &A[0+bs*5] ); a_00 = _mm256_blend_pd( a_00, zeros, 0x1 ); temp = _mm256_mul_pd( a_00, x_n_5 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); a_00 = _mm256_blend_pd( a_00, zeros, 0x3 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_5 = _mm256_add_pd( temp, y_t_5 ); _mm256_storeu_pd( &z_n[0], y_n_0 ); A += sda*bs; y_n += 4; z_n += 4; x_t += 4; k += 8; } else // starting from the second row of a panel { A -= 2; y_n -= 2; z_n -= 2; x_t -= 2; __builtin_prefetch( A + sda*bs +bs*0 ); __builtin_prefetch( A + sda*bs +bs*2 ); __builtin_prefetch( A + sda*bs +bs*4 ); y_n_0 = _mm256_loadu_pd( &y_n[0] ); x_t_0 = _mm256_loadu_pd( &x_t[0] ); a_00 = _mm256_load_pd( &A[0+bs*0] ); a_00 = _mm256_blend_pd( a_00, zeros, 0x3 ); temp = _mm256_mul_pd( a_00, x_n_0 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); a_00 = _mm256_blend_pd( a_00, zeros, 0x7 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_0 = _mm256_add_pd( temp, y_t_0 ); a_00 = _mm256_load_pd( &A[0+bs*1] ); a_00 = _mm256_blend_pd( a_00, zeros, 0x7 ); temp = _mm256_mul_pd( a_00, x_n_1 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); _mm256_storeu_pd( &z_n[0], y_n_0 ); A += sda*bs; y_n += 4; z_n += 4; x_t += 4; __builtin_prefetch( A + sda*bs +bs*0 ); __builtin_prefetch( A + sda*bs +bs*2 ); __builtin_prefetch( A + sda*bs +bs*4 ); y_n_0 = _mm256_loadu_pd( &y_n[0] ); x_t_0 = _mm256_loadu_pd( &x_t[0] ); a_00 = _mm256_load_pd( &A[0+bs*0] ); temp = _mm256_mul_pd( a_00, x_n_0 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_0 = _mm256_add_pd( temp, y_t_0 ); a_00 = _mm256_load_pd( &A[0+bs*1] ); temp = _mm256_mul_pd( a_00, x_n_1 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_1 = _mm256_add_pd( temp, y_t_1 ); a_00 = _mm256_load_pd( &A[0+bs*2] ); temp = _mm256_mul_pd( a_00, x_n_2 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); a_00 = _mm256_blend_pd( a_00, zeros, 0x1 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_2 = _mm256_add_pd( temp, y_t_2 ); a_00 = _mm256_load_pd( &A[0+bs*3] ); a_00 = _mm256_blend_pd( a_00, zeros, 0x1 ); temp = _mm256_mul_pd( a_00, x_n_3 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); a_00 = _mm256_blend_pd( a_00, zeros, 0x3 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_3 = _mm256_add_pd( temp, y_t_3 ); a_00 = _mm256_load_pd( &A[0+bs*4] ); a_00 = _mm256_blend_pd( a_00, zeros, 0x3 ); temp = _mm256_mul_pd( a_00, x_n_4 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); a_00 = _mm256_blend_pd( a_00, zeros, 0x7 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_4 = _mm256_add_pd( temp, y_t_4 ); a_00 = _mm256_load_pd( &A[0+bs*5] ); a_00 = _mm256_blend_pd( a_00, zeros, 0x7 ); temp = _mm256_mul_pd( a_00, x_n_5 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); _mm256_storeu_pd( &z_n[0], y_n_0 ); A += sda*bs; y_n += 4; z_n += 4; x_t += 4; k += 6; } } for(; k<kmax-7; k+=8) { __builtin_prefetch( A + sda*bs +bs*0 ); __builtin_prefetch( A + sda*bs +bs*2 ); __builtin_prefetch( A + sda*bs +bs*4 ); y_n_0 = _mm256_loadu_pd( &y_n[0] ); x_t_0 = _mm256_loadu_pd( &x_t[0] ); a_00 = _mm256_load_pd( &A[0+bs*0] ); temp = _mm256_mul_pd( a_00, x_n_0 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_0 = _mm256_add_pd( temp, y_t_0 ); a_00 = _mm256_load_pd( &A[0+bs*1] ); temp = _mm256_mul_pd( a_00, x_n_1 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_1 = _mm256_add_pd( temp, y_t_1 ); a_00 = _mm256_load_pd( &A[0+bs*2] ); temp = _mm256_mul_pd( a_00, x_n_2 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_2 = _mm256_add_pd( temp, y_t_2 ); a_00 = _mm256_load_pd( &A[0+bs*3] ); temp = _mm256_mul_pd( a_00, x_n_3 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_3 = _mm256_add_pd( temp, y_t_3 ); a_00 = _mm256_load_pd( &A[0+bs*4] ); temp = _mm256_mul_pd( a_00, x_n_4 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_4 = _mm256_add_pd( temp, y_t_4 ); a_00 = _mm256_load_pd( &A[0+bs*5] ); A += sda*bs; temp = _mm256_mul_pd( a_00, x_n_5 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_5 = _mm256_add_pd( temp, y_t_5 ); _mm256_storeu_pd( &z_n[0], y_n_0 ); __builtin_prefetch( A + sda*bs +bs*0 ); __builtin_prefetch( A + sda*bs +bs*2 ); __builtin_prefetch( A + sda*bs +bs*4 ); y_n_0 = _mm256_loadu_pd( &y_n[4] ); y_n += 8; x_t_0 = _mm256_loadu_pd( &x_t[4] ); x_t += 8; a_00 = _mm256_load_pd( &A[0+bs*0] ); temp = _mm256_mul_pd( a_00, x_n_0 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_0 = _mm256_add_pd( temp, y_t_0 ); a_00 = _mm256_load_pd( &A[0+bs*1] ); temp = _mm256_mul_pd( a_00, x_n_1 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_1 = _mm256_add_pd( temp, y_t_1 ); a_00 = _mm256_load_pd( &A[0+bs*2] ); temp = _mm256_mul_pd( a_00, x_n_2 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_2 = _mm256_add_pd( temp, y_t_2 ); a_00 = _mm256_load_pd( &A[0+bs*3] ); temp = _mm256_mul_pd( a_00, x_n_3 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_3 = _mm256_add_pd( temp, y_t_3 ); a_00 = _mm256_load_pd( &A[0+bs*4] ); temp = _mm256_mul_pd( a_00, x_n_4 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_4 = _mm256_add_pd( temp, y_t_4 ); a_00 = _mm256_load_pd( &A[0+bs*5] ); A += sda*bs; temp = _mm256_mul_pd( a_00, x_n_5 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_5 = _mm256_add_pd( temp, y_t_5 ); _mm256_storeu_pd( &z_n[4], y_n_0 ); z_n += 8; } for(; k<kmax-3; k+=bs) { __builtin_prefetch( A + sda*bs +bs*0 ); __builtin_prefetch( A + sda*bs +bs*2 ); __builtin_prefetch( A + sda*bs +bs*4 ); y_n_0 = _mm256_loadu_pd( &y_n[0] ); x_t_0 = _mm256_loadu_pd( &x_t[0] ); a_00 = _mm256_load_pd( &A[0+bs*0] ); temp = _mm256_mul_pd( a_00, x_n_0 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_0 = _mm256_add_pd( temp, y_t_0 ); a_00 = _mm256_load_pd( &A[0+bs*1] ); temp = _mm256_mul_pd( a_00, x_n_1 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_1 = _mm256_add_pd( temp, y_t_1 ); a_00 = _mm256_load_pd( &A[0+bs*2] ); temp = _mm256_mul_pd( a_00, x_n_2 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_2 = _mm256_add_pd( temp, y_t_2 ); a_00 = _mm256_load_pd( &A[0+bs*3] ); temp = _mm256_mul_pd( a_00, x_n_3 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_3 = _mm256_add_pd( temp, y_t_3 ); a_00 = _mm256_load_pd( &A[0+bs*4] ); temp = _mm256_mul_pd( a_00, x_n_4 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_4 = _mm256_add_pd( temp, y_t_4 ); a_00 = _mm256_load_pd( &A[0+bs*5] ); temp = _mm256_mul_pd( a_00, x_n_5 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_5 = _mm256_add_pd( temp, y_t_5 ); _mm256_storeu_pd( &z_n[0], y_n_0 ); A += sda*bs; y_n += 4; z_n += 4; x_t += 4; } if(k<kmax) { k_left = kmax-k; v_mask = _mm256_sub_pd( _mm256_loadu_pd( d_mask ), _mm256_broadcast_sd( &k_left ) ); i_mask = _mm256_castpd_si256( v_mask ); y_n_0 = _mm256_loadu_pd( &y_n[0] ); x_t_0 = _mm256_maskload_pd( &x_t[0], i_mask ); a_00 = _mm256_load_pd( &A[0+bs*0] ); temp = _mm256_mul_pd( a_00, x_n_0 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_0 = _mm256_add_pd( temp, y_t_0 ); a_00 = _mm256_load_pd( &A[0+bs*1] ); temp = _mm256_mul_pd( a_00, x_n_1 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_1 = _mm256_add_pd( temp, y_t_1 ); a_00 = _mm256_load_pd( &A[0+bs*2] ); temp = _mm256_mul_pd( a_00, x_n_2 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_2 = _mm256_add_pd( temp, y_t_2 ); a_00 = _mm256_load_pd( &A[0+bs*3] ); temp = _mm256_mul_pd( a_00, x_n_3 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_3 = _mm256_add_pd( temp, y_t_3 ); a_00 = _mm256_load_pd( &A[0+bs*4] ); temp = _mm256_mul_pd( a_00, x_n_4 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_4 = _mm256_add_pd( temp, y_t_4 ); a_00 = _mm256_load_pd( &A[0+bs*5] ); temp = _mm256_mul_pd( a_00, x_n_5 ); y_n_0 = _mm256_add_pd( temp, y_n_0 ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_5 = _mm256_add_pd( temp, y_t_5 ); _mm256_maskstore_pd( &z_n[0], i_mask, y_n_0 ); // A += sda*bs; // y_n += 4; // z_n += 4; // x_t += 4; } __m256d y_0_1_2_3; __m128d tmp, y_0_1; y_t_0 = _mm256_hadd_pd( y_t_0, y_t_1 ); y_t_2 = _mm256_hadd_pd( y_t_2, y_t_3 ); y_t_4 = _mm256_hadd_pd( y_t_4, y_t_5 ); y_t_1 = _mm256_permute2f128_pd( y_t_2, y_t_0, 2 ); y_t_0 = _mm256_permute2f128_pd( y_t_2, y_t_0, 19 ); // y_t_5 = _mm256_permute2f128_pd( zeros, y_t_4, 2 ); // y_t_4 = _mm256_permute2f128_pd( zeros, y_t_4, 19 ); y_t_0 = _mm256_add_pd( y_t_0, y_t_1 ); // y_t_4 = _mm256_add_pd( y_t_5, y_t_4 ); tmp = _mm_add_pd( _mm256_extractf128_pd( y_t_4, 0x1 ) , _mm256_castpd256_pd128( y_t_4 ) ); if(alg_t==1) { y_0_1_2_3 = _mm256_loadu_pd( &y_t[0] ); y_0_1 = _mm_loadu_pd( &y_t[4] ); y_0_1_2_3 = _mm256_add_pd( y_0_1_2_3, y_t_0 ); // y_0_1 = _mm_add_pd( y_0_1, _mm256_castpd256_pd128( y_t_4 ) ); y_0_1 = _mm_add_pd( y_0_1, tmp ); _mm256_storeu_pd( &z_t[0], y_0_1_2_3 ); _mm_storeu_pd( &z_t[4], y_0_1 ); } else // alg_t==-1 { y_0_1_2_3 = _mm256_loadu_pd( &y_t[0] ); y_0_1 = _mm_loadu_pd( &y_t[4] ); y_0_1_2_3 = _mm256_sub_pd( y_0_1_2_3, y_t_0 ); // y_0_1 = _mm_sub_pd( y_0_1, _mm256_castpd256_pd128( y_t_4 ) ); y_0_1 = _mm_sub_pd( y_0_1, tmp ); _mm256_storeu_pd( &z_t[0], y_0_1_2_3 ); _mm_storeu_pd( &z_t[4], y_0_1 ); } } // it moves vertically across blocks void kernel_dsymv_4_lib4(int kmax, double *A, int sda, double *x_n, double *y_n, double *z_n, double *x_t, double *y_t, double *z_t, int tri, int alg_n, int alg_t) { if(kmax<=0) return; /*printf("\nciao %d\n", kmax); */ const int bs = 4; __builtin_prefetch( A + bs*0 ); __builtin_prefetch( A + bs*2 ); int k, ka; ka = kmax; // number from aligned positon double k_left; // double *sA, *sy_n, *sx_t; static double d_mask[4] = {0.5, 1.5, 2.5, 3.5}; __m256d v_mask, zeros, temp, a_00, a_01, a_02, a_03, x_n_0, x_n_1, x_n_2, x_n_3, y_n_0, x_t_0, y_t_0, y_t_1, y_t_2, y_t_3; __m256i i_mask; #if 0 __m128d stemp, sa_00, sa_01, sa_02, sa_03, sx_n_0, sx_n_1, sx_n_2, sx_n_3, sy_n_0, sx_t_0, sy_t_0, sy_t_1, sy_t_2, sy_t_3; #endif zeros = _mm256_setzero_pd(); x_n_0 = _mm256_broadcast_sd( &x_n[0] ); x_n_1 = _mm256_broadcast_sd( &x_n[1] ); x_n_2 = _mm256_broadcast_sd( &x_n[2] ); x_n_3 = _mm256_broadcast_sd( &x_n[3] ); if(alg_n==-1) // TODO xor { x_n_0 = _mm256_sub_pd( zeros, x_n_0 ); x_n_1 = _mm256_sub_pd( zeros, x_n_1 ); x_n_2 = _mm256_sub_pd( zeros, x_n_2 ); x_n_3 = _mm256_sub_pd( zeros, x_n_3 ); } y_t_0 = _mm256_setzero_pd(); y_t_1 = _mm256_setzero_pd(); y_t_2 = _mm256_setzero_pd(); y_t_3 = _mm256_setzero_pd(); #if 0 sx_n_0 = _mm256_castpd256_pd128( x_n_0 ); sx_n_1 = _mm256_castpd256_pd128( x_n_1 ); sx_n_2 = _mm256_castpd256_pd128( x_n_2 ); sx_n_3 = _mm256_castpd256_pd128( x_n_3 ); sy_t_0 = _mm256_castpd256_pd128( y_t_0 ); sy_t_1 = _mm256_castpd256_pd128( y_t_1 ); sy_t_2 = _mm256_castpd256_pd128( y_t_2 ); sy_t_3 = _mm256_castpd256_pd128( y_t_3 ); k = bs*(ka/bs); sA = A + (ka/bs)*sda*bs; sy_n = y_n + (ka/bs)*bs; sx_t = x_t + (ka/bs)*bs; for(; k<ka; k++) { sy_n_0 = _mm_load_sd( &sy_n[0] ); sx_t_0 = _mm_load_sd( &sx_t[0] ); sa_00 = _mm_load_sd( &sA[0+bs*0] ); sa_01 = _mm_load_sd( &sA[0+bs*1] ); sa_02 = _mm_load_sd( &sA[0+bs*2] ); sa_03 = _mm_load_sd( &sA[0+bs*3] ); stemp = _mm_mul_sd( sa_00, sx_n_0 ); sy_n_0 = _mm_add_sd( sy_n_0, stemp ); stemp = _mm_mul_sd( sa_00, sx_t_0 ); sy_t_0 = _mm_add_sd( sy_t_0, stemp ); stemp = _mm_mul_sd( sa_01, sx_n_1 ); sy_n_0 = _mm_add_sd( sy_n_0, stemp ); stemp = _mm_mul_sd( sa_01, sx_t_0 ); sy_t_1 = _mm_add_sd( sy_t_1, stemp ); stemp = _mm_mul_sd( sa_02, sx_n_2 ); sy_n_0 = _mm_add_sd( sy_n_0, stemp ); stemp = _mm_mul_sd( sa_02, sx_t_0 ); sy_t_2 = _mm_add_sd( sy_t_2, stemp ); stemp = _mm_mul_sd( sa_03, sx_n_3 ); sy_n_0 = _mm_add_sd( sy_n_0, stemp ); stemp = _mm_mul_sd( sa_03, sx_t_0 ); sy_t_3 = _mm_add_sd( sy_t_3, stemp ); _mm_store_sd( &sy_n[0], sy_n_0 ); sA += 1; sy_n += 1; sx_t += 1; } y_t_0 = _mm256_castpd128_pd256( sy_t_0 ); y_t_1 = _mm256_castpd128_pd256( sy_t_1 ); y_t_2 = _mm256_castpd128_pd256( sy_t_2 ); y_t_3 = _mm256_castpd128_pd256( sy_t_3 ); #endif k=0; // corner if(tri==1) { __builtin_prefetch( A + sda*bs +bs*0 ); __builtin_prefetch( A + sda*bs +bs*2 ); y_n_0 = _mm256_loadu_pd( &y_n[0] ); x_t_0 = _mm256_loadu_pd( &x_t[0] ); a_00 = _mm256_load_pd( &A[0+bs*0] ); a_01 = _mm256_load_pd( &A[0+bs*1] ); a_02 = _mm256_load_pd( &A[0+bs*2] ); a_03 = _mm256_load_pd( &A[0+bs*3] ); temp = _mm256_mul_pd( a_00, x_n_0 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_00, x_t_0 ); temp = _mm256_blend_pd( zeros, temp, 14 ); y_t_0 = _mm256_add_pd( y_t_0, temp ); temp = _mm256_mul_pd( a_01, x_n_1 ); temp = _mm256_blend_pd( zeros, temp, 14 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_01, x_t_0 ); temp = _mm256_blend_pd( zeros, temp, 12 ); y_t_1 = _mm256_add_pd( y_t_1, temp ); temp = _mm256_mul_pd( a_02, x_n_2 ); temp = _mm256_blend_pd( zeros, temp, 12 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_02, x_t_0 ); temp = _mm256_blend_pd( zeros, temp, 8 ); y_t_2 = _mm256_add_pd( y_t_2, temp ); temp = _mm256_mul_pd( a_03, x_n_3 ); temp = _mm256_blend_pd( zeros, temp, 8 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); _mm256_storeu_pd( &z_n[0], y_n_0 ); A += sda*bs; y_n += 4; z_n += 4; x_t += 4; k += 4; } for(; k<ka-7; k+=2*bs) { __builtin_prefetch( A + sda*bs +bs*0 ); __builtin_prefetch( A + sda*bs +bs*2 ); y_n_0 = _mm256_loadu_pd( &y_n[0] ); x_t_0 = _mm256_loadu_pd( &x_t[0] ); a_00 = _mm256_load_pd( &A[0+bs*0] ); a_01 = _mm256_load_pd( &A[0+bs*1] ); a_02 = _mm256_load_pd( &A[0+bs*2] ); a_03 = _mm256_load_pd( &A[0+bs*3] ); temp = _mm256_mul_pd( a_00, x_n_0 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_0 = _mm256_add_pd( y_t_0, temp ); temp = _mm256_mul_pd( a_01, x_n_1 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_01, x_t_0 ); y_t_1 = _mm256_add_pd( y_t_1, temp ); temp = _mm256_mul_pd( a_02, x_n_2 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_02, x_t_0 ); y_t_2 = _mm256_add_pd( y_t_2, temp ); temp = _mm256_mul_pd( a_03, x_n_3 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_03, x_t_0 ); y_t_3 = _mm256_add_pd( y_t_3, temp ); _mm256_storeu_pd( &z_n[0], y_n_0 ); A += sda*bs; y_n += 4; z_n += 4; x_t += 4; __builtin_prefetch( A + sda*bs +bs*0 ); __builtin_prefetch( A + sda*bs +bs*2 ); y_n_0 = _mm256_loadu_pd( &y_n[0] ); x_t_0 = _mm256_loadu_pd( &x_t[0] ); a_00 = _mm256_load_pd( &A[0+bs*0] ); a_01 = _mm256_load_pd( &A[0+bs*1] ); a_02 = _mm256_load_pd( &A[0+bs*2] ); a_03 = _mm256_load_pd( &A[0+bs*3] ); temp = _mm256_mul_pd( a_00, x_n_0 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_0 = _mm256_add_pd( y_t_0, temp ); temp = _mm256_mul_pd( a_01, x_n_1 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_01, x_t_0 ); y_t_1 = _mm256_add_pd( y_t_1, temp ); temp = _mm256_mul_pd( a_02, x_n_2 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_02, x_t_0 ); y_t_2 = _mm256_add_pd( y_t_2, temp ); temp = _mm256_mul_pd( a_03, x_n_3 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_03, x_t_0 ); y_t_3 = _mm256_add_pd( y_t_3, temp ); _mm256_storeu_pd( &z_n[0], y_n_0 ); A += sda*bs; y_n += 4; z_n += 4; x_t += 4; } for(; k<ka-3; k+=bs) { __builtin_prefetch( A + sda*bs +bs*0 ); __builtin_prefetch( A + sda*bs +bs*2 ); y_n_0 = _mm256_loadu_pd( &y_n[0] ); x_t_0 = _mm256_loadu_pd( &x_t[0] ); a_00 = _mm256_load_pd( &A[0+bs*0] ); a_01 = _mm256_load_pd( &A[0+bs*1] ); a_02 = _mm256_load_pd( &A[0+bs*2] ); a_03 = _mm256_load_pd( &A[0+bs*3] ); temp = _mm256_mul_pd( a_00, x_n_0 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_0 = _mm256_add_pd( y_t_0, temp ); temp = _mm256_mul_pd( a_01, x_n_1 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_01, x_t_0 ); y_t_1 = _mm256_add_pd( y_t_1, temp ); temp = _mm256_mul_pd( a_02, x_n_2 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_02, x_t_0 ); y_t_2 = _mm256_add_pd( y_t_2, temp ); temp = _mm256_mul_pd( a_03, x_n_3 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_03, x_t_0 ); y_t_3 = _mm256_add_pd( y_t_3, temp ); _mm256_storeu_pd( &z_n[0], y_n_0 ); A += sda*bs; y_n += 4; z_n += 4; x_t += 4; } if(k<ka) { k_left = ka-k; v_mask = _mm256_sub_pd( _mm256_loadu_pd( d_mask ), _mm256_broadcast_sd( &k_left ) ); i_mask = _mm256_castpd_si256( v_mask ); // __builtin_prefetch( A + sda*bs +bs*0 ); // __builtin_prefetch( A + sda*bs +bs*2 ); y_n_0 = _mm256_loadu_pd( &y_n[0] ); x_t_0 = _mm256_maskload_pd( &x_t[0], i_mask ); a_00 = _mm256_load_pd( &A[0+bs*0] ); a_01 = _mm256_load_pd( &A[0+bs*1] ); a_02 = _mm256_load_pd( &A[0+bs*2] ); a_03 = _mm256_load_pd( &A[0+bs*3] ); temp = _mm256_mul_pd( a_00, x_n_0 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_00, x_t_0 ); y_t_0 = _mm256_add_pd( y_t_0, temp ); temp = _mm256_mul_pd( a_01, x_n_1 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_01, x_t_0 ); y_t_1 = _mm256_add_pd( y_t_1, temp ); temp = _mm256_mul_pd( a_02, x_n_2 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_02, x_t_0 ); y_t_2 = _mm256_add_pd( y_t_2, temp ); temp = _mm256_mul_pd( a_03, x_n_3 ); y_n_0 = _mm256_add_pd( y_n_0, temp ); temp = _mm256_mul_pd( a_03, x_t_0 ); y_t_3 = _mm256_add_pd( y_t_3, temp ); _mm256_maskstore_pd( &z_n[0], i_mask, y_n_0 ); // A += sda*bs; // y_n += 4; // z_n += 4; // x_t += 4; } __m256d y_0_1_2_3; y_t_0 = _mm256_hadd_pd( y_t_0, y_t_1 ); y_t_2 = _mm256_hadd_pd( y_t_2, y_t_3 ); y_t_1 = _mm256_permute2f128_pd( y_t_2, y_t_0, 2 ); y_t_0 = _mm256_permute2f128_pd( y_t_2, y_t_0, 19 ); y_t_0 = _mm256_add_pd( y_t_0, y_t_1 ); if(alg_t==1) { y_0_1_2_3 = _mm256_loadu_pd( &y_t[0] ); y_0_1_2_3 = _mm256_add_pd( y_0_1_2_3, y_t_0 ); _mm256_storeu_pd( &z_t[0], y_0_1_2_3 ); } else // alg_t==-1 { y_0_1_2_3 = _mm256_loadu_pd( &y_t[0] ); y_0_1_2_3 = _mm256_sub_pd( y_0_1_2_3, y_t_0 ); _mm256_storeu_pd( &z_t[0], y_0_1_2_3 ); } } void kernel_dsymv_3_lib4(int kmax, double *A, int sda, double *x_n, double *y_n, double *z_n, double *x_t, double *y_t, double *z_t, int tri, int alg_n, int alg_t) { if(kmax<=0) return; const int bs = 4; int k; double a_00, a_01, a_02, x_n_0, x_n_1, x_n_2, y_n_0, x_t_0, y_t_0, y_t_1, y_t_2; if(alg_n==1) { x_n_0 = x_n[0]; x_n_1 = x_n[1]; x_n_2 = x_n[2]; } else // alg_n==-1 { x_n_0 = - x_n[0]; x_n_1 = - x_n[1]; x_n_2 = - x_n[2]; } y_t_0 = 0; y_t_1 = 0; y_t_2 = 0; k=0; // corner if(tri==1) { y_n_0 = y_n[0]; x_t_0 = x_t[0]; a_00 = A[0+bs*0]; y_t_0 += a_00 * x_t_0; z_n[0] = y_n_0; y_n_0 = y_n[1]; x_t_0 = x_t[1]; a_00 = A[1+bs*0]; a_01 = A[1+bs*1]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; y_t_1 += a_01 * x_t_0; z_n[1] = y_n_0; y_n_0 = y_n[2]; x_t_0 = x_t[2]; a_00 = A[2+bs*0]; a_01 = A[2+bs*1]; a_02 = A[2+bs*2]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; y_n_0 += a_01 * x_n_1; y_t_1 += a_01 * x_t_0; y_t_2 += a_02 * x_t_0; z_n[2] = y_n_0; if(kmax==3) goto STORE_3; y_n_0 = y_n[3]; x_t_0 = x_t[3]; a_00 = A[3+bs*0]; a_01 = A[3+bs*1]; a_02 = A[3+bs*2]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; y_n_0 += a_01 * x_n_1; y_t_1 += a_01 * x_t_0; y_n_0 += a_02 * x_n_2; y_t_2 += a_02 * x_t_0; z_n[3] = y_n_0; if(kmax==4) goto STORE_3; A += 4; y_n += 4; z_n += 4; x_t += 4; k += 4; A += (sda-1)*bs; } for(; k<kmax-3; k+=bs) { y_n_0 = y_n[0]; x_t_0 = x_t[0]; a_00 = A[0+bs*0]; a_01 = A[0+bs*1]; a_02 = A[0+bs*2]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; y_n_0 += a_01 * x_n_1; y_t_1 += a_01 * x_t_0; y_n_0 += a_02 * x_n_2; y_t_2 += a_02 * x_t_0; z_n[0] = y_n_0; y_n_0 = y_n[1]; x_t_0 = x_t[1]; a_00 = A[1+bs*0]; a_01 = A[1+bs*1]; a_02 = A[1+bs*2]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; y_n_0 += a_01 * x_n_1; y_t_1 += a_01 * x_t_0; y_n_0 += a_02 * x_n_2; y_t_2 += a_02 * x_t_0; z_n[1] = y_n_0; y_n_0 = y_n[2]; x_t_0 = x_t[2]; a_00 = A[2+bs*0]; a_01 = A[2+bs*1]; a_02 = A[2+bs*2]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; y_n_0 += a_01 * x_n_1; y_t_1 += a_01 * x_t_0; y_n_0 += a_02 * x_n_2; y_t_2 += a_02 * x_t_0; z_n[2] = y_n_0; y_n_0 = y_n[3]; x_t_0 = x_t[3]; a_00 = A[3+bs*0]; a_01 = A[3+bs*1]; a_02 = A[3+bs*2]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; y_n_0 += a_01 * x_n_1; y_t_1 += a_01 * x_t_0; y_n_0 += a_02 * x_n_2; y_t_2 += a_02 * x_t_0; z_n[3] = y_n_0; A += sda*bs; y_n += 4; z_n += 4; x_t += 4; } for(; k<kmax; k++) { y_n_0 = y_n[0]; x_t_0 = x_t[0]; a_00 = A[0+bs*0]; a_01 = A[0+bs*1]; a_02 = A[0+bs*2]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; y_n_0 += a_01 * x_n_1; y_t_1 += a_01 * x_t_0; y_n_0 += a_02 * x_n_2; y_t_2 += a_02 * x_t_0; z_n[0] = y_n_0; A += 1; y_n += 1; z_n += 1; x_t += 1; } STORE_3: if(alg_t==1) { z_t[0] = y_t[0] + y_t_0; z_t[1] = y_t[1] + y_t_1; z_t[2] = y_t[2] + y_t_2; } else // alg_t==-1 { z_t[0] = y_t[0] - y_t_0; z_t[1] = y_t[1] - y_t_1; z_t[2] = y_t[2] - y_t_2; } } void kernel_dsymv_2_lib4(int kmax, double *A, int sda, double *x_n, double *y_n, double *z_n, double *x_t, double *y_t, double *z_t, int tri, int alg_n, int alg_t) { if(kmax<=0) return; const int bs = 4; int k; double a_00, a_01, x_n_0, x_n_1, y_n_0, x_t_0, y_t_0, y_t_1; if(alg_n==1) { x_n_0 = x_n[0]; x_n_1 = x_n[1]; } else // alg_n==-1 { x_n_0 = - x_n[0]; x_n_1 = - x_n[1]; } y_t_0 = 0; y_t_1 = 0; k=0; // corner if(tri==1) { y_n_0 = y_n[0]; x_t_0 = x_t[0]; a_00 = A[0+bs*0]; y_t_0 += a_00 * x_t_0; z_n[0] = y_n_0; y_n_0 = y_n[1]; x_t_0 = x_t[1]; a_00 = A[1+bs*0]; a_01 = A[1+bs*1]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; y_t_1 += a_01 * x_t_0; z_n[1] = y_n_0; if(kmax==2) goto STORE_2; y_n_0 = y_n[2]; x_t_0 = x_t[2]; a_00 = A[2+bs*0]; a_01 = A[2+bs*1]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; y_n_0 += a_01 * x_n_1; y_t_1 += a_01 * x_t_0; z_n[2] = y_n_0; if(kmax==3) goto STORE_2; y_n_0 = y_n[3]; x_t_0 = x_t[3]; a_00 = A[3+bs*0]; a_01 = A[3+bs*1]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; y_n_0 += a_01 * x_n_1; y_t_1 += a_01 * x_t_0; z_n[3] = y_n_0; if(kmax==4) goto STORE_2; A += 4; y_n += 4; z_n += 4; x_t += 4; k += 4; A += (sda-1)*bs; } for(; k<kmax-3; k+=bs) { y_n_0 = y_n[0]; x_t_0 = x_t[0]; a_00 = A[0+bs*0]; a_01 = A[0+bs*1]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; y_n_0 += a_01 * x_n_1; y_t_1 += a_01 * x_t_0; z_n[0] = y_n_0; y_n_0 = y_n[1]; x_t_0 = x_t[1]; a_00 = A[1+bs*0]; a_01 = A[1+bs*1]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; y_n_0 += a_01 * x_n_1; y_t_1 += a_01 * x_t_0; z_n[1] = y_n_0; y_n_0 = y_n[2]; x_t_0 = x_t[2]; a_00 = A[2+bs*0]; a_01 = A[2+bs*1]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; y_n_0 += a_01 * x_n_1; y_t_1 += a_01 * x_t_0; z_n[2] = y_n_0; y_n_0 = y_n[3]; x_t_0 = x_t[3]; a_00 = A[3+bs*0]; a_01 = A[3+bs*1]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; y_n_0 += a_01 * x_n_1; y_t_1 += a_01 * x_t_0; z_n[3] = y_n_0; A += sda*bs; y_n += 4; z_n += 4; x_t += 4; } for(; k<kmax; k++) { y_n_0 = y_n[0]; x_t_0 = x_t[0]; a_00 = A[0+bs*0]; a_01 = A[0+bs*1]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; y_n_0 += a_01 * x_n_1; y_t_1 += a_01 * x_t_0; z_n[0] = y_n_0; A += 1; y_n += 1; z_n += 1; x_t += 1; } STORE_2: if(alg_t==1) { z_t[0] = y_t[0] + y_t_0; z_t[1] = y_t[1] + y_t_1; } else // alg_t==-1 { z_t[0] = y_t[0] - y_t_0; z_t[1] = y_t[1] - y_t_1; } } void kernel_dsymv_1_lib4(int kmax, double *A, int sda, double *x_n, double *y_n, double *z_n, double *x_t, double *y_t, double *z_t, int tri, int alg_n, int alg_t) { if(kmax<=0) return; const int bs = 4; int k; double a_00, x_n_0, y_n_0, x_t_0, y_t_0; if(alg_n==1) { x_n_0 = x_n[0]; } else // alg_n==-1 { x_n_0 = - x_n[0]; } y_t_0 = 0; k=0; // corner if(tri==1) { x_t_0 = x_t[0]; a_00 = A[0+bs*0]; y_t_0 += a_00 * x_t_0; if(kmax==1) goto STORE_1; y_n_0 = y_n[1]; x_t_0 = x_t[1]; a_00 = A[1+bs*0]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; z_n[1] = y_n_0; if(kmax==2) goto STORE_1; y_n_0 = y_n[2]; x_t_0 = x_t[2]; a_00 = A[2+bs*0]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; z_n[2] = y_n_0; if(kmax==3) goto STORE_1; y_n_0 = y_n[3]; x_t_0 = x_t[3]; a_00 = A[3+bs*0]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; z_n[3] = y_n_0; if(kmax==4) goto STORE_1; A += 4; y_n += 4; z_n += 4; x_t += 4; k += 4; A += (sda-1)*bs; } for(; k<kmax-3; k+=bs) { y_n_0 = y_n[0]; x_t_0 = x_t[0]; a_00 = A[0+bs*0]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; z_n[0] = y_n_0; y_n_0 = y_n[1]; x_t_0 = x_t[1]; a_00 = A[1+bs*0]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; z_n[1] = y_n_0; y_n_0 = y_n[2]; x_t_0 = x_t[2]; a_00 = A[2+bs*0]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; z_n[2] = y_n_0; y_n_0 = y_n[3]; x_t_0 = x_t[3]; a_00 = A[3+bs*0]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; z_n[3] = y_n_0; A += sda*bs; y_n += 4; z_n += 4; x_t += 4; } for(; k<kmax; k++) { y_n_0 = y_n[0]; x_t_0 = x_t[0]; a_00 = A[0+bs*0]; y_n_0 += a_00 * x_n_0; y_t_0 += a_00 * x_t_0; z_n[0] = y_n_0; A += 1; y_n += 1; z_n += 1; x_t += 1; } STORE_1: if(alg_t==1) { z_t[0] = y_t[0] + y_t_0; } else // alg_t==-1 { z_t[0] = y_t[0] - y_t_0; } } #endif
lgpl-2.1
vathpela/fwupd
src/fu-udev-device.h
1225
/* * Copyright (C) 2017-2019 Richard Hughes <richard@hughsie.com> * * SPDX-License-Identifier: LGPL-2.1+ */ #pragma once #include <glib-object.h> #include <gudev/gudev.h> #include "fu-plugin.h" G_BEGIN_DECLS #define FU_TYPE_UDEV_DEVICE (fu_udev_device_get_type ()) G_DECLARE_DERIVABLE_TYPE (FuUdevDevice, fu_udev_device, FU, UDEV_DEVICE, FuDevice) struct _FuUdevDeviceClass { FuDeviceClass parent_class; gboolean (*probe) (FuUdevDevice *device, GError **error); gpointer __reserved[31]; }; FuUdevDevice *fu_udev_device_new (GUdevDevice *udev_device); GUdevDevice *fu_udev_device_get_dev (FuUdevDevice *self); const gchar *fu_udev_device_get_sysfs_path (FuUdevDevice *self); const gchar *fu_udev_device_get_subsystem (FuUdevDevice *self); guint16 fu_udev_device_get_vendor (FuUdevDevice *self); guint16 fu_udev_device_get_model (FuUdevDevice *self); guint8 fu_udev_device_get_revision (FuUdevDevice *self); guint fu_udev_device_get_slot_depth (FuUdevDevice *self, const gchar *subsystem); gboolean fu_udev_device_set_physical_id (FuUdevDevice *self, const gchar *subsystem, GError **error); void fu_udev_device_dump (FuUdevDevice *self); G_END_DECLS
lgpl-2.1
Web5design/libvips
libvips/draw/drawink.c
3329
/* drawink with a constant ink * * 27/9/10 * - from im_drawink_circle() * 17/11/10 * - oops, scanline clipping was off by 1 */ /* This file is part of VIPS. VIPS 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 */ /* These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk */ #ifdef HAVE_CONFIG_H #include <config.h> #endif /*HAVE_CONFIG_H*/ #include <vips/intl.h> #include <string.h> #include <vips/vips.h> #include <vips/internal.h> #include "drawink.h" G_DEFINE_ABSTRACT_TYPE( VipsDrawink, vips_drawink, VIPS_TYPE_DRAW ); static int vips_drawink_build( VipsObject *object ) { VipsObjectClass *class = VIPS_OBJECT_GET_CLASS( object ); VipsDraw *draw = VIPS_DRAW( object ); VipsDrawink *drawink = VIPS_DRAWINK( object ); #ifdef DEBUG printf( "vips_drawink_build: " ); vips_object_print_name( object ); printf( "\n" ); #endif /*DEBUG*/ if( VIPS_OBJECT_CLASS( vips_drawink_parent_class )->build( object ) ) return( -1 ); if( drawink->ink && !(drawink->pixel_ink = vips__vector_to_ink( class->nickname, draw->image, drawink->ink->data, NULL, drawink->ink->n )) ) return( -1 ); return( 0 ); } static void vips_drawink_class_init( VipsDrawinkClass *class ) { GObjectClass *gobject_class = G_OBJECT_CLASS( class ); VipsObjectClass *vobject_class = VIPS_OBJECT_CLASS( class ); gobject_class->set_property = vips_object_set_property; gobject_class->get_property = vips_object_get_property; vobject_class->nickname = "drawink"; vobject_class->description = _( "Draw with ink operations" ); vobject_class->build = vips_drawink_build; VIPS_ARG_BOXED( class, "ink", 2, _( "Ink" ), _( "Colour for pixels" ), VIPS_ARGUMENT_REQUIRED_INPUT, G_STRUCT_OFFSET( VipsDrawink, ink ), VIPS_TYPE_ARRAY_DOUBLE ); } static void vips_drawink_init( VipsDrawink *drawink ) { drawink->ink = vips_area_new_array( G_TYPE_DOUBLE, sizeof( double ), 1 ); ((double *) (drawink->ink->data))[0] = 0; } /* Fill a scanline between points x1 and x2 inclusive. x1 < x2. */ void vips__drawink_scanline( VipsDrawink *drawink, int y, int x1, int x2 ) { VipsDraw *draw = (VipsDraw *) drawink; VipsPel *mp; int i; int len; g_assert( x1 <= x2 ); if( y < 0 || y >= draw->image->Ysize ) return; if( x1 < 0 && x2 < 0 ) return; if( x1 >= draw->image->Xsize && x2 >= draw->image->Xsize ) return; x1 = VIPS_CLIP( 0, x1, draw->image->Xsize - 1 ); x2 = VIPS_CLIP( 0, x2, draw->image->Xsize - 1 ); mp = VIPS_IMAGE_ADDR( draw->image, x1, y ); len = x2 - x1 + 1; for( i = 0; i < len; i++ ) { vips__drawink_pel( drawink, mp ); mp += draw->psize; } }
lgpl-2.1
ironjacamar/ironjacamar
sjc/src/main/java/org/jboss/jca/sjc/maven/Deploy.java
3793
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2012, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.jca.sjc.maven; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.Serializable; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; /** * A deploy mojo * @author <a href="mailto:jesper.pedersen@ironjacamar.org">Jesper Pedersen</a> */ public class Deploy extends AbstractHostPortMojo { /** The file */ private File file; /** * Constructor */ public Deploy() { this.file = null; } /** * Set the file * @param v The value */ public void setFile(File v) { file = v; } /** * {@inheritDoc} */ public void execute() throws MojoExecutionException, MojoFailureException { if (file == null) throw new MojoFailureException("File not defined"); if (!file.exists()) throw new MojoFailureException("File doesn't exists: " + file); FileInputStream fis = null; try { Boolean result = null; if (isLocal()) { Object value = executeCommand("local-deploy", new Serializable[] {file.toURI().toURL()}); if (value instanceof Boolean) { result = (Boolean)value; } else { throw (Throwable)value; } } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); fis = new FileInputStream(file); int i = fis.read(); while (i != -1) { baos.write(i); i = fis.read(); } byte[] bytes = baos.toByteArray(); Object value = executeCommand("remote-deploy", new Serializable[] {file.getName(), bytes}); if (value instanceof Boolean) { result = (Boolean)value; } else { throw (Throwable)value; } } if (result.booleanValue()) { getLog().info("Deployed: " + file.getName()); } else { getLog().info(file.getName() + " wasn't deployed"); } } catch (Throwable t) { throw new MojoFailureException("Unable to deploy to " + getHost() + ":" + getPort() + " (" + t.getMessage() + ")", t); } finally { if (fis != null) { try { fis.close(); } catch (IOException ioe) { // Ignore } } } } }
lgpl-2.1
MenesesEvandro/WCF
wcfsetup/install/files/lib/system/option/user/group/TextUserGroupOptionType.class.php
921
<?php namespace wcf\system\option\user\group; use wcf\system\option\TextOptionType; use wcf\util\StringUtil; /** * User group option type implementation for textual input fields. * * The merge of option values returns merge of all text values. * * @author Marcel Werk * @copyright 2001-2019 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Option\User\Group */ class TextUserGroupOptionType extends TextOptionType implements IUserGroupOptionType { /** * @inheritDoc */ public function merge($defaultValue, $groupValue) { $defaultValue = empty($defaultValue) ? [] : explode("\n", StringUtil::unifyNewlines($defaultValue)); $groupValue = empty($groupValue) ? [] : explode("\n", StringUtil::unifyNewlines($groupValue)); return implode("\n", array_unique(array_merge($defaultValue, $groupValue))); } }
lgpl-2.1
Oslandia/horao
src/poly2tri/common/shapes.cc
9354
/* * Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "shapes.h" #include <iostream> #include <stdexcept> namespace p2t { Triangle::Triangle(Point& a, Point& b, Point& c) { points_[0] = &a; points_[1] = &b; points_[2] = &c; neighbors_[0] = NULL; neighbors_[1] = NULL; neighbors_[2] = NULL; constrained_edge[0] = constrained_edge[1] = constrained_edge[2] = false; delaunay_edge[0] = delaunay_edge[1] = delaunay_edge[2] = false; interior_ = false; } // Update neighbor pointers void Triangle::MarkNeighbor(Point* p1, Point* p2, Triangle* t) { if ((p1 == points_[2] && p2 == points_[1]) || (p1 == points_[1] && p2 == points_[2])) neighbors_[0] = t; else if ((p1 == points_[0] && p2 == points_[2]) || (p1 == points_[2] && p2 == points_[0])) neighbors_[1] = t; else if ((p1 == points_[0] && p2 == points_[1]) || (p1 == points_[1] && p2 == points_[0])) neighbors_[2] = t; else throw std::runtime_error("failed to MarkNeighbor"); } // Exhaustive search to update neighbor pointers void Triangle::MarkNeighbor(Triangle& t) { if (t.Contains(points_[1], points_[2])) { neighbors_[0] = &t; t.MarkNeighbor(points_[1], points_[2], this); } else if (t.Contains(points_[0], points_[2])) { neighbors_[1] = &t; t.MarkNeighbor(points_[0], points_[2], this); } else if (t.Contains(points_[0], points_[1])) { neighbors_[2] = &t; t.MarkNeighbor(points_[0], points_[1], this); } } /** * Clears all references to all other triangles and points */ void Triangle::Clear() { Triangle *t; for( int i=0; i<3; i++ ) { t = neighbors_[i]; if( t != NULL ) { t->ClearNeighbor( this ); } } ClearNeighbors(); points_[0]=points_[1]=points_[2] = NULL; } void Triangle::ClearNeighbor(Triangle *triangle ) { if( neighbors_[0] == triangle ) { neighbors_[0] = NULL; } else if( neighbors_[1] == triangle ) { neighbors_[1] = NULL; } else { neighbors_[2] = NULL; } } void Triangle::ClearNeighbors() { neighbors_[0] = NULL; neighbors_[1] = NULL; neighbors_[2] = NULL; } void Triangle::ClearDelunayEdges() { delaunay_edge[0] = delaunay_edge[1] = delaunay_edge[2] = false; } Point* Triangle::OppositePoint(Triangle& t, Point& p) { Point *cw = t.PointCW(p); //double x = cw->x; //double y = cw->y; //x = p.x; //y = p.y; assert(cw); return PointCW(*cw); } // Legalized triangle by rotating clockwise around point(0) void Triangle::Legalize(Point& point) { points_[1] = points_[0]; points_[0] = points_[2]; points_[2] = &point; } // Legalize triagnle by rotating clockwise around oPoint void Triangle::Legalize(Point& opoint, Point& npoint) { if (&opoint == points_[0]) { points_[1] = points_[0]; points_[0] = points_[2]; points_[2] = &npoint; } else if (&opoint == points_[1]) { points_[2] = points_[1]; points_[1] = points_[0]; points_[0] = &npoint; } else if (&opoint == points_[2]) { points_[0] = points_[2]; points_[2] = points_[1]; points_[1] = &npoint; } else { throw std::runtime_error("failed to Legalize"); } } int Triangle::Index(const Point* p) { if (p == points_[0]) { return 0; } else if (p == points_[1]) { return 1; } else if (p == points_[2]) { return 2; } throw std::runtime_error("failed to Index"); } int Triangle::EdgeIndex(const Point* p1, const Point* p2) { if (points_[0] == p1) { if (points_[1] == p2) { return 2; } else if (points_[2] == p2) { return 1; } } else if (points_[1] == p1) { if (points_[2] == p2) { return 0; } else if (points_[0] == p2) { return 2; } } else if (points_[2] == p1) { if (points_[0] == p2) { return 1; } else if (points_[1] == p2) { return 0; } } return -1; } void Triangle::MarkConstrainedEdge(const int index) { constrained_edge[index] = true; } void Triangle::MarkConstrainedEdge(Edge& edge) { MarkConstrainedEdge(edge.p, edge.q); } // Mark edge as constrained void Triangle::MarkConstrainedEdge(Point* p, Point* q) { if ((q == points_[0] && p == points_[1]) || (q == points_[1] && p == points_[0])) { constrained_edge[2] = true; } else if ((q == points_[0] && p == points_[2]) || (q == points_[2] && p == points_[0])) { constrained_edge[1] = true; } else if ((q == points_[1] && p == points_[2]) || (q == points_[2] && p == points_[1])) { constrained_edge[0] = true; } } // The point counter-clockwise to given point Point* Triangle::PointCW(Point& point) { if (&point == points_[0]) { return points_[2]; } else if (&point == points_[1]) { return points_[0]; } else if (&point == points_[2]) { return points_[1]; } throw std::runtime_error("failed in PointCW"); } // The point counter-clockwise to given point Point* Triangle::PointCCW(Point& point) { if (&point == points_[0]) { return points_[1]; } else if (&point == points_[1]) { return points_[2]; } else if (&point == points_[2]) { return points_[0]; } throw std::runtime_error("failed in PointCCW"); } // The neighbor clockwise to given point Triangle* Triangle::NeighborCW(Point& point) { if (&point == points_[0]) { return neighbors_[1]; } else if (&point == points_[1]) { return neighbors_[2]; } return neighbors_[0]; } // The neighbor counter-clockwise to given point Triangle* Triangle::NeighborCCW(Point& point) { if (&point == points_[0]) { return neighbors_[2]; } else if (&point == points_[1]) { return neighbors_[0]; } return neighbors_[1]; } bool Triangle::GetConstrainedEdgeCCW(Point& p) { if (&p == points_[0]) { return constrained_edge[2]; } else if (&p == points_[1]) { return constrained_edge[0]; } return constrained_edge[1]; } bool Triangle::GetConstrainedEdgeCW(Point& p) { if (&p == points_[0]) { return constrained_edge[1]; } else if (&p == points_[1]) { return constrained_edge[2]; } return constrained_edge[0]; } void Triangle::SetConstrainedEdgeCCW(Point& p, bool ce) { if (&p == points_[0]) { constrained_edge[2] = ce; } else if (&p == points_[1]) { constrained_edge[0] = ce; } else { constrained_edge[1] = ce; } } void Triangle::SetConstrainedEdgeCW(Point& p, bool ce) { if (&p == points_[0]) { constrained_edge[1] = ce; } else if (&p == points_[1]) { constrained_edge[2] = ce; } else { constrained_edge[0] = ce; } } bool Triangle::GetDelunayEdgeCCW(Point& p) { if (&p == points_[0]) { return delaunay_edge[2]; } else if (&p == points_[1]) { return delaunay_edge[0]; } return delaunay_edge[1]; } bool Triangle::GetDelunayEdgeCW(Point& p) { if (&p == points_[0]) { return delaunay_edge[1]; } else if (&p == points_[1]) { return delaunay_edge[2]; } return delaunay_edge[0]; } void Triangle::SetDelunayEdgeCCW(Point& p, bool e) { if (&p == points_[0]) { delaunay_edge[2] = e; } else if (&p == points_[1]) { delaunay_edge[0] = e; } else { delaunay_edge[1] = e; } } void Triangle::SetDelunayEdgeCW(Point& p, bool e) { if (&p == points_[0]) { delaunay_edge[1] = e; } else if (&p == points_[1]) { delaunay_edge[2] = e; } else { delaunay_edge[0] = e; } } // The neighbor across to given point Triangle& Triangle::NeighborAcross(Point& opoint) { if (&opoint == points_[0]) { return *neighbors_[0]; } else if (&opoint == points_[1]) { return *neighbors_[1]; } return *neighbors_[2]; } void Triangle::DebugPrint() { using namespace std; cout << points_[0]->x << "," << points_[0]->y << " "; cout << points_[1]->x << "," << points_[1]->y << " "; cout << points_[2]->x << "," << points_[2]->y << endl; } }
lgpl-2.1
spaghettidba/ExtendedTSQLCollector
ExtendedTSQLCollector/Common/Properties/AssemblyInfo.cs
1388
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Common")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Common")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("15fcb70e-9a51-4d36-a2bc-51541204eebe")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
lgpl-2.1
richardmg/qtcreator
src/plugins/git/branchdialog.h
2551
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #ifndef BRANCHDIALOG_H #define BRANCHDIALOG_H #include <QDialog> QT_BEGIN_NAMESPACE class QModelIndex; QT_END_NAMESPACE namespace Git { namespace Internal { namespace Ui { class BranchDialog; } class BranchAddDialog; class BranchModel; /** * Branch dialog. Displays a list of local branches at the top and remote * branches below. Offers to checkout/delete local branches. * */ class BranchDialog : public QDialog { Q_OBJECT public: explicit BranchDialog(QWidget *parent = 0); ~BranchDialog(); public slots: void refresh(const QString &repository, bool force); void refreshIfSame(const QString &repository); private slots: void enableButtons(); void refresh(); void add(); void checkout(); void remove(); void rename(); void diff(); void log(); void merge(); void rebase(); void cherryPick(); void setRemoteTracking(); private: QModelIndex selectedIndex(); Ui::BranchDialog *m_ui; BranchModel *m_model; QString m_repository; }; } // namespace Internal } // namespace Git #endif // BRANCHDIALOG_H
lgpl-2.1
KDE/android-qt-creator
src/plugins/debugger/lldb/lldbenginehost.cpp
7149
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #define QT_NO_CAST_FROM_ASCII #include "lldbenginehost.h" #include "debuggerstartparameters.h" #include "debuggeractions.h" #include "debuggerconstants.h" #include "debuggerdialogs.h" #include "debuggerplugin.h" #include "debuggerstringutils.h" #include "breakhandler.h" #include "breakpoint.h" #include "moduleshandler.h" #include "registerhandler.h" #include "stackhandler.h" #include "watchhandler.h" #include "watchutils.h" #include "threadshandler.h" #include "disassembleragent.h" #include "memoryagent.h" #include <coreplugin/icore.h> #include <utils/qtcassert.h> #include <QDebug> #include <QProcess> #include <QFileInfo> #include <QThread> #include <QCoreApplication> namespace Debugger { namespace Internal { SshIODevice::SshIODevice(QSsh::SshRemoteProcessRunner *r) : runner(r) , buckethead(0) { setOpenMode(QIODevice::ReadWrite | QIODevice::Unbuffered); connect (runner, SIGNAL(processStarted()), this, SLOT(processStarted())); connect(runner, SIGNAL(readyReadStandardOutput()), this, SLOT(outputAvailable())); connect(runner, SIGNAL(readyReadStandardError()), this, SLOT(errorOutputAvailable())); } SshIODevice::~SshIODevice() { delete runner; } qint64 SshIODevice::bytesAvailable () const { qint64 r = QIODevice::bytesAvailable(); foreach (const QByteArray &bucket, buckets) r += bucket.size(); r-= buckethead; return r; } qint64 SshIODevice::writeData (const char * data, qint64 maxSize) { if (proc == 0) { startupbuffer += QByteArray::fromRawData(data, maxSize); return maxSize; } proc->write(data, maxSize); return maxSize; } qint64 SshIODevice::readData (char * data, qint64 maxSize) { if (proc == 0) return 0; qint64 size = maxSize; while (size > 0) { if (!buckets.size()) { return maxSize - size; } QByteArray &bucket = buckets.head(); if ((size + buckethead) >= bucket.size()) { int d = bucket.size() - buckethead; memcpy(data, bucket.data() + buckethead, d); data += d; size -= d; buckets.dequeue(); buckethead = 0; } else { memcpy(data, bucket.data() + buckethead, size); data += size; buckethead += size; size = 0; } } return maxSize - size; } void SshIODevice::processStarted() { runner->writeDataToProcess(startupbuffer); } void SshIODevice::outputAvailable() { buckets.enqueue(runner->readAllStandardOutput()); emit readyRead(); } void SshIODevice::errorOutputAvailable() { fprintf(stderr, "%s", runner->readAllStandardError().data()); } LldbEngineHost::LldbEngineHost(const DebuggerStartParameters &startParameters) :IPCEngineHost(startParameters), m_ssh(0) { showMessage(QLatin1String("setting up coms")); if (startParameters.startMode == StartRemoteEngine) { m_guestProcess = 0; QSsh::SshRemoteProcessRunner * const runner = new QSsh::SshRemoteProcessRunner; connect (runner, SIGNAL(connectionError(QSsh::SshError)), this, SLOT(sshConnectionError(QSsh::SshError))); runner->run(startParameters.serverStartScript.toUtf8(), startParameters.connParams); setGuestDevice(new SshIODevice(runner)); } else { m_guestProcess = new QProcess(this); connect(m_guestProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(finished(int,QProcess::ExitStatus))); connect(m_guestProcess, SIGNAL(readyReadStandardError()), this, SLOT(stderrReady())); QString a = Core::ICore::resourcePath() + QLatin1String("/qtcreator-lldb"); if(getenv("QTC_LLDB_GUEST") != 0) a = QString::fromLocal8Bit(getenv("QTC_LLDB_GUEST")); showStatusMessage(QString(QLatin1String("starting %1")).arg(a)); m_guestProcess->start(a, QStringList(), QIODevice::ReadWrite | QIODevice::Unbuffered); m_guestProcess->setReadChannel(QProcess::StandardOutput); if (!m_guestProcess->waitForStarted()) { showStatusMessage(tr("qtcreator-lldb failed to start: %1").arg(m_guestProcess->errorString())); notifyEngineSpontaneousShutdown(); return; } setGuestDevice(m_guestProcess); } } LldbEngineHost::~LldbEngineHost() { showMessage(QLatin1String("tear down qtcreator-lldb")); if (m_guestProcess) { disconnect(m_guestProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(finished(int,QProcess::ExitStatus))); m_guestProcess->terminate(); m_guestProcess->kill(); } if (m_ssh && m_ssh->isProcessRunning()) { // TODO: openssh doesn't do that m_ssh->sendSignalToProcess(QSsh::SshRemoteProcess::KillSignal); } } void LldbEngineHost::nuke() { stderrReady(); showMessage(QLatin1String("Nuke engaged. Bug in Engine/IPC or incompatible IPC versions. "), LogError); showStatusMessage(tr("Fatal engine shutdown. Consult debugger log for details.")); m_guestProcess->terminate(); m_guestProcess->kill(); notifyEngineSpontaneousShutdown(); } void LldbEngineHost::sshConnectionError(QSsh::SshError e) { showStatusMessage(tr("SSH connection error: %1").arg(e)); } void LldbEngineHost::finished(int, QProcess::ExitStatus status) { showMessage(QString(QLatin1String("guest went bye bye. exit status: %1 and code: %2")) .arg(status).arg(m_guestProcess->exitCode()), LogError); nuke(); } void LldbEngineHost::stderrReady() { fprintf(stderr,"%s", m_guestProcess->readAllStandardError().data()); } DebuggerEngine *createLldbEngine(const DebuggerStartParameters &startParameters) { return new LldbEngineHost(startParameters); } } // namespace Internal } // namespace Debugger
lgpl-2.1
solmix/datax
core/src/main/java/org/solmix/datax/support/RequestContextResourceResolver.java
1570
/* * Copyright 2014 The Solmix Project * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.gnu.org/licenses/ * or see the FSF site: http://www.fsf.org. */ package org.solmix.datax.support; import org.solmix.datax.RequestContext; import org.solmix.runtime.resource.support.ResourceResolverAdaptor; /** * * @author solmix.f@gmail.com * @version $Id$ 2015年7月26日 */ public class RequestContextResourceResolver extends ResourceResolverAdaptor { private final RequestContext context; public RequestContextResourceResolver(RequestContext context){ this.context=context; } @SuppressWarnings("unchecked") @Override public <T> T resolve(String resourceName, Class<T> resourceType) { if (resourceType == RequestContext.class) { return (T) context; } else if (context != null) { return context.get(resourceType); } return null; } }
lgpl-2.1
mrchapp/gst-plugins-good
docs/plugins/html/gst-plugins-good-plugins-jackaudiosink.html
9106
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>jackaudiosink</title> <meta name="generator" content="DocBook XSL Stylesheets V1.75.2"> <link rel="home" href="index.html" title="GStreamer Good Plugins 0.10 Plugins Reference Manual"> <link rel="up" href="ch01.html" title="gst-plugins-good Elements"> <link rel="prev" href="gst-plugins-good-plugins-jackaudiosrc.html" title="jackaudiosrc"> <link rel="next" href="gst-plugins-good-plugins-jpegdec.html" title="jpegdec"> <meta name="generator" content="GTK-Doc V1.15 (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="2"> <tr valign="middle"> <td><a accesskey="p" href="gst-plugins-good-plugins-jackaudiosrc.html"><img src="left.png" width="24" height="24" border="0" alt="Prev"></a></td> <td><a accesskey="u" href="ch01.html"><img src="up.png" width="24" height="24" border="0" alt="Up"></a></td> <td><a accesskey="h" href="index.html"><img src="home.png" width="24" height="24" border="0" alt="Home"></a></td> <th width="100%" align="center">GStreamer Good Plugins 0.10 Plugins Reference Manual</th> <td><a accesskey="n" href="gst-plugins-good-plugins-jpegdec.html"><img src="right.png" width="24" height="24" border="0" alt="Next"></a></td> </tr> <tr><td colspan="5" class="shortcuts"> <a href="#gst-plugins-good-plugins-jackaudiosink.synopsis" class="shortcut">Top</a>  |  <a href="#gst-plugins-good-plugins-jackaudiosink.description" class="shortcut">Description</a>  |  <a href="#gst-plugins-good-plugins-jackaudiosink.object-hierarchy" class="shortcut">Object Hierarchy</a>  |  <a href="#gst-plugins-good-plugins-jackaudiosink.properties" class="shortcut">Properties</a> </td></tr> </table> <div class="refentry" title="jackaudiosink"> <a name="gst-plugins-good-plugins-jackaudiosink"></a><div class="titlepage"></div> <div class="refnamediv"><table width="100%"><tr> <td valign="top"> <h2><span class="refentrytitle"><a name="gst-plugins-good-plugins-jackaudiosink.top_of_page"></a>jackaudiosink</span></h2> <p>jackaudiosink — Output audio to a JACK server</p> </td> <td valign="top" align="right"></td> </tr></table></div> <div class="refsynopsisdiv" title="Synopsis"> <a name="gst-plugins-good-plugins-jackaudiosink.synopsis"></a><h2>Synopsis</h2> <a name="GstJackAudioSink"></a><pre class="synopsis"> <a class="link" href="gst-plugins-good-plugins-jackaudiosink.html#GstJackAudioSink-struct" title="GstJackAudioSink">GstJackAudioSink</a>; </pre> </div> <div class="refsect1" title="Object Hierarchy"> <a name="gst-plugins-good-plugins-jackaudiosink.object-hierarchy"></a><h2>Object Hierarchy</h2> <pre class="synopsis"> <a href="http://library.gnome.org/devel/gobject/unstable/gobject-The-Base-Object-Type.html#GObject">GObject</a> +----<a href="http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gstreamer/html/GstObject.html">GstObject</a> +----<a href="http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gstreamer/html/GstElement.html">GstElement</a> +----<a href="http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gstreamer-libs/html/GstBaseSink.html">GstBaseSink</a> +----<a href="http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-base-libs/html/gst-plugins-base-libs-gstbaseaudiosink.html#GstBaseAudioSink">GstBaseAudioSink</a> +----GstJackAudioSink </pre> </div> <div class="refsect1" title="Properties"> <a name="gst-plugins-good-plugins-jackaudiosink.properties"></a><h2>Properties</h2> <pre class="synopsis"> "<a class="link" href="gst-plugins-good-plugins-jackaudiosink.html#GstJackAudioSink--client" title='The "client" property'>client</a>" <span class="type">JackClient</span>* : Read / Write "<a class="link" href="gst-plugins-good-plugins-jackaudiosink.html#GstJackAudioSink--connect" title='The "connect" property'>connect</a>" <span class="type">GstJackConnect</span> : Read / Write "<a class="link" href="gst-plugins-good-plugins-jackaudiosink.html#GstJackAudioSink--server" title='The "server" property'>server</a>" <a href="http://library.gnome.org/devel/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a>* : Read / Write </pre> </div> <div class="refsect1" title="Description"> <a name="gst-plugins-good-plugins-jackaudiosink.description"></a><h2>Description</h2> <p> A Sink that outputs data to Jack ports. </p> <p> It will create N Jack ports named out_&lt;name&gt;_&lt;num&gt; where &lt;name&gt; is the element name and &lt;num&gt; is starting from 1. Each port corresponds to a gstreamer channel. </p> <p> The samplerate as exposed on the caps is always the same as the samplerate of the jack server. </p> <p> When the <a class="link" href="gst-plugins-good-plugins-jackaudiosink.html#GstJackAudioSink--connect" title='The "connect" property'><span class="type">"connect"</span></a> property is set to auto, this element will try to connect each output port to a random physical jack input pin. In this mode, the sink will expose the number of physical channels on its pad caps. </p> <p> When the <a class="link" href="gst-plugins-good-plugins-jackaudiosink.html#GstJackAudioSink--connect" title='The "connect" property'><span class="type">"connect"</span></a> property is set to none, the element will accept any number of input channels and will create (but not connect) an output port for each channel. </p> <p> The element will generate an error when the Jack server is shut down when it was PAUSED or PLAYING. This element does not support dynamic rate and buffer size changes at runtime. </p> <div class="refsect2" title="Example launch line"> <a name="id597070"></a><h3>Example launch line</h3> <div class="informalexample"> <table class="listing_frame" border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td class="listing_lines" align="right"><pre>1</pre></td> <td class="listing_code"><pre class="programlisting">gst<span class="symbol">-</span>launch audiotestsrc <span class="symbol">!</span> jackaudiosink</pre></td> </tr> </tbody> </table> </div> Play a sine wave to using jack. </div> <p> Last reviewed on 2006-11-30 (0.10.4) </p> </div> <div class="refsect1" title="Details"> <a name="gst-plugins-good-plugins-jackaudiosink.details"></a><h2>Details</h2> <div class="refsect2" title="GstJackAudioSink"> <a name="GstJackAudioSink-struct"></a><h3>GstJackAudioSink</h3> <pre class="programlisting">typedef struct _GstJackAudioSink GstJackAudioSink;</pre> <p> Opaque <a class="link" href="gst-plugins-good-plugins-jackaudiosink.html#GstJackAudioSink"><span class="type">GstJackAudioSink</span></a>. </p> </div> </div> <div class="refsect1" title="Property Details"> <a name="gst-plugins-good-plugins-jackaudiosink.property-details"></a><h2>Property Details</h2> <div class="refsect2" title='The "client" property'> <a name="GstJackAudioSink--client"></a><h3>The <code class="literal">"client"</code> property</h3> <pre class="programlisting"> "client" <span class="type">JackClient</span>* : Read / Write</pre> <p>Handle for jack client.</p> </div> <hr> <div class="refsect2" title='The "connect" property'> <a name="GstJackAudioSink--connect"></a><h3>The <code class="literal">"connect"</code> property</h3> <pre class="programlisting"> "connect" <span class="type">GstJackConnect</span> : Read / Write</pre> <p>Specify how the output ports will be connected.</p> <p>Default value: Automatically connect ports to physical ports</p> </div> <hr> <div class="refsect2" title='The "server" property'> <a name="GstJackAudioSink--server"></a><h3>The <code class="literal">"server"</code> property</h3> <pre class="programlisting"> "server" <a href="http://library.gnome.org/devel/glib/unstable/glib-Basic-Types.html#gchar"><span class="type">gchar</span></a>* : Read / Write</pre> <p>The Jack server to connect to (NULL = default).</p> <p>Default value: NULL</p> </div> </div> <div class="refsect1" title="See Also"> <a name="gst-plugins-good-plugins-jackaudiosink.see-also"></a><h2>See Also</h2> <a href="http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-base-libs/html/gst-plugins-base-libs-gstbaseaudiosink.html#GstBaseAudioSink"><span class="type">GstBaseAudioSink</span></a>, <a href="http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-base-libs/html/gst-plugins-base-libs-gstringbuffer.html#GstRingBuffer"><span class="type">GstRingBuffer</span></a> </div> </div> <div class="footer"> <hr> Generated by GTK-Doc V1.15</div> </body> </html>
lgpl-2.1
thobens/PHPlug
plugins/phplug_core/annotations/ReflectionAnnotatedClass.php
2601
<?php namespace phplug\plugins\phplug_core\annotations; class ReflectionAnnotatedClass extends \ReflectionClass { private $annotations; public function __construct($class) { parent::__construct($class); $this->annotations = $this->createAnnotationBuilder()->build($this); } public function hasAnnotation($class) { $class = AnnotationMap::getInstance()->getClass($class); return $this->annotations->hasAnnotation($class); } public function getAnnotation($annotation) { $class = AnnotationMap::getInstance()->getClass($annotation); return $this->annotations->getAnnotation($class); } public function getAnnotations() { return $this->annotations->getAnnotations(); } public function getAllAnnotations($restriction = false) { return $this->annotations->getAllAnnotations($restriction); } public function getConstructor() { return $this->createReflectionAnnotatedMethod(parent::getConstructor()); } public function getMethod($name) { return $this->createReflectionAnnotatedMethod(parent::getMethod($name)); } public function getMethods($filter = -1) { $result = array(); foreach(parent::getMethods($filter) as $method) { $result[] = $this->createReflectionAnnotatedMethod($method); } return $result; } public function getProperty($name) { return $this->createReflectionAnnotatedProperty(parent::getProperty($name)); } public function getProperties($filter = -1) { $result = array(); foreach(parent::getProperties($filter) as $property) { $result[] = $this->createReflectionAnnotatedProperty($property); } return $result; } public function getInterfaces() { $result = array(); foreach(parent::getInterfaces() as $interface) { $result[] = $this->createReflectionAnnotatedClass($interface); } return $result; } public function getParentClass() { $class = parent::getParentClass(); return $this->createReflectionAnnotatedClass($class); } protected function createAnnotationBuilder() { return new AnnotationsBuilder(); } private function createReflectionAnnotatedClass($class) { return ($class !== false) ? new ReflectionAnnotatedClass($class->getName()) : false; } private function createReflectionAnnotatedMethod($method) { return ($method !== null) ? new ReflectionAnnotatedMethod($this->getName(), $method->getName()) : null; } private function createReflectionAnnotatedProperty($property) { return ($property !== null) ? new ReflectionAnnotatedProperty($this->getName(), $property->getName()) : null; } }
lgpl-2.1
zooko/egtp_new
egtp/tristero.py
687
# Copyright (c) 2002 Zooko, blanu # This file is licensed under the # GNU Lesser General Public License v2.1. # See the file COPYING or visit http://www.gnu.org/ for details. __revision__ = "$Id: tristero.py,v 1.2 2002/12/02 19:58:54 myers_carpenter Exp $" nodeSchema='http://tristero.sourceforge.net/mnet/MetaTracker#' commSchema='http://tristero.sourceforge.net/mnet/CommStrategies#' lowerSchema='http://tristero.sourceforge.net/mnet/LowerStrategy#' pubkeySchema='http://tristero.sourceforge.net/mnet/Pubkey#' keyHeaderSchema='http://tristero.sourceforge.net/mnet/PubkeyHeader#' keyValueSchema='http://tristero.sourceforge.net/mnet/PubkeyValue#' LITERAL=0 RESOURCE=1 NODE=2
lgpl-2.1
zhangbailong945/LoachBlog
application/models/loachblog/Article_Model.php
882
<?php class Article_Model extends CI_Model { function getArticleById($id) { $data=array(); $this->db->where('article_id',$id); $query=$this->db->get('article'); $row=$query->row(); if(isset($row)) { $data['article_id']=$row->article_id; $data['article_author_id']=$row->article_author_id; $data['article_type_id']=$row->article_type_id; $data['article_title']=$row->article_title; $data['article_introduction']=$row->article_introduction; $data['article_content']=$row->article_content; $data['article_posttime']=$row->article_posttime; $data['article_comment_nums']=$row->article_comment_nums; $data['article_view_nums']=$row->article_view_nums; $data['article_tags']=$row->article_tags; } return $data; } }
lgpl-2.1
rolfrm/tcc_patched
tccpe.c
58177
/* * TCCPE.C - PE file output for the Tiny C Compiler * * Copyright (c) 2005-2007 grischka * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "tcc.h" #ifndef _WIN32 #define stricmp strcasecmp #define strnicmp strncasecmp #endif #ifndef MAX_PATH #define MAX_PATH 260 #endif #define PE_MERGE_DATA // #define PE_PRINT_SECTIONS #ifdef TCC_TARGET_X86_64 # define ADDR3264 ULONGLONG #else # define ADDR3264 DWORD #endif #ifdef _WIN32 void dbg_printf (const char *fmt, ...) { char buffer[4000]; va_list arg; int x; va_start(arg, fmt); x = vsprintf (buffer, fmt, arg); strcpy(buffer+x, "\n"); OutputDebugString(buffer); } #endif /* ----------------------------------------------------------- */ #ifndef IMAGE_NT_SIGNATURE /* ----------------------------------------------------------- */ /* definitions below are from winnt.h */ typedef unsigned char BYTE; typedef unsigned short WORD; typedef unsigned int DWORD; typedef unsigned long long ULONGLONG; #pragma pack(push, 1) typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */ WORD e_magic; /* Magic number */ WORD e_cblp; /* Bytes on last page of file */ WORD e_cp; /* Pages in file */ WORD e_crlc; /* Relocations */ WORD e_cparhdr; /* Size of header in paragraphs */ WORD e_minalloc; /* Minimum extra paragraphs needed */ WORD e_maxalloc; /* Maximum extra paragraphs needed */ WORD e_ss; /* Initial (relative) SS value */ WORD e_sp; /* Initial SP value */ WORD e_csum; /* Checksum */ WORD e_ip; /* Initial IP value */ WORD e_cs; /* Initial (relative) CS value */ WORD e_lfarlc; /* File address of relocation table */ WORD e_ovno; /* Overlay number */ WORD e_res[4]; /* Reserved words */ WORD e_oemid; /* OEM identifier (for e_oeminfo) */ WORD e_oeminfo; /* OEM information; e_oemid specific */ WORD e_res2[10]; /* Reserved words */ DWORD e_lfanew; /* File address of new exe header */ } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER; #define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */ #define SIZE_OF_NT_SIGNATURE 4 typedef struct _IMAGE_FILE_HEADER { WORD Machine; WORD NumberOfSections; DWORD TimeDateStamp; DWORD PointerToSymbolTable; DWORD NumberOfSymbols; WORD SizeOfOptionalHeader; WORD Characteristics; } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER; #define IMAGE_SIZEOF_FILE_HEADER 20 typedef struct _IMAGE_DATA_DIRECTORY { DWORD VirtualAddress; DWORD Size; } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY; typedef struct _IMAGE_OPTIONAL_HEADER { /* Standard fields. */ WORD Magic; BYTE MajorLinkerVersion; BYTE MinorLinkerVersion; DWORD SizeOfCode; DWORD SizeOfInitializedData; DWORD SizeOfUninitializedData; DWORD AddressOfEntryPoint; DWORD BaseOfCode; #ifndef TCC_TARGET_X86_64 DWORD BaseOfData; #endif /* NT additional fields. */ ADDR3264 ImageBase; DWORD SectionAlignment; DWORD FileAlignment; WORD MajorOperatingSystemVersion; WORD MinorOperatingSystemVersion; WORD MajorImageVersion; WORD MinorImageVersion; WORD MajorSubsystemVersion; WORD MinorSubsystemVersion; DWORD Win32VersionValue; DWORD SizeOfImage; DWORD SizeOfHeaders; DWORD CheckSum; WORD Subsystem; WORD DllCharacteristics; ADDR3264 SizeOfStackReserve; ADDR3264 SizeOfStackCommit; ADDR3264 SizeOfHeapReserve; ADDR3264 SizeOfHeapCommit; DWORD LoaderFlags; DWORD NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[16]; } IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER; #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */ #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */ #define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */ #define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */ #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */ #define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */ #define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */ /* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */ #define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */ #define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */ #define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */ #define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */ #define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */ #define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */ #define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */ #define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */ /* Section header format. */ #define IMAGE_SIZEOF_SHORT_NAME 8 typedef struct _IMAGE_SECTION_HEADER { BYTE Name[IMAGE_SIZEOF_SHORT_NAME]; union { DWORD PhysicalAddress; DWORD VirtualSize; } Misc; DWORD VirtualAddress; DWORD SizeOfRawData; DWORD PointerToRawData; DWORD PointerToRelocations; DWORD PointerToLinenumbers; WORD NumberOfRelocations; WORD NumberOfLinenumbers; DWORD Characteristics; } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER; #define IMAGE_SIZEOF_SECTION_HEADER 40 typedef struct _IMAGE_EXPORT_DIRECTORY { DWORD Characteristics; DWORD TimeDateStamp; WORD MajorVersion; WORD MinorVersion; DWORD Name; DWORD Base; DWORD NumberOfFunctions; DWORD NumberOfNames; DWORD AddressOfFunctions; DWORD AddressOfNames; DWORD AddressOfNameOrdinals; } IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY; typedef struct _IMAGE_IMPORT_DESCRIPTOR { union { DWORD Characteristics; DWORD OriginalFirstThunk; }; DWORD TimeDateStamp; DWORD ForwarderChain; DWORD Name; DWORD FirstThunk; } IMAGE_IMPORT_DESCRIPTOR; typedef struct _IMAGE_BASE_RELOCATION { DWORD VirtualAddress; DWORD SizeOfBlock; // WORD TypeOffset[1]; } IMAGE_BASE_RELOCATION; #define IMAGE_SIZEOF_BASE_RELOCATION 8 #define IMAGE_REL_BASED_ABSOLUTE 0 #define IMAGE_REL_BASED_HIGH 1 #define IMAGE_REL_BASED_LOW 2 #define IMAGE_REL_BASED_HIGHLOW 3 #define IMAGE_REL_BASED_HIGHADJ 4 #define IMAGE_REL_BASED_MIPS_JMPADDR 5 #define IMAGE_REL_BASED_SECTION 6 #define IMAGE_REL_BASED_REL32 7 #pragma pack(pop) /* ----------------------------------------------------------- */ #endif /* ndef IMAGE_NT_SIGNATURE */ /* ----------------------------------------------------------- */ #pragma pack(push, 1) struct pe_header { IMAGE_DOS_HEADER doshdr; BYTE dosstub[0x40]; DWORD nt_sig; IMAGE_FILE_HEADER filehdr; #ifdef TCC_TARGET_X86_64 IMAGE_OPTIONAL_HEADER64 opthdr; #else #ifdef _WIN64 IMAGE_OPTIONAL_HEADER32 opthdr; #else IMAGE_OPTIONAL_HEADER opthdr; #endif #endif }; struct pe_reloc_header { DWORD offset; DWORD size; }; struct pe_rsrc_header { struct _IMAGE_FILE_HEADER filehdr; struct _IMAGE_SECTION_HEADER sectionhdr; }; struct pe_rsrc_reloc { DWORD offset; DWORD size; WORD type; }; #pragma pack(pop) /* ------------------------------------------------------------- */ /* internal temporary structures */ /* #define IMAGE_SCN_CNT_CODE 0x00000020 #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040 #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080 #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000 #define IMAGE_SCN_MEM_SHARED 0x10000000 #define IMAGE_SCN_MEM_EXECUTE 0x20000000 #define IMAGE_SCN_MEM_READ 0x40000000 #define IMAGE_SCN_MEM_WRITE 0x80000000 */ enum { sec_text = 0, sec_data , sec_bss , sec_idata , sec_pdata , sec_other , sec_rsrc , sec_stab , sec_reloc , sec_last }; static const DWORD pe_sec_flags[] = { 0x60000020, /* ".text" , */ 0xC0000040, /* ".data" , */ 0xC0000080, /* ".bss" , */ 0x40000040, /* ".idata" , */ 0x40000040, /* ".pdata" , */ 0xE0000060, /* < other > , */ 0x40000040, /* ".rsrc" , */ 0x42000802, /* ".stab" , */ 0x42000040, /* ".reloc" , */ }; struct section_info { int cls, ord; char name[32]; DWORD sh_addr; DWORD sh_size; DWORD sh_flags; unsigned char *data; DWORD data_size; IMAGE_SECTION_HEADER ish; }; struct import_symbol { int sym_index; int iat_index; int thk_offset; }; struct pe_import_info { int dll_index; int sym_count; struct import_symbol **symbols; }; struct pe_info { TCCState *s1; Section *reloc; Section *thunk; const char *filename; int type; DWORD sizeofheaders; ADDR3264 imagebase; DWORD start_addr; DWORD imp_offs; DWORD imp_size; DWORD iat_offs; DWORD iat_size; DWORD exp_offs; DWORD exp_size; int subsystem; DWORD section_align; DWORD file_align; struct section_info *sec_info; int sec_count; struct pe_import_info **imp_info; int imp_count; }; #define PE_NUL 0 #define PE_DLL 1 #define PE_GUI 2 #define PE_EXE 3 #define PE_RUN 4 /* --------------------------------------------*/ static const char *pe_export_name(TCCState *s1, ElfW(Sym) *sym) { const char *name = symtab_section->link->data + sym->st_name; if (s1->leading_underscore && name[0] == '_' && !(sym->st_other & 2)) return name + 1; return name; } static int pe_find_import(TCCState * s1, ElfW(Sym) *sym) { char buffer[200]; const char *s, *p; int sym_index = 0, n = 0; do { s = pe_export_name(s1, sym); if (n) { /* second try: */ if (sym->st_other & 2) { /* try w/0 stdcall deco (windows API convention) */ p = strrchr(s, '@'); if (!p || s[0] != '_') break; strcpy(buffer, s+1)[p-s-1] = 0; } else if (s[0] != '_') { /* try non-ansi function */ buffer[0] = '_', strcpy(buffer + 1, s); } else if (0 == memcmp(s, "__imp__", 7)) { /* mingw 2.0 */ strcpy(buffer, s + 6); } else if (0 == memcmp(s, "_imp___", 7)) { /* mingw 3.7 */ strcpy(buffer, s + 6); } else { break; } s = buffer; } sym_index = find_elf_sym(s1->dynsymtab_section, s); // printf("find (%d) %d %s\n", n, sym_index, s); } while (0 == sym_index && ++n < 2); return sym_index; } /*----------------------------------------------------------------------------*/ static int dynarray_assoc(void **pp, int n, int key) { int i; for (i = 0; i < n; ++i, ++pp) if (key == **(int **) pp) return i; return -1; } #if 0 ST_FN DWORD umin(DWORD a, DWORD b) { return a < b ? a : b; } #endif static DWORD umax(DWORD a, DWORD b) { return a < b ? b : a; } static DWORD pe_file_align(struct pe_info *pe, DWORD n) { return (n + (pe->file_align - 1)) & ~(pe->file_align - 1); } static DWORD pe_virtual_align(struct pe_info *pe, DWORD n) { return (n + (pe->section_align - 1)) & ~(pe->section_align - 1); } static void pe_align_section(Section *s, int a) { int i = s->data_offset & (a-1); if (i) section_ptr_add(s, a - i); } static void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size) { hdr->opthdr.DataDirectory[dir].VirtualAddress = addr; hdr->opthdr.DataDirectory[dir].Size = size; } static int pe_fwrite(void *data, unsigned len, FILE *fp, DWORD *psum) { if (psum) { DWORD sum = *psum; WORD *p = data; int i; for (i = len; i > 0; i -= 2) { sum += (i >= 2) ? *p++ : *(BYTE*)p; sum = (sum + (sum >> 16)) & 0xFFFF; } *psum = sum; } return len == fwrite(data, 1, len, fp) ? 0 : -1; } static void pe_fpad(FILE *fp, DWORD new_pos) { DWORD pos = ftell(fp); while (++pos <= new_pos) fputc(0, fp); } /*----------------------------------------------------------------------------*/ static int pe_write(struct pe_info *pe) { static const struct pe_header pe_template = { { /* IMAGE_DOS_HEADER doshdr */ 0x5A4D, /*WORD e_magic; Magic number */ 0x0090, /*WORD e_cblp; Bytes on last page of file */ 0x0003, /*WORD e_cp; Pages in file */ 0x0000, /*WORD e_crlc; Relocations */ 0x0004, /*WORD e_cparhdr; Size of header in paragraphs */ 0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */ 0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */ 0x0000, /*WORD e_ss; Initial (relative) SS value */ 0x00B8, /*WORD e_sp; Initial SP value */ 0x0000, /*WORD e_csum; Checksum */ 0x0000, /*WORD e_ip; Initial IP value */ 0x0000, /*WORD e_cs; Initial (relative) CS value */ 0x0040, /*WORD e_lfarlc; File address of relocation table */ 0x0000, /*WORD e_ovno; Overlay number */ {0,0,0,0}, /*WORD e_res[4]; Reserved words */ 0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */ 0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */ {0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */ 0x00000080 /*DWORD e_lfanew; File address of new exe header */ },{ /* BYTE dosstub[0x40] */ /* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */ 0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68, 0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f, 0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20, 0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00, }, 0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */ { /* IMAGE_FILE_HEADER filehdr */ #if defined(TCC_TARGET_I386) 0x014C, /*WORD Machine; */ #elif defined(TCC_TARGET_X86_64) 0x8664, /*WORD Machine; */ #elif defined(TCC_TARGET_ARM) 0x01C0, /*WORD Machine; */ #endif 0x0003, /*WORD NumberOfSections; */ 0x00000000, /*DWORD TimeDateStamp; */ 0x00000000, /*DWORD PointerToSymbolTable; */ 0x00000000, /*DWORD NumberOfSymbols; */ #if defined(TCC_TARGET_X86_64) 0x00F0, /*WORD SizeOfOptionalHeader; */ 0x022F /*WORD Characteristics; */ #define CHARACTERISTICS_DLL 0x222E #elif defined(TCC_TARGET_I386) 0x00E0, /*WORD SizeOfOptionalHeader; */ 0x030F /*WORD Characteristics; */ #define CHARACTERISTICS_DLL 0x230E #elif defined(TCC_TARGET_ARM) 0x00E0, /*WORD SizeOfOptionalHeader; */ 0x010F, /*WORD Characteristics; */ #define CHARACTERISTICS_DLL 0x230F #endif },{ /* IMAGE_OPTIONAL_HEADER opthdr */ /* Standard fields. */ #ifdef TCC_TARGET_X86_64 0x020B, /*WORD Magic; */ #else 0x010B, /*WORD Magic; */ #endif 0x06, /*BYTE MajorLinkerVersion; */ 0x00, /*BYTE MinorLinkerVersion; */ 0x00000000, /*DWORD SizeOfCode; */ 0x00000000, /*DWORD SizeOfInitializedData; */ 0x00000000, /*DWORD SizeOfUninitializedData; */ 0x00000000, /*DWORD AddressOfEntryPoint; */ 0x00000000, /*DWORD BaseOfCode; */ #ifndef TCC_TARGET_X86_64 0x00000000, /*DWORD BaseOfData; */ #endif /* NT additional fields. */ #if defined(TCC_TARGET_ARM) 0x00100000, /*DWORD ImageBase; */ #else 0x00400000, /*DWORD ImageBase; */ #endif 0x00001000, /*DWORD SectionAlignment; */ 0x00000200, /*DWORD FileAlignment; */ 0x0004, /*WORD MajorOperatingSystemVersion; */ 0x0000, /*WORD MinorOperatingSystemVersion; */ 0x0000, /*WORD MajorImageVersion; */ 0x0000, /*WORD MinorImageVersion; */ 0x0004, /*WORD MajorSubsystemVersion; */ 0x0000, /*WORD MinorSubsystemVersion; */ 0x00000000, /*DWORD Win32VersionValue; */ 0x00000000, /*DWORD SizeOfImage; */ 0x00000200, /*DWORD SizeOfHeaders; */ 0x00000000, /*DWORD CheckSum; */ 0x0002, /*WORD Subsystem; */ 0x0000, /*WORD DllCharacteristics; */ 0x00100000, /*DWORD SizeOfStackReserve; */ 0x00001000, /*DWORD SizeOfStackCommit; */ 0x00100000, /*DWORD SizeOfHeapReserve; */ 0x00001000, /*DWORD SizeOfHeapCommit; */ 0x00000000, /*DWORD LoaderFlags; */ 0x00000010, /*DWORD NumberOfRvaAndSizes; */ /* IMAGE_DATA_DIRECTORY DataDirectory[16]; */ {{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}} }}; struct pe_header pe_header = pe_template; int i; FILE *op; DWORD file_offset, sum; struct section_info *si; IMAGE_SECTION_HEADER *psh; op = fopen(pe->filename, "wb"); if (NULL == op) { tcc_error_noabort("could not write '%s': %s", pe->filename, strerror(errno)); return -1; } pe->sizeofheaders = pe_file_align(pe, sizeof (struct pe_header) + pe->sec_count * sizeof (IMAGE_SECTION_HEADER) ); file_offset = pe->sizeofheaders; if (2 == pe->s1->verbose) printf("-------------------------------" "\n virt file size section" "\n"); for (i = 0; i < pe->sec_count; ++i) { DWORD addr, size; const char *sh_name; si = pe->sec_info + i; sh_name = si->name; addr = si->sh_addr - pe->imagebase; size = si->sh_size; psh = &si->ish; if (2 == pe->s1->verbose) printf("%6x %6x %6x %s\n", (unsigned)addr, (unsigned)file_offset, (unsigned)size, sh_name); switch (si->cls) { case sec_text: pe_header.opthdr.BaseOfCode = addr; pe_header.opthdr.AddressOfEntryPoint = addr + pe->start_addr; break; case sec_data: #ifndef TCC_TARGET_X86_64 pe_header.opthdr.BaseOfData = addr; #endif break; case sec_bss: break; case sec_reloc: pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size); break; case sec_rsrc: pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size); break; case sec_pdata: pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXCEPTION, addr, size); break; case sec_stab: break; } if (pe->thunk == pe->s1->sections[si->ord]) { if (pe->imp_size) { pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT, pe->imp_offs + addr, pe->imp_size); pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT, pe->iat_offs + addr, pe->iat_size); } if (pe->exp_size) { pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT, pe->exp_offs + addr, pe->exp_size); } } pstrcpy((char*)psh->Name, sizeof psh->Name, sh_name); psh->Characteristics = pe_sec_flags[si->cls]; psh->VirtualAddress = addr; psh->Misc.VirtualSize = size; pe_header.opthdr.SizeOfImage = umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage); if (si->data_size) { psh->PointerToRawData = file_offset; file_offset = pe_file_align(pe, file_offset + si->data_size); psh->SizeOfRawData = file_offset - psh->PointerToRawData; } } //pe_header.filehdr.TimeDateStamp = time(NULL); pe_header.filehdr.NumberOfSections = pe->sec_count; pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders; pe_header.opthdr.ImageBase = pe->imagebase; pe_header.opthdr.Subsystem = pe->subsystem; if (pe->s1->pe_stack_size) pe_header.opthdr.SizeOfStackReserve = pe->s1->pe_stack_size; if (PE_DLL == pe->type) pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL; sum = 0; pe_fwrite(&pe_header, sizeof pe_header, op, &sum); for (i = 0; i < pe->sec_count; ++i) pe_fwrite(&pe->sec_info[i].ish, sizeof(IMAGE_SECTION_HEADER), op, &sum); pe_fpad(op, pe->sizeofheaders); for (i = 0; i < pe->sec_count; ++i) { si = pe->sec_info + i; psh = &si->ish; if (si->data_size) { pe_fwrite(si->data, si->data_size, op, &sum); file_offset = psh->PointerToRawData + psh->SizeOfRawData; pe_fpad(op, file_offset); } } pe_header.opthdr.CheckSum = sum + file_offset; fseek(op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET); pe_fwrite(&pe_header.opthdr.CheckSum, sizeof pe_header.opthdr.CheckSum, op, NULL); fclose (op); if (2 == pe->s1->verbose) printf("-------------------------------\n"); if (pe->s1->verbose) printf("<- %s (%u bytes)\n", pe->filename, (unsigned)file_offset); return 0; } /*----------------------------------------------------------------------------*/ #if defined(TCC_TARGET_X86_64) #define REL_TYPE_DIRECT R_X86_64_64 #define R_XXX_THUNKFIX R_X86_64_PC32 #define R_XXX_RELATIVE R_X86_64_RELATIVE #elif defined(TCC_TARGET_I386) #define REL_TYPE_DIRECT R_386_32 #define R_XXX_THUNKFIX R_386_32 #define R_XXX_RELATIVE R_386_RELATIVE #elif defined(TCC_TARGET_ARM) #define REL_TYPE_DIRECT R_ARM_ABS32 #define R_XXX_THUNKFIX R_ARM_ABS32 #define R_XXX_RELATIVE R_ARM_RELATIVE #endif /*----------------------------------------------------------------------------*/ static struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index) { int i; int dll_index; struct pe_import_info *p; struct import_symbol *s; ElfW(Sym) *isym; isym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index; dll_index = isym->st_size; i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index); if (-1 != i) { p = pe->imp_info[i]; goto found_dll; } p = tcc_mallocz(sizeof *p); p->dll_index = dll_index; dynarray_add((void***)&pe->imp_info, &pe->imp_count, p); found_dll: i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index); if (-1 != i) return p->symbols[i]; s = tcc_mallocz(sizeof *s); dynarray_add((void***)&p->symbols, &p->sym_count, s); s->sym_index = sym_index; return s; } /*----------------------------------------------------------------------------*/ static void pe_build_imports(struct pe_info *pe) { int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i; DWORD rva_base = pe->thunk->sh_addr - pe->imagebase; int ndlls = pe->imp_count; for (sym_cnt = i = 0; i < ndlls; ++i) sym_cnt += pe->imp_info[i]->sym_count; if (0 == sym_cnt) return; pe_align_section(pe->thunk, 16); pe->imp_offs = dll_ptr = pe->thunk->data_offset; pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR); pe->iat_offs = dll_ptr + pe->imp_size; pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264); section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size); thk_ptr = pe->iat_offs; ent_ptr = pe->iat_offs + pe->iat_size; for (i = 0; i < pe->imp_count; ++i) { IMAGE_IMPORT_DESCRIPTOR *hdr; int k, n, dllindex; ADDR3264 v; struct pe_import_info *p = pe->imp_info[i]; const char *name; DLLReference *dllref; dllindex = p->dll_index; if (dllindex) name = (dllref = pe->s1->loaded_dlls[dllindex-1])->name; else name = "", dllref = NULL; /* put the dll name into the import header */ v = put_elf_str(pe->thunk, name); hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr); hdr->FirstThunk = thk_ptr + rva_base; hdr->OriginalFirstThunk = ent_ptr + rva_base; hdr->Name = v + rva_base; for (k = 0, n = p->sym_count; k <= n; ++k) { if (k < n) { int iat_index = p->symbols[k]->iat_index; int sym_index = p->symbols[k]->sym_index; ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index; ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index; const char *name = pe->s1->dynsymtab_section->link->data + imp_sym->st_name; org_sym->st_value = thk_ptr; org_sym->st_shndx = pe->thunk->sh_num; v = pe->thunk->data_offset + rva_base; section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */ put_elf_str(pe->thunk, name); #ifdef TCC_IS_NATIVE if (pe->type == PE_RUN) { v = imp_sym->st_value; if (dllref) { if ( !dllref->handle ) dllref->handle = LoadLibrary(dllref->name); v = (ADDR3264)GetProcAddress(dllref->handle, name); } if (!v) tcc_error_noabort("undefined symbol '%s'", name); } #endif } else { v = 0; /* last entry is zero */ } *(ADDR3264*)(pe->thunk->data+thk_ptr) = *(ADDR3264*)(pe->thunk->data+ent_ptr) = v; thk_ptr += sizeof (ADDR3264); ent_ptr += sizeof (ADDR3264); } dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR); dynarray_reset(&p->symbols, &p->sym_count); } dynarray_reset(&pe->imp_info, &pe->imp_count); } /* ------------------------------------------------------------- */ struct pe_sort_sym { int index; const char *name; }; static int sym_cmp(const void *va, const void *vb) { const char *ca = (*(struct pe_sort_sym**)va)->name; const char *cb = (*(struct pe_sort_sym**)vb)->name; return strcmp(ca, cb); } static void pe_build_exports(struct pe_info *pe) { ElfW(Sym) *sym; int sym_index, sym_end; DWORD rva_base, func_o, name_o, ord_o, str_o; IMAGE_EXPORT_DIRECTORY *hdr; int sym_count, ord; struct pe_sort_sym **sorted, *p; FILE *op; char buf[MAX_PATH]; const char *dllname; const char *name; rva_base = pe->thunk->sh_addr - pe->imagebase; sym_count = 0, sorted = NULL, op = NULL; sym_end = symtab_section->data_offset / sizeof(ElfW(Sym)); for (sym_index = 1; sym_index < sym_end; ++sym_index) { sym = (ElfW(Sym)*)symtab_section->data + sym_index; name = pe_export_name(pe->s1, sym); if ((sym->st_other & 1) /* export only symbols from actually written sections */ && pe->s1->sections[sym->st_shndx]->sh_addr) { p = tcc_malloc(sizeof *p); p->index = sym_index; p->name = name; dynarray_add((void***)&sorted, &sym_count, p); } #if 0 if (sym->st_other & 1) printf("export: %s\n", name); if (sym->st_other & 2) printf("stdcall: %s\n", name); #endif } if (0 == sym_count) return; qsort (sorted, sym_count, sizeof *sorted, sym_cmp); pe_align_section(pe->thunk, 16); dllname = tcc_basename(pe->filename); pe->exp_offs = pe->thunk->data_offset; func_o = pe->exp_offs + sizeof(IMAGE_EXPORT_DIRECTORY); name_o = func_o + sym_count * sizeof (DWORD); ord_o = name_o + sym_count * sizeof (DWORD); str_o = ord_o + sym_count * sizeof(WORD); hdr = section_ptr_add(pe->thunk, str_o - pe->exp_offs); hdr->Characteristics = 0; hdr->Base = 1; hdr->NumberOfFunctions = sym_count; hdr->NumberOfNames = sym_count; hdr->AddressOfFunctions = func_o + rva_base; hdr->AddressOfNames = name_o + rva_base; hdr->AddressOfNameOrdinals = ord_o + rva_base; hdr->Name = str_o + rva_base; put_elf_str(pe->thunk, dllname); #if 1 /* automatically write exports to <output-filename>.def */ pstrcpy(buf, sizeof buf, pe->filename); strcpy(tcc_fileextension(buf), ".def"); op = fopen(buf, "w"); if (NULL == op) { tcc_error_noabort("could not create '%s': %s", buf, strerror(errno)); } else { fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname); if (pe->s1->verbose) printf("<- %s (%d symbols)\n", buf, sym_count); } #endif for (ord = 0; ord < sym_count; ++ord) { p = sorted[ord], sym_index = p->index, name = p->name; /* insert actual address later in pe_relocate_rva */ put_elf_reloc(symtab_section, pe->thunk, func_o, R_XXX_RELATIVE, sym_index); *(DWORD*)(pe->thunk->data + name_o) = pe->thunk->data_offset + rva_base; *(WORD*)(pe->thunk->data + ord_o) = ord; put_elf_str(pe->thunk, name); func_o += sizeof (DWORD); name_o += sizeof (DWORD); ord_o += sizeof (WORD); if (op) fprintf(op, "%s\n", name); } pe->exp_size = pe->thunk->data_offset - pe->exp_offs; dynarray_reset(&sorted, &sym_count); if (op) fclose(op); } /* ------------------------------------------------------------- */ static void pe_build_reloc (struct pe_info *pe) { DWORD offset, block_ptr, addr; int count, i; ElfW_Rel *rel, *rel_end; Section *s = NULL, *sr; offset = addr = block_ptr = count = i = 0; rel = rel_end = NULL; for(;;) { if (rel < rel_end) { int type = ELFW(R_TYPE)(rel->r_info); addr = rel->r_offset + s->sh_addr; ++ rel; if (type != REL_TYPE_DIRECT) continue; if (count == 0) { /* new block */ block_ptr = pe->reloc->data_offset; section_ptr_add(pe->reloc, sizeof(struct pe_reloc_header)); offset = addr & 0xFFFFFFFF<<12; } if ((addr -= offset) < (1<<12)) { /* one block spans 4k addresses */ WORD *wp = section_ptr_add(pe->reloc, sizeof (WORD)); *wp = addr | IMAGE_REL_BASED_HIGHLOW<<12; ++count; continue; } -- rel; } else if (i < pe->sec_count) { sr = (s = pe->s1->sections[pe->sec_info[i++].ord])->reloc; if (sr) { rel = (ElfW_Rel *)sr->data; rel_end = (ElfW_Rel *)(sr->data + sr->data_offset); } continue; } if (count) { /* store the last block and ready for a new one */ struct pe_reloc_header *hdr; if (count & 1) /* align for DWORDS */ section_ptr_add(pe->reloc, sizeof(WORD)), ++count; hdr = (struct pe_reloc_header *)(pe->reloc->data + block_ptr); hdr -> offset = offset - pe->imagebase; hdr -> size = count * sizeof(WORD) + sizeof(struct pe_reloc_header); count = 0; } if (rel >= rel_end) break; } } /* ------------------------------------------------------------- */ static int pe_section_class(Section *s) { int type, flags; const char *name; type = s->sh_type; flags = s->sh_flags; name = s->name; if (flags & SHF_ALLOC) { if (type == SHT_PROGBITS) { if (flags & SHF_EXECINSTR) return sec_text; if (flags & SHF_WRITE) return sec_data; if (0 == strcmp(name, ".rsrc")) return sec_rsrc; if (0 == strcmp(name, ".iedat")) return sec_idata; if (0 == strcmp(name, ".pdata")) return sec_pdata; return sec_other; } else if (type == SHT_NOBITS) { if (flags & SHF_WRITE) return sec_bss; } } else { if (0 == strcmp(name, ".reloc")) return sec_reloc; if (0 == strncmp(name, ".stab", 5)) /* .stab and .stabstr */ return sec_stab; } return -1; } static int pe_assign_addresses (struct pe_info *pe) { int i, k, o, c; DWORD addr; int *section_order; struct section_info *si; Section *s; // pe->thunk = new_section(pe->s1, ".iedat", SHT_PROGBITS, SHF_ALLOC); section_order = tcc_malloc(pe->s1->nb_sections * sizeof (int)); for (o = k = 0 ; k < sec_last; ++k) { for (i = 1; i < pe->s1->nb_sections; ++i) { s = pe->s1->sections[i]; if (k == pe_section_class(s)) { // printf("%s %d\n", s->name, k); s->sh_addr = pe->imagebase; section_order[o++] = i; } } } pe->sec_info = tcc_mallocz(o * sizeof (struct section_info)); addr = pe->imagebase + 1; for (i = 0; i < o; ++i) { k = section_order[i]; s = pe->s1->sections[k]; c = pe_section_class(s); si = &pe->sec_info[pe->sec_count]; #ifdef PE_MERGE_DATA if (c == sec_bss && pe->sec_count && si[-1].cls == sec_data) { /* append .bss to .data */ s->sh_addr = addr = ((addr-1) | (s->sh_addralign-1)) + 1; addr += s->data_offset; si[-1].sh_size = addr - si[-1].sh_addr; continue; } #endif if (c == sec_stab && 0 == pe->s1->do_debug) continue; strcpy(si->name, s->name); si->cls = c; si->ord = k; si->sh_addr = s->sh_addr = addr = pe_virtual_align(pe, addr); si->sh_flags = s->sh_flags; if (c == sec_data && NULL == pe->thunk) pe->thunk = s; if (s == pe->thunk) { pe_build_imports(pe); pe_build_exports(pe); } if (c == sec_reloc) pe_build_reloc (pe); if (s->data_offset) { if (s->sh_type != SHT_NOBITS) { si->data = s->data; si->data_size = s->data_offset; } addr += s->data_offset; si->sh_size = s->data_offset; ++pe->sec_count; } // printf("%08x %05x %s\n", si->sh_addr, si->sh_size, si->name); } #if 0 for (i = 1; i < pe->s1->nb_sections; ++i) { Section *s = pe->s1->sections[i]; int type = s->sh_type; int flags = s->sh_flags; printf("section %-16s %-10s %5x %s,%s,%s\n", s->name, type == SHT_PROGBITS ? "progbits" : type == SHT_NOBITS ? "nobits" : type == SHT_SYMTAB ? "symtab" : type == SHT_STRTAB ? "strtab" : type == SHT_RELX ? "rel" : "???", s->data_offset, flags & SHF_ALLOC ? "alloc" : "", flags & SHF_WRITE ? "write" : "", flags & SHF_EXECINSTR ? "exec" : "" ); } pe->s1->verbose = 2; #endif tcc_free(section_order); return 0; } /* ------------------------------------------------------------- */ static void pe_relocate_rva (struct pe_info *pe, Section *s) { Section *sr = s->reloc; ElfW_Rel *rel, *rel_end; rel_end = (ElfW_Rel *)(sr->data + sr->data_offset); for(rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) { if (ELFW(R_TYPE)(rel->r_info) == R_XXX_RELATIVE) { int sym_index = ELFW(R_SYM)(rel->r_info); DWORD addr = s->sh_addr; if (sym_index) { ElfW(Sym) *sym = (ElfW(Sym) *)symtab_section->data + sym_index; addr = sym->st_value; } // printf("reloc rva %08x %08x %s\n", (DWORD)rel->r_offset, addr, s->name); *(DWORD*)(s->data + rel->r_offset) += addr - pe->imagebase; } } } /*----------------------------------------------------------------------------*/ static int pe_isafunc(int sym_index) { Section *sr = text_section->reloc; ElfW_Rel *rel, *rel_end; Elf32_Word info = ELF32_R_INFO(sym_index, R_386_PC32); if (!sr) return 0; rel_end = (ElfW_Rel *)(sr->data + sr->data_offset); for (rel = (ElfW_Rel *)sr->data; rel < rel_end; rel++) if (rel->r_info == info) return 1; return 0; } /*----------------------------------------------------------------------------*/ static int pe_check_symbols(struct pe_info *pe) { ElfW(Sym) *sym; int sym_index, sym_end; int ret = 0; pe_align_section(text_section, 8); sym_end = symtab_section->data_offset / sizeof(ElfW(Sym)); for (sym_index = 1; sym_index < sym_end; ++sym_index) { sym = (ElfW(Sym) *)symtab_section->data + sym_index; if (sym->st_shndx == SHN_UNDEF) { const char *name = symtab_section->link->data + sym->st_name; unsigned type = ELFW(ST_TYPE)(sym->st_info); int imp_sym = pe_find_import(pe->s1, sym); struct import_symbol *is; if (0 == imp_sym) goto not_found; if (type == STT_NOTYPE) { /* symbols from assembler have no type, find out which */ if (pe_isafunc(sym_index)) type = STT_FUNC; else type = STT_OBJECT; } is = pe_add_import(pe, imp_sym); if (type == STT_FUNC) { unsigned long offset = is->thk_offset; if (offset) { /* got aliased symbol, like stricmp and _stricmp */ } else { char buffer[100]; WORD *p; offset = text_section->data_offset; /* add the 'jmp IAT[x]' instruction */ #ifdef TCC_TARGET_ARM p = section_ptr_add(text_section, 8+4); // room for code and address (*(DWORD*)(p)) = 0xE59FC000; // arm code ldr ip, [pc] ; PC+8+0 = 0001xxxx (*(DWORD*)(p+2)) = 0xE59CF000; // arm code ldr pc, [ip] #else p = section_ptr_add(text_section, 8); *p = 0x25FF; #ifdef TCC_TARGET_X86_64 *(DWORD*)(p+1) = (DWORD)-4; #endif #endif /* add a helper symbol, will be patched later in pe_build_imports */ sprintf(buffer, "IAT.%s", name); is->iat_index = put_elf_sym( symtab_section, 0, sizeof(DWORD), ELFW(ST_INFO)(STB_GLOBAL, STT_OBJECT), 0, SHN_UNDEF, buffer); #ifdef TCC_TARGET_ARM put_elf_reloc(symtab_section, text_section, offset + 8, R_XXX_THUNKFIX, is->iat_index); // offset to IAT position #else put_elf_reloc(symtab_section, text_section, offset + 2, R_XXX_THUNKFIX, is->iat_index); #endif is->thk_offset = offset; } /* tcc_realloc might have altered sym's address */ sym = (ElfW(Sym) *)symtab_section->data + sym_index; /* patch the original symbol */ sym->st_value = offset; sym->st_shndx = text_section->sh_num; sym->st_other &= ~1; /* do not export */ continue; } if (type == STT_OBJECT) { /* data, ptr to that should be */ if (0 == is->iat_index) { /* original symbol will be patched later in pe_build_imports */ is->iat_index = sym_index; continue; } } not_found: tcc_error_noabort("undefined symbol '%s'", name); ret = -1; } else if (pe->s1->rdynamic && ELFW(ST_BIND)(sym->st_info) != STB_LOCAL) { /* if -rdynamic option, then export all non local symbols */ sym->st_other |= 1; } } return ret; } /*----------------------------------------------------------------------------*/ #ifdef PE_PRINT_SECTIONS static void pe_print_section(FILE * f, Section * s) { /* just if you'r curious */ BYTE *p, *e, b; int i, n, l, m; p = s->data; e = s->data + s->data_offset; l = e - p; fprintf(f, "section \"%s\"", s->name); if (s->link) fprintf(f, "\nlink \"%s\"", s->link->name); if (s->reloc) fprintf(f, "\nreloc \"%s\"", s->reloc->name); fprintf(f, "\nv_addr %08X", (unsigned)s->sh_addr); fprintf(f, "\ncontents %08X", (unsigned)l); fprintf(f, "\n\n"); if (s->sh_type == SHT_NOBITS) return; if (0 == l) return; if (s->sh_type == SHT_SYMTAB) m = sizeof(ElfW(Sym)); else if (s->sh_type == SHT_RELX) m = sizeof(ElfW_Rel); else m = 16; fprintf(f, "%-8s", "offset"); for (i = 0; i < m; ++i) fprintf(f, " %02x", i); n = 56; if (s->sh_type == SHT_SYMTAB || s->sh_type == SHT_RELX) { const char *fields1[] = { "name", "value", "size", "bind", "type", "other", "shndx", NULL }; const char *fields2[] = { "offs", "type", "symb", NULL }; const char **p; if (s->sh_type == SHT_SYMTAB) p = fields1, n = 106; else p = fields2, n = 58; for (i = 0; p[i]; ++i) fprintf(f, "%6s", p[i]); fprintf(f, " symbol"); } fprintf(f, "\n"); for (i = 0; i < n; ++i) fprintf(f, "-"); fprintf(f, "\n"); for (i = 0; i < l;) { fprintf(f, "%08X", i); for (n = 0; n < m; ++n) { if (n + i < l) fprintf(f, " %02X", p[i + n]); else fprintf(f, " "); } if (s->sh_type == SHT_SYMTAB) { ElfW(Sym) *sym = (ElfW(Sym) *) (p + i); const char *name = s->link->data + sym->st_name; fprintf(f, " %04X %04X %04X %02X %02X %02X %04X \"%s\"", (unsigned)sym->st_name, (unsigned)sym->st_value, (unsigned)sym->st_size, (unsigned)ELFW(ST_BIND)(sym->st_info), (unsigned)ELFW(ST_TYPE)(sym->st_info), (unsigned)sym->st_other, (unsigned)sym->st_shndx, name); } else if (s->sh_type == SHT_RELX) { ElfW_Rel *rel = (ElfW_Rel *) (p + i); ElfW(Sym) *sym = (ElfW(Sym) *) s->link->data + ELFW(R_SYM)(rel->r_info); const char *name = s->link->link->data + sym->st_name; fprintf(f, " %04X %02X %04X \"%s\"", (unsigned)rel->r_offset, (unsigned)ELFW(R_TYPE)(rel->r_info), (unsigned)ELFW(R_SYM)(rel->r_info), name); } else { fprintf(f, " "); for (n = 0; n < m; ++n) { if (n + i < l) { b = p[i + n]; if (b < 32 || b >= 127) b = '.'; fprintf(f, "%c", b); } } } i += m; fprintf(f, "\n"); } fprintf(f, "\n\n"); } static void pe_print_sections(TCCState *s1, const char *fname) { Section *s; FILE *f; int i; f = fopen(fname, "w"); for (i = 1; i < s1->nb_sections; ++i) { s = s1->sections[i]; pe_print_section(f, s); } pe_print_section(f, s1->dynsymtab_section); fclose(f); } #endif /* ------------------------------------------------------------- */ /* helper function for load/store to insert one more indirection */ ST_FUNC SValue *pe_getimport(SValue *sv, SValue *v2) { Sym *sym; ElfW(Sym) *esym; int r2; if ((sv->r & (VT_VALMASK|VT_SYM)) != (VT_CONST|VT_SYM) || (sv->r2 != VT_CONST)) return sv; sym = sv->sym; if ((sym->type.t & (VT_EXTERN|VT_STATIC)) != VT_EXTERN) return sv; if (!sym->c) put_extern_sym(sym, NULL, 0, 0); esym = &((ElfW(Sym) *)symtab_section->data)[sym->c]; if (!(esym->st_other & 4)) return sv; // printf("import %04x %04x %04x %s\n", sv->type.t, sym->type.t, sv->r, get_tok_str(sv->sym->v, NULL)); memset(v2, 0, sizeof *v2); v2->type.t = VT_PTR; v2->r = VT_CONST | VT_SYM | VT_LVAL; v2->sym = sv->sym; r2 = get_reg(RC_INT); load(r2, v2); v2->r = r2; if (sv->c.ui) { vpushv(v2); vpushi(sv->c.ui); gen_opi('+'); *v2 = *vtop--; } v2->type.t = sv->type.t; v2->r |= sv->r & VT_LVAL; return v2; } ST_FUNC int pe_putimport(TCCState *s1, int dllindex, const char *name, addr_t value) { return add_elf_sym( s1->dynsymtab_section, value, dllindex, /* st_size */ ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0, value ? SHN_ABS : SHN_UNDEF, name ); } static int add_dllref(TCCState *s1, const char *dllname) { DLLReference *dllref; int i; for (i = 0; i < s1->nb_loaded_dlls; ++i) if (0 == strcmp(s1->loaded_dlls[i]->name, dllname)) return i + 1; dllref = tcc_mallocz(sizeof(DLLReference) + strlen(dllname)); strcpy(dllref->name, dllname); dynarray_add((void ***) &s1->loaded_dlls, &s1->nb_loaded_dlls, dllref); return s1->nb_loaded_dlls; } /* ------------------------------------------------------------- */ static int read_mem(int fd, unsigned offset, void *buffer, unsigned len) { lseek(fd, offset, SEEK_SET); return len == read(fd, buffer, len); } /* ------------------------------------------------------------- * This is for compiled windows resources in 'coff' format * as generated by 'windres.exe -O coff ...'. */ static int pe_load_res(TCCState *s1, int fd) { struct pe_rsrc_header hdr; Section *rsrc_section; int i, ret = -1; BYTE *ptr; unsigned offs; if (!read_mem(fd, 0, &hdr, sizeof hdr)) goto quit; if (hdr.filehdr.Machine != 0x014C || hdr.filehdr.NumberOfSections != 1 || strcmp(hdr.sectionhdr.Name, ".rsrc") != 0) goto quit; rsrc_section = new_section(s1, ".rsrc", SHT_PROGBITS, SHF_ALLOC); ptr = section_ptr_add(rsrc_section, hdr.sectionhdr.SizeOfRawData); offs = hdr.sectionhdr.PointerToRawData; if (!read_mem(fd, offs, ptr, hdr.sectionhdr.SizeOfRawData)) goto quit; offs = hdr.sectionhdr.PointerToRelocations; for (i = 0; i < hdr.sectionhdr.NumberOfRelocations; ++i) { struct pe_rsrc_reloc rel; if (!read_mem(fd, offs, &rel, sizeof rel)) goto quit; // printf("rsrc_reloc: %x %x %x\n", rel.offset, rel.size, rel.type); if (rel.type != 7) /* DIR32NB */ goto quit; put_elf_reloc(symtab_section, rsrc_section, rel.offset, R_XXX_RELATIVE, 0); offs += sizeof rel; } ret = 0; quit: return ret; } /* ------------------------------------------------------------- */ static char *trimfront(char *p) { while (*p && (unsigned char)*p <= ' ') ++p; return p; } static char *trimback(char *a, char *e) { while (e > a && (unsigned char)e[-1] <= ' ') --e; *e = 0;; return a; } static char *get_line(char *line, int size, int fd) { int n; for (n = 0; n < size - 1; ) if (read(fd, line + n, 1) < 1 || line[n++] == '\n') break; if (0 == n) return NULL; trimback(line, line + n); return trimfront(line); } /* ------------------------------------------------------------- */ static int pe_load_def(TCCState *s1, int fd) { int state = 0, ret = -1, dllindex = 0; char line[400], dllname[80], *p; for (;;) { p = get_line(line, sizeof line, fd); if (NULL == p) break; if (0 == *p || ';' == *p) continue; switch (state) { case 0: if (0 != strnicmp(p, "LIBRARY", 7)) goto quit; pstrcpy(dllname, sizeof dllname, trimfront(p+7)); ++state; continue; case 1: if (0 != stricmp(p, "EXPORTS")) goto quit; ++state; continue; case 2: dllindex = add_dllref(s1, dllname); ++state; default: pe_putimport(s1, dllindex, p, 0); continue; } } ret = 0; quit: return ret; } /* ------------------------------------------------------------- */ #define TINY_IMPDEF_GET_EXPORT_NAMES_ONLY #include "win32/tools/tiny_impdef.c" static int pe_load_dll(TCCState *s1, const char *dllname, int fd) { char *p, *q; int index; p = get_export_names(fd); if (!p) return -1; index = add_dllref(s1, dllname); for (q = p; *q; q += 1 + strlen(q)) pe_putimport(s1, index, q, 0); tcc_free(p); return 0; } /* ------------------------------------------------------------- */ ST_FUNC int pe_load_file(struct TCCState *s1, const char *filename, int fd) { int ret = -1; char buf[10]; if (0 == strcmp(tcc_fileextension(filename), ".def")) ret = pe_load_def(s1, fd); else if (pe_load_res(s1, fd) == 0) ret = 0; else if (read_mem(fd, 0, buf, sizeof buf) && 0 == strncmp(buf, "MZ", 2)) ret = pe_load_dll(s1, tcc_basename(filename), fd); return ret; } /* ------------------------------------------------------------- */ #ifdef TCC_TARGET_X86_64 static unsigned pe_add_uwwind_info(TCCState *s1) { if (NULL == s1->uw_pdata) { s1->uw_pdata = find_section(tcc_state, ".pdata"); s1->uw_pdata->sh_addralign = 4; s1->uw_sym = put_elf_sym(symtab_section, 0, 0, 0, 0, text_section->sh_num, NULL); } if (0 == s1->uw_offs) { /* As our functions all have the same stackframe, we use one entry for all */ static const unsigned char uw_info[] = { 0x01, // UBYTE: 3 Version , UBYTE: 5 Flags 0x04, // UBYTE Size of prolog 0x02, // UBYTE Count of unwind codes 0x05, // UBYTE: 4 Frame Register (rbp), UBYTE: 4 Frame Register offset (scaled) // USHORT * n Unwind codes array // 0x0b, 0x01, 0xff, 0xff, // stack size 0x04, 0x03, // set frame ptr (mov rsp -> rbp) 0x01, 0x50 // push reg (rbp) }; Section *s = text_section; unsigned char *p; section_ptr_add(s, -s->data_offset & 3); /* align */ s1->uw_offs = s->data_offset; p = section_ptr_add(s, sizeof uw_info); memcpy(p, uw_info, sizeof uw_info); } return s1->uw_offs; } ST_FUNC void pe_add_unwind_data(unsigned start, unsigned end, unsigned stack) { TCCState *s1 = tcc_state; Section *pd; unsigned o, n, d; struct /* _RUNTIME_FUNCTION */ { DWORD BeginAddress; DWORD EndAddress; DWORD UnwindData; } *p; d = pe_add_uwwind_info(s1); pd = s1->uw_pdata; o = pd->data_offset; p = section_ptr_add(pd, sizeof *p); /* record this function */ p->BeginAddress = start; p->EndAddress = end; p->UnwindData = d; /* put relocations on it */ for (n = o + sizeof *p; o < n; o += sizeof p->BeginAddress) put_elf_reloc(symtab_section, pd, o, R_X86_64_RELATIVE, s1->uw_sym); } #endif /* ------------------------------------------------------------- */ #ifdef TCC_TARGET_X86_64 #define PE_STDSYM(n,s) n #else #define PE_STDSYM(n,s) "_" n s #endif extern unsigned long long int start; unsigned long long int timestamp(); static void pe_add_runtime(TCCState *s1, struct pe_info *pe) { const char *start_symbol; ADDR3264 addr = 0; int pe_type = 0; if (find_elf_sym(symtab_section, PE_STDSYM("WinMain","@16"))) pe_type = PE_GUI; else if (TCC_OUTPUT_DLL == s1->output_type) { pe_type = PE_DLL; /* need this for 'tccelf.c:relocate_section()' */ s1->output_type = TCC_OUTPUT_EXE; } else pe_type = PE_EXE; //printf("trace 13: %i\n", timestamp() - start); start_symbol = TCC_OUTPUT_MEMORY == s1->output_type ? PE_GUI == pe_type ? "__runwinmain" : "_main" : PE_DLL == pe_type ? PE_STDSYM("__dllstart","@12") : PE_GUI == pe_type ? "__winstart" : "__start" ; if (!s1->leading_underscore || strchr(start_symbol, '@')) { ++start_symbol; if (start_symbol[0] != '_') start_symbol = NULL; } //printf("trace 14: %i\n", timestamp() - start); /* grab the startup code from libtcc1 */ if (start_symbol) add_elf_sym(symtab_section, 0, 0, ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0, SHN_UNDEF, start_symbol); if (0 == s1->nostdlib) { static const char *libs[] = { "libtcc1.a", "msvcrt", "kernel32", "", "user32", "gdi32", NULL }; const char **pp, *p; int idx = 0; for (pp = libs; 0 != (p = *pp); ++pp) { if (0 == *p) { if (PE_DLL != pe_type && PE_GUI != pe_type) break; } else if (pp == libs ? tcc_add_dll(s1, p, 0) : tcc_add_library(s1, p)) { tcc_error_noabort("cannot find library: %s", p); break; } } } //printf("trace 15: %i\n", timestamp() - start); if (TCC_OUTPUT_MEMORY == s1->output_type) pe_type = PE_RUN; if (start_symbol) { addr = get_elf_sym_addr(s1, start_symbol, 1); //printf("trace 16: %i\n", timestamp() - start); if (PE_RUN == pe_type && addr) /* for -run GUI's, put '_runwinmain' instead of 'main' */ add_elf_sym(symtab_section, addr, 0, ELFW(ST_INFO)(STB_GLOBAL, STT_NOTYPE), 0, text_section->sh_num, "main"); } pe->type = pe_type; pe->start_addr = addr; } #include <stdio.h> ST_FUNC int pe_output_file(TCCState * s1, const char *filename) { int ret; struct pe_info pe; int i; //printf("trace 8: %i\n", timestamp() - start); memset(&pe, 0, sizeof pe); pe.filename = filename; pe.s1 = s1; tcc_add_bcheck(s1); //printf("trace 9: %i\n", timestamp() - start); pe_add_runtime(s1, &pe); //printf("trace 10: %i\n", timestamp() - start); relocate_common_syms(); /* assign bss adresses */ //printf("trace 11: %i\n", timestamp() - start); tcc_add_linker_symbols(s1); //printf("trace 3: %i\n", timestamp() - start); ret = pe_check_symbols(&pe); if (ret) ; else if (filename) { if (PE_DLL == pe.type) { pe.reloc = new_section(pe.s1, ".reloc", SHT_PROGBITS, 0); /* XXX: check if is correct for arm-pe target */ pe.imagebase = 0x10000000; } else { #if defined(TCC_TARGET_ARM) pe.imagebase = 0x00010000; #else pe.imagebase = 0x00400000; #endif } //printf("trace 4: %i\n", timestamp() - start); #if defined(TCC_TARGET_ARM) /* we use "console" subsystem by default */ pe.subsystem = 9; #else if (PE_DLL == pe.type || PE_GUI == pe.type) pe.subsystem = 2; else pe.subsystem = 3; #endif /* Allow override via -Wl,-subsystem=... option */ if (s1->pe_subsystem != 0) pe.subsystem = s1->pe_subsystem; /* set default file/section alignment */ if (pe.subsystem == 1) { pe.section_align = 0x20; pe.file_align = 0x20; } else { pe.section_align = 0x1000; pe.file_align = 0x200; } if (s1->section_align != 0) pe.section_align = s1->section_align; if (s1->pe_file_align != 0) pe.file_align = s1->pe_file_align; if ((pe.subsystem >= 10) && (pe.subsystem <= 12)) pe.imagebase = 0; if (s1->has_text_addr) pe.imagebase = s1->text_addr; //printf("trace 5: %i\n", timestamp() - start); pe_assign_addresses(&pe); relocate_syms(s1, 0); for (i = 1; i < s1->nb_sections; ++i) { Section *s = s1->sections[i]; if (s->reloc) { relocate_section(s1, s); pe_relocate_rva(&pe, s); } } if (s1->nb_errors) ret = -1; else ret = pe_write(&pe); tcc_free(pe.sec_info); } else { #ifdef TCC_IS_NATIVE pe.thunk = data_section; pe_build_imports(&pe); #endif } //printf("trace 6: %i\n", timestamp() - start); #ifdef PE_PRINT_SECTIONS pe_print_sections(s1, "tcc.log"); #endif //printf("trace 7: %i\n", timestamp() - start); return ret; } /* ------------------------------------------------------------- */
lgpl-2.1
orbeon/orbeon-forms
src/main/java/org/orbeon/oxf/processor/impl/DelegatingProcessorInput.java
3194
/** * Copyright (C) 2010 Orbeon, Inc. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version * 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ package org.orbeon.oxf.processor.impl; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.processor.Processor; import org.orbeon.oxf.processor.ProcessorImpl; import org.orbeon.oxf.processor.ProcessorInput; import org.orbeon.oxf.processor.ProcessorOutput; import org.orbeon.datatypes.LocationData; public class DelegatingProcessorInput implements ProcessorInput { private final String originalName; private ProcessorInput delegateInput; private ProcessorOutput delegateOutput; private ProcessorImpl processor; public DelegatingProcessorInput(ProcessorImpl processor, String originalName, ProcessorInput delegateInput, ProcessorOutput delegateOutput) { this.processor = processor; this.originalName = originalName; this.delegateInput = delegateInput; this.delegateOutput = delegateOutput; } DelegatingProcessorInput(ProcessorImpl processor, String originalName) { this.processor = processor; this.originalName = originalName; } public Processor getProcessor(PipelineContext pipelineContext) { return processor; } public void setDelegateInput(ProcessorInput delegateInput) { this.delegateInput = delegateInput; } public void setDelegateOutput(ProcessorOutput delegateOutput) { this.delegateOutput = delegateOutput; } public void setOutput(ProcessorOutput output) { delegateInput.setOutput(output); } public ProcessorOutput getOutput() { // Not sure why the input validation stuff expects another output here. For now, allow caller to specify // which output is returned. Once we are confident, switch to delegateInput.getOutput(). return delegateOutput; // return delegateInput.getOutput(); } public String getSchema() { return delegateInput.getSchema(); } public void setSchema(String schema) { delegateInput.setSchema(schema); } public Class getProcessorClass() { return processor.getClass(); } public String getName() { return originalName; } public void setDebug(String debugMessage) { delegateInput.setDebug(debugMessage); } public void setLocationData(LocationData locationData) { delegateInput.setLocationData(locationData); } public String getDebugMessage() { return delegateInput.getDebugMessage(); } public LocationData getLocationData() { return delegateInput.getLocationData(); } }
lgpl-2.1
nacho/libgit2
include/git2/threads.h
1106
/* * Copyright (C) 2009-2012 the libgit2 contributors * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #ifndef INCLUDE_git_threads_h__ #define INCLUDE_git_threads_h__ #include "common.h" /** * @file git2/threads.h * @brief Library level thread functions * @defgroup git_thread Threading functions * @ingroup Git * @{ */ GIT_BEGIN_DECL /** * Init the threading system. * * If libgit2 has been built with GIT_THREADS * on, this function must be called once before * any other library functions. * * If libgit2 has been built without GIT_THREADS * support, this function is a no-op. * * @return 0 or an error code */ GIT_EXTERN(int) git_threads_init(void); /** * Shutdown the threading system. * * If libgit2 has been built with GIT_THREADS * on, this function must be called before shutting * down the library. * * If libgit2 has been built without GIT_THREADS * support, this function is a no-op. */ GIT_EXTERN(void) git_threads_shutdown(void); /** @} */ GIT_END_DECL #endif
lgpl-2.1
KDE/android-qt-creator
src/plugins/coreplugin/editormanager/openeditorswindow.cpp
10060
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "openeditorswindow.h" #include "openeditorsmodel.h" #include "editormanager.h" #include "editorview.h" #include "idocument.h" #include <utils/qtcassert.h> #include <QFocusEvent> #include <QHeaderView> #include <QTreeWidget> #include <QVBoxLayout> Q_DECLARE_METATYPE(Core::Internal::EditorView*) Q_DECLARE_METATYPE(Core::IDocument*) using namespace Core; using namespace Core::Internal; const int WIDTH = 300; const int HEIGHT = 200; OpenEditorsWindow::OpenEditorsWindow(QWidget *parent) : QFrame(parent, Qt::Popup), m_emptyIcon(QLatin1String(":/core/images/empty14.png")), m_editorList(new QTreeWidget(this)) { resize(QSize(WIDTH, HEIGHT)); m_editorList->setColumnCount(1); m_editorList->header()->hide(); m_editorList->setIndentation(0); m_editorList->setSelectionMode(QAbstractItemView::SingleSelection); m_editorList->setTextElideMode(Qt::ElideMiddle); #ifdef Q_OS_MAC m_editorList->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); #endif m_editorList->installEventFilter(this); // We disable the frame on this list view and use a QFrame around it instead. // This improves the look with QGTKStyle. #ifndef Q_OS_MAC setFrameStyle(m_editorList->frameStyle()); #endif m_editorList->setFrameStyle(QFrame::NoFrame); QVBoxLayout *layout = new QVBoxLayout(this); layout->setMargin(0); layout->addWidget(m_editorList); connect(m_editorList, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(editorClicked(QTreeWidgetItem*))); } void OpenEditorsWindow::selectAndHide() { setVisible(false); selectEditor(m_editorList->currentItem()); } void OpenEditorsWindow::setVisible(bool visible) { QWidget::setVisible(visible); if (visible) { setFocus(); } } bool OpenEditorsWindow::isCentering() { int internalMargin = m_editorList->viewport()->mapTo(m_editorList, QPoint(0,0)).y(); QRect rect0 = m_editorList->visualItemRect(m_editorList->topLevelItem(0)); QRect rect1 = m_editorList->visualItemRect(m_editorList->topLevelItem(m_editorList->topLevelItemCount()-1)); int height = rect1.y() + rect1.height() - rect0.y(); height += 2 * internalMargin; if (height > HEIGHT) return true; return false; } bool OpenEditorsWindow::eventFilter(QObject *obj, QEvent *e) { if (obj == m_editorList) { if (e->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent*>(e); if (ke->key() == Qt::Key_Escape) { setVisible(false); return true; } if (ke->key() == Qt::Key_Return) { selectEditor(m_editorList->currentItem()); return true; } } else if (e->type() == QEvent::KeyRelease) { QKeyEvent *ke = static_cast<QKeyEvent*>(e); if (ke->modifiers() == 0 /*HACK this is to overcome some event inconsistencies between platforms*/ || (ke->modifiers() == Qt::AltModifier && (ke->key() == Qt::Key_Alt || ke->key() == -1))) { selectAndHide(); } } } return QWidget::eventFilter(obj, e); } void OpenEditorsWindow::focusInEvent(QFocusEvent *) { m_editorList->setFocus(); } void OpenEditorsWindow::selectUpDown(bool up) { int itemCount = m_editorList->topLevelItemCount(); if (itemCount < 2) return; int index = m_editorList->indexOfTopLevelItem(m_editorList->currentItem()); if (index < 0) return; QTreeWidgetItem *editor = 0; int count = 0; while (!editor && count < itemCount) { if (up) { index--; if (index < 0) index = itemCount-1; } else { index++; if (index >= itemCount) index = 0; } editor = m_editorList->topLevelItem(index); count++; } if (editor) { m_editorList->setCurrentItem(editor); ensureCurrentVisible(); } } void OpenEditorsWindow::selectPreviousEditor() { selectUpDown(false); } void OpenEditorsWindow::selectNextEditor() { selectUpDown(true); } void OpenEditorsWindow::centerOnItem(int selectedIndex) { if (selectedIndex >= 0) { QTreeWidgetItem *item; int num = m_editorList->topLevelItemCount(); int rotate = selectedIndex-(num-1)/2; for (int i = 0; i < rotate; ++i) { item = m_editorList->takeTopLevelItem(0); m_editorList->addTopLevelItem(item); } rotate = -rotate; for (int i = 0; i < rotate; ++i) { item = m_editorList->takeTopLevelItem(num-1); m_editorList->insertTopLevelItem(0, item); } } } void OpenEditorsWindow::setEditors(EditorView *mainView, EditorView *view, OpenEditorsModel *model) { m_editorList->clear(); bool first = true; QSet<IDocument*> documentsDone; foreach (const EditLocation &hi, view->editorHistory()) { if (hi.document.isNull() || documentsDone.contains(hi.document)) continue; QString title = model->displayNameForDocument(hi.document); QTC_ASSERT(!title.isEmpty(), continue); documentsDone.insert(hi.document.data()); QTreeWidgetItem *item = new QTreeWidgetItem(); if (hi.document->isModified()) title += tr("*"); item->setIcon(0, !hi.document->fileName().isEmpty() && hi.document->isFileReadOnly() ? model->lockedIcon() : m_emptyIcon); item->setText(0, title); item->setToolTip(0, hi.document->fileName()); item->setData(0, Qt::UserRole, QVariant::fromValue(hi.document.data())); item->setData(0, Qt::UserRole+1, QVariant::fromValue(view)); item->setTextAlignment(0, Qt::AlignLeft); m_editorList->addTopLevelItem(item); if (first){ m_editorList->setCurrentItem(item); first = false; } } // add missing editors from the main view if (mainView != view) { foreach (const EditLocation &hi, mainView->editorHistory()) { if (hi.document.isNull() || documentsDone.contains(hi.document)) continue; documentsDone.insert(hi.document.data()); QTreeWidgetItem *item = new QTreeWidgetItem(); QString title = model->displayNameForDocument(hi.document); if (hi.document->isModified()) title += tr("*"); item->setIcon(0, !hi.document->fileName().isEmpty() && hi.document->isFileReadOnly() ? model->lockedIcon() : m_emptyIcon); item->setText(0, title); item->setToolTip(0, hi.document->fileName()); item->setData(0, Qt::UserRole, QVariant::fromValue(hi.document.data())); item->setData(0, Qt::UserRole+1, QVariant::fromValue(view)); item->setData(0, Qt::UserRole+2, QVariant::fromValue(hi.id)); item->setTextAlignment(0, Qt::AlignLeft); m_editorList->addTopLevelItem(item); if (first){ m_editorList->setCurrentItem(item); first = false; } } } // add purely restored editors which are not initialised yet foreach (const OpenEditorsModel::Entry &entry, model->entries()) { if (entry.editor) continue; QTreeWidgetItem *item = new QTreeWidgetItem(); QString title = entry.displayName(); item->setIcon(0, m_emptyIcon); item->setText(0, title); item->setToolTip(0, entry.fileName()); item->setData(0, Qt::UserRole+2, QVariant::fromValue(entry.id())); item->setTextAlignment(0, Qt::AlignLeft); m_editorList->addTopLevelItem(item); } } void OpenEditorsWindow::selectEditor(QTreeWidgetItem *item) { if (!item) return; if (IDocument *document = item->data(0, Qt::UserRole).value<IDocument*>()) { EditorView *view = item->data(0, Qt::UserRole+1).value<EditorView*>(); EditorManager::instance()->activateEditorForDocument(view, document, EditorManager::ModeSwitch); } else { if (!EditorManager::openEditor( item->toolTip(0), item->data(0, Qt::UserRole+2).value<Core::Id>(), Core::EditorManager::ModeSwitch)) { EditorManager::instance()->openedEditorsModel()->removeEditor(item->toolTip(0)); delete item; } } } void OpenEditorsWindow::editorClicked(QTreeWidgetItem *item) { selectEditor(item); setFocus(); } void OpenEditorsWindow::ensureCurrentVisible() { m_editorList->scrollTo(m_editorList->currentIndex(), QAbstractItemView::PositionAtCenter); }
lgpl-2.1
ignatenkobrain/beignet
utests/compiler_local_memory_two_ptr.cpp
1557
/* * Copyright © 2012 Intel Corporation * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * * Author: Benjamin Segovia <benjamin.segovia@intel.com> */ #include "utest_helper.hpp" static void compiler_local_memory_two_ptr(void) { const size_t n = 1024; // Setup kernel and buffers OCL_CREATE_KERNEL("compiler_local_memory_two_ptr"); OCL_CREATE_BUFFER(buf[0], 0, n * sizeof(uint32_t), NULL); OCL_SET_ARG(0, sizeof(cl_mem), &buf[0]); OCL_SET_ARG(1, 64, NULL); // 16 x int OCL_SET_ARG(2, 64, NULL); // 16 x int // Run the kernel globals[0] = n; locals[0] = 16; OCL_NDRANGE(1); OCL_MAP_BUFFER(0); // Check results int32_t *dst = (int32_t*)buf_data[0]; for (int32_t i = 0; i < (int) n; i+=16) for (int32_t j = 0; j < 16; ++j) { const int gid = i + j; const int tid = j; OCL_ASSERT(dst[i+j] == (gid&~0xf) + 15-tid + 15-tid); } } MAKE_UTEST_FROM_FUNCTION(compiler_local_memory_two_ptr);
lgpl-2.1
eaulisa/MyFEMuS
src/enums/MarkerTypeEnum.hpp
180
#ifndef __femus_enums_MarkerTypeEnum_hpp__ #define __femus_enums_MarkerTypeEnum_hpp__ enum MarkerType { VOLUME = 0, INTERSECTION, FIXED, BOUNDARY, INTERIOR }; #endif
lgpl-2.1
roboidstudio/embedded
org.roboid.studio.timeline.model/src/org/roboid/studio/timeline/impl/AudioTrackImpl.java
10917
/* * Part of the ROBOID project * Copyright (C) 2016 Kwang-Hyun Park (akaii@kw.ac.kr) and Kyoung Jin Kim * https://github.com/roboidstudio/embedded * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package org.roboid.studio.timeline.impl; import java.util.Arrays; import java.util.List; import javax.sound.sampled.AudioFormat; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.ui.views.properties.IPropertyDescriptor; import org.eclipse.ui.views.properties.PropertyDescriptor; import org.roboid.audio.AudioUtil; import org.roboid.robot.AudioMode; import org.roboid.robot.DataType; import org.roboid.robot.Device; import org.roboid.studio.timeline.AudioPoint; import org.roboid.studio.timeline.AudioTrack; import org.roboid.studio.timeline.ChannelTrack; import org.roboid.studio.timeline.ControlPoint; import org.roboid.studio.timeline.TimelineFactory; import org.roboid.studio.timeline.TimelinePackage; import org.roboid.studio.timeline.VoicePoint; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Audio Track</b></em>'. * @author Kyoung Jin Kim * @author Kwang-Hyun Park * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.roboid.studio.timeline.impl.AudioTrackImpl#getMode <em>Mode</em>}</li> * </ul> * </p> * * @generated */ public class AudioTrackImpl extends ChannelTrackImpl implements AudioTrack { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected AudioTrackImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return TimelinePackage.Literals.AUDIO_TRACK; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMode(AudioMode newMode) { AudioMode oldMode = mode; mode = newMode == null ? MODE_EDEFAULT : newMode; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TimelinePackage.AUDIO_TRACK__MODE, oldMode, mode)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case TimelinePackage.AUDIO_TRACK__MODE: return getMode(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case TimelinePackage.AUDIO_TRACK__MODE: setMode((AudioMode)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case TimelinePackage.AUDIO_TRACK__MODE: setMode(MODE_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case TimelinePackage.AUDIO_TRACK__MODE: return mode != MODE_EDEFAULT; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (mode: "); result.append(mode); result.append(')'); return result.toString(); } /*===================================================================================== *===================================================================================== * MODIFIED *===================================================================================== *===================================================================================== */ /** * The default value of the '{@link #getMode() <em>Mode</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMode() * @generated NOT * @ordered */ protected static final AudioMode MODE_EDEFAULT = null; /** * The cached value of the '{@link #getMode() <em>Mode</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMode() * @generated * @ordered */ protected AudioMode mode = MODE_EDEFAULT; private static final String P_MODE = "_mode"; int[] wave; // temporary wave data for one frame private AudioFormat audioFormat; @Override protected void getPropertyDescriptors(List<IPropertyDescriptor> propertyDescriptors) { super.getPropertyDescriptors(propertyDescriptors); propertyDescriptors.add(new PropertyDescriptor(P_MODE, "Mode")); } @Override public Object getPropertyValue(Object id) { if(id.equals(P_CHANNEL)) return "Audio Channel"; if(id.equals(P_MODE)) return getMode().getLiteral(); if(id.equals(P_TARGET_DEVICE)) { Device left = getTargetDevice(0); if(left == null) return ""; Device right = getTargetDevice(1); if(right == null) return left.getName(); else return left.getName() + ", " + right.getName(); } return super.getPropertyValue(id); } @Override public ChannelTrack deepCopy() { AudioTrack newTrack = TimelineFactory.eINSTANCE.createAudioTrack(); copyTo(newTrack); return newTrack; } @Override public boolean canCopy(ControlPoint cp) { if(cp instanceof AudioPoint) return true; return false; } @Override public AudioPoint deepCopy(ControlPoint cp) { if(cp instanceof VoicePoint) { AudioPoint newPoint = TimelineFactory.eINSTANCE.createAudioPoint(); ((AudioPointImpl)cp).copyTo(newPoint); return newPoint; } else if(cp instanceof AudioPoint) return (AudioPoint)cp.deepCopy(); return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ public AudioMode getMode() { if(mode == null) { if(getTargetDevices().size() == 1) mode = AudioMode.MONO; else mode = AudioMode.STEREO; } return mode; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated NOT */ public void setMode(int newMode) { AudioMode mode = AudioMode.get(newMode); if(mode != null) setMode(mode); } @Override public int getTotalFrames() { int maxFrame = 0; for(ControlPoint cp : getPoints()) { int frame = cp.getFrame() + ((AudioPoint)cp).getLength(); // start frame + length of frames if(maxFrame < frame) maxFrame = frame; } return maxFrame; } private AudioFormat getAudioFormatOfChannel(Device device) { // exception // support only BYTE, SHORT, INTEGER types if(!(device.getDataType().equals(DataType.BYTE) || device.getDataType().equals(DataType.SHORT) || device.getDataType().equals(DataType.INTEGER))) throw new IllegalArgumentException("The datatype of target device should be BYTE, SHORT or INTEGER only."); // format int sampleSizeInBits = device.getDataType().getValue(); int channels = (getMode() == AudioMode.STEREO) ? 2 : 1; int frameSize = ((sampleSizeInBits + 7) / 8) * channels; float sampleRate = 50 * device.getDataSize(); AudioFormat targetFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, sampleRate, sampleSizeInBits, channels, frameSize, sampleRate, false); return targetFormat; } public void preLoad() { Device leftDevice = getTargetDevice(0); audioFormat = getAudioFormatOfChannel(leftDevice); for(ControlPoint cp : getPoints()) { ((AudioPoint)cp).getPcm(audioFormat); } } @Override public void dump(int frame) { if(getPoints().size() == 0) return; // no control points Device leftDevice = getTargetDevice(0); Device rightDevice = getTargetDevice(1); dump(frame, leftDevice, rightDevice); } /** * writes audio data at current frame to the corresponding device * * @param frame * @param leftDevice * @param rightDevice */ protected void dump(int frame, Device leftDevice, Device rightDevice) { if(leftDevice == null) return; // device format if(audioFormat == null) audioFormat = getAudioFormatOfChannel(leftDevice); // obtain audio data at current frame wave = getAudioData(frame, leftDevice, audioFormat); if(getMode() == AudioMode.MONO) { leftDevice.write(wave); } else { if(rightDevice == null) return; // stereo case AudioFormat rightDeviceFormat = getAudioFormatOfChannel(rightDevice); // exception // audio formats of two target devices should be same if(!AudioUtil.isEqual(audioFormat, rightDeviceFormat)) { throw new IllegalArgumentException("The type of two target audio devices should be the same: " + audioFormat + " and " + rightDeviceFormat); } // divide two channels into seperate arrays int stereo[][] = AudioUtil.splitChannel(wave, audioFormat.getChannels()); // write to each device leftDevice.write(stereo[1]); // IMPORTANT: exchange left and right rightDevice.write(stereo[0]); } } /** * returns audio data at current frame in target format * * @param frame * @param targetFormat * @return */ private int[] getAudioData(int frame, Device device, AudioFormat targetFormat) { int dataSize = device.getDataSize() * targetFormat.getChannels(); int maxValue = device.getMax();; int minValue = device.getMin(); if(wave == null) wave = new int[dataSize]; Arrays.fill(wave, 0); for(ControlPoint cp : getPoints()) { AudioPoint ap = (AudioPoint)cp; if(frame < ap.getFrame()) break; else if(frame >= ap.getFrame() + ap.getLength()) continue; int[] pcm = ap.getPcm(targetFormat); if(pcm == null) continue; // calculate offset of current frame in whole audio data int offset = (frame - ap.getFrame()) * dataSize; int len = pcm.length > offset + dataSize ? dataSize : pcm.length - offset; // apply volume to audio data AudioUtil.multiplyAndSum(pcm, offset, ap.getVolume()/100.0f, wave, 0, len, minValue, maxValue); } return wave; } } //AudioTrackImpl
lgpl-2.1
tinybit/nextweb
include/nextweb/utils/Iterator.hpp
8530
// nextweb - modern web framework for Python and C++ // Copyright (C) 2011 Oleg Obolenskiy <highpower@yandex-team.ru> // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. #ifndef NEXTWEB_UTILS_ITERATOR_HPP_INCLUDED #define NEXTWEB_UTILS_ITERATOR_HPP_INCLUDED #include <iterator> #include "nextweb/Config.hpp" namespace nextweb { namespace utils { template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference, typename Tag> struct IteratorBase; template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> struct IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag> { Pointer operator -> (); Reference operator * (); Derived& operator ++ (); Derived operator ++ (int); bool operator == (Derived const &other) const; bool operator != (Derived const &other) const; }; template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> struct IteratorBase<Derived, Type, Dist, Pointer, Reference, std::bidirectional_iterator_tag> : public IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag> { Derived& operator -- (); Derived operator -- (int); }; template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> struct IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag> : public IteratorBase<Derived, Type, Dist, Pointer, Reference, std::bidirectional_iterator_tag> { Derived operator + (Dist dist) const; Derived& operator += (Dist dist); Derived operator - (Dist dist) const; Derived& operator -= (Dist dist); Type operator [] (Dist dist) const; Dist operator - (Derived const &other) const; bool operator < (Derived const &other) const; bool operator > (Derived const &other) const; bool operator <= (Derived const &other) const; bool operator >= (Derived const &other) const; }; template <typename Derived, typename Tag, typename Type, typename Dist = std::ptrdiff_t, typename Pointer = Type*, typename Reference = Type&> struct Iterator : public IteratorBase<Derived, Type, Dist, Pointer, Reference, Tag>, public std::iterator<Tag, Type, Dist, Pointer, Reference> { }; template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived& IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>::operator ++ () { Derived &object = static_cast<Derived&>(*this); object.increment(); return object; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>::operator ++ (int) { Derived copy(static_cast<Derived const&>(*this)); ++(*this); return copy; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Pointer IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>::operator -> () { Reference ref = static_cast<Derived*>(this)->dereference(); return &ref; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Reference IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>::operator * () { return static_cast<Derived*>(this)->dereference(); } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE bool IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>::operator == (Derived const &other) const { return static_cast<Derived const*>(this)->equal(other); } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE bool IteratorBase<Derived, Type, Dist, Pointer, Reference, std::forward_iterator_tag>::operator != (Derived const &other) const { return !static_cast<Derived const*>(this)->equal(other); } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived& IteratorBase<Derived, Type, Dist, Pointer, Reference, std::bidirectional_iterator_tag>::operator -- () { Derived &object = static_cast<Derived&>(*this); object.decrement(); return object; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived IteratorBase<Derived, Type, Dist, Pointer, Reference, std::bidirectional_iterator_tag>::operator -- (int) { Derived copy(static_cast<Derived const&>(*this)); --(*this); return copy; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator + (Dist dist) const { Derived copy(static_cast<Derived const&>(*this)); copy += dist; return copy; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived& IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator += (Dist dist) { Derived &object = static_cast<Derived&>(*this); object.advance(dist); return object; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator - (Dist dist) const { Derived copy(static_cast<Derived const&>(*this)); copy -= dist; return copy; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Derived& IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator -= (Dist dist) { Derived &object = static_cast<Derived&>(*this); object.advance(-dist); return object; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Type IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator [] (Dist dist) const { Derived copy(static_cast<Derived const&>(*this)); copy += dist; return copy.dereference(); } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE Dist IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator - (Derived const &other) const { return other.distance(static_cast<Derived const&>(*this)); } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE bool IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator < (Derived const &other) const { return (static_cast<Derived const&>(*this) - other) < 0; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE bool IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator > (Derived const &other) const { return (static_cast<Derived const&>(*this) - other) > 0; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE bool IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator <= (Derived const &other) const { return (static_cast<Derived const&>(*this) - other) <= 0; } template <typename Derived, typename Type, typename Dist, typename Pointer, typename Reference> NEXTWEB_INLINE bool IteratorBase<Derived, Type, Dist, Pointer, Reference, std::random_access_iterator_tag>::operator >= (Derived const &other) const { return (static_cast<Derived const&>(*this) - other) >= 0; } }} // namespaces #endif // NEXTWEB_UTILS_ITERATOR_HPP_INCLUDED
lgpl-2.1
oliverchang/libavoid
tests/forwardFlowingConnectors01.cpp
14496
#include "libavoid/libavoid.h" using namespace Avoid; int main(void) { Router *router = new Router(OrthogonalRouting); router->setRoutingParameter((RoutingParameter)0, 10); router->setRoutingParameter((RoutingParameter)1, 0); router->setRoutingParameter((RoutingParameter)2, 1000); router->setRoutingParameter((RoutingParameter)3, 4000); router->setRoutingParameter((RoutingParameter)4, 0); router->setRoutingParameter((RoutingParameter)5, 100); router->setRoutingParameter((RoutingParameter)6, 1); router->setRoutingParameter((RoutingParameter)7, 10); router->setRoutingParameter(reverseDirectionPenalty, 500); router->setRoutingOption((RoutingOption)0, false); router->setRoutingOption((RoutingOption)1, true); router->setRoutingOption((RoutingOption)2, false); router->setRoutingOption((RoutingOption)3, false); router->setRoutingOption((RoutingOption)4, true); router->setRoutingOption((RoutingOption)5, true); Polygon polygon; ConnRef *connRef = NULL; ConnEnd srcPt; ConnEnd dstPt; PolyLine newRoute; // shapeRef1 polygon = Polygon(4); polygon.ps[0] = Point(0, 0); polygon.ps[1] = Point(0, 0); polygon.ps[2] = Point(0, 0); polygon.ps[3] = Point(0, 0); new ShapeRef(router, polygon, 1); // shapeRef2 polygon = Polygon(4); polygon.ps[0] = Point(0, 0); polygon.ps[1] = Point(0, 0); polygon.ps[2] = Point(0, 0); polygon.ps[3] = Point(0, 0); new ShapeRef(router, polygon, 2); // shapeRef3 polygon = Polygon(4); polygon.ps[0] = Point(0, 0); polygon.ps[1] = Point(0, 0); polygon.ps[2] = Point(0, 0); polygon.ps[3] = Point(0, 0); new ShapeRef(router, polygon, 3); // shapeRef4 polygon = Polygon(4); polygon.ps[0] = Point(0, 0); polygon.ps[1] = Point(0, 0); polygon.ps[2] = Point(0, 0); polygon.ps[3] = Point(0, 0); new ShapeRef(router, polygon, 4); // shapeRef5 polygon = Polygon(4); polygon.ps[0] = Point(501, 345); polygon.ps[1] = Point(501, 404); polygon.ps[2] = Point(421, 404); polygon.ps[3] = Point(421, 345); ShapeRef *shapeRef5 = new ShapeRef(router, polygon, 5); new ShapeConnectionPin(shapeRef5, 5, 1, 0.652542, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef5, 6, 0, 0.79096, true, 0, (ConnDirFlags) 4); new ShapeConnectionPin(shapeRef5, 7, 0, 0.514124, true, 0, (ConnDirFlags) 4); // shapeRef6 polygon = Polygon(4); polygon.ps[0] = Point(94, 251.5); polygon.ps[1] = Point(94, 315.5); polygon.ps[2] = Point(12, 315.5); polygon.ps[3] = Point(12, 251.5); ShapeRef *shapeRef6 = new ShapeRef(router, polygon, 6); new ShapeConnectionPin(shapeRef6, 8, 1, 0.640625, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef6, 9, 0, 0.640625, true, 0, (ConnDirFlags) 4); // shapeRef7 polygon = Polygon(4); polygon.ps[0] = Point(634.366, 262); polygon.ps[1] = Point(634.366, 305); polygon.ps[2] = Point(416.366, 305); polygon.ps[3] = Point(416.366, 262); ShapeRef *shapeRef7 = new ShapeRef(router, polygon, 7); new ShapeConnectionPin(shapeRef7, 10, 1, 0.709302, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef7, 11, 0, 0.709302, true, 0, (ConnDirFlags) 4); // shapeRef8 polygon = Polygon(4); polygon.ps[0] = Point(324, 147.167); polygon.ps[1] = Point(324, 206.167); polygon.ps[2] = Point(236, 206.167); polygon.ps[3] = Point(236, 147.167); ShapeRef *shapeRef8 = new ShapeRef(router, polygon, 8); new ShapeConnectionPin(shapeRef8, 12, 1, 0.652542, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef8, 13, 0, 0.79096, true, 0, (ConnDirFlags) 4); new ShapeConnectionPin(shapeRef8, 14, 0, 0.514124, true, 0, (ConnDirFlags) 4); // shapeRef9 polygon = Polygon(4); polygon.ps[0] = Point(816, 353.167); polygon.ps[1] = Point(816, 412.167); polygon.ps[2] = Point(735, 412.167); polygon.ps[3] = Point(735, 353.167); ShapeRef *shapeRef9 = new ShapeRef(router, polygon, 9); new ShapeConnectionPin(shapeRef9, 15, 1, 0.514124, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef9, 16, 1, 0.79096, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef9, 17, 0, 0.79096, true, 0, (ConnDirFlags) 4); new ShapeConnectionPin(shapeRef9, 18, 0, 0.514124, true, 0, (ConnDirFlags) 4); // shapeRef10 polygon = Polygon(4); polygon.ps[0] = Point(981, 263.833); polygon.ps[1] = Point(981, 321.833); polygon.ps[2] = Point(828, 321.833); polygon.ps[3] = Point(828, 263.833); ShapeRef *shapeRef10 = new ShapeRef(router, polygon, 10); new ShapeConnectionPin(shapeRef10, 19, 0, 0.655172, true, 0, (ConnDirFlags) 4); // shapeRef11 polygon = Polygon(4); polygon.ps[0] = Point(1011.49, 361.833); polygon.ps[1] = Point(1011.49, 419.833); polygon.ps[2] = Point(834.489, 419.833); polygon.ps[3] = Point(834.489, 361.833); ShapeRef *shapeRef11 = new ShapeRef(router, polygon, 11); new ShapeConnectionPin(shapeRef11, 20, 0, 0.655172, true, 0, (ConnDirFlags) 4); // shapeRef12 polygon = Polygon(4); polygon.ps[0] = Point(511, 155.333); polygon.ps[1] = Point(511, 214.333); polygon.ps[2] = Point(422, 214.333); polygon.ps[3] = Point(422, 155.333); ShapeRef *shapeRef12 = new ShapeRef(router, polygon, 12); new ShapeConnectionPin(shapeRef12, 21, 1, 0.514124, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef12, 22, 1, 0.79096, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef12, 23, 0, 0.79096, true, 0, (ConnDirFlags) 4); new ShapeConnectionPin(shapeRef12, 24, 0, 0.514124, true, 0, (ConnDirFlags) 4); // shapeRef13 polygon = Polygon(4); polygon.ps[0] = Point(690, 66); polygon.ps[1] = Point(690, 124); polygon.ps[2] = Point(523, 124); polygon.ps[3] = Point(523, 66); ShapeRef *shapeRef13 = new ShapeRef(router, polygon, 13); new ShapeConnectionPin(shapeRef13, 25, 0, 0.655172, true, 0, (ConnDirFlags) 4); // shapeRef14 polygon = Polygon(4); polygon.ps[0] = Point(720.212, 164); polygon.ps[1] = Point(720.212, 222); polygon.ps[2] = Point(529.212, 222); polygon.ps[3] = Point(529.212, 164); ShapeRef *shapeRef14 = new ShapeRef(router, polygon, 14); new ShapeConnectionPin(shapeRef14, 26, 0, 0.655172, true, 0, (ConnDirFlags) 4); // shapeRef15 polygon = Polygon(4); polygon.ps[0] = Point(217, 336.833); polygon.ps[1] = Point(217, 395.833); polygon.ps[2] = Point(98, 395.833); polygon.ps[3] = Point(98, 336.833); ShapeRef *shapeRef15 = new ShapeRef(router, polygon, 15); new ShapeConnectionPin(shapeRef15, 27, 1, 0.652542, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef15, 28, 0, 0.652542, true, 0, (ConnDirFlags) 4); // shapeRef16 polygon = Polygon(4); polygon.ps[0] = Point(413, 147.167); polygon.ps[1] = Point(413, 206.167); polygon.ps[2] = Point(336, 206.167); polygon.ps[3] = Point(336, 147.167); ShapeRef *shapeRef16 = new ShapeRef(router, polygon, 16); new ShapeConnectionPin(shapeRef16, 29, 1, 0.652542, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef16, 30, 0, 0.652542, true, 0, (ConnDirFlags) 4); // shapeRef17 polygon = Polygon(4); polygon.ps[0] = Point(306, 336.833); polygon.ps[1] = Point(306, 395.833); polygon.ps[2] = Point(229, 395.833); polygon.ps[3] = Point(229, 336.833); ShapeRef *shapeRef17 = new ShapeRef(router, polygon, 17); new ShapeConnectionPin(shapeRef17, 31, 1, 0.652542, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef17, 32, 0, 0.652542, true, 0, (ConnDirFlags) 4); // shapeRef18 polygon = Polygon(4); polygon.ps[0] = Point(175, 139); polygon.ps[1] = Point(175, 198); polygon.ps[2] = Point(98, 198); polygon.ps[3] = Point(98, 139); ShapeRef *shapeRef18 = new ShapeRef(router, polygon, 18); new ShapeConnectionPin(shapeRef18, 33, 1, 0.652542, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef18, 34, 0, 0.652542, true, 0, (ConnDirFlags) 4); // shapeRef19 polygon = Polygon(4); polygon.ps[0] = Point(409, 399.333); polygon.ps[1] = Point(409, 458.333); polygon.ps[2] = Point(298, 458.333); polygon.ps[3] = Point(298, 399.333); ShapeRef *shapeRef19 = new ShapeRef(router, polygon, 19); new ShapeConnectionPin(shapeRef19, 35, 1, 0.652542, true, 0, (ConnDirFlags) 8); // shapeRef20 polygon = Polygon(4); polygon.ps[0] = Point(224, 40); polygon.ps[1] = Point(224, 99); polygon.ps[2] = Point(106, 99); polygon.ps[3] = Point(106, 40); ShapeRef *shapeRef20 = new ShapeRef(router, polygon, 20); new ShapeConnectionPin(shapeRef20, 36, 1, 0.652542, true, 0, (ConnDirFlags) 8); // shapeRef21 polygon = Polygon(4); polygon.ps[0] = Point(604, 345); polygon.ps[1] = Point(604, 404); polygon.ps[2] = Point(513, 404); polygon.ps[3] = Point(513, 345); ShapeRef *shapeRef21 = new ShapeRef(router, polygon, 21); new ShapeConnectionPin(shapeRef21, 37, 1, 0.652542, true, 0, (ConnDirFlags) 8); new ShapeConnectionPin(shapeRef21, 38, 0, 0.652542, true, 0, (ConnDirFlags) 4); // connRef1 connRef = new ConnRef(router, 1); srcPt = ConnEnd(shapeRef5, 5); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef21, 38); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef2 connRef = new ConnRef(router, 2); srcPt = ConnEnd(shapeRef6, 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef18, 34); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef3 connRef = new ConnRef(router, 3); srcPt = ConnEnd(shapeRef6, 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef15, 28); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef4 connRef = new ConnRef(router, 4); srcPt = ConnEnd(shapeRef6, 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef12, 23); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef5 connRef = new ConnRef(router, 5); srcPt = ConnEnd(shapeRef6, 8); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef7, 11); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef6 connRef = new ConnRef(router, 6); srcPt = ConnEnd(shapeRef7, 10); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef9, 17); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); ConnRef *connector6 = connRef; // connRef7 connRef = new ConnRef(router, 7); srcPt = ConnEnd(shapeRef8, 12); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef16, 30); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef8 connRef = new ConnRef(router, 8); srcPt = ConnEnd(shapeRef9, 15); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef10, 19); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef9 connRef = new ConnRef(router, 9); srcPt = ConnEnd(shapeRef9, 16); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef11, 20); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef10 connRef = new ConnRef(router, 10); srcPt = ConnEnd(shapeRef12, 21); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef13, 25); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef11 connRef = new ConnRef(router, 11); srcPt = ConnEnd(shapeRef12, 22); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef14, 26); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef12 connRef = new ConnRef(router, 12); srcPt = ConnEnd(shapeRef15, 27); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef17, 32); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef13 connRef = new ConnRef(router, 13); srcPt = ConnEnd(shapeRef16, 29); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef12, 24); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef14 connRef = new ConnRef(router, 14); srcPt = ConnEnd(shapeRef17, 31); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef5, 7); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef15 connRef = new ConnRef(router, 15); srcPt = ConnEnd(shapeRef18, 33); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef8, 14); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef16 connRef = new ConnRef(router, 16); srcPt = ConnEnd(shapeRef19, 35); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef5, 7); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef17 connRef = new ConnRef(router, 17); srcPt = ConnEnd(shapeRef20, 36); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef8, 14); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); // connRef18 connRef = new ConnRef(router, 18); srcPt = ConnEnd(shapeRef21, 37); connRef->setSourceEndpoint(srcPt); dstPt = ConnEnd(shapeRef9, 18); connRef->setDestEndpoint(dstPt); connRef->setRoutingType((ConnType)2); router->processTransaction(); // Test that connector 6 has three segments and doesnt loop right // around the shapes on the right due to the crossing penalty. bool suceeds = (connector6->displayRoute().size() == 4); //router->outputInstanceToSVG("output/forwardFlowingConnectors01"); delete router; return (suceeds ? 0 : 1); };
lgpl-2.1