answer
stringlengths
15
1.25M
#ifndef <API key> #define <API key> /** @file * "Add Expression" dialog box. * @ingroup dialog_group */ /** User requested the "Add Expression" dialog box by menu or toolbar. * * @param widget corresponding text entry widget * @return the newly created dialog widget */ GtkWidget *<API key>(GtkWidget *widget); #endif /* dfilter_expr_dlg.h */
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.7"/> <title>oRTP: /Users/jehanmonnier/workspaces/<API key>/linphone-iphone/submodules/linphone/oRTP/src Directory Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">oRTP &#160;<span id="projectnumber">0.24.0</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.7 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="<API key>.html">Users</a></li><li class="navelem"><a class="el" href="<API key>.html">jehanmonnier</a></li><li class="navelem"><a class="el" href="<API key>.html">workspaces</a></li><li class="navelem"><a class="el" href="<API key>.html"><API key></a></li><li class="navelem"><a class="el" href="<API key>.html">linphone-iphone</a></li><li class="navelem"><a class="el" href="<API key>.html">submodules</a></li><li class="navelem"><a class="el" href="<API key>.html">linphone</a></li><li class="navelem"><a class="el" href="<API key>.html">oRTP</a></li><li class="navelem"><a class="el" href="<API key>.html">src</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">src Directory Reference</div> </div> </div><!--header <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="files"></a> Files</h2></td></tr> <tr class="memitem:avprofile_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>avprofile.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:b64_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="b64_8c.html">b64.c</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:dll__entry_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>dll_entry.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:event_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>event.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:extremum_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>extremum.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:jitterctl_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>jitterctl.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:jitterctl_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>jitterctl.h</b> <a href="jitterctl_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:logging_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>logging.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:netsim_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>netsim.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ortp_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>ortp.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:payloadtype_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>payloadtype.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:port_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>port.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:posixtimer_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>posixtimer.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtcp_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtcp.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtcp__fb_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtcp_fb.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtcp__xr_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtcp_xr.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtcpparse_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtcpparse.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpparse_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpparse.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpprofile_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpprofile.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsession_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsession.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsession__inet_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsession_inet.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsession__priv_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsession_priv.h</b> <a href="<API key>.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsignaltable_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsignaltable.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtptimer_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtptimer.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtptimer_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtptimer.h</b> <a href="rtptimer_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:scheduler_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>scheduler.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:scheduler_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>scheduler.h</b> <a href="scheduler_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:sessionset_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>sessionset.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:str__utils_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>str_utils.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:telephonyevents_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>telephonyevents.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:utils_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>utils.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:utils_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>utils.h</b> <a href="utils_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:winrttimer_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>winrttimer.h</b> <a href="<API key>.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Mon Mar 23 2015 12:57:57 for oRTP by & <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.7 </small></address> </body> </html>
<?php /** * Shows a welcome or update message after the plugin is installed/updated */ class <API key> { /** @var self */ private static $instance = null; public function add_hooks() { add_action( 'admin_init', array( $this, 'maybe_redirect' ), 10, 0 ); add_action( 'admin_menu', array( $this, 'register_page' ), 100, 0 ); // come in after the default page is registered add_action( '<API key>', array( $this, '<API key>' ), 15, 2 ); add_action( '<API key>', array( $this, '<API key>' ), 15, 2 ); } /** * Filter the Default WordPress actions when updating the plugin to prevent users to be redirected if they have an * specfific intention of going back to the plugins page. * * @param array $actions The Array of links (html) * @param string $plugin Which plugins are been updated * @return array The filtered Links */ public function <API key>( $actions, $plugin ) { $plugins = array(); if ( ! empty( $_GET['plugins'] ) ) { $plugins = explode( ',', esc_attr( $_GET['plugins'] ) ); } if ( ! in_array( Tribe__Events__Main::instance()->pluginDir . 'the-events-calendar.php', $plugins ) ){ return $actions; } if ( isset( $actions['plugins_page'] ) ) { $actions['plugins_page'] = '<a href="' . esc_url( self_admin_url( 'plugins.php?tec-skip-welcome' ) ) . '" title="' . esc_attr__( 'Go to plugins page' ) . '" target="_parent">' . esc_html__( 'Return to Plugins page' ) . '</a>'; if ( ! current_user_can( 'activate_plugins' ) ){ unset( $actions['plugins_page'] ); } } if ( isset( $actions['updates_page'] ) ) { $actions['updates_page'] = '<a href="' . esc_url( self_admin_url( 'update-core.php?tec-skip-welcome' ) ) . '" title="' . esc_attr__( 'Go to WordPress Updates page' ) . '" target="_parent">' . esc_html__( 'Return to WordPress Updates' ) . '</a>'; } return $actions; } public function maybe_redirect() { if ( ! empty( $_POST ) ) { return; // don't interrupt anything the user's trying to do } if ( ! is_admin() || defined( 'DOING_AJAX' ) ) { return; } if ( defined( 'IFRAME_REQUEST' ) && IFRAME_REQUEST ) { return; // probably the plugin update/install iframe } if ( isset( $_GET['tec-welcome-message'] ) || isset( $_GET['tec-update-message'] ) ) { return; // no infinite redirects } if ( isset( $_GET['tec-skip-welcome'] ) ) { return; // a way to skip these checks and } // bail if we aren't activating a plugin if ( ! get_transient( '<API key>' ) ) { return; } delete_transient( '<API key>' ); if ( ! current_user_can( <API key>::instance()->requiredCap ) ){ return; } if ( $this-><API key>() ) { return; } // the redirect might be intercepted by another plugin, but // we'll go ahead and mark it as viewed right now, just in case // we end up in a redirect loop // see #31088 $this-><API key>(); if ( $this->is_new_install() ) { $this-><API key>(); } /* * TODO: determine if we wish to keep the update splash screen in the future else { $this-><API key>(); } */ } /** * Have we shown the welcome/update message for the current version? * * @return bool */ protected function <API key>() { $tec = Tribe__Events__Main::instance(); $<API key> = $tec->getOption( 'last-update-message' ); if ( empty( $<API key> ) ) { return false; } if ( version_compare( $<API key>, Tribe__Events__Main::VERSION, '<' ) ) { return false; } return true; } protected function <API key>() { $tec = Tribe__Events__Main::instance(); $tec->setOption( 'last-update-message', Tribe__Events__Main::VERSION ); } /** * The <API key> option will be empty or set to 0 * if the current version is the first version to be installed. * * @return bool * @see Tribe__Events__Main::maybeSetTECVersion() */ protected function is_new_install() { $tec = Tribe__Events__Main::instance(); $previous_versions = $tec->getOption( '<API key>' ); return empty( $previous_versions ) || ( end( $previous_versions ) == '0' ); } protected function <API key>() { $url = $this-><API key>( 'tec-welcome-message' ); wp_safe_redirect( $url ); exit(); } protected function <API key>() { $url = $this-><API key>( 'tec-update-message' ); wp_safe_redirect( $url ); exit(); } protected function <API key>( $slug ) { $settings = <API key>::instance(); // get the base settings page url $url = apply_filters( 'tribe_settings_url', add_query_arg( array( 'post_type' => Tribe__Events__Main::POSTTYPE, 'page' => $settings->adminSlug, ), admin_url( 'edit.php' ) ) ); $url = esc_url_raw( add_query_arg( $slug, 1, $url ) ); return $url; } public function register_page() { // <API key> if ( isset( $_GET['tec-welcome-message'] ) ) { $this-><API key>(); add_action( '<API key>', array( $this, '<API key>' ) ); } elseif ( isset( $_GET['tec-update-message'] ) ) { $this-><API key>(); add_action( '<API key>', array( $this, 'display_update_page' ) ); } } protected function <API key>() { remove_action( '<API key>', array( <API key>::instance(), 'generatePage' ) ); } public function <API key>() { do_action( 'tribe_settings_top' ); echo '<div class="tribe_settings tribe_welcome_page wrap">'; echo '<h1>'; echo $this->welcome_page_title(); echo '</h1>'; echo $this-><API key>(); echo '</div>'; do_action( '<API key>' ); $this-><API key>(); } protected function welcome_page_title() { return __( 'Welcome to The Events Calendar', 'the-events-calendar' ); } protected function <API key>() { return $this->load_template( '<API key>' ); } public function display_update_page() { do_action( 'tribe_settings_top' ); echo '<div class="tribe_settings tribe_update_page wrap">'; echo '<h1>'; echo $this->update_page_title(); echo '</h1>'; echo $this->update_page_content(); echo '</div>'; do_action( '<API key>' ); $this-><API key>(); } protected function update_page_title() { return __( 'Thanks for Updating The Events Calendar', 'the-events-calendar' ); } protected function update_page_content() { return $this->load_template( '<API key>' ); } protected function load_template( $name ) { ob_start(); include trailingslashit( Tribe__Events__Main::instance()->pluginPath ) . 'src/admin-views/' . $name . '.php'; return ob_get_clean(); } /** * Initialize the global instance of the class. */ public static function init() { self::instance()->add_hooks(); } /** * @return self */ public static function instance() { if ( empty( self::$instance ) ) { self::$instance = new self(); } return self::$instance; } }
<?php defined('_JEXEC') or die('Restricted access'); ?> <form action="index.php" method="post" name="adminForm" id="adminForm"> <table class="adminform"> <tr> <td width="100%"> <?php echo JText::_('COM_REDEVENT_SEARCH' );?> <input type="text" name="search" id="search" value="<?php echo $this->lists['search']; ?>" class="text_area" onChange="document.adminForm.submit();" /> <button onclick="this.form.submit();"><?php echo JText::_('COM_REDEVENT_Go' ); ?></button> <button onclick="this.form.getElementById('search').value='';this.form.submit();"><?php echo JText::_('COM_REDEVENT_Reset' ); ?></button> </td> </tr> </table> <table class="adminlist" cellspacing="1"> <thead> <tr> <th width="5"> <th width="20"><input type="checkbox" name="toggle" value="" onClick="checkAll(<?php echo count( $this->rows ); ?>);" /></th> <th width="30%" class="title"><?php echo JHTML::_('grid.sort', '<API key>', 'name', $this->lists['order_Dir'], $this->lists['order'] ); ?></th> <th><?php echo JText::_('<API key>' ); ?></th> <th width="5"><?php echo JText::_('<API key>' ); ?></th> <th width="5"><?php echo JText::_('<API key>' ); ?></th> <th width="5"><?php echo JText::_('<API key>' ); ?></th> </tr> </thead> <tfoot> <tr> <td colspan="7"> <?php echo $this->pageNav->getListFooter(); ?> </td> </tr> </tfoot> <tbody> <?php $k = 0; for($i=0, $n=count( $this->rows ); $i < $n; $i++) { $row = &$this->rows[$i]; $link = 'index.php?option=com_redevent&amp;controller=groups&amp;task=edit&amp;cid[]='.$row->id; $checked = JHTML::_('grid.checkedout', $row, $i ); ?> <tr class="<?php echo "row$k"; ?>"> <td><?php echo $this->pageNav->getRowOffset( $i ); ?></td> <td><?php echo $checked; ?></td> <td> <?php if ( $row->checked_out && ( $row->checked_out != $this->user->get('id') ) ) { echo htmlspecialchars($row->name, ENT_QUOTES, 'UTF-8'); } else { ?> <span class="editlinktip hasTip" title="<?php echo JText::_('<API key>' );?>::<?php echo $row->name; ?>"> <a href="<?php echo $link; ?>"> <?php echo htmlspecialchars($row->name, ENT_QUOTES, 'UTF-8'); ?> </a></span> <?php } ?> </td> <td><?php echo htmlspecialchars($row->description, ENT_QUOTES, 'UTF-8'); ?></td> <td><?php echo ($row->isdefault ? 'yes' : 'no'); ?></td> <td style="text-align:center;"><?php echo JHTML::link('index.php?option=com_redevent&amp;controller=groups&amp;task=editmembers&amp;group_id='.$row->id, $row->members . ' ' . JHTML::_( 'image', 'administrator/components/com_redevent/assets/images/groupmembers.png', JText::_('<API key>' ), 'title= "'. JText::_('<API key>' ) . '"' )); ?> </td> <td style="text-align:center;"><?php echo JHTML::link('index.php?option=com_redevent&amp;controller=groups&amp;task=groupacl&amp;group_id='.$row->id, JHTML::_( 'image', 'administrator/components/com_redevent/assets/images/icon-16-categories.png', JText::_('<API key>' ), 'title= "'. JText::_('<API key>' ) . '"' )); ?> </td> </tr> <?php $k = 1 - $k; } ?> </tbody> </table> <input type="hidden" name="boxchecked" value="0" /> <input type="hidden" name="option" value="com_redevent" /> <input type="hidden" name="controller" value="groups" /> <input type="hidden" name="view" value="groups" /> <input type="hidden" name="task" value="" /> <input type="hidden" name="filter_order" value="<?php echo $this->lists['order']; ?>" /> <input type="hidden" name="filter_order_Dir" value="<?php echo $this->lists['order_Dir']; ?>" /> </form>
#!/usr/bin/env python # -*- coding: utf-8 -*- # progreso.py # This program is free software; you can redistribute it and/or modify # (at your option) any later version. # This program is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. import gtk, time import threading import thread import gobject #Iniciando el hilo sin usarlo gtk.gdk.threads_init() #La clase App hereda threading.Thread class App(threading.Thread): def __init__(self): self.glade_file = "progreso.glade" self.glade = gtk.Builder() self.glade.add_from_file(self.glade_file) self.window1 = self.glade.get_object('window1') self.togglebutton1 = self.glade.get_object('togglebutton1') self.button1 = self.glade.get_object('button1') self.progressbar1 = self.glade.get_object('progressbar1') self.new_val = 0.0 self.rango =60 #Definiendo el valor inicial de la barra de proceso, definiendo los saltos en 0.1 self.progressbar1.set_fraction(self.new_val) self.progressbar1.set_pulse_step(0.1) self.window1.connect("destroy",self.on_window1_destroy) self.button1.connect('clicked', self.on_button1_clicked) self.togglebutton1.connect('toggled',self.<API key>) #Iniciando el hilo en el constructor threading.Thread.__init__(self) self.window1.show_all() def __iteracion__(self): for i in range(self.rango): if self.togglebutton1.get_active() == True: self.new_val = self.progressbar1.get_fraction() + 0.01 if self.new_val > 1.0: self.new_val = 0.0 self.togglebutton1.set_active(False) break else: time.sleep(1) self.x = self.new_val*100 self.progressbar1.set_text("%s" %self.x) self.progressbar1.set_fraction(self.new_val) else: return def <API key>(self,*args): los hilos. variable = self.togglebutton1.get_active() self.rango = 100 if variable == True: lock = thread.allocate_lock() lock.acquire() thread.start_new_thread( self.__iteracion__, ()) lock.release() else: #Se detiene la barra de progreso self.progressbar1.set_fraction(self.new_val) self.progressbar1.set_text("%s" %self.x)
#include "Battery.hpp" #ifdef HAVE_BATTERY #if (defined(_WIN32_WCE) && !defined(GNAV)) #include <windows.h> namespace Power { namespace Battery{ unsigned Temperature = 0; unsigned RemainingPercent = 0; bool <API key> = false; batterystatus Status = UNKNOWN; }; namespace External{ externalstatus Status = UNKNOWN; }; }; void UpdateBatteryInfo() { <API key> sps; // request the power status DWORD result = <API key>(&sps, sizeof(sps), TRUE); if (result >= sizeof(sps)) { if (sps.BatteryLifePercent != <API key>){ Power::Battery::RemainingPercent = sps.BatteryLifePercent; Power::Battery::<API key> = true; } else Power::Battery::<API key> = false; switch (sps.BatteryFlag) { case BATTERY_FLAG_HIGH: Power::Battery::Status = Power::Battery::HIGH; break; case BATTERY_FLAG_LOW: Power::Battery::Status = Power::Battery::LOW; break; case <API key>: Power::Battery::Status = Power::Battery::CRITICAL; break; case <API key>: Power::Battery::Status = Power::Battery::CHARGING; break; case <API key>: Power::Battery::Status = Power::Battery::NOBATTERY; break; case <API key>: default: Power::Battery::Status = Power::Battery::UNKNOWN; } switch (sps.ACLineStatus) { case AC_LINE_OFFLINE: Power::External::Status = Power::External::OFF; break; case <API key>: case AC_LINE_ONLINE: Power::External::Status = Power::External::ON; break; case AC_LINE_UNKNOWN: default: Power::External::Status = Power::External::UNKNOWN; } } else { Power::Battery::Status = Power::Battery::UNKNOWN; Power::External::Status = Power::External::UNKNOWN; } } #endif #ifdef KOBO #include "OS/FileUtil.hpp" #include <string.h> #include <stdlib.h> namespace Power { namespace Battery{ unsigned Temperature = 0; unsigned RemainingPercent = 0; bool <API key> = false; batterystatus Status = UNKNOWN; }; namespace External{ externalstatus Status = UNKNOWN; }; }; void UpdateBatteryInfo() { // assume failure at entry Power::Battery::<API key> = false; Power::Battery::Status = Power::Battery::UNKNOWN; Power::External::Status = Power::External::UNKNOWN; // code shamelessly copied from OS/SystemLoad.cpp char line[256]; if (!File::ReadString("/sys/bus/platform/drivers/pmic_battery/pmic_battery.1/power_supply/mc13892_bat/uevent", line, sizeof(line))) return; char field[80], value[80]; int n; char* ptr = line; while (sscanf(ptr, "%[^=]=%[^\n]\n%n", field, value, &n)==2) { ptr += n; if (!strcmp(field,"POWER_SUPPLY_STATUS")) { if (!strcmp(value,"Not charging") || !strcmp(value,"Charging")) { Power::External::Status = Power::External::ON; } else if (!strcmp(value,"Discharging")) { Power::External::Status = Power::External::OFF; } } else if (!strcmp(field,"<API key>")) { int rem = atoi(value); Power::Battery::<API key> = true; Power::Battery::RemainingPercent = rem; if (Power::External::Status == Power::External::OFF) { if (rem>30) { Power::Battery::Status = Power::Battery::HIGH; } else if (rem>10) { Power::Battery::Status = Power::Battery::LOW; } else if (rem<10) { Power::Battery::Status = Power::Battery::CRITICAL; } } else { Power::Battery::Status = Power::Battery::CHARGING; } } } } #endif #endif
<?php namespace Finna\ILS\Driver; use VuFind\Exception\ILS as ILSException; class KohaRest extends \VuFind\ILS\Driver\KohaRest { /** * Mappings from Koha messaging preferences * * @var array */ protected $<API key> = [ 'Advance_Notice' => 'dueDateAlert', 'Hold_Filled' => 'pickUpNotice', 'Item_Check_in' => 'checkinNotice', 'Item_Checkout' => 'checkoutNotice', 'Item_Due' => 'dueDateNotice' ]; /** * Whether to use location in addition to branch when grouping holdings * * @param bool */ protected $<API key>; /** * Priority settings for the order of branches or branch/location combinations * * @var array */ protected $holdingsBranchOrder; /** * Priority settings for the order of locations (in branches) * * @var array */ protected $<API key>; /** * Initialize the driver. * * Validate configuration and perform all resource-intensive tasks needed to * make the driver active. * * @throws ILSException * @return void */ public function init() { parent::init(); $this-><API key> = isset($this->config['Holdings']['group_by_location']) ? $this->config['Holdings']['group_by_location'] : ''; if (isset($this->config['Holdings']['<API key>'])) { $values = explode( ':', $this->config['Holdings']['<API key>'] ); foreach ($values as $i => $value) { $parts = explode('=', $value, 2); $idx = $parts[1] ?? $i; $this->holdingsBranchOrder[$parts[0]] = $idx; } } $this-><API key> = isset($this->config['Holdings']['<API key>']) ? explode(':', $this->config['Holdings']['<API key>']) : []; $this-><API key> = array_flip($this-><API key>); } /** * Get Holding * * This is responsible for retrieving the holding information of a certain * record. * * @param string $id The record id to retrieve the holdings for * @param array $patron Patron data * @param array $options Extra options * * @throws \VuFind\Exception\ILS * @return array On success, an associative array with the following * keys: id, availability (boolean), status, location, reserve, callnumber, * duedate, number, barcode. * * @SuppressWarnings(PHPMD.<API key>) */ public function getHolding($id, array $patron = null, array $options = []) { $data = parent::getHolding($id, $patron); if (!empty($data['holdings'])) { $summary = $this->getHoldingsSummary($data['holdings']); // Remove request counts before adding the summary if necessary if (isset($this->config['Holdings']['<API key>']) && !$this->config['Holdings']['<API key>'] ) { foreach ($data['holdings'] as &$item) { unset($item['requests_placed']); } } $data['holdings'][] = $summary; } return $data; } /** * Get Status * * This is responsible for retrieving the status information of a certain * record. * * @param string $id The record id to retrieve the holdings for * * @return array An associative array with the following keys: * id, availability (boolean), status, location, reserve, callnumber. */ public function getStatus($id) { $data = parent::getStatus($id); if (!empty($data)) { $summary = $this->getHoldingsSummary($data); $data[] = $summary; } return $data; } /** * Get Statuses * * This is responsible for retrieving the status information for a * collection of records. * * @param array $ids The array of record ids to retrieve the status for * * @return mixed An array of getStatus() return values on success. */ public function getStatuses($ids) { $items = []; foreach ($ids as $id) { $statuses = $this-><API key>($id); if (isset($statuses['holdings'])) { $items[] = array_merge( $statuses['holdings'], $statuses['electronic_holdings'] ); } else { $items[] = $statuses; } } return $items; } /** * Get Patron Fines * * This is responsible for retrieving all fines by a specific patron. * * @param array $patron The patron array from patronLogin * * @throws DateException * @throws ILSException * @return array Array of the patron's fines on success. */ public function getMyFines($patron) { $fines = parent::getMyFines($patron); foreach ($fines as &$fine) { $fine['payableOnline'] = true; } return $fines; } /** * Get Patron Profile * * This is responsible for retrieving the profile for a specific patron. * * @param array $patron The patron array * * @throws ILSException * @return array Array of the patron's profile data on success. */ public function getMyProfile($patron) { $result = $this->makeRequest( ['v1', 'patrons', $patron['id']], false, 'GET', $patron ); $expirationDate = !empty($result['dateexpiry']) ? $this->dateConverter-><API key>( 'Y-m-d', $result['dateexpiry'] ) : ''; $guarantor = []; $guarantees = []; if (!empty($result['guarantorid'])) { $guarantorRecord = $this->makeRequest( ['v1', 'patrons', $result['guarantorid']], false, 'GET', $patron ); if ($guarantorRecord) { $guarantor['firstname'] = $guarantorRecord['firstname']; $guarantor['lastname'] = $guarantorRecord['surname']; } } else { // Assume patron can have guarantees only if there is no guarantor $guaranteeRecords = $this->makeRequest( ['v1', 'patrons'], ['guarantorid' => $patron['id']], 'GET', $patron ); foreach ($guaranteeRecords as $guarantee) { $guarantees[] = [ 'firstname' => $guarantee['firstname'], 'lastname' => $guarantee['surname'] ]; } } list($resultCode, $messagingPrefs) = $this->makeRequest( ['v1', '<API key>'], ['borrowernumber' => $patron['id']], 'GET', $patron, true ); $messagingSettings = []; if (200 === $resultCode) { foreach ($messagingPrefs as $type => $prefs) { $typeName = isset($this-><API key>[$type]) ? $this-><API key>[$type] : $type; $settings = [ 'type' => $typeName ]; if (isset($prefs['transport_types'])) { $settings['settings']['transport_types'] = [ 'type' => 'multiselect' ]; foreach ($prefs['transport_types'] as $key => $active) { $settings['settings']['transport_types']['options'][$key] = [ 'active' => $active ]; } } if (isset($prefs['digest'])) { $settings['settings']['digest'] = [ 'type' => 'boolean', 'name' => '', 'active' => $prefs['digest']['value'], 'readonly' => !$prefs['digest']['configurable'] ]; } if (isset($prefs['days_in_advance']) && ($prefs['days_in_advance']['configurable'] || null !== $prefs['days_in_advance']['value']) ) { $options = []; for ($i = 0; $i <= 30; $i++) { $options[$i] = [ 'name' => $this->translate( 1 === $i ? '<API key>' : '<API key>', ['%%days%%' => $i] ), 'active' => $i == $prefs['days_in_advance']['value'] ]; } $settings['settings']['days_in_advance'] = [ 'type' => 'select', 'value' => $prefs['days_in_advance']['value'], 'options' => $options, 'readonly' => !$prefs['days_in_advance']['configurable'] ]; } $messagingSettings[$type] = $settings; } } $phoneField = isset($this->config['Profile']['phoneNumberField']) ? $this->config['Profile']['phoneNumberField'] : 'mobile'; return [ 'firstname' => $result['firstname'], 'lastname' => $result['surname'], 'phone' => $phoneField && !empty($result[$phoneField]) ? $result[$phoneField] : '', 'smsnumber' => $result['smsalertnumber'], 'email' => $result['email'], 'address1' => $result['address'], 'address2' => $result['address2'], 'zip' => $result['zipcode'], 'city' => $result['city'], 'country' => $result['country'], 'category' => $result['categorycode'] ?? '', 'expiration_date' => $expirationDate, 'hold_identifier' => $result['othernames'], 'guarantor' => $guarantor, 'guarantees' => $guarantees, 'loan_history' => $result['privacy'], 'messagingServices' => $messagingSettings, 'notes' => $result['opacnote'], 'full_data' => $result ]; } /** * Purge Patron Transaction History * * @param array $patron The patron array from patronLogin * * @throws ILSException * @return array Associative array of the results */ public function <API key>($patron) { list($code, $result) = $this->makeRequest( ['v1', 'checkouts', 'history'], ['borrowernumber' => $patron['id']], 'DELETE', $patron, true ); if (!in_array($code, [200, 202, 204])) { return [ 'success' => false, 'status' => 'Purging the loan history failed', 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => 'loan_history_purged', 'sys_message' => '' ]; } /** * Update Patron Transaction History State * * Enable or disable patron's transaction history * * @param array $patron The patron array from patronLogin * @param mixed $state Any of the configured values * * @return array Associative array of the results */ public function <API key>($patron, $state) { $request = [ 'privacy' => (int)$state ]; list($code, $result) = $this->makeRequest( ['v1', 'patrons', $patron['id']], json_encode($request), 'PATCH', $patron, true ); if (!in_array($code, [200, 202, 204])) { return [ 'success' => false, 'status' => 'Changing the checkout history state failed', 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => $code == 202 ? 'request_change_done' : '<API key>', 'sys_message' => '' ]; } /** * Update patron's phone number * * @param array $patron Patron array * @param string $phone Phone number * * @throws ILSException * * @return array Associative array of the results */ public function updatePhone($patron, $phone) { $request = [ 'mobile' => $phone ]; list($code, $result) = $this->makeRequest( ['v1', 'patrons', $patron['id']], json_encode($request), 'PATCH', $patron, true ); if (!in_array($code, [200, 202, 204])) { return [ 'success' => false, 'status' => 'Changing the phone number failed', 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => $code == 202 ? 'request_change_done' : '<API key>', 'sys_message' => '' ]; } /** * Update patron's SMS alert number * * @param array $patron Patron array * @param string $number SMS alert number * * @throws ILSException * * @return array Associative array of the results */ public function updateSmsNumber($patron, $number) { $fields = !empty($this->config['updateSmsNumber']['fields']) ? explode(',', $this->config['updateSmsNumber']['fields']) : ['smsalertnumber']; $request = []; foreach ($fields as $field) { $request[$field] = $number; } list($code, $result) = $this->makeRequest( ['v1', 'patrons', $patron['id']], json_encode($request), 'PATCH', $patron, true ); if (!in_array($code, [200, 202, 204])) { return [ 'success' => false, 'status' => 'Changing the phone number failed', 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => $code == 202 ? 'request_change_done' : '<API key>', 'sys_message' => '' ]; } /** * Update patron's email address * * @param array $patron Patron array * @param String $email Email address * * @throws ILSException * * @return array Associative array of the results */ public function updateEmail($patron, $email) { $request = [ 'email' => $email ]; list($code, $result) = $this->makeRequest( ['v1', 'patrons', $patron['id']], json_encode($request), 'PATCH', $patron, true ); if (!in_array($code, [200, 202, 204])) { return [ 'success' => false, 'status' => 'Changing the email address failed', 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => $code == 202 ? 'request_change_done' : '<API key>', 'sys_message' => '' ]; } /** * Update patron contact information * * @param array $patron Patron array * @param array $details Associative array of patron contact information * * @throws ILSException * * @return array Associative array of the results */ public function updateAddress($patron, $details) { $addressFields = []; $fieldConfig = isset($this->config['updateAddress']['fields']) ? $this->config['updateAddress']['fields'] : []; foreach ($fieldConfig as $field) { $parts = explode(':', $field, 2); if (isset($parts[1])) { $addressFields[$parts[1]] = $parts[0]; } } // Pick the configured fields from the request $request = []; foreach ($details as $key => $value) { if (isset($addressFields[$key])) { $request[$key] = $value; } } list($code, $result) = $this->makeRequest( ['v1', 'patrons', $patron['id']], json_encode($request), 'PATCH', $patron, true ); if (!in_array($code, [200, 202, 204])) { if (409 === $code && !empty($result['conflict'])) { $keys = array_keys($result['conflict']); $key = reset($keys); $fieldName = isset($addressFields[$key]) ? $this->translate($addressFields[$key]) : '???'; $status = $this->translate( '<API key>', ['%%field%%' => $fieldName] ); } else { $status = 'Changing the contact information failed'; } return [ 'success' => false, 'status' => $status, 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => $code == 202 ? 'request_change_done' : '<API key>', 'sys_message' => '' ]; } /** * Update patron messaging settings * * @param array $patron Patron array * @param array $details Associative array of messaging settings * * @throws ILSException * * @return array Associative array of the results */ public function <API key>($patron, $details) { $messagingPrefs = $this->makeRequest( ['v1', '<API key>'], ['borrowernumber' => $patron['id']], 'GET', $patron ); $messagingSettings = []; foreach ($details as $prefId => $pref) { $result = []; foreach ($pref['settings'] as $settingId => $setting) { if (!empty($setting['readonly'])) { continue; } if ('boolean' === $setting['type']) { $result[$settingId] = [ 'value' => $setting['active'] ]; } elseif ('select' === $setting['type']) { $result[$settingId] = [ 'value' => ctype_digit($setting['value']) ? (int)$setting['value'] : $setting['value'] ]; } else { foreach ($setting['options'] as $optionId => $option) { $result[$settingId][$optionId] = $option['active']; } } } $messagingSettings[$prefId] = $result; } list($code, $result) = $this->makeRequest( ['v1', '<API key>'], [ 'borrowernumber' => $patron['id'], '##body##' => json_encode($messagingSettings) ], 'PUT', $patron, true ); if ($code >= 300) { return [ 'success' => false, 'status' => 'Changing the preferences failed', 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => $code == 202 ? 'request_change_done' : '<API key>', 'sys_message' => '' ]; } /** * Change pickup location * * This is responsible for changing the pickup location of a hold * * @param string $patron Patron array * @param string $holdDetails The request details * * @return array Associative array of the results */ public function <API key>($patron, $holdDetails) { $requestId = $holdDetails['requestId']; $pickUpLocation = $holdDetails['pickupLocationId']; if (!$this-><API key>($pickUpLocation, $patron, $holdDetails)) { return $this->holdError('hold_invalid_pickup'); } $request = [ 'branchcode' => $pickUpLocation ]; list($code, $result) = $this->makeRequest( ['v1', 'holds', $requestId], json_encode($request), 'PUT', $patron, true ); if ($code >= 300) { return $this->holdError($code, $result); } return ['success' => true]; } /** * Change request status * * This is responsible for changing the status of a hold request * * @param string $patron Patron array * @param string $holdDetails The request details (at the moment only 'frozen' * is supported) * * @return array Associative array of the results */ public function changeRequestStatus($patron, $holdDetails) { $requestId = $holdDetails['requestId']; $frozen = !empty($holdDetails['frozen']); $request = [ 'suspend' => $frozen ]; list($code, $result) = $this->makeRequest( ['v1', 'holds', $requestId], json_encode($request), 'PUT', $patron, true ); if ($code >= 300) { return $this->holdError($code, $result); } return ['success' => true]; } /** * Return total amount of fees that may be paid online. * * @param array $patron Patron * @param array $fines Patron's fines * * @throws ILSException * @return array Associative array of payment info, * false if an ILSException occurred. */ public function <API key>($patron, $fines) { if (!empty($fines)) { $amount = 0; foreach ($fines as $fine) { $amount += $fine['balance']; } $config = $this->getConfig('onlinePayment'); $nonPayableReason = false; if (isset($config['minimumFee']) && $amount < $config['minimumFee']) { $nonPayableReason = '<API key>'; } $res = ['payable' => empty($nonPayableReason), 'amount' => $amount]; if ($nonPayableReason) { $res['reason'] = $nonPayableReason; } return $res; } return [ 'payable' => false, 'amount' => 0, 'reason' => '<API key>' ]; } /** * Mark fees as paid. * * This is called after a successful online payment. * * @param array $patron Patron * @param int $amount Amount to be registered as paid * @param string $transactionId Transaction ID * @param int $transactionNumber Internal transaction number * * @throws ILSException * @return boolean success */ public function markFeesAsPaid($patron, $amount, $transactionId, $transactionNumber ) { $request = [ 'amount' => $amount / 100, 'note' => "Online transaction $transactionId" ]; $operator = $patron; if (!empty($this->config['onlinePayment']['userId']) && !empty($this->config['onlinePayment']['userPassword']) ) { $operator = [ 'cat_username' => $this->config['onlinePayment']['userId'], 'cat_password' => $this->config['onlinePayment']['userPassword'] ]; } list($code, $result) = $this->makeRequest( ['v1', 'patrons', $patron['id'], 'payment'], json_encode($request), 'POST', $operator, true ); if ($code != 204) { $error = "Failed to mark payment of $amount paid for patron" . " {$patron['id']}: $code: " . print_r($result, true); $this->error($error); throw new ILSException($error); } // Clear patron's block cache $cacheId = 'blocks|' . $patron['id']; $this->removeCachedData($cacheId); return true; } /** * Get a password recovery token for a user * * @param array $params Required params such as cat_username and email * * @return array Associative array of the results */ public function <API key>($params) { $request = [ 'cardnumber' => $params['cat_username'], 'email' => $params['email'], 'skip_email' => true ]; $operator = []; if (!empty($this->config['PasswordRecovery']['userId']) && !empty($this->config['PasswordRecovery']['userPassword']) ) { $operator = [ 'cat_username' => $this->config['PasswordRecovery']['userId'], 'cat_password' => $this->config['PasswordRecovery']['userPassword'] ]; } list($code, $result) = $this->makeRequest( ['v1', 'patrons', 'password', 'recovery'], json_encode($request), 'POST', $operator, true ); if (201 != $code) { if (404 != $code) { throw new ILSException("Failed to get a recovery token: $code"); } return [ 'success' => false, 'error' => $result['error'] ]; } return [ 'success' => true, 'token' => $result['uuid'] ]; } /** * Recover user's password with a token from <API key> * * @param array $params Required params such as cat_username, token and new * password * * @return array Associative array of the results */ public function recoverPassword($params) { $request = [ 'uuid' => $params['token'], 'new_password' => $params['password'], '<API key>' => $params['password'] ]; $operator = []; if (!empty($this->config['passwordRecovery']['userId']) && !empty($this->config['passwordRecovery']['userPassword']) ) { $operator = [ 'cat_username' => $this->config['passwordRecovery']['userId'], 'cat_password' => $this->config['passwordRecovery']['userPassword'] ]; } list($code, $result) = $this->makeRequest( ['v1', 'patrons', 'password', 'recovery', 'complete'], json_encode($request), 'POST', $operator, true ); if (200 != $code) { return [ 'success' => false, 'error' => $result['error'] ]; } return [ 'success' => true ]; } /** * Get Patron Holds * * This is responsible for retrieving all holds by a specific patron. * * @param array $patron The patron array from patronLogin * * @throws DateException * @throws ILSException * @return array Array of the patron's holds on success. */ public function getMyHolds($patron) { $result = $this->makeRequest( ['v1', 'holds'], ['borrowernumber' => $patron['id']], 'GET', $patron ); if (!isset($result)) { return []; } $holds = []; foreach ($result as $entry) { $bibId = $entry['biblionumber'] ?? null; $itemId = $entry['itemnumber'] ?? null; $title = ''; $volume = ''; if ($itemId) { $item = $this->getItem($itemId); $bibId = $item['biblionumber'] ?? null; $volume = $item['enumchron'] ?? ''; } if (!empty($bibId)) { $bib = $this->getBibRecord($bibId); $title = $bib['title'] ?? ''; if (!empty($bib['title_remainder'])) { $title .= ' ' . $bib['title_remainder']; $title = trim($title); } } $frozen = false; if (!empty($entry['suspend'])) { $frozen = !empty($entry['suspend_until']) ? $entry['suspend_until'] : true; } $available = !empty($entry['waitingdate']); $inTransit = isset($entry['found']) && strtolower($entry['found']) == 't'; $holds[] = [ 'id' => $bibId, 'item_id' => $itemId ? $itemId : $entry['reserve_id'], 'location' => $entry['branchcode'], 'create' => $this->dateConverter-><API key>( 'Y-m-d', $entry['reservedate'] ), 'expire' => !empty($entry['expirationdate']) ? $this->dateConverter-><API key>( 'Y-m-d', $entry['expirationdate'] ) : '', 'position' => $entry['priority'], 'available' => $available, 'in_transit' => $inTransit, 'requestId' => $entry['reserve_id'], 'title' => $title, 'volume' => $volume, 'frozen' => $frozen, 'is_editable' => !$available && !$inTransit ]; } return $holds; } /** * Public Function which retrieves renew, hold and cancel settings from the * driver ini file. * * @param string $function The name of the feature to be checked * @param array $params Optional feature-specific parameters (array) * * @return array An array with key-value pairs. * * @SuppressWarnings(PHPMD.<API key>) */ public function getConfig($function, $params = null) { if ('<API key>' === $function || 'recoverPassword' === $function ) { return !empty($this->config['PasswordRecovery']['enabled']) ? $this->config['PasswordRecovery'] : false; } elseif ('<API key>' === $function) { return ['enabled' => true]; } $functionConfig = parent::getConfig($function, $params); if ($functionConfig && 'onlinePayment' === $function) { if (!isset($functionConfig['<API key>'])) { $functionConfig['<API key>'] = false; } } return $functionConfig; } /** * Check if patron belongs to staff. * * @param array $patron The patron array from patronLogin * * @return bool True if patron is staff, false if not */ public function <API key>($patron) { $username = $patron['cat_username']; if ($this->sessionCache->patron != $username) { if (!$this->renewPatronCookie($patron)) { return false; } } return !empty( array_intersect( ['superlibrarian', 'catalogue'], $this->sessionCache->patronPermissions ) ); } /** * Get Pick Up Locations * * This is responsible for gettting a list of valid library locations for * holds / recall retrieval * * @param array $patron Patron information returned by the patronLogin * method. * @param array $holdDetails Optional array, only passed in when getting a list * in the context of placing a hold; contains most of the same values passed to * placeHold, minus the patron data. May be used to limit the pickup options * or may be ignored. The driver must not add new options to the return array * based on this data or other areas of VuFind may behave incorrectly. * * @throws ILSException * @return array An array of associative arrays with locationID and * locationDisplay keys * * @SuppressWarnings(PHPMD.<API key>) */ public function getPickUpLocations($patron = false, $holdDetails = null) { $locations = []; $section = array_key_exists('<API key>', $holdDetails ?? []) ? '<API key>' : 'Holds'; $excluded = isset($this->config[$section]['<API key>']) ? explode(':', $this->config[$section]['<API key>']) : []; $included = null; if (!empty($this->config['Catalog']['<API key>']) ) { $included = []; $level = isset($holdDetails['level']) && !empty($holdDetails['level']) ? $holdDetails['level'] : 'copy'; $bibId = $holdDetails['id']; $itemId = $holdDetails['item_id'] ?? false; if ('copy' === $level && false === $itemId) { return []; } // Collect branch codes that are to be included if ('copy' === $level) { $result = $this->makeRequest( ['v1', 'availability', 'item', 'hold'], [ 'itemnumber' => $itemId, 'borrowernumber' => (int)$patron['id'], '<API key>' => 1 ], 'GET', $patron ); if (empty($result)) { return []; } $pickupLocs = $result[0]['availability']['notes']['Item::PickupLocations'] ?? []; } else { $result = $this->makeRequest( ['v1', 'availability', 'biblio', 'hold'], [ 'biblionumber' => $bibId, 'borrowernumber' => (int)$patron['id'], '<API key>' => 1 ], 'GET', $patron ); if (empty($result)) { return []; } $pickupLocs = $result[0]['availability']['notes']['Biblio::PickupLocations'] ?? []; } foreach ($pickupLocs['to_libraries'] ?? [] as $code) { $included[] = $code; } } $result = $this->makeRequest( ['v1', 'libraries'], false, 'GET', $patron ); if (empty($result)) { return []; } foreach ($result as $location) { $code = $location['branchcode']; if ((null === $included && !$location['pickup_location']) || in_array($code, $excluded) || (null !== $included && !in_array($code, $included)) ) { continue; } $locations[] = [ 'locationID' => $code, 'locationDisplay' => $location['branchname'] ]; } // Do we need to sort pickup locations? If the setting is false, don't // bother doing any more work. If it's not set at all, default to // alphabetical order. $orderSetting = isset($this->config[$section]['pickUpLocationOrder']) ? $this->config[$section]['pickUpLocationOrder'] : 'default'; if (count($locations) > 1 && !empty($orderSetting)) { $locationOrder = $orderSetting === 'default' ? [] : array_flip(explode(':', $orderSetting)); $sortFunction = function ($a, $b) use ($locationOrder) { $aLoc = $a['locationID']; $bLoc = $b['locationID']; if (isset($locationOrder[$aLoc])) { if (isset($locationOrder[$bLoc])) { return $locationOrder[$aLoc] - $locationOrder[$bLoc]; } return -1; } if (isset($locationOrder[$bLoc])) { return 1; } return strcasecmp($a['locationDisplay'], $b['locationDisplay']); }; usort($locations, $sortFunction); } return $locations; } /** * Return summary of holdings items. * * @param array $holdings Parsed holdings items * * @return array summary */ protected function getHoldingsSummary($holdings) { $availableTotal = $itemsTotal = $reservationsTotal = 0; $requests = 0; $locations = []; foreach ($holdings as $item) { if (!empty($item['availability'])) { $availableTotal++; } if (strncmp($item['item_id'], 'HLD_', 4) !== 0) { $itemsTotal++; } $locations[$item['location']] = true; if ($item['requests_placed'] > $requests) { $requests = $item['requests_placed']; } } // Since summary data is appended to the holdings array as a fake item, // we need to add a few dummy-fields that VuFind expects to be // defined for all elements. // Use a stupid location name to make sure this doesn't get mixed with // real items that don't have a proper location. $result = [ 'available' => $availableTotal, 'total' => $itemsTotal, 'locations' => count($locations), 'availability' => null, 'callnumber' => null, 'location' => '<API key>' ]; if (!empty($this->config['Holdings']['<API key>'])) { $result['reservations'] = $requests; } return $result; } /** * Return a location for a Koha item * * @param array $item Item * * @return string */ protected function getItemLocationName($item) { $result = parent::getItemLocationName($item); if ($this-><API key>) { $location = $this->translateLocation( $item['location'], !empty($item['<API key>']) ? $item['<API key>'] : $item['location'] ); if ($location) { // Empty translation will result in &#x200C $emptyChar = html_entity_decode('&#x200C;', ENT_NOQUOTES, 'UTF-8'); if ($result && $result !== $emptyChar) { $result .= ', '; } $result .= $location; } } return $result; } /** * Return a call number for a Koha item * * @param array $item Item * * @return string */ protected function getItemCallNumber($item) { $result = []; if (!empty($item['ccode']) && !empty($this->config['Holdings']['display_ccode']) ) { $result[] = $this->translateCollection( $item['ccode'], $item['ccode_description'] ?? $item['ccode'] ); } if (!$this-><API key>) { $result[] = $this->translateLocation( $item['location'], !empty($item['<API key>']) ? $item['<API key>'] : $item['location'] ); } if ((!empty($item['itemcallnumber']) || !empty($item['<API key>'])) && !empty($this->config['Holdings']['<API key>']) ) { if (!empty($this->config['Holdings']['<API key>'])) { $result[] = $item['itemcallnumber']; } else { $result[] = !empty($item['<API key>']) ? $item['<API key>'] : $item['itemcallnumber']; } } $str = implode(', ', $result); return $str; } /** * Place Hold * * Attempts to place a hold or recall on a particular item and returns * an array with result details or throws an exception on failure of support * classes * * @param array $holdDetails An array of item and patron data * * @throws ILSException * @return mixed An array of data on the request including * whether or not it was successful and a system message (if available) */ public function placeHold($holdDetails) { $patron = $holdDetails['patron']; $level = isset($holdDetails['level']) && !empty($holdDetails['level']) ? $holdDetails['level'] : 'copy'; $pickUpLocation = !empty($holdDetails['pickUpLocation']) ? $holdDetails['pickUpLocation'] : $this-><API key>; $itemId = $holdDetails['item_id'] ?? false; $comment = $holdDetails['comment'] ?? ''; $bibId = $holdDetails['id']; // Convert last interest date from Display Format to Koha's required format try { $lastInterestDate = $this->dateConverter-><API key>( 'Y-m-d', $holdDetails['requiredBy'] ); } catch (DateException $e) { // Hold Date is invalid return $this->holdError('hold_date_invalid'); } if ($level == 'copy' && empty($itemId)) { throw new ILSException("Hold level is 'copy', but item ID is empty"); } try { $checkTime = $this->dateConverter-><API key>( 'U', $holdDetails['requiredBy'] ); if (!is_numeric($checkTime)) { throw new DateException('Result should be numeric'); } } catch (DateException $e) { throw new ILSException('Problem parsing required by date.'); } if (time() > $checkTime) { // Hold Date is in the past return $this->holdError('hold_date_past'); } // Make sure pickup location is valid if (!$this-><API key>($pickUpLocation, $patron, $holdDetails)) { return $this->holdError('hold_invalid_pickup'); } $request = [ 'biblionumber' => (int)$bibId, 'borrowernumber' => (int)$patron['id'], 'branchcode' => $pickUpLocation, 'reservenotes' => $comment, 'expirationdate' => $this->dateConverter-><API key>( 'Y-m-d', $holdDetails['requiredBy'] ) ]; if ($level == 'copy') { $request['itemnumber'] = (int)$itemId; } list($code, $result) = $this->makeRequest( ['v1', 'holds'], json_encode($request), 'POST', $patron, true ); if ($code >= 300) { return $this->holdError($code, $result); } return ['success' => true]; } /** * Get Item Statuses * * This is responsible for retrieving the status information of a certain * record. * * @param string $id The record id to retrieve the holdings for * @param array $patron Patron information, if available * * @return array An associative array with the following keys: * id, availability (boolean), status, location, reserve, callnumber. */ protected function <API key>($id, $patron = null) { $holdings = []; if (!empty($this->config['Holdings']['use_holding_records'])) { list($code, $holdingsResult) = $this->makeRequest( ['v1', 'biblios', $id, 'holdings'], [], 'GET', $patron, true ); if (404 === $code) { return []; } if ($code !== 200) { throw new ILSException('Problem with Koha REST API.'); } // Turn the holdings into a keyed array if (!empty($holdingsResult['holdings'])) { foreach ($holdingsResult['holdings'] as $holding) { $holdings[$holding['holding_id']] = $holding; } } } list($code, $result) = $this->makeRequest( ['v1', 'availability', 'biblio', 'search'], ['biblionumber' => $id], 'GET', $patron, true ); if (404 === $code) { return []; } if ($code !== 200) { throw new ILSException('Problem with Koha REST API.'); } $statuses = []; foreach ($result[0]['item_availabilities'] ?? [] as $i => $item) { // $holding is a reference! unset($holding); if (!empty($item['holding_id']) && isset($holdings[$item['holding_id']]) ) { $holding = &$holdings[$item['holding_id']]; if ($holding['suppress']) { continue; } } $avail = $item['availability']; $available = $avail['available']; $statusCodes = $this->getItemStatusCodes($item); $status = $this->pickStatus($statusCodes); if (isset($avail['unavailabilities']['Item::CheckedOut']['date_due'])) { $duedate = $this->dateConverter-><API key>( 'Y-m-d\TH:i:sP', $avail['unavailabilities']['Item::CheckedOut']['date_due'] ); } else { $duedate = null; } $location = $this->getItemLocationName($item); $callnumber = $this->getItemCallNumber($item); $sublocation = $item['sub_description'] ?? ''; $branchId = (!$this->useHomeBranch && null !== $item['holdingbranch']) ? $item['holdingbranch'] : $item['homebranch']; $locationId = $item['location']; $entry = [ 'id' => $id, 'item_id' => $item['itemnumber'], 'location' => $location, 'department' => $sublocation, 'availability' => $available, 'status' => $status, 'status_array' => $statusCodes, 'reserve' => 'N', 'callnumber' => $callnumber, 'duedate' => $duedate, 'number' => $item['enumchron'], 'barcode' => $item['barcode'], 'sort' => $i, 'requests_placed' => max( [$item['hold_queue_length'], $result[0]['hold_queue_length']] ), 'branchId' => $branchId, 'locationId' => $locationId ]; if (!empty($item['itemnotes'])) { $entry['item_notes'] = [$item['itemnotes']]; } if ($patron && $this->itemHoldAllowed($item)) { $entry['is_holdable'] = true; $entry['level'] = 'copy'; $entry['addLink'] = 'check'; } else { $entry['is_holdable'] = false; } if ($patron && $this-><API key>($item)) { $entry['<API key>'] = 'auto'; $entry['<API key>'] = 'check'; } if (isset($holding)) { $entry += $this->getHoldingData($holding); $holding['_hasItems'] = true; } $statuses[] = $entry; } // $holding is a reference! unset($holding); if (!isset($i)) { $i = 0; } // Add holdings that don't have items if (!empty($holdings)) { foreach ($holdings as $holding) { if ($holding['suppress'] || !empty($holding['_hasItems'])) { continue; } $holdingData = $this->getHoldingData($holding, true); $i++; $entry = $this->createHoldingEntry($id, $holding, $i); $entry += $holdingData; $statuses[] = $entry; } } // See if there are links in holdings $electronic = []; if (!empty($holdings)) { foreach ($holdings as $holding) { $marc = $this->getHoldingMarc($holding); if (null === $marc) { continue; } $notes = []; if ($fields = $marc->getFields('852')) { foreach ($fields as $field) { if ($subfield = $field->getSubfield('z')) { $notes[] = $subfield->getData(); } } } if ($fields = $marc->getFields('856')) { foreach ($fields as $field) { if ($subfields = $field->getSubfields()) { $urls = []; $desc = []; $parts = []; foreach ($subfields as $code => $subfield) { if ('u' === $code) { $urls[] = $subfield->getData(); } elseif ('3' === $code) { $parts[] = $subfield->getData(); } elseif (in_array($code, ['y', 'z'])) { $desc[] = $subfield->getData(); } } foreach ($urls as $url) { ++$i; $entry = $this->createHoldingEntry($id, $holding, $i); $entry['availability'] = true; $entry['location'] = implode('. ', $desc); $entry['locationhref'] = $url; $entry['use_unknown_message'] = false; $entry['status'] = implode('. ', array_merge($parts, $notes)); $electronic[] = $entry; } } } } } } usort($statuses, [$this, 'statusSortFunction']); usort($electronic, [$this, 'statusSortFunction']); return [ 'holdings' => $statuses, 'electronic_holdings' => $electronic ]; } /** * Create a holding entry * * @param string $id Bib ID * @param array $holding Holding * @param int $sortKey Sort key * * @return array */ protected function createHoldingEntry($id, $holding, $sortKey) { $location = $this->getBranchName($holding['holdingbranch']); $callnumber = ''; if (!empty($holding['ccode']) && !empty($this->config['Holdings']['display_ccode']) ) { $callnumber = $this->translateCollection( $holding['ccode'], $holding['ccode_description'] ?? $holding['ccode'] ); } if ($this-><API key>) { $holdingLoc = $this->translateLocation( $holding['location'], !empty($holding['<API key>']) ? $holding['<API key>'] : $holding['location'] ); if ($holdingLoc) { if ($location) { $location .= ', '; } $location .= $holdingLoc; } } else { if ($callnumber) { $callnumber .= ', '; } $callnumber .= $this->translateLocation( $holding['location'], !empty($holding['<API key>']) ? $holding['<API key>'] : $holding['location'] ); } if ($holding['callnumber']) { $callnumber .= ' ' . $holding['callnumber']; } $callnumber = trim($callnumber); $branchId = $holding['holdingbranch']; $locationId = $holding['location']; return [ 'id' => $id, 'item_id' => 'HLD_' . $holding['biblionumber'], 'location' => $location, 'requests_placed' => 0, 'status' => '', 'use_unknown_message' => true, 'availability' => false, 'duedate' => '', 'barcode' => '', 'callnumber' => $callnumber, 'sort' => $sortKey, 'branchId' => $branchId, 'locationId' => $locationId ]; } /** * Return a location for a Koha branch ID * * @param string $branchId Branch ID * * @return string */ protected function getBranchName($branchId) { $name = $this->translate("location_$branchId"); if ($name === "location_$branchId") { $branches = $this->getCachedData('branches'); if (null === $branches) { $result = $this->makeRequest( ['v1', 'libraries'], false, 'GET' ); $branches = []; foreach ($result as $branch) { $branches[$branch['branchcode']] = $branch['branchname']; } $this->putCachedData('branches', $branches); } $name = $branches[$branchId] ?? $branchId; } return $name; } /** * Get a MARC record for the given holding or null if not available * * @param array $holding Holding * * @return \File_MARCXML */ protected function getHoldingMarc(&$holding) { if (!isset($holding['_marcRecord'])) { foreach ($holding['holdings_metadata'] ?? [$holding['metadata']] as $metadata ) { if ('marcxml' === $metadata['format'] && 'MARC21' === $metadata['marcflavour'] ) { $marc = new \File_MARCXML( $metadata['metadata'], \File_MARCXML::SOURCE_STRING ); $holding['_marcRecord'] = $marc->next(); return $holding['_marcRecord']; } } $holding['_marcRecord'] = null; } return $holding['_marcRecord']; } /** * Get holding data from a holding record * * @param array $holding Holding record from Koha * * @return array */ protected function getHoldingData(&$holding) { $marc = $this->getHoldingMarc($holding); if (null === $marc) { return []; } $marcDetails = []; // Get Notes $data = $this->getMFHDData( $marc, isset($this->config['Holdings']['notes']) ? $this->config['Holdings']['notes'] : '852z' ); if ($data) { $marcDetails['notes'] = $data; } // Get Summary (may be multiple lines) $data = $this->getMFHDData( $marc, isset($this->config['Holdings']['summary']) ? $this->config['Holdings']['summary'] : '866a' ); if ($data) { $marcDetails['summary'] = $data; } // Get Supplements if (isset($this->config['Holdings']['supplements'])) { $data = $this->getMFHDData( $marc, $this->config['Holdings']['supplements'] ); if ($data) { $marcDetails['supplements'] = $data; } } // Get Indexes if (isset($this->config['Holdings']['indexes'])) { $data = $this->getMFHDData( $marc, $this->config['Holdings']['indexes'] ); if ($data) { $marcDetails['indexes'] = $data; } } // Get links if (isset($this->config['Holdings']['links'])) { $data = $this->getMFHDData( $marc, $this->config['Holdings']['links'] ); if ($data) { $marcDetails['links'] = $data; } } // Make sure to return an empty array unless we have details to display if (!empty($marcDetails)) { $marcDetails['holdings_id'] = $holding['holding_id']; } return $marcDetails; } /** * Get specified fields from an MFHD MARC Record * * @param object $record File_MARC object * @param array|string $fieldSpecs Array or colon-separated list of * field/subfield specifications (3 chars for field code and then subfields, * e.g. 866az) * * @return string|string[] Results as a string if single, array if multiple */ protected function getMFHDData($record, $fieldSpecs) { if (!is_array($fieldSpecs)) { $fieldSpecs = explode(':', $fieldSpecs); } $results = ''; foreach ($fieldSpecs as $fieldSpec) { $fieldCode = substr($fieldSpec, 0, 3); $subfieldCodes = substr($fieldSpec, 3); if ($fields = $record->getFields($fieldCode)) { foreach ($fields as $field) { if ($subfields = $field->getSubfields()) { $line = ''; foreach ($subfields as $code => $subfield) { if (!strstr($subfieldCodes, $code)) { continue; } if ($line) { $line .= ' '; } $line .= $subfield->getData(); } if ($line) { if (!$results) { $results = $line; } else { if (!is_array($results)) { $results = [$results]; } $results[] = $line; } } } } } } return $results; } /** * Translate location name * * @param string $location Location code * @param string $default Default value if translation is not available * * @return string */ protected function translateLocation($location, $default = null) { if (empty($location)) { return null !== $default ? $default : ''; } $prefix = $catPrefix = 'location_'; if (!empty($this->config['Catalog']['id'])) { $catPrefix .= $this->config['Catalog']['id'] . '_'; } return $this->translate( "$catPrefix$location", null, $this->translate( "$prefix$location", null, null !== $default ? $default : $location ) ); } /** * Translate collection name * * @param string $code Collection code * @param string $description Collection description * * @return string */ protected function translateCollection($code, $description) { $prefix = 'collection_'; if (!empty($this->config['Catalog']['id'])) { $prefix .= $this->config['Catalog']['id'] . '_'; } return $this->translate( "$prefix$code", null, $description ); } /** * Status item sort function * * @param array $a First status record to compare * @param array $b Second status record to compare * * @return int */ protected function statusSortFunction($a, $b) { $orderA = $this->holdingsBranchOrder[$a['branchId'] . '/' . $a['locationId']] ?? $this->holdingsBranchOrder[$a['branchId']] ?? 999; $orderB = $this->holdingsBranchOrder[$b['branchId'] . '/' . $b['locationId']] ?? $this->holdingsBranchOrder[$b['branchId']] ?? 999; $result = $orderA - $orderB; if (0 === $result) { $orderA = $this-><API key>[$a['locationId']] ?? 999; $orderB = $this-><API key>[$b['locationId']] ?? 999; $result = $orderA - $orderB; } if (0 === $result) { $result = strcmp($a['location'], $b['location']); } if (0 === $result && $this-><API key>) { // Reverse chronological order $result = strnatcmp($b['number'] ?? '', $a['number'] ?? ''); } if (0 === $result) { $result = $a['sort'] - $b['sort']; } return $result; } }
package com.github.esadmin.meta.model; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.persistence.Table; import org.guess.core.orm.IdEntity; import org.hibernate.annotations.Cache; import org.hibernate.annotations.<API key>; import com.fasterxml.jackson.annotation.<API key>; /** * Entity * @author Joe.zhang * @version 2015-12-08 */ @Entity @Table(name = "meta_dbindex") @<API key>(value = {"<API key>","handler", "columns"}) @Cache(usage = <API key>.READ_WRITE) public class DBIndex extends IdEntity { @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, targetEntity = DBTable.class) @JoinTable(name = "meta_table_index", joinColumns = { @JoinColumn(name = "index_id") }, inverseJoinColumns = { @JoinColumn(name = "table_id") }) @<API key>(value = { "<API key>","handler","datasource"}) @Cache(usage = <API key>.READ_WRITE) private Set<DBTable> tables = new HashSet<DBTable>(0); @Column(name="index_name") private String index_name; @Column(name="type_name") private String type_name; @Column(name="index_type") private Integer indexType; @Column(name="createby_id") private Long createbyId; @Column(name="updateby_id") private Long updatebyId; @Column(name="create_date") private Date createDate; @Column(name="update_date") private Date updateDate; @Column(name="remark") private String remark; @OneToMany(targetEntity = DbColumn.class, fetch = FetchType.LAZY, cascade = CascadeType.ALL,mappedBy="dbindex") @OrderBy("id ASC") private Set<DbColumn> columns; @Column(name="check_label") private Integer checkLabel; public Integer getCheckLabel() { return checkLabel; } public void setCheckLabel(Integer checkLabel) { this.checkLabel = checkLabel; } public Set<DBTable> getTables() { return tables; } public void setTables(Set<DBTable> tables) { this.tables = tables; } public String getIndex_name() { return index_name; } public void setIndex_name(String index_name) { this.index_name = index_name; } public String getType_name() { return type_name; } public void setType_name(String type_name) { this.type_name = type_name; } public Integer getIndexType() { return indexType; } public void setIndexType(Integer indexType) { this.indexType = indexType; } public Long getCreatebyId() { return createbyId; } public void setCreatebyId(Long createbyId) { this.createbyId = createbyId; } public Set<DbColumn> getColumns() { return columns; } public void setColumns(Set<DbColumn> columns) { this.columns = columns; } public Long getUpdatebyId() { return updatebyId; } public void setUpdatebyId(Long updatebyId) { this.updatebyId = updatebyId; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
# notice is included verbatim in any distributions. No written agreement, # and need not follow the licensing terms described here, provided that # the new terms are clearly indicated on the first page of each file where # they apply. DESTDIR = VPATH = ../../.././libgloss/libnosys srcdir = ../../.././libgloss/libnosys objdir = . srcroot = $(srcdir)/../.. objroot = $(objdir)/../.. prefix = /usr/local exec_prefix = ${prefix} host_alias = arm-none-eabi target_alias = arm-none-eabi <API key> = s&^&arm-none-eabi-& bindir = ${exec_prefix}/bin libdir = ${exec_prefix}/lib tooldir = $(exec_prefix)/$(target_alias) # Multilib support variables. # TOP is used instead of MULTI{BUILD,SRC}TOP. MULTIDIRS = MULTISUBDIR = MULTIDO = true MULTICLEAN = true INSTALL = /usr/bin/install -c INSTALL_PROGRAM = /usr/bin/install -c INSTALL_DATA = /usr/bin/install -c -m 644 SHELL = /bin/sh CC = arm-none-eabi-gcc -B/sources/newlib/newlib-1.18.0/arm-none-eabi/newlib/ -isystem /sources/newlib/newlib-1.18.0/arm-none-eabi/newlib/targ-include -isystem /sources/newlib/newlib-1.18.0/newlib/libc/include -B/sources/newlib/newlib-1.18.0/arm-none-eabi/libgloss/arm -L/sources/newlib/newlib-1.18.0/arm-none-eabi/libgloss/libnosys -L/sources/newlib/newlib-1.18.0/libgloss/arm #AS = arm-none-eabi-as AS = `if [ -f ${objroot}/../gas/as-new ] ; \ then echo ${objroot}/../gas/as-new ; \ else echo as ; fi` AR = arm-none-eabi-ar #LD = arm-none-eabi-ld LD = `if [ -f ${objroot}/../ld/ld-new ] ; \ then echo ${objroot}/../ld/ld-new ; \ else echo ld ; fi` RANLIB = <API key> OBJDUMP = `if [ -f ${objroot}/../binutils/objdump ] ; \ then echo ${objroot}/../binutils/objdump ; \ else t='$(<API key>)'; echo objdump | sed -e $$t ; fi` OBJCOPY = `if [ -f ${objroot}/../binutils/objcopy ] ; \ then echo ${objroot}/../binutils/objcopy ; \ else t='$(<API key>)'; echo objcopy | sed -e $$t ; fi` # object files needed OBJS = chown.o close.o environ.o errno.o execve.o fork.o fstat.o \ getpid.o gettod.o isatty.o kill.o link.o lseek.o open.o \ read.o readlink.o sbrk.o stat.o symlink.o times.o unlink.o \ wait.o write.o _exit.o # Object files specific to particular targets. EVALOBJS = ${OBJS} GCC_LDFLAGS = `if [ -d ${objroot}/../gcc ] ; \ then echo -L${objroot}/../gcc ; fi` OUTPUTS = libnosys.a NEWLIB_CFLAGS = `if [ -d ${objroot}/newlib ]; then echo -I${objroot}/newlib/targ-include -I${srcroot}/newlib/libc/include; fi` NEWLIB_LDFLAGS = `if [ -d ${objroot}/newlib ]; then echo -B${objroot}/newlib/ -L${objroot}/newlib/; fi` INCLUDES = -I. -I$(srcdir)/.. # Note that when building the library, ${MULTILIB} is not the way multilib # options are passed; they're passed in $(CFLAGS). CFLAGS_FOR_TARGET = ${MULTILIB} ${INCLUDES} ${NEWLIB_CFLAGS} LDFLAGS_FOR_TARGET = ${MULTILIB} ${NEWLIB_LDFLAGS} AR_FLAGS = qc .c.o: $(CC) $(CFLAGS_FOR_TARGET) -O2 $(INCLUDES) -c $(CFLAGS) $< .C.o: $(CC) $(CFLAGS_FOR_TARGET) -O2 $(INCLUDES) -c $(CFLAGS) $< .s.o: $(AS) $(ASFLAGS_FOR_TARGET) $(INCLUDES) $(ASFLAGS) -o $*.o $< # GCC knows to run the preprocessor on .S files before it assembles them. .S.o: $(CC) $(CFLAGS_FOR_TARGET) $(INCLUDES) $(CFLAGS) -c $< # this is a bogus target that'll produce an assembler from the # C source with the right compiler options. this is so we can # track down code generation or debug symbol bugs. .c.s: $(CC) $(CFLAGS_FOR_TARGET) -S $(INCLUDES) $(CFLAGS) $< all: ${OUTPUTS} # here's where we build the library for each target libnosys.a: $(EVALOBJS) ${AR} ${ARFLAGS} $@ $(EVALOBJS) ${RANLIB} $@ doc: clean mostlyclean: rm -f $(OUTPUTS) *.i *~ *.o *-test *.srec *.dis *.map *.x distclean maintainer-clean realclean: clean rm -f Makefile config.status $(OUTPUTS) .PHONY: install info install-info clean-info install: @for outputs in ${OUTPUTS}; do\ mkdir -p $(DESTDIR)$(tooldir)/lib${MULTISUBDIR}; \ $(INSTALL_PROGRAM) $${outputs} $(DESTDIR)$(tooldir)/lib${MULTISUBDIR}; \ done info: install-info: clean-info: Makefile: Makefile.in config.status ../../.././libgloss/libnosys/../config/default.mh $(SHELL) config.status config.status: configure $(SHELL) config.status --recheck
\hypertarget{padlock_8h}{\section{C\-:/dev2/luambedtls/dependencies/mbedtls/include/mbedtls/padlock.h File Reference} \label{padlock_8h}\index{C\-:/dev2/luambedtls/dependencies/mbedtls/include/mbedtls/padlock.\-h@{C\-:/dev2/luambedtls/dependencies/mbedtls/include/mbedtls/padlock.\-h}} } V\-I\-A Pad\-Lock A\-C\-E for H\-W encryption/decryption supported by some processors. {\ttfamily \#include \char`\"{}aes.\-h\char`\"{}}\\* \subsection*{Macros} \begin{DoxyCompactItemize} \item \#define \hyperlink{<API key>}{M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D}~-\/0x0030 \end{DoxyCompactItemize} \subsection{Detailed Description} V\-I\-A Pad\-Lock A\-C\-E for H\-W encryption/decryption supported by some processors. Copyright (C) 2006-\/2015, A\-R\-M Limited, All Rights Reserved This file is part of mbed T\-L\-S (\href{https://tls.mbed.org}{\tt https\-://tls.\-mbed.\-org}) This program is free software; you can redistribute it and/or modify it under the terms of the G\-N\-U 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 W\-I\-T\-H\-O\-U\-T A\-N\-Y W\-A\-R\-R\-A\-N\-T\-Y; without even the implied warranty of M\-E\-R\-C\-H\-A\-N\-T\-A\-B\-I\-L\-I\-T\-Y or F\-I\-T\-N\-E\-S\-S F\-O\-R A P\-A\-R\-T\-I\-C\-U\-L\-A\-R P\-U\-R\-P\-O\-S\-E. See the G\-N\-U General Public License for more details. You should have received a copy of the G\-N\-U General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, M\-A 02110-\/1301 U\-S\-A. Definition in file \hyperlink{padlock_8h_source}{padlock.\-h}. \subsection{Macro Definition Documentation} \hypertarget{<API key>}{\index{padlock.\-h@{padlock.\-h}!M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D@{M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D}} \index{M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D@{M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D}!padlock.h@{padlock.\-h}} \subsubsection[{M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D}]{\setlength{\rightskip}{0pt plus 5cm}\#define M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D~-\/0x0030}}\label{<API key>} Input data should be aligned. Definition at line 30 of file padlock.\-h.
<?php /* core/themes/stable/templates/block/<API key>.html.twig */ class <API key> extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { $tags = array(); $filters = array(); $functions = array(); try { $this->env->getExtension('sandbox')->checkSecurity( array(), array(), array() ); } catch (<API key> $e) { $e->setTemplateFile($this->getTemplateName()); if ($e instanceof <API key> && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof <API key> && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof <API key> && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } // line 13 echo $this->env->getExtension('sandbox')-><API key>($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["content"]) ? $context["content"] : null), "html", null, true)); echo " "; } public function getTemplateName() { return "core/themes/stable/templates/block/<API key>.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 43 => 13,); } } /* * @file*/ /* * Theme override for the messages block.*/ /* * Removes wrapper elements from block so that empty block does not appear when*/ /* * there are no messages.*/ /* * Available variables:*/ /* * - content: The content of this block.*/ /* {{ content }}*/
import unittest from pyxt.mda import * from pyxt.chargen import <API key> class MDATests(unittest.TestCase): def setUp(self): self.cg = <API key>(width = 9, height = 14) self.mda = <API key>(self.cg) # Hijack reset so it doesn't call into Pygame during the tests. self.reset_count = 0 self.mda.reset = self.reset_testable def reset_testable(self): self.reset_count += 1 def test_ports_list(self): self.assertEqual(self.mda.get_ports_list(), [0x03B0, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB]) def <API key>(self): self.assertEqual(self.mda.get_memory_size(), 4096) def test_initial_state(self): self.assertEqual(self.mda.control_reg, 0x00) self.assertEqual(self.mda.control_reg, 0x00) self.assertEqual(self.mda.screen, None) self.assertEqual(self.mda.char_generator, self.cg) self.assertEqual(len(self.mda.video_ram), 4096) def <API key>(self): self.mda.mem_write_byte(0x0000, 0x41) self.assertEqual(self.mda.video_ram[0x0000], 0x41) def <API key>(self): self.mda.mem_write_byte(0x0000, 0x41) self.assertEqual(self.cg.last_blit, (None, (0, 0), 0x41, MDA_GREEN, MDA_BLACK)) def <API key>(self): self.mda.mem_write_byte(3998, 0xFF) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0xFF, MDA_GREEN, MDA_BLACK)) def <API key>(self): self.mda.mem_write_byte(3998, 0xFF) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0xFF, MDA_GREEN, MDA_BLACK)) self.mda.mem_write_byte(3999, MDA_ATTR_INTENSITY) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0xFF, MDA_BRIGHT_GREEN, MDA_BLACK)) def <API key>(self): self.mda.mem_write_byte(3999, MDA_ATTR_INTENSITY) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0x00, MDA_BRIGHT_GREEN, MDA_BLACK)) self.mda.mem_write_byte(3998, 0xFF) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0xFF, MDA_BRIGHT_GREEN, MDA_BLACK)) def <API key>(self): self.mda.mem_write_byte(4000, 0xFF) self.assertEqual(self.cg.last_blit, None) def test_mem_read_byte(self): self.mda.video_ram[77] = 0xA5 self.assertEqual(self.mda.mem_read_byte(77), 0xA5) def <API key>(self): self.assertEqual(self.mda.mem_read_byte(4000), 0x00) @unittest.skip("We need to initialize Pygame exactly once at startup.") def <API key>(self): self.assertEqual(self.reset_count, 0) self.mda.io_write_byte(0x3B8, 0x01) self.assertEqual(self.reset_count, 1) # Second write shouldn't call reset again. self.mda.io_write_byte(0x3B8, 0x01) self.assertEqual(self.reset_count, 1) def <API key>(self): self.mda.mem_write_word(0x0000, 0x0841) # 'A' with intensity. self.assertEqual(self.mda.video_ram[0x0000], 0x41) self.assertEqual(self.mda.video_ram[0x0001], 0x08) self.assertEqual(self.cg.last_blit, (None, (0, 0), 0x41, MDA_BRIGHT_GREEN, MDA_BLACK)) def <API key>(self): self.mda.mem_write_word(3998, 0x085A) # 'Z' with intensity. self.assertEqual(self.mda.video_ram[3998], 0x5A) self.assertEqual(self.mda.video_ram[3999], 0x08) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0x5A, MDA_BRIGHT_GREEN, MDA_BLACK)) def <API key>(self): self.mda.mem_write_word(3999, 0xFF08) # 'Z' with intensity. self.assertEqual(self.mda.video_ram[3998], 0x00) # Should be unmodified. self.assertEqual(self.mda.video_ram[3999], 0x08) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0x00, MDA_BRIGHT_GREEN, MDA_BLACK)) def test_mem_read_word(self): self.mda.video_ram[0x0000] = 0x41 self.mda.video_ram[0x0001] = 0x08 self.assertEqual(self.mda.mem_read_word(0x0000), 0x0841) def <API key>(self): self.mda.video_ram[3998] = 0x12 self.mda.video_ram[3999] = 0x34 self.assertEqual(self.mda.mem_read_word(3999), 0x0034) def <API key>(self): self.assertEqual(self.mda.io_read_byte(0x3BA), 0xF0) self.assertEqual(self.mda.io_read_byte(0x3BA), 0xF1) self.assertEqual(self.mda.io_read_byte(0x3BA), 0xF0) def <API key>(self): self.assertEqual(self.mda.current_pixel, [0, 0]) self.mda.io_read_byte(0x3BA) self.assertEqual(self.mda.current_pixel, [1, 0]) def <API key>(self): self.mda.current_pixel = [719, 0] self.mda.io_read_byte(0x3BA) self.assertEqual(self.mda.current_pixel, [0, 1]) def <API key>(self): self.mda.current_pixel = [719, 349] self.mda.io_read_byte(0x3BA) self.assertEqual(self.mda.current_pixel, [0, 0])
( function($) { } )( jQuery ); var waitForFinalEvent = (function () { var timers = {}; return function (callback, ms, uniqueId) { if (!uniqueId) { uniqueId = "Don't call this twice without a uniqueId"; } if (timers[uniqueId]) { clearTimeout (timers[uniqueId]); } timers[uniqueId] = setTimeout(callback, ms); }; })();
#include <asm/gpio.h> /* Board GPIO configuration entry */ struct gpio_cfg_ent { /* GPIO number */ int gpio_num; /* Configure GPIO as output */ int is_output; /* Initial output value for output */ int output_val; }; /** * Board GPIO Initialization * * @param[in] cfg * Board GPIO configuration entry array * * @param[in] cnt * Number of board GPIO configuration entries * * @return 0 upon success */ int gpio_board_init( const struct gpio_cfg_ent *cfg, int cnt);
/* ScriptData SDName: <API key> SD%Complete: 70% SDComment: SDCategory: Sunwell_Plateau EndScriptData */ #include "precompiled.h" #include "sunwell_plateau.h" /* Sunwell Plateau: 0 - Kalecgos and Sathrovarr 1 - Brutallus 2 - Felmyst 3 - Eredar Twins (Alythess and Sacrolash) 4 - M'uru 5 - Kil'Jaeden */ static const DialogueEntry <API key>[] = { {<API key>, 0, 10000}, {SAY_KALECGOS_OUTRO, <API key>, 5000}, {NPC_FELMYST, 0, 5000}, {<API key>, 0, 9000}, {NPC_BRUTALLUS, 0, 0}, {0, 0, 0}, }; <API key>::<API key>(Map* pMap) : ScriptedInstance(pMap), DialogueHelper(<API key>), m_uiDeceiversKilled(0), <API key>(5000), <API key>(0), <API key>(0), <API key>(90000) { Initialize(); } void <API key>::Initialize() { memset(&m_auiEncounter, 0, sizeof(m_auiEncounter)); <API key>(this); } bool <API key>::<API key>() const { for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) { if (m_auiEncounter[i] == IN_PROGRESS) return true; } return false; } void <API key>::OnPlayerEnter(Player* pPlayer) { // Return if Felmyst already dead, or Brutallus alive if (m_auiEncounter[TYPE_BRUTALLUS] != DONE || m_auiEncounter[TYPE_FELMYST] == DONE) return; // Return if already summoned if (<API key>(NPC_FELMYST, true)) return; // Summon Felmyst in reload case pPlayer->SummonCreature(NPC_FELMYST, aMadrigosaLoc[0].m_fX, aMadrigosaLoc[0].m_fY, aMadrigosaLoc[0].m_fZ, aMadrigosaLoc[0].m_fO, <API key>, 0); } void <API key>::OnCreatureCreate(Creature* pCreature) { switch (pCreature->GetEntry()) { case NPC_KALECGOS_DRAGON: case NPC_KALECGOS_HUMAN: case NPC_SATHROVARR: case <API key>: case <API key>: case NPC_MADRIGOSA: case NPC_BRUTALLUS: case NPC_FELMYST: case <API key>: case NPC_ALYTHESS: case NPC_SACROLASH: case NPC_MURU: case NPC_ENTROPIUS: case <API key>: case NPC_KILJAEDEN: case NPC_KALECGOS: case NPC_ANVEENA: case NPC_VELEN: case NPC_LIADRIN: <API key>[pCreature->GetEntry()] = pCreature->GetObjectGuid(); break; case NPC_DECEIVER: <API key>.push_back(pCreature->GetObjectGuid()); break; case NPC_WORLD_TRIGGER: // sort triggers for flightpath if (pCreature->GetPositionZ() < 51.0f) <API key>.push_back(pCreature->GetObjectGuid()); break; case <API key>: if (pCreature->GetPositionY() < 523.0f) <API key>.push_back(pCreature->GetObjectGuid()); break; } } void <API key>::OnCreatureDeath(Creature* pCreature) { if (pCreature->GetEntry() == NPC_DECEIVER) { ++m_uiDeceiversKilled; // Spawn Kiljaeden when all deceivers are killed if (m_uiDeceiversKilled == MAX_DECEIVERS) { if (Creature* pController = <API key>(<API key>)) { if (Creature* pKiljaeden = pController->SummonCreature(NPC_KILJAEDEN, pController->GetPositionX(), pController->GetPositionY(), pController->GetPositionZ(), pController->GetOrientation(), <API key>, 0)) pKiljaeden->SetInCombatWithZone(); pController-><API key>(SPELL_ANVEENA_DRAIN); } } } } void <API key>::OnCreatureEvade(Creature* pCreature) { // Reset encounter if raid wipes at deceivers if (pCreature->GetEntry() == NPC_DECEIVER) SetData(TYPE_KILJAEDEN, FAIL); } void <API key>::OnObjectCreate(GameObject* pGo) { switch (pGo->GetEntry()) { case GO_FORCEFIELD: case GO_BOSS_COLLISION_1: case GO_BOSS_COLLISION_2: case GO_ICE_BARRIER: break; case GO_FIRE_BARRIER: if (m_auiEncounter[TYPE_KALECGOS] == DONE && m_auiEncounter[TYPE_BRUTALLUS] == DONE && m_auiEncounter[TYPE_FELMYST] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_FIRST_GATE: break; case GO_SECOND_GATE: if (m_auiEncounter[TYPE_EREDAR_TWINS] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_MURU_ENTER_GATE: if (m_auiEncounter[TYPE_EREDAR_TWINS] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_MURU_EXIT_GATE: if (m_auiEncounter[TYPE_MURU] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_THIRD_GATE: if (m_auiEncounter[TYPE_MURU] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case <API key>: case <API key>: case <API key>: case <API key>: break; default: return; } m_mGoEntryGuidStore[pGo->GetEntry()] = pGo->GetObjectGuid(); } void <API key>::SetData(uint32 uiType, uint32 uiData) { switch (uiType) { case TYPE_KALECGOS: m_auiEncounter[uiType] = uiData; // combat doors DoUseDoorOrButton(GO_FORCEFIELD); DoUseDoorOrButton(GO_BOSS_COLLISION_1); DoUseDoorOrButton(GO_BOSS_COLLISION_2); if (uiData == FAIL) { <API key> = 20000; if (Creature* pKalecDragon = <API key>(NPC_KALECGOS_DRAGON)) pKalecDragon->ForcedDespawn(); if (Creature* pKalecHuman = <API key>(NPC_KALECGOS_HUMAN)) pKalecHuman->ForcedDespawn(); if (Creature* pSathrovarr = <API key>(NPC_SATHROVARR)) pSathrovarr->AI()->EnterEvadeMode(); } break; case TYPE_BRUTALLUS: m_auiEncounter[uiType] = uiData; break; case TYPE_FELMYST: m_auiEncounter[uiType] = uiData; if (uiData == DONE) <API key>(<API key>); else if (uiData == IN_PROGRESS) <API key>(); break; case TYPE_EREDAR_TWINS: m_auiEncounter[uiType] = uiData; if (uiData == DONE) { DoUseDoorOrButton(GO_SECOND_GATE); DoUseDoorOrButton(GO_MURU_ENTER_GATE); } break; case TYPE_MURU: m_auiEncounter[uiType] = uiData; // combat door DoUseDoorOrButton(GO_MURU_ENTER_GATE); if (uiData == DONE) { DoUseDoorOrButton(GO_MURU_EXIT_GATE); DoUseDoorOrButton(GO_THIRD_GATE); } else if (uiData == IN_PROGRESS) <API key> = 10 * MINUTE * IN_MILLISECONDS; break; case TYPE_KILJAEDEN: m_auiEncounter[uiType] = uiData; if (uiData == FAIL) { m_uiDeceiversKilled = 0; // Reset Orbs <API key>(<API key>, GO_FLAG_NO_INTERACT, true); <API key>(<API key>, GO_FLAG_NO_INTERACT, true); <API key>(<API key>, GO_FLAG_NO_INTERACT, true); <API key>(<API key>, GO_FLAG_NO_INTERACT, true); // Respawn deceivers for (GuidList::const_iterator itr = <API key>.begin(); itr != <API key>.end(); ++itr) { if (Creature* pDeceiver = instance->GetCreature(*itr)) { if (!pDeceiver->isAlive()) pDeceiver->Respawn(); } } } break; } if (uiData == DONE) { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << m_auiEncounter[0] << " " << m_auiEncounter[1] << " " << m_auiEncounter[2] << " " << m_auiEncounter[3] << " " << m_auiEncounter[4] << " " << m_auiEncounter[5]; m_strInstData = saveStream.str(); SaveToDB(); <API key>; } } uint32 <API key>::GetData(uint32 uiType) const { if (uiType < MAX_ENCOUNTER) return m_auiEncounter[uiType]; return 0; } void <API key>::Update(uint32 uiDiff) { DialogueUpdate(uiDiff); if (<API key>) { if (<API key> <= uiDiff) { if (Creature* pKalecDragon = <API key>(NPC_KALECGOS_DRAGON)) pKalecDragon->Respawn(); if (Creature* pKalecHuman = <API key>(NPC_KALECGOS_HUMAN)) pKalecHuman->Respawn(); <API key> = 0; } else <API key> -= uiDiff; } // Muru berserk timer; needs to be done here because it involves two distinct creatures if (m_auiEncounter[TYPE_MURU] == IN_PROGRESS) { if (<API key> < uiDiff) { if (Creature* pEntrpius = <API key>(NPC_ENTROPIUS, true)) pEntrpius->CastSpell(pEntrpius, SPELL_MURU_BERSERK, true); else if (Creature* pMuru = <API key>(NPC_MURU)) pMuru->CastSpell(pMuru, SPELL_MURU_BERSERK, true); <API key> = 10 * MINUTE * IN_MILLISECONDS; } else <API key> -= uiDiff; } if (m_auiEncounter[TYPE_KILJAEDEN] == NOT_STARTED || m_auiEncounter[TYPE_KILJAEDEN] == FAIL) { if (<API key> < uiDiff) { switch (urand(0, 4)) { case 0: <API key>(SAY_ORDER_1, <API key>); break; case 1: <API key>(SAY_ORDER_2, <API key>); break; case 2: <API key>(SAY_ORDER_3, <API key>); break; case 3: <API key>(SAY_ORDER_4, <API key>); break; case 4: <API key>(SAY_ORDER_5, <API key>); break; } <API key> = 90000; } else <API key> -= uiDiff; } } void <API key>::Load(const char* in) { if (!in) { <API key>; return; } OUT_LOAD_INST_DATA(in); std::istringstream loadStream(in); loadStream >> m_auiEncounter[0] >> m_auiEncounter[1] >> m_auiEncounter[2] >> m_auiEncounter[3] >> m_auiEncounter[4] >> m_auiEncounter[5]; for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) { if (m_auiEncounter[i] == IN_PROGRESS) m_auiEncounter[i] = NOT_STARTED; } <API key>; } static bool sortByPositionX(Creature* pFirst, Creature* pSecond) { return pFirst && pSecond && pFirst->GetPositionX() > pSecond->GetPositionX(); } void <API key>::<API key>() { if (<API key>.empty()) { script_error_log("Instance Sunwell Plateau: ERROR Failed to load flight triggers for creature id %u.", NPC_FELMYST); return; } std::list<Creature*> lTriggers; // Valid pointers, only used locally for (GuidList::const_iterator itr = <API key>.begin(); itr != <API key>.end(); ++itr) { if (Creature* pTrigger = instance->GetCreature(*itr)) lTriggers.push_back(pTrigger); } if (lTriggers.empty()) return; // sort the flight triggers; first by position X, then group them by Y (left and right) lTriggers.sort(sortByPositionX); for (std::list<Creature*>::iterator itr = lTriggers.begin(); itr != lTriggers.end(); ++itr) { if ((*itr)->GetPositionY() < 600.0f) <API key>.push_back((*itr)->GetObjectGuid()); else <API key>.push_back((*itr)->GetObjectGuid()); } } ObjectGuid <API key>::<API key>(bool bLeftSide, uint8 uiIndex) { // Return the flight trigger from the selected index GuidVector& vTemp = bLeftSide ? <API key> : <API key>; if (uiIndex >= vTemp.size()) return ObjectGuid(); return vTemp[uiIndex]; } void <API key>::<API key>() { for (GuidSet::const_iterator itr = <API key>.begin(); itr != <API key>.end(); ++itr) { if (Player* pPlayer = instance->GetPlayer(*itr)) { if (!pPlayer->HasAura(<API key>)) continue; pPlayer->CastSpell(pPlayer, <API key>, true); pPlayer->CastSpell(pPlayer, <API key>, true); pPlayer-><API key>(<API key>); } } } void <API key>::JustDidDialogueStep(int32 iEntry) { switch (iEntry) { case <API key>: if (Creature* pTrigger = <API key>(<API key>)) { if (Creature* pKalec = pTrigger->SummonCreature(<API key>, aKalecLoc[0].m_fX, aKalecLoc[0].m_fY, aKalecLoc[0].m_fZ, aKalecLoc[0].m_fO, <API key>, 0)) { pKalec->SetWalk(false); pKalec->SetLevitate(true); pKalec->GetMotionMaster()->MovePoint(0, aKalecLoc[1].m_fX, aKalecLoc[1].m_fY, aKalecLoc[1].m_fZ, false); } } break; case NPC_FELMYST: if (Creature* pKalec = <API key>(<API key>)) pKalec->GetMotionMaster()->MovePoint(0, aKalecLoc[2].m_fX, aKalecLoc[2].m_fY, aKalecLoc[2].m_fZ, false); break; case <API key>: if (Creature* pKalec = <API key>(<API key>)) { // ToDo: update this when the AoE spell targeting will support many explicit target. Kalec should target all creatures from the list if (Creature* pTrigger = instance->GetCreature(<API key>.front())) pKalec->CastSpell(pTrigger, <API key>, true); } break; case NPC_BRUTALLUS: if (Creature* pKalec = <API key>(<API key>)) { pKalec->ForcedDespawn(10000); pKalec->GetMotionMaster()->MovePoint(0, aKalecLoc[3].m_fX, aKalecLoc[3].m_fY, aKalecLoc[3].m_fZ, false); } break; } } InstanceData* <API key>(Map* pMap) { return new <API key>(pMap); } bool <API key>(Player* pPlayer, AreaTriggerEntry const* pAt) { if (pAt->id == AREATRIGGER_TWINS) { if (pPlayer->isGameMaster() || pPlayer->isDead()) return false; <API key>* pInstance = (<API key>*)pPlayer->GetInstanceData(); if (pInstance && pInstance->GetData(TYPE_EREDAR_TWINS) == NOT_STARTED) pInstance->SetData(TYPE_EREDAR_TWINS, SPECIAL); } return false; } void <API key>() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "<API key>"; pNewScript->GetInstanceData = &<API key>; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "at_sunwell_plateau"; pNewScript->pAreaTrigger = &<API key>; pNewScript->RegisterSelf(); }
package com.cluit.util.dataTypes; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import com.cluit.util.Const; import com.cluit.util.AoP.MethodMapper; import com.cluit.util.methods.ClusteringUtils; import com.cluit.util.structures.<API key>; import com.cluit.util.structures.Pair; /**A cluster is a collection of entries. * * The class has a lot of utility functions related to clusters such as calculating centoid, finding the entry furthest * from the centoid and so on. * * @author Simon * */ public class Cluster { /** * * @param position * @param centoidIsMember */ public Cluster(double[] position) { if( position.length < 1){ API_Exeption("A cluster's position must be defined and have 1 or more dimenstions!"); } this.centoid = new Entry(position); this.dimensions = centoid.getDimensions(); }; //region STATIC METHODS /**Calculates a central point (centoid) from a collection of entries. Not that all entries must have the same dimensionality. * * @param entries * @return A new entry, with a position that is the mean of all parameter entries (NULL if entries.lenght == 0) */ public static Entry calculateCentoid(Entry[] entries){ if( entries.length == 0) return null; //Fetch dimensionality for the entries and set up the coordinate array int dim = entries[0].getDimensions(); double[] centoidCoordinates = new double[dim]; //Add all entries positions together (for example, add all entries x-values together in one array slot, //and all y-values together in the next array slot). for( Entry p : entries ){ for( int i = 0; i < p.getDimensions(); i++ ) centoidCoordinates[i] += p.getCoordinateAt(i); } //Divide each position by the number of entries (to get the mean of each dimension's position for( int i = 0; i < centoidCoordinates.length; i++) centoidCoordinates[i] /= entries.length; return new Entry(centoidCoordinates); } /**Calculates the sum of squared errors for a given set of entries, given a centoid.<br> * The calculation is simply: For each point, calculate the euclidian distance from that point to the centoid, and square the distance * * @param centoid The mean position of the entries (see @link {@link Cluster.calculateCentoid} ) * @param entries * @return */ public static double <API key>(Entry centoid, Entry[] entries){ double out = 0; double dist = 0; for(Entry e : entries ){ dist = ClusteringUtils.eucDistance(centoid, e); out += (dist*dist); } return out; } //region PUBLIC /**Returns the distance to the centoid for the point which is farthest from the centoid * * @return The distance, if there are any members of the cluster. -1 otherwise */ public double <API key>(){ if( distanceQueue.size() == 0 ) return -1; return distanceQueue.peekKey(); } /** Calculates a new centoid for the cluster. This method also update each points distance to the centoid * <br><br> * Complexity = <b>O(n * d)</b>, * where <b>n</b> is the number of elements in the cluster * where <b>d</b> the number of dimensions for each point */ public void calculateCentoid(){ int dim = centoid.getDimensions(); double[] <API key> = new double[dim]; for( Entry p : distanceQueue.values() ){ for( int i = 0; i < p.getDimensions(); i++ ) <API key>[i] += p.getCoordinateAt(i); } for( int i = 0; i < <API key>.length; i++) <API key>[i] /= distanceQueue.size(); centoid = new Entry(<API key> ); <API key>(); } /**Fetches a <b>copy</b> of the centoid of the cluster * * @return A new Entry, which is a copy of the cluster's centoid */ public Entry getCentoid(){ return new Entry(centoid); } /**Adds an entry to the cluster. The same entry cannot be added twice to the same cluster. * This does not automatically update the cluster centoid. To do that, call "UpdateCentoid" * * @param e * @return True if the entry was added, false if it was not */ public boolean add(Entry e){ if( e.getDimensions() != dimensions ){ API_Exeption("An entry cannot be added to a cluster if their dimenstions does not match! Cluster.dim = "+dimensions+" Entry.dim = "+e.getDimensions() ); return false; } if( members.contains(e) ){ API_Exeption("An entry cannot be added to a cluster twice! The entry "+e+" is already present in the cluster" ); return false; } double dist; if( e == cache.right ) dist = cache.left; else dist = ClusteringUtils.eucDistance(e, centoid); boolean a = distanceQueue.put(dist, e); boolean b = members.add(e); return a & b; } /**Removes a point from the cluster * * @param e The point to be removed * @return True if it was found. False if the point wasn't found. */ public boolean removeEntry(Entry e){ boolean a = distanceQueue.remove(e); boolean b = members.remove(e); return a & b; } /**Calculates a points distance to the clusters centoid. * The result is cached (the cache stores only 1 element), to prevent * the result from having to be re-computed in the near future. * <br>It is therefore recommended that whenever a point checks its distance to * all clusters, it should be added to a cluster before another point checks * it's distances. * * @param p The point * @return Distance to the centoid */ public double distanceToCentoid(Entry p){ double dist = ClusteringUtils.eucDistance(p, centoid); cache = new Pair<Double, Entry>(dist, p); return dist; } /**Checks whether a given point is member of this cluster or not * * @param p The point * @return True if the point is found within the cluster */ public boolean isMember(Entry e) { return members.contains(e); } /**Fetches an array of all entries that are present within this cluster. This array can have a lenght of 0, in case no * entries are registered within this cluster */ public Entry[] getMembers() { return members.toArray( new Entry[0] ); } /**Calculates the sum of squared errors for this cluster * * @return */ public double getSquaredError(){ return Cluster.<API key>(centoid, getMembers()) ; } public String toString(){ String out = "[ "; for( Entry e : members ){ out += e.toString() + " : "; } return members.size() > 0 ? out.substring(0, out.length() - 3) + " ]" : "[ ]"; } //region PRIVATE /**Update each member's distance to the centoid * */ private void <API key>() { ArrayList<Entry> list = distanceQueue.values(); distanceQueue.clear(); for(Entry p : list){ double newDistance = ClusteringUtils.eucDistance(centoid, p); distanceQueue.add(newDistance, p); } } private int API_Exeption(String s){ MethodMapper.invoke(Const.<API key>, "Error in Cluster.java! " + s +" " + com.cluit.util.methods.MiscUtils.getStackPos(), new Exception() ); return -1; }
SUBROUTINE STPTRS( UPLO, TRANS, DIAG, N, NRHS, AP, B, LDB, INFO ) * * -- LAPACK routine (version 3.2) -- * Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. * November 2006 * * .. Scalar Arguments .. CHARACTER DIAG, TRANS, UPLO INTEGER INFO, LDB, N, NRHS * .. * .. Array Arguments .. REAL AP( * ), B( LDB, * ) * .. * * Purpose * ======= * * STPTRS solves a triangular system of the form * * A * X = B or A**T * X = B, * * where A is a triangular matrix of order N stored in packed format, * and B is an N-by-NRHS matrix. A check is made to verify that A is * nonsingular. * * Arguments * ========= * * UPLO (input) CHARACTER*1 * = 'U': A is upper triangular; * = 'L': A is lower triangular. * * TRANS (input) CHARACTER*1 * Specifies the form of the system of equations: * = 'N': A * X = B (No transpose) * = 'T': A**T * X = B (Transpose) * = 'C': A**H * X = B (Conjugate transpose = Transpose) * * DIAG (input) CHARACTER*1 * = 'N': A is non-unit triangular; * = 'U': A is unit triangular. * * N (input) INTEGER * The order of the matrix A. N >= 0. * * NRHS (input) INTEGER * The number of right hand sides, i.e., the number of columns * of the matrix B. NRHS >= 0. * * AP (input) REAL array, dimension (N*(N+1)/2) * The upper or lower triangular matrix A, packed columnwise in * a linear array. The j-th column of A is stored in the array * AP as follows: * if UPLO = 'U', AP(i + (j-1)*j/2) = A(i,j) for 1<=i<=j; * if UPLO = 'L', AP(i + (j-1)*(2*n-j)/2) = A(i,j) for j<=i<=n. * * B (input/output) REAL array, dimension (LDB,NRHS) * On entry, the right hand side matrix B. * On exit, if INFO = 0, the solution matrix X. * * LDB (input) INTEGER * The leading dimension of the array B. LDB >= max(1,N). * * INFO (output) INTEGER * = 0: successful exit * < 0: if INFO = -i, the i-th argument had an illegal value * > 0: if INFO = i, the i-th diagonal element of A is zero, * indicating that the matrix is singular and the * solutions X have not been computed. * * ===================================================================== * * .. Parameters .. REAL ZERO PARAMETER ( ZERO = 0.0E+0 ) * .. * .. Local Scalars .. LOGICAL NOUNIT, UPPER INTEGER J, JC * .. * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL STPSV, XERBLA * .. * .. Intrinsic Functions .. INTRINSIC MAX * .. * .. Executable Statements .. * * Test the input parameters. * INFO = 0 UPPER = LSAME( UPLO, 'U' ) NOUNIT = LSAME( DIAG, 'N' ) IF( .NOT.UPPER .AND. .NOT.LSAME( UPLO, 'L' ) ) THEN INFO = -1 ELSE IF( .NOT.LSAME( TRANS, 'N' ) .AND. .NOT. $ LSAME( TRANS, 'T' ) .AND. .NOT.LSAME( TRANS, 'C' ) ) THEN INFO = -2 ELSE IF( .NOT.NOUNIT .AND. .NOT.LSAME( DIAG, 'U' ) ) THEN INFO = -3 ELSE IF( N.LT.0 ) THEN INFO = -4 ELSE IF( NRHS.LT.0 ) THEN INFO = -5 ELSE IF( LDB.LT.MAX( 1, N ) ) THEN INFO = -8 END IF IF( INFO.NE.0 ) THEN CALL XERBLA( 'STPTRS', -INFO ) RETURN END IF * * Quick return if possible * IF( N.EQ.0 ) $ RETURN * * Check for singularity. * IF( NOUNIT ) THEN IF( UPPER ) THEN JC = 1 DO 10 INFO = 1, N IF( AP( JC+INFO-1 ).EQ.ZERO ) $ RETURN JC = JC + INFO 10 CONTINUE ELSE JC = 1 DO 20 INFO = 1, N IF( AP( JC ).EQ.ZERO ) $ RETURN JC = JC + N - INFO + 1 20 CONTINUE END IF END IF INFO = 0 * * Solve A * x = b or A' * x = b. * DO 30 J = 1, NRHS CALL STPSV( UPLO, TRANS, DIAG, N, AP, B( 1, J ), 1 ) 30 CONTINUE * RETURN * * End of STPTRS * END
<?php /** * Plugin class. * * * @package SNF_Live_Report * @author Hampus Persson <hampus@hampuspersson.se> */ class SFN_Live_Report { /** * Plugin version, used for cache-busting of style and script file references. * * @since 1.0.0 * * @var string */ protected $version = '1.1.0'; /** * Unique identifier for your plugin. * * Use this value (not the variable name) as the text domain when internationalizing strings of text. It should * match the Text Domain file header in the main plugin file. * * @since 1.0.0 * * @var string */ protected $plugin_slug = 'sfn-live-report'; /** * Instance of this class. * * @since 1.0.0 * * @var object */ protected static $instance = null; /** * Slug of the plugin screen. * * @since 1.0.0 * * @var string */ protected $<API key> = null; /** * Initialize the plugin by setting localization, filters, and administration functions. * * @since 1.0.0 */ private function __construct() { // Load plugin text domain add_action( 'init', array( $this, '<API key>' ) ); // At this point no options are needed but if the need arises this is // how to add the options page and menu item. // add_action( 'admin_menu', array( $this, '<API key>' ) ); // Load admin style sheet and JavaScript. add_action( '<API key>', array( $this, '<API key>' ) ); add_action( '<API key>', array( $this, '<API key>' ) ); // Load public-facing style sheet and JavaScript. add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_styles' ) ); add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) ); // Add actions to remove some unwanted scripts and styles that wp_head() forces on us // add_action( 'wp_print_scripts', array( $this, '<API key>' ) ); // add_action( 'wp_print_styles', array( $this, '<API key>' ) ); // Setup callback for AJAX, through WPs admin-ajax add_action('wp_ajax_sfn-submit', array( $this, '<API key>' )); // Add the shortcode that sets up the whole operation add_shortcode( 'sfn-live-report', array( $this, 'report_games' ) ); } /** * Return an instance of this class. * * @since 1.0.0 * * @return object A single instance of this class. */ public static function get_instance() { // If the single instance hasn't been set, set it now. if ( null == self::$instance ) { self::$instance = new self; } return self::$instance; } /** * Fired when the plugin is activated. * * @since 1.0.0 * * @param boolean $network_wide True if WPMU superadmin uses "Network Activate" action, false if WPMU is disabled or plugin is activated on an individual blog. */ public static function activate( $network_wide ) { // TODO: Define activation functionality here } /** * Fired when the plugin is deactivated. * * @since 1.0.0 * * @param boolean $network_wide True if WPMU superadmin uses "Network Deactivate" action, false if WPMU is disabled or plugin is deactivated on an individual blog. */ public static function deactivate( $network_wide ) { // TODO: Define deactivation functionality here } /** * Load the plugin text domain for translation. * * @since 1.0.0 */ public function <API key>() { $domain = $this->plugin_slug; $locale = apply_filters( 'plugin_locale', get_locale(), $domain ); load_textdomain( $domain, WP_LANG_DIR . '/' . $domain . '/' . $domain . '-' . $locale . '.mo' ); <API key>( $domain, FALSE, dirname( plugin_basename( __FILE__ ) ) . '/lang/' ); } /** * Register and enqueue admin-specific style sheet. * * @since 1.0.0 * * @return null Return early if no settings page is registered. */ public function <API key>() { if ( ! isset( $this-><API key> ) ) { return; } $screen = get_current_screen(); if ( $screen->id == $this-><API key> ) { wp_enqueue_style( $this->plugin_slug .'-admin-styles', plugins_url( 'assets/css/admin.css', __FILE__ ), array(), $this->version ); } } /** * Register and enqueue admin-specific JS. * * @since 1.0.0 * * @return null Return early if no settings page is registered. */ public function <API key>() { if ( ! isset( $this-><API key> ) ) { return; } $screen = get_current_screen(); if ( $screen->id == $this-><API key> ) { wp_enqueue_script( $this->plugin_slug . '-admin-script', plugins_url( 'assets/javascripts/admin.js', __FILE__ ), array( 'jquery' ), $this->version ); } } /** * Register and enqueue public-facing style sheet. * * @since 1.0.0 */ public function enqueue_styles() { wp_enqueue_style( $this->plugin_slug . '-plugin-styles', plugins_url( 'assets/css/style.css', __FILE__ ), array(), $this->version ); } /** * Register and enqueues public-facing JS files. * * @since 1.0.0 */ public function enqueue_scripts() { wp_enqueue_script( $this->plugin_slug . '-plugin-script', plugins_url( 'assets/javascripts/main.min.js', __FILE__ ), array( 'jquery' ), $this->version ); // Set an object with the ajaxurl for use in main JS wp_localize_script( $this->plugin_slug . '-plugin-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); } /** * Since this plugin doesn't use any other plugins we can remove all scripts that are queued and registered properly * * @since 1.0.0 */ public function <API key>() { global $wp_scripts; foreach( $wp_scripts->queue as $handle ) : if( 'jquery' != $handle && '<API key>' != $handle ) { <API key>( $handle ); wp_dequeue_script( $handle ); } endforeach; } /** * Since this plugin doesn't use any other plugins we can remove all styles that are queued and registered properly * * @since 1.0.0 */ public function <API key>() { global $wp_styles; foreach( $wp_styles->queue as $handle ) : if( '<API key>' != $handle ) { wp_deregister_style( $handle ); wp_dequeue_style( $handle ); } endforeach; } /** * Register the administration menu for this plugin into the WordPress Dashboard menu. * * @since 1.0.0 */ public function <API key>() { $this-><API key> = add_plugins_page( __( 'SFN Live Report', $this->plugin_slug ), __( 'Settings', $this->plugin_slug ), 'read', $this->plugin_slug, array( $this, '<API key>' ) ); } /** * Render the settings page for this plugin. * * @since 1.0.0 */ public function <API key>() { include_once( 'views/admin.php' ); } /** * Callback for ajax call when the form is submitted * * @since 1.0.0 */ public function <API key>() { // Check that the user has access rights if ( !$this->check_access() ) { echo '<p>Du har inte behörighet att komma åt detta verktyg.</p>'; echo '<h3><a href="' . wp_login_url( site_url( $_SERVER["REQUEST_URI"] ) ) . '">Logga in</a></h3>'; die(); } // If everything checks out and a game is submitted we'll update the meta if( $_POST['game'] ) { update_post_meta($_POST['game'], 'hemmares', $_POST['home']); update_post_meta($_POST['game'], 'bortares', $_POST['away']); update_post_meta($_POST['game'], 'matchtid', $_POST['time']); if( "true" === $_POST['sendToTwitter'] ) { $url = "http: if( "true" === $_POST['finalScore'] ) { $time = ' (Slut)'; } else { $time = empty($_POST['time']) ? '' : ' (' . $_POST['time'] . ')'; } $tweet = $_POST['home-team'] . ' - ' . $_POST['away-team'] . ' ' . $_POST['home'] . '-' . $_POST['away'] . $time . '. Mer info om matchen på: ' . $url; $this->tweetUpdate($tweet); } } } private function tweetUpdate($tweet) { require_once('twitteroauth/twitteroauth.php'); define('CONSUMER_KEY', '<API key>'); define('CONSUMER_SECRET', '<API key>'); define('OAUTH_CALLBACK', 'http://example.com/twitteroauth/callback.php'); /* TOP SECRET STUFF, DO NOT SHARE! */ $access_token = array( "oauth_token" => "<API key>", "oauth_token_secret" => "<API key>" ); $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']); $parameters = array('status' => $tweet); $content = $connection->post('statuses/update', $parameters); return $content; } /** * Function to output the form to the user * * @since 1.0.0 */ public function report_games( $atts ) { // Check that the user has access rights if ( !$this->check_access() ) { echo '<p>Du har inte behörighet att komma åt detta verktyg.</p>'; echo '<h3><a href="' . wp_login_url( site_url( $_SERVER["REQUEST_URI"] ) ) . '">Logga in</a></h3>'; die(); } // Store the output we want in a variable $return_page = include('views/public.php'); return $return_page; } private function check_access() { $allowed_users = array( 6, // Hampus Persson, SFN 373 // Carl Klimfors, LG ); $current_user = wp_get_current_user(); if ( in_array($current_user->ID, $allowed_users) ) { return true; } return false; } }
# MSH ## Beta Version Created by Ne02ptzero (Louis Solofrizzo), Fusiow (Ryad Kharif) and Ivory9334 (Aurelien Ardjoune) Stable version for **MacOSX** Work on **Linux**, but no manual completion (options & description of command) ## What's MSH ? Msh is a colorful shell to help beginners in learning Linux, but also to confirm that users desire to enjoy a visual comfort. ![alt text](screens/screen1.png) ____ ![alt text](screens/screen2.png) ____ ![alt text](screens/screen3.png) ____ ![alt text](screens/screen5.png) ____ # Why? - The command is colored in blue if it exists, otherwise red. - When the command is good, all options for this command are posters suggestions. - In addition, there is an auto-completion on the options that allows to know the list of options for a command, and their utilites. - Autocompletion also on files as well as folders. # Builtins: - Builtins environment (env, setenv and unsetenv) - Alias - Local Variables - Job Control - Configuration file - Advanced prompt ____ ![alt text](screens/screen4.png) For more information see the documentation (docs /). # Installation: ## -Compilation: git clone https://github.com/Ne02ptzero/msh.git && cd msh && make ## -Installation: make install; (For 42 students) make install42; *(Copy the binary to ~/.brew/bin)* Launch with "msh" You don't want the amazing colored read ? Launch with -no-color options.
# encoding: utf-8 # This program is free software; you can redistribute it and/or modify it # by the Free Software Foundation. # This program is distributed in the hope that it will be useful, but WITHOUT # more details. # with this program; if not, contact Novell, Inc. # To contact Novell about this file by physical or electronic mail, you may require "yast" module UI # UI layout helpers. # These started out in the Expert Partitioner in yast2-storage. # The use case is reusing pieces of this legacy code in the new # yast2-partitioner. # That is why the API and the implementation look old. module Greasemonkey include Yast::UIShortcuts extend Yast::UIShortcuts Builtins = Yast::Builtins Convert = Yast::Convert Ops = Yast::Ops Yast.import "Directory" @handlers = [ :VStackFrames, :FrameWithMarginBox, :ComboBoxSelected, :LeftRadioButton, :<API key>, :LeftCheckBox, :<API key>, :IconAndHeading ] # The compatibility API needs CamelCase method names # rubocop:disable MethodName # Wrap terms in a VBox with small vertical spacings in between. # @param old [Yast::Term] # @return [Yast::Term] # @example # term( # :VStackFrames, # Frame("f1"), # Frame("f2"), # Frame("f3") # VBox( # Frame("f1"), # VSpacing(0.45), # Frame("f2"), # VSpacing(0.45), # Frame("f3") def VStackFrames(old) frames = Convert.convert( Builtins.argsof(old), from: "list", to: "list <term>" ) new = VBox() Builtins.foreach(frames) do |frame| new = Builtins.add(new, VSpacing(0.45)) if Builtins.size(new) != 0 new = Builtins.add(new, frame) end new end module_function :VStackFrames # @param old [Yast::Term] # @return [Yast::Term] # @example # term(:FrameWithMarginBox, "Title", "arg1", "arg2") # Frame("Title", MarginBox(1.45, 0.45, "arg1", "arg2")) def FrameWithMarginBox(old) title = Ops.get_string(old, 0, "error") args = Builtins.sublist(Builtins.argsof(old), 1) Frame( title, Builtins.toterm(:MarginBox, Builtins.union([1.45, 0.45], args)) ) end module_function :FrameWithMarginBox # @param old [Yast::Term] # @return [Yast::Term] # @example # term( # :ComboBoxSelected, # Id(:wish), Opt(:notify), "Wish", # Item(Id(:time), "Time"), # Item(Id(:love), "Love"), # Item(Id(:money), "Money") # Id(:love) # ComboBox( # Id(:wish), Opt(:notify), "Wish", # Item(Id(:time), "Time", false), # Item(Id(:love), "Love", true), # Item(Id(:money), "Money", false) def ComboBoxSelected(old) args = Builtins.argsof(old) tmp = Builtins.sublist(args, 0, Ops.subtract(Builtins.size(args), 2)) items = Ops.get_list(args, Ops.subtract(Builtins.size(args), 2), []) id = Ops.get_term(args, Ops.subtract(Builtins.size(args), 1), Id()) items = Builtins.maplist(items) do |item| Item(Ops.get(item, 0), Ops.get(item, 1), Ops.get(item, 0) == id) end Builtins.toterm(:ComboBox, Builtins.add(tmp, items)) end module_function :ComboBoxSelected # @param old [Yast::Term] # @return [Yast::Term] # @example # term(:LeftRadioButton, Id(...), "args") # Left(RadioButton(Id(...), "args")) def LeftRadioButton(old) Left(Builtins.toterm(:RadioButton, Builtins.argsof(old))) end module_function :LeftRadioButton # NOTE that it does not expand the nested # Greasemonkey term LeftRadioButton! {#transform} does that. # @param old [Yast::Term] # @return [Yast::Term] # @example # term(:<API key>, "foo", "bar", "contents") # VBox( # term(:LeftRadioButton, "foo", "bar"), # HBox(HSpacing(4), "contents") def <API key>(old) args = Builtins.argsof(old) tmp1 = Builtins.sublist(args, 0, Ops.subtract(Builtins.size(args), 1)) tmp2 = Ops.get(args, Ops.subtract(Builtins.size(args), 1)) if tmp2 == Empty() # rubocop:disable Style/GuardClause return VBox(Builtins.toterm(:LeftRadioButton, tmp1)) else return VBox( Builtins.toterm(:LeftRadioButton, tmp1), HBox(HSpacing(4), tmp2) ) end end module_function :<API key> # @param old [Yast::Term] # @return [Yast::Term] # @example # term(:LeftCheckBox, Id(...), "args") # Left(CheckBox(Id(...), "args")) def LeftCheckBox(old) Left(Builtins.toterm(:CheckBox, Builtins.argsof(old))) end module_function :LeftCheckBox # NOTE that it does not expand the nested # Greasemonkey term LeftCheckBox! {#transform} does that. # @param old [Yast::Term] # @return [Yast::Term] # @example # term(:<API key>, "foo", "bar", "contents") # VBox( # term(:LeftCheckBox, "foo", "bar"), # HBox(HSpacing(4), "contents") def <API key>(old) args = Builtins.argsof(old) tmp1 = Builtins.sublist(args, 0, Ops.subtract(Builtins.size(args), 1)) tmp2 = Ops.get(args, Ops.subtract(Builtins.size(args), 1)) if tmp2 == Empty() # rubocop:disable Style/GuardClause return VBox(Builtins.toterm(:LeftCheckBox, tmp1)) else return VBox( Builtins.toterm(:LeftCheckBox, tmp1), HBox(HSpacing(4), tmp2) ) end end module_function :<API key> # @param old [Yast::Term] # @return [Yast::Term] # @example # term(:IconAndHeading, "title", "icon") # Left( # HBox( # Image("/usr/share/YaST2/theme/current/icons/22x22/apps/icon", ""), # Heading("title") def IconAndHeading(old) args = Builtins.argsof(old) title = Ops.get_string(args, 0, "") icon = Ops.get_string(args, 1, "") Left(HBox(Image(icon, ""), Heading(title))) end module_function :IconAndHeading # Recursively apply all Greasemonkey methods on *old* # @param old [Yast::Term] # @return [Yast::Term] def Transform(old) s = Builtins.symbolof(old) handler = Greasemonkey.method(s) if @handlers.include?(s) return Transform(handler.call(old)) if !handler.nil? new = Builtins::List.reduce(Builtins.toterm(s), Builtins.argsof(old)) do |tmp, arg| arg = Transform(Convert.to_term(arg)) if Ops.is_term?(arg) Builtins.add(tmp, arg) end new end module_function :Transform alias_method :transform, :Transform module_function :transform end end
{ int n, dx, dy, sx, pp_inc_1, pp_inc_2; register int a; register PIXEL *pp; #if defined(INTERP_RGB) register unsigned int r, g, b; #endif #ifdef INTERP_RGB register unsigned int rinc, ginc, binc; #endif #ifdef INTERP_Z register unsigned int *pz; int zinc; register unsigned int z; #endif if (p1->y > p2->y || (p1->y == p2->y && p1->x > p2->x)) { ZBufferPoint *tmp; tmp = p1; p1 = p2; p2 = tmp; } sx = zb->xsize; pp = (PIXEL *)((char *) zb->pbuf.getRawBuffer() + zb->linesize * p1->y + p1->x * PSZB); #ifdef INTERP_Z pz = zb->zbuf + (p1->y * sx + p1->x); z = p1->z; #endif dx = p2->x - p1->x; dy = p2->y - p1->y; #ifdef INTERP_RGB r = p2->r << 8; g = p2->g << 8; b = p2->b << 8; #endif #ifdef INTERP_RGB #define RGB(x) x #define RGBPIXEL *pp = RGB_TO_PIXEL(r >> 8,g >> 8,b >> 8) #else // INTERP_RGB #define RGB(x) #define RGBPIXEL *pp = color #endif // INTERP_RGB #ifdef INTERP_Z #define ZZ(x) x #define PUTPIXEL() \ { \ if (ZCMP(z, *pz)) { \ RGBPIXEL; \ *pz = z; \ } \ } #else // INTERP_Z #define ZZ(x) #define PUTPIXEL() RGBPIXEL #endif // INTERP_Z #define DRAWLINE(dx, dy, inc_1, inc_2) \ n = dx; \ ZZ(zinc = (p2->z - p1->z)/n); \ RGB(rinc=((p2->r - p1->r) << 8)/n; \ ginc=((p2->g - p1->g) << 8)/n; \ binc=((p2->b - p1->b) << 8)/n); \ a = 2 * dy - dx; \ dy = 2 * dy; \ dx = 2 * dx - dy; \ pp_inc_1 = (inc_1) * PSZB; \ pp_inc_2 = (inc_2) * PSZB; \ do { \ PUTPIXEL(); \ ZZ(z += zinc); \ RGB(r += rinc; g += ginc; b += binc); \ if (a > 0) { \ pp = (PIXEL *)((char *)pp + pp_inc_1); \ ZZ(pz+=(inc_1)); \ a -= dx; \ } else { \ pp = (PIXEL *)((char *)pp + pp_inc_2); \ ZZ(pz += (inc_2)); \ a += dy; \ } \ } while (--n >= 0); // fin macro if (dx == 0 && dy == 0) { PUTPIXEL(); } else if (dx > 0) { if (dx >= dy) { DRAWLINE(dx, dy, sx + 1, 1); } else { DRAWLINE(dy, dx, sx + 1, sx); } } else { dx = -dx; if (dx >= dy) { DRAWLINE(dx, dy, sx - 1, -1); } else { DRAWLINE(dy, dx, sx - 1, sx); } } } #undef INTERP_Z #undef INTERP_RGB // internal defines #undef DRAWLINE #undef PUTPIXEL #undef ZZ #undef RGB #undef RGBPIXEL
/* utility routines for keeping some statistics */ #include <sys/types.h> #include <osmocore/linuxlist.h> #include <osmocore/talloc.h> #include <osmocore/statistics.h> static LLIST_HEAD(counters); void *tall_ctr_ctx; struct counter *counter_alloc(const char *name) { struct counter *ctr = talloc_zero(tall_ctr_ctx, struct counter); if (!ctr) return NULL; ctr->name = name; llist_add_tail(&ctr->list, &counters); return ctr; } void counter_free(struct counter *ctr) { llist_del(&ctr->list); talloc_free(ctr); } int counters_for_each(int (*handle_counter)(struct counter *, void *), void *data) { struct counter *ctr; int rc = 0; <API key>(ctr, &counters, list) { rc = handle_counter(ctr, data); if (rc < 0) return rc; } return rc; }
using NetworkProbe.Port.Services; using System.Collections.Generic; using System.Net; using NetworkProbe.Port; using NetworkProbe.Model; using System.Threading.Tasks; using System.Linq; namespace NetworkProbe { public static class Probe { <summary> Initiates a service scan on a single service to a single network device </summary> public static ProbeResult Single(ProbeEntity entity) { var result = Task.Run(() => ReturnSingleResult(entity)); return result.Result; } <summary> Initiates a service scan on multiple services on multiple devices </summary> public static IEnumerable<ProbeResult> Multiple(IEnumerable<ProbeEntity> entities) { List<ProbeResult> results = new List<ProbeResult>(); //Run each probe in parallel Parallel.ForEach(entities, x => { var result = Task.Run(() => ReturnSingleResult(x)); results.Add(result.Result); }); return results.OrderBy(x => int.Parse(x.IP.ToString().Split('.')[3])); } private async static Task<ProbeResult> ReturnSingleResult(ProbeEntity entity) { var service = ServiceFactory.Create(entity.Type, entity.IP, entity.Port); await service.ReturnPortData(); PortStatus status = service.PortLive ? PortStatus.Live : PortStatus.Dead; bool isData = service.PortResult != null && service.PortResult.Count > 0 ? true : false; Dictionary<string, string> data = isData ? service.PortResult : new Dictionary<string, string>(); return new ProbeResult(entity.Type, entity.Port, entity.IP, status, isData, data); } } }
import urllib2 def sumaDos(): print 10*20 def division(a,b): result=a/b print result def areatriangulo(base,altura): result2=(base*altura)/2 print result2 def cast(): lista=[1,2,3,"hola"] tupla=(1,2,3) diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"} for k,v in diccionario: print "%s %s" % (k,v) class Estudiante(object): def __init__(self, nombre, edad): self.nombre=nombre self.edad=edad def hola(self): return self.nombre def esMayor(self): if self.edad>=18: return true else: return false def EXCEPTION(): try: 3/0 except Exception: print "error" def main(): e=Estudiante("Diego",22) print"Hola %s" % e.hola() if e.esMayor(): print"Es mayor de edad" else: print"Es menor de edad" contador = 0 while contador <=10: print contador contador +=1 EXCEPTION(): def getWeb(): try: web=urllib2.urlopen("http://itjiquilpan.edu.mx/") print web.read() web.close() except urllib2.HTTPError, e: print e except urllib2.URLError as e: print e def main(): cast() if __name__=="__main__": main()
#ifndef QGSMEASUREDIALOG_H #define QGSMEASUREDIALOG_H #include "ui_qgsmeasurebase.h" #include "qgspoint.h" #include "qgsdistancearea.h" #include "qgscontexthelp.h" class QCloseEvent; class QgsMeasureTool; class QgsMeasureDialog : public QDialog, private Ui::QgsMeasureBase { Q_OBJECT public: //! Constructor QgsMeasureDialog( QgsMeasureTool* tool, Qt::WFlags f = 0 ); //! Save position void saveWindowLocation( void ); //! Restore last window position/size void restorePosition( void ); //! Add new point void addPoint( QgsPoint &point ); //! Mose move void mouseMove( QgsPoint &point ); //! Mouse press void mousePress( QgsPoint &point ); public slots: //! Reject void <API key>( void ); //! Reset and start new void restart(); //! Close event void closeEvent( QCloseEvent *e ); //! Show the help for the dialog void <API key>() { QgsContextHelp::run( metaObject()->className() ); } private: //! formats distance to most appropriate units QString formatDistance( double distance, int decimalPlaces ); //! formats area to most appropriate units QString formatArea( double area, int decimalPlaces ); //! shows/hides table, shows correct units void updateUi(); //! Converts the measurement, depending on settings in options and current transformation void convertMeasurement( double &measure, QGis::UnitType &u, bool isArea ); double mTotal; //! indicates whether we're measuring distances or areas bool mMeasureArea; //! pointer to measure tool which owns this dialog QgsMeasureTool* mTool; }; #endif
class EmailToken < ActiveRecord::Base belongs_to :user <API key> :<API key> :user_id <API key> :email before_validation(:on => :create) do self.token = EmailToken.generate_token end after_create do # Expire the previous tokens EmailToken.update_all 'expired = true', ['user_id = ? and id != ?', self.user_id, self.id] end def self.token_length 16 end def self.valid_after 1.week.ago end def self.unconfirmed where(confirmed: false) end def self.active where(expired: false).where('created_at > ?', valid_after) end def self.generate_token SecureRandom.hex(EmailToken.token_length) end def self.confirm(token) return unless token.present? return unless token.length/2 == EmailToken.token_length email_token = EmailToken.where("token = ? AND expired = FALSE and created_at >= ?", token, EmailToken.valid_after).includes(:user).first return if email_token.blank? user = email_token.user User.transaction do row_count = EmailToken.update_all 'confirmed = true', ['id = ? AND confirmed = false', email_token.id] if row_count == 1 # If we are activating the user, send the welcome message user.<API key> = !user.active? user.active = true user.email = email_token.email user.save! end end user rescue ActiveRecord::RecordInvalid # If the user's email is already taken, just return nil (failure) nil end end
#include <linux/fs.h> #include <linux/f2fs_fs.h> #include "f2fs.h" #include "node.h" #include "segment.h" /* * Roll forward recovery scenarios. * * [Term] F: fsync_mark, D: dentry_mark * * 1. inode(x) | CP | inode(x) | dnode(F) * -> Update the latest inode(x). * * 2. inode(x) | CP | inode(F) | dnode(F) * -> No problem. * * 3. inode(x) | CP | dnode(F) | inode(x) * -> Recover to the latest dnode(F), and drop the last inode(x) * * 4. inode(x) | CP | dnode(F) | inode(F) * -> No problem. * * 5. CP | inode(x) | dnode(F) * -> The inode(DF) was missing. Should drop this dnode(F). * * 6. CP | inode(DF) | dnode(F) * -> No problem. * * 7. CP | dnode(F) | inode(DF) * -> If f2fs_iget fails, then goto next to find inode(DF). * * 8. CP | dnode(F) | inode(x) * -> If f2fs_iget fails, then goto next to find inode(DF). * But it will fail due to no inode(DF). */ static struct kmem_cache *fsync_entry_slab; bool <API key>(struct f2fs_sb_info *sbi) { s64 nalloc = <API key>(&sbi-><API key>); if (sbi-><API key> + nalloc > sbi->user_block_count) return false; return true; } static struct fsync_inode_entry *get_fsync_inode(struct list_head *head, nid_t ino) { struct fsync_inode_entry *entry; list_for_each_entry(entry, head, list) if (entry->inode->i_ino == ino) return entry; return NULL; } static struct fsync_inode_entry *add_fsync_inode(struct list_head *head, struct inode *inode) { struct fsync_inode_entry *entry; entry = kmem_cache_alloc(fsync_entry_slab, GFP_F2FS_ZERO); if (!entry) return NULL; entry->inode = inode; list_add_tail(&entry->list, head); return entry; } static void del_fsync_inode(struct fsync_inode_entry *entry) { iput(entry->inode); list_del(&entry->list); kmem_cache_free(fsync_entry_slab, entry); } static int recover_dentry(struct inode *inode, struct page *ipage, struct list_head *dir_list) { struct f2fs_inode *raw_inode = F2FS_INODE(ipage); nid_t pino = le32_to_cpu(raw_inode->i_pino); struct f2fs_dir_entry *de; struct fscrypt_name fname; struct page *page; struct inode *dir, *einode; struct fsync_inode_entry *entry; int err = 0; char *name; entry = get_fsync_inode(dir_list, pino); if (!entry) { dir = f2fs_iget(inode->i_sb, pino); if (IS_ERR(dir)) { err = PTR_ERR(dir); goto out; } entry = add_fsync_inode(dir_list, dir); if (!entry) { err = -ENOMEM; iput(dir); goto out; } } dir = entry->inode; memset(&fname, 0, sizeof(struct fscrypt_name)); fname.disk_name.len = le32_to_cpu(raw_inode->i_namelen); fname.disk_name.name = raw_inode->i_name; if (unlikely(fname.disk_name.len > F2FS_NAME_LEN)) { WARN_ON(1); err = -ENAMETOOLONG; goto out; } retry: de = __f2fs_find_entry(dir, &fname, &page); if (de && inode->i_ino == le32_to_cpu(de->ino)) goto out_unmap_put; if (de) { einode = f2fs_iget(inode->i_sb, le32_to_cpu(de->ino)); if (IS_ERR(einode)) { WARN_ON(1); err = PTR_ERR(einode); if (err == -ENOENT) err = -EEXIST; goto out_unmap_put; } err = <API key>(F2FS_I_SB(inode)); if (err) { iput(einode); goto out_unmap_put; } f2fs_delete_entry(de, page, dir, einode); iput(einode); goto retry; } else if (IS_ERR(page)) { err = PTR_ERR(page); } else { err = __f2fs_do_add_link(dir, &fname, inode, inode->i_ino, inode->i_mode); } goto out; out_unmap_put: f2fs_dentry_kunmap(dir, page); f2fs_put_page(page, 0); out: if (file_enc_name(inode)) name = "<encrypted>"; else name = raw_inode->i_name; f2fs_msg(inode->i_sb, KERN_NOTICE, "%s: ino = %x, name = %s, dir = %lx, err = %d", __func__, ino_of_node(ipage), name, IS_ERR(dir) ? 0 : dir->i_ino, err); return err; } static void recover_inode(struct inode *inode, struct page *page) { struct f2fs_inode *raw = F2FS_INODE(page); char *name; inode->i_mode = le16_to_cpu(raw->i_mode); f2fs_i_size_write(inode, le64_to_cpu(raw->i_size)); inode->i_atime.tv_sec = le64_to_cpu(raw->i_mtime); inode->i_ctime.tv_sec = le64_to_cpu(raw->i_ctime); inode->i_mtime.tv_sec = le64_to_cpu(raw->i_mtime); inode->i_atime.tv_nsec = le32_to_cpu(raw->i_mtime_nsec); inode->i_ctime.tv_nsec = le32_to_cpu(raw->i_ctime_nsec); inode->i_mtime.tv_nsec = le32_to_cpu(raw->i_mtime_nsec); if (file_enc_name(inode)) name = "<encrypted>"; else name = F2FS_INODE(page)->i_name; f2fs_msg(inode->i_sb, KERN_NOTICE, "recover_inode: ino = %x, name = %s", ino_of_node(page), name); } static bool is_same_inode(struct inode *inode, struct page *ipage) { struct f2fs_inode *ri = F2FS_INODE(ipage); struct timespec disk; if (!IS_INODE(ipage)) return true; disk.tv_sec = le64_to_cpu(ri->i_ctime); disk.tv_nsec = le32_to_cpu(ri->i_ctime_nsec); if (timespec_compare(&inode->i_ctime, &disk) > 0) return false; disk.tv_sec = le64_to_cpu(ri->i_atime); disk.tv_nsec = le32_to_cpu(ri->i_atime_nsec); if (timespec_compare(&inode->i_atime, &disk) > 0) return false; disk.tv_sec = le64_to_cpu(ri->i_mtime); disk.tv_nsec = le32_to_cpu(ri->i_mtime_nsec); if (timespec_compare(&inode->i_mtime, &disk) > 0) return false; return true; } static int find_fsync_dnodes(struct f2fs_sb_info *sbi, struct list_head *head) { unsigned long long cp_ver = cur_cp_version(F2FS_CKPT(sbi)); struct curseg_info *curseg; struct inode *inode; struct page *page = NULL; block_t blkaddr; int err = 0; /* get node pages in the current segment */ curseg = CURSEG_I(sbi, CURSEG_WARM_NODE); blkaddr = NEXT_FREE_BLKADDR(sbi, curseg); while (1) { struct fsync_inode_entry *entry; if (!is_valid_blkaddr(sbi, blkaddr, META_POR)) return 0; page = get_tmp_page(sbi, blkaddr); if (cp_ver != cpver_of_node(page)) break; if (!is_fsync_dnode(page)) goto next; entry = get_fsync_inode(head, ino_of_node(page)); if (entry) { if (!is_same_inode(entry->inode, page)) goto next; } else { if (IS_INODE(page) && is_dent_dnode(page)) { err = recover_inode_page(sbi, page); if (err) break; } /* * CP | dnode(F) | inode(DF) * For this case, we should not give up now. */ inode = f2fs_iget(sbi->sb, ino_of_node(page)); if (IS_ERR(inode)) { err = PTR_ERR(inode); if (err == -ENOENT) { err = 0; goto next; } break; } /* add this fsync inode to the list */ entry = add_fsync_inode(head, inode); if (!entry) { err = -ENOMEM; iput(inode); break; } } entry->blkaddr = blkaddr; if (IS_INODE(page) && is_dent_dnode(page)) entry->last_dentry = blkaddr; next: /* check next segment */ blkaddr = <API key>(page); f2fs_put_page(page, 1); ra_meta_pages_cond(sbi, blkaddr); } f2fs_put_page(page, 1); return err; } static void <API key>(struct list_head *head) { struct fsync_inode_entry *entry, *tmp; <API key>(entry, tmp, head, list) del_fsync_inode(entry); } static int <API key>(struct f2fs_sb_info *sbi, block_t blkaddr, struct dnode_of_data *dn) { struct seg_entry *sentry; unsigned int segno = GET_SEGNO(sbi, blkaddr); unsigned short blkoff = <API key>(sbi, blkaddr); struct f2fs_summary_block *sum_node; struct f2fs_summary sum; struct page *sum_page, *node_page; struct dnode_of_data tdn = *dn; nid_t ino, nid; struct inode *inode; unsigned int offset; block_t bidx; int i; sentry = get_seg_entry(sbi, segno); if (!f2fs_test_bit(blkoff, sentry->cur_valid_map)) return 0; /* Get the previous summary */ for (i = CURSEG_WARM_DATA; i <= CURSEG_COLD_DATA; i++) { struct curseg_info *curseg = CURSEG_I(sbi, i); if (curseg->segno == segno) { sum = curseg->sum_blk->entries[blkoff]; goto got_it; } } sum_page = get_sum_page(sbi, segno); sum_node = (struct f2fs_summary_block *)page_address(sum_page); sum = sum_node->entries[blkoff]; f2fs_put_page(sum_page, 1); got_it: /* Use the locked dnode page and inode */ nid = le32_to_cpu(sum.nid); if (dn->inode->i_ino == nid) { tdn.nid = nid; if (!dn->inode_page_locked) lock_page(dn->inode_page); tdn.node_page = dn->inode_page; tdn.ofs_in_node = le16_to_cpu(sum.ofs_in_node); goto truncate_out; } else if (dn->nid == nid) { tdn.ofs_in_node = le16_to_cpu(sum.ofs_in_node); goto truncate_out; } /* Get the node page */ node_page = get_node_page(sbi, nid); if (IS_ERR(node_page)) return PTR_ERR(node_page); offset = ofs_of_node(node_page); ino = ino_of_node(node_page); f2fs_put_page(node_page, 1); if (ino != dn->inode->i_ino) { /* Deallocate previous index in the node page */ inode = f2fs_iget(sbi->sb, ino); if (IS_ERR(inode)) return PTR_ERR(inode); } else { inode = dn->inode; } bidx = start_bidx_of_node(offset, inode) + le16_to_cpu(sum.ofs_in_node); /* * if inode page is locked, unlock temporarily, but its reference * count keeps alive. */ if (ino == dn->inode->i_ino && dn->inode_page_locked) unlock_page(dn->inode_page); set_new_dnode(&tdn, inode, NULL, NULL, 0); if (get_dnode_of_data(&tdn, bidx, LOOKUP_NODE)) goto out; if (tdn.data_blkaddr == blkaddr) <API key>(&tdn, 1); f2fs_put_dnode(&tdn); out: if (ino != dn->inode->i_ino) iput(inode); else if (dn->inode_page_locked) lock_page(dn->inode_page); return 0; truncate_out: if (datablock_addr(tdn.node_page, tdn.ofs_in_node) == blkaddr) <API key>(&tdn, 1); if (dn->inode->i_ino == nid && !dn->inode_page_locked) unlock_page(dn->inode_page); return 0; } static int do_recover_data(struct f2fs_sb_info *sbi, struct inode *inode, struct page *page, block_t blkaddr) { struct dnode_of_data dn; struct node_info ni; unsigned int start, end; int err = 0, recovered = 0; /* step 1: recover xattr */ if (IS_INODE(page)) { <API key>(inode, page); } else if (<API key>(ofs_of_node(page))) { /* * Deprecated; xattr blocks should be found from cold log. * But, we should remain this for backward compatibility. */ recover_xattr_data(inode, page, blkaddr); goto out; } /* step 2: recover inline data */ if (recover_inline_data(inode, page)) goto out; /* step 3: recover data indices */ start = start_bidx_of_node(ofs_of_node(page), inode); end = start + ADDRS_PER_PAGE(page, inode); set_new_dnode(&dn, inode, NULL, NULL, 0); err = get_dnode_of_data(&dn, start, ALLOC_NODE); if (err) goto out; <API key>(dn.node_page, NODE, true); get_node_info(sbi, dn.nid, &ni); f2fs_bug_on(sbi, ni.ino != ino_of_node(page)); f2fs_bug_on(sbi, ofs_of_node(dn.node_page) != ofs_of_node(page)); for (; start < end; start++, dn.ofs_in_node++) { block_t src, dest; src = datablock_addr(dn.node_page, dn.ofs_in_node); dest = datablock_addr(page, dn.ofs_in_node); /* skip recovering if dest is the same as src */ if (src == dest) continue; /* dest is invalid, just invalidate src block */ if (dest == NULL_ADDR) { <API key>(&dn, 1); continue; } if ((start + 1) << PAGE_SHIFT > i_size_read(inode)) f2fs_i_size_write(inode, (start + 1) << PAGE_SHIFT); /* * dest is reserved block, invalidate src block * and then reserve one new block in dnode page. */ if (dest == NEW_ADDR) { <API key>(&dn, 1); reserve_new_block(&dn); continue; } /* dest is valid block, try to recover from src to dest */ if (is_valid_blkaddr(sbi, dest, META_POR)) { if (src == NULL_ADDR) { err = reserve_new_block(&dn); #ifdef <API key> while (err) err = reserve_new_block(&dn); #endif /* We should not get -ENOSPC */ f2fs_bug_on(sbi, err); if (err) goto err; } /* Check the previous node page having this index */ err = <API key>(sbi, dest, &dn); if (err) goto err; /* write dummy data page */ f2fs_replace_block(sbi, &dn, src, dest, ni.version, false, false); recovered++; } } copy_node_footer(dn.node_page, page); fill_node_footer(dn.node_page, dn.nid, ni.ino, ofs_of_node(page), false); set_page_dirty(dn.node_page); err: f2fs_put_dnode(&dn); out: f2fs_msg(sbi->sb, KERN_NOTICE, "recover_data: ino = %lx, recovered = %d blocks, err = %d", inode->i_ino, recovered, err); return err; } static int recover_data(struct f2fs_sb_info *sbi, struct list_head *inode_list, struct list_head *dir_list) { unsigned long long cp_ver = cur_cp_version(F2FS_CKPT(sbi)); struct curseg_info *curseg; struct page *page = NULL; int err = 0; block_t blkaddr; /* get node pages in the current segment */ curseg = CURSEG_I(sbi, CURSEG_WARM_NODE); blkaddr = NEXT_FREE_BLKADDR(sbi, curseg); while (1) { struct fsync_inode_entry *entry; if (!is_valid_blkaddr(sbi, blkaddr, META_POR)) break; ra_meta_pages_cond(sbi, blkaddr); page = get_tmp_page(sbi, blkaddr); if (cp_ver != cpver_of_node(page)) { f2fs_put_page(page, 1); break; } entry = get_fsync_inode(inode_list, ino_of_node(page)); if (!entry) goto next; /* * inode(x) | CP | inode(x) | dnode(F) * In this case, we can lose the latest inode(x). * So, call recover_inode for the inode update. */ if (IS_INODE(page)) recover_inode(entry->inode, page); if (entry->last_dentry == blkaddr) { err = recover_dentry(entry->inode, page, dir_list); if (err) { f2fs_put_page(page, 1); break; } } err = do_recover_data(sbi, entry->inode, page, blkaddr); if (err) { f2fs_put_page(page, 1); break; } if (entry->blkaddr == blkaddr) del_fsync_inode(entry); next: /* check next segment */ blkaddr = <API key>(page); f2fs_put_page(page, 1); } if (!err) <API key>(sbi); return err; } int recover_fsync_data(struct f2fs_sb_info *sbi, bool check_only) { struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_WARM_NODE); struct list_head inode_list; struct list_head dir_list; block_t blkaddr; int err; int ret = 0; bool need_writecp = false; fsync_entry_slab = <API key>("<API key>", sizeof(struct fsync_inode_entry)); if (!fsync_entry_slab) return -ENOMEM; INIT_LIST_HEAD(&inode_list); INIT_LIST_HEAD(&dir_list); /* prevent checkpoint */ mutex_lock(&sbi->cp_mutex); blkaddr = NEXT_FREE_BLKADDR(sbi, curseg); /* step #1: find fsynced inode numbers */ err = find_fsync_dnodes(sbi, &inode_list); if (err || list_empty(&inode_list)) goto out; if (check_only) { ret = 1; goto out; } need_writecp = true; /* step #2: recover data */ err = recover_data(sbi, &inode_list, &dir_list); if (!err) f2fs_bug_on(sbi, !list_empty(&inode_list)); out: <API key>(&inode_list); /* truncate meta pages to be used by the recovery */ <API key>(META_MAPPING(sbi), (loff_t)MAIN_BLKADDR(sbi) << PAGE_SHIFT, -1); if (err) { <API key>(NODE_MAPPING(sbi)); <API key>(META_MAPPING(sbi)); } clear_sbi_flag(sbi, SBI_POR_DOING); if (err) { bool invalidate = false; if (test_opt(sbi, LFS)) { update_meta_page(sbi, NULL, blkaddr); invalidate = true; } else if (discard_next_dnode(sbi, blkaddr)) { invalidate = true; } <API key>(sbi); /* Flush all the NAT/SIT pages */ while (get_pages(sbi, F2FS_DIRTY_META)) sync_meta_pages(sbi, META, LONG_MAX); /* invalidate temporary meta page */ if (invalidate) <API key>(META_MAPPING(sbi), blkaddr, blkaddr); set_ckpt_flags(sbi->ckpt, CP_ERROR_FLAG); mutex_unlock(&sbi->cp_mutex); } else if (need_writecp) { struct cp_control cpc = { .reason = CP_RECOVERY, }; mutex_unlock(&sbi->cp_mutex); err = write_checkpoint(sbi, &cpc); } else { mutex_unlock(&sbi->cp_mutex); } <API key>(&dir_list); kmem_cache_destroy(fsync_entry_slab); return ret ? ret: err; }
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include "config.h" #include "mp_msg.h" #include "help_mp.h" #ifdef __FreeBSD__ #include <sys/cdrio.h> #endif #include "m_option.h" #include "stream.h" #include "libmpdemux/demuxer.h" We keep these 2 for the gui atm, but they will be removed. char* cdrom_device=NULL; int dvd_chapter=1; int dvd_last_chapter=0; char* dvd_device=NULL; char *bluray_device=NULL; // Open a new stream (stdin/file/vcd/url) stream_t* open_stream(const char* filename,char** options, int* file_format){ int dummy = <API key>; if (!file_format) file_format = &dummy; // Check if playlist or unknown if (*file_format != <API key>){ *file_format=<API key>; } if(!filename) { mp_msg(MSGT_OPEN,MSGL_ERR,"NULL filename, report this bug\n"); return NULL; } return open_stream_full(filename,STREAM_READ,options,file_format); }
#include "<API key>.hpp" #include "Import.hpp" #include "DataSource.h" #include "DataSourceTableSync.h" #include "DBTransaction.hpp" #include "ImportableTableSync.hpp" #include "<API key>.h" #include "StopPointTableSync.hpp" #include "<API key>.h" #include "<API key>.hpp" #include "<API key>.hpp" #include "LineStopTableSync.h" #include <boost/lexical_cast.hpp> using namespace std; using namespace boost; using namespace boost::posix_time; using namespace gregorian; namespace synthese { using namespace data_exchange; using namespace pt; using namespace server; using namespace util; using namespace impex; using namespace db; using namespace graph; using namespace util; namespace util { template<> const string FactorableTemplate<FileFormat, <API key>>::FACTORY_KEY("ineo_temps_reel"); } namespace data_exchange { const string <API key>::Importer_::<API key>("ps"); const string <API key>::Importer_::PARAMETER_COURSE_ID("ci"); const string <API key>::Importer_::<API key>("conn_string"); const string <API key>::Importer_::<API key>("stop_code_prefix"); bool <API key>::Importer_::_read( ) const { if(_database.empty() || !_plannedDataSource.get()) { return false; } DataSource& dataSource(*_import.get<DataSource>()); boost::shared_ptr<DB> db; if(_dbConnString) { db = DBModule::<API key>(*_dbConnString); } else { db = DBModule::GetDBSPtr(); } date today(day_clock::local_day()); string todayStr("'"+ <API key>(today) +"'"); // Services linked to the planned source ImportableTableSync::ObjectBySource<StopPointTableSync> stops(*_plannedDataSource, _env); ImportableTableSync::ObjectBySource<<API key>> lines(*_plannedDataSource, _env); if(!_courseId) { BOOST_FOREACH(const ImportableTableSync::ObjectBySource<<API key>>::Map::value_type& itLine, lines.getMap()) { BOOST_FOREACH(const ImportableTableSync::ObjectBySource<<API key>>::Map::mapped_type::value_type& line, itLine.second) { <API key>::Search(_env, line->getKey()); <API key>::Search(_env, optional<RegistryKeyType>(), line->getKey()); BOOST_FOREACH(const Path* route, line->getPaths()) { LineStopTableSync::Search(_env, route->getKey()); } } } // 1 : clean the old references to the current source ImportableTableSync::ObjectBySource<<API key>> sourcedServices(dataSource, _env); BOOST_FOREACH(const ImportableTableSync::ObjectBySource<<API key>>::Map::value_type& itService, sourcedServices.getMap()) { BOOST_FOREACH(const ImportableTableSync::ObjectBySource<<API key>>::Map::mapped_type::value_type& obj, itService.second) { obj->removeSourceLinks(dataSource); } } } else { // 1 : clean the old references to the current source ImportableTableSync::ObjectBySource<<API key>> sourcedServices(dataSource, _env); set<ScheduledService*> services(sourcedServices.get(*_courseId)); BOOST_FOREACH(ScheduledService* service, services) { service->removeSourceLinks(dataSource); _services.insert(service); } } // 2 : loop on the services present in the database and link to existing or new services stringstream query; query << "SELECT c.ref, c.chainage, c.ligne, l.mnemo as ligne_ref FROM " << _database << ".COURSE c " << "INNER JOIN " << _database << ".LIGNE l on c.ligne=l.ref AND l.jour=c.jour " << "WHERE c.jour=" << todayStr << " AND c.type='C'"; if(_courseId) { query << " AND c.ref=" << *_courseId; } DBResultSPtr result(db->execQuery(query.str())); while(result->next()) { string serviceRef(result->getText("ref")); string chainage(result->getText("chainage")); string ligneRef(result->getText("ligne_ref")); _logDebug( "Processing serviceRef="+ serviceRef +" chainage="+ chainage +" ligneRef="+ ligneRef ); CommercialLine* line( _getLine( lines, ligneRef, *_plannedDataSource ) ); if(!line) { _logWarning( "Line "+ ligneRef +" was not found for service "+ serviceRef ); continue; } stringstream chainageQuery; chainageQuery << "SELECT a.mnemol AS mnemol, h.htd AS htd, h.hta AS hta, h.type AS type, c.pos AS pos FROM " << _database << ".ARRETCHN c " << "INNER JOIN " << _database << ".ARRET a ON a.ref=c.arret AND a.jour=c.jour " << "INNER JOIN " << _database << ".HORAIRE h ON h.arretchn=c.ref AND h.jour=a.jour " << "INNER JOIN " << _database << ".COURSE o ON o.chainage=c.chainage AND o.ref=h.course AND c.jour=o.jour " << "WHERE h.course='" << serviceRef << "' AND h.jour=" << todayStr << " ORDER BY c.pos"; DBResultSPtr chainageResult(db->execQuery(chainageQuery.str())); JourneyPattern::<API key> servedStops; <API key>::Schedules departureSchedules; <API key>::Schedules arrivalSchedules; while(chainageResult->next()) { string type(chainageResult->getText("type")); string stopCode(chainageResult->getText("mnemol")); time_duration departureTime(<API key>(chainageResult->getText("htd"))); time_duration arrivalTime(<API key>(chainageResult->getText("hta"))); MetricOffset stopPos(chainageResult->getInt("pos")); bool referenceStop(type != "N"); std::set<StopPoint*> stopsSet( _getStopPoints( stops, _stopCodePrefix + stopCode, boost::optional<const std::string&>() ) ); if(stopsSet.empty()) { _logWarning( "Can't find stops for code "+ _stopCodePrefix + stopCode ); continue; } servedStops.push_back( JourneyPattern::<API key>( stopsSet, stopPos, (type != "A"), (type != "D"), referenceStop ) ); // Ignoring interpolated times if(referenceStop) { // If the bus leaves after midnight, the hours are stored as 0 instead of 24 if( !departureSchedules.empty() && departureTime < *departureSchedules.rbegin()) { departureTime += hours(24); } if( !arrivalSchedules.empty() && arrivalTime < *arrivalSchedules.rbegin()) { arrivalTime += hours(24); } // round of the seconds departureTime -= seconds(departureTime.seconds()); if(arrivalTime.seconds()) { arrivalTime += seconds(60 - arrivalTime.seconds()); } // storage of the times departureSchedules.push_back(departureTime); arrivalSchedules.push_back(arrivalTime); } } set<JourneyPattern*> routes( _getRoutes( *line, servedStops, *_plannedDataSource ) ); if(routes.empty()) { stringstream routeQuery; routeQuery << "SELECT * FROM " << _database << ".CHAINAGE c " << "WHERE c.ref='" << chainage << "' AND c.jour=" << todayStr; DBResultSPtr routeResult(db->execQuery(routeQuery.str())); if(routeResult->next()) { string routeName(routeResult->getText("nom")); bool wayBack(routeResult->getText("sens") != "A"); _logCreation( "Creation of route "+ routeName ); JourneyPattern* result = new JourneyPattern( <API key>::getId() ); result->setCommercialLine(line); line->addPath(result); result->setName(routeName); result->setWayBack(wayBack); result->addCodeBySource(*_plannedDataSource, string()); _env.getEditableRegistry<JourneyPattern>().add(boost::shared_ptr<JourneyPattern>(result)); routes.insert(result); size_t rank(0); BOOST_FOREACH(const JourneyPattern::<API key> stop, servedStops) { boost::shared_ptr<LineStop> ls( new LineStop( LineStopTableSync::getId(), result, rank, rank+1 < servedStops.size() && stop._departure, rank > 0 && stop._arrival, *stop._metricOffset, **stop._stop.begin() ) ); ls->set<ScheduleInput>(stop._withTimes ? *stop._withTimes : true); ls->link(_env, true); _env.getEditableRegistry<LineStop>().add(ls); ++rank; } } } assert(!routes.empty()); ScheduledService* service(NULL); BOOST_FOREACH(JourneyPattern* route, routes) { boost::shared_lock<util::<API key>> sharedServicesLock( *route->sharedServicesMutex ); BOOST_FOREACH(Service* sservice, route->getAllServices()) { service = dynamic_cast<ScheduledService*>(sservice); if(!service) { continue; } if( service->isActive(today) && service-><API key>(departureSchedules, arrivalSchedules) ){ _logLoad( "Use of service "+ lexical_cast<string>(service->getKey()) +" ("+ lexical_cast<string>(departureSchedules[0]) +") on route "+ lexical_cast<string>(route->getKey()) +" ("+ route->getName() +")" ); service->addCodeBySource(dataSource, serviceRef); _services.insert(service); break; } service = NULL; } if(service) { break; } } if(!service) { if (!departureSchedules.empty() && !arrivalSchedules.empty()) { JourneyPattern* route(*routes.begin()); service = new ScheduledService( <API key>::getId(), string(), route ); service->setDataSchedules(departureSchedules, arrivalSchedules); service->setPath(route); service->addCodeBySource(dataSource, serviceRef); service->setActive(today); route->addService(*service, false); _env.getEditableRegistry<ScheduledService>().add(boost::shared_ptr<ScheduledService>(service)); _services.insert(service); _logCreation( "Creation of service ("+ lexical_cast<string>(departureSchedules[0]) +") on route "+ lexical_cast<string>(route->getKey()) +" ("+ route->getName() +")" ); } else { _logWarning( "Service (ref="+ serviceRef +") has empty departure or arrival schedules, not creating" ); } } } // 3 : loop on the planned services and remove current day of run if not linked to current source BOOST_FOREACH(const ImportableTableSync::ObjectBySource<<API key>>::Map::value_type& itLine, lines.getMap()) { BOOST_FOREACH(const ImportableTableSync::ObjectBySource<<API key>>::Map::mapped_type::value_type& obj, itLine.second) { BOOST_FOREACH(Path* route, obj->getPaths()) { // Avoid junctions if(!dynamic_cast<JourneyPattern*>(route)) { continue; } JourneyPattern* jp(static_cast<JourneyPattern*>(route)); if(!jp->hasLinkWithSource(*_plannedDataSource)) { continue; } boost::shared_lock<util::<API key>> sharedServicesLock( *jp->sharedServicesMutex ); BOOST_FOREACH(const Service* service, jp->getAllServices()) { const ScheduledService* sservice(dynamic_cast<const ScheduledService*>(service)); if( sservice && sservice->isActive(today) && !sservice->hasLinkWithSource(dataSource) ){ const_cast<ScheduledService*>(sservice)->setInactive(today); _logInfo( "Deactivating unlinked service "+ lexical_cast<string>(sservice->getKey()) + " on route "+ lexical_cast<string>(sservice->getRoute()->getKey()) +" (" + sservice->getRoute()->getName() +")" ); } } } } } return true; } <API key>::Importer_::Importer_( util::Env& env, const impex::Import& import, impex::ImportLogLevel minLogLevel, const std::string& logPath, boost::optional<std::ostream&> outputStream, util::ParametersMap& pm ): Importer(env, import, minLogLevel, logPath, outputStream, pm), <API key><<API key>>(env, import, minLogLevel, logPath, outputStream, pm), PTFileFormat(env, import, minLogLevel, logPath, outputStream, pm) {} util::ParametersMap <API key>::Importer_::_getParametersMap() const { ParametersMap map; if(_plannedDataSource.get()) { map.insert(<API key>, _plannedDataSource->getKey()); } if(_courseId) { map.insert(PARAMETER_COURSE_ID, *_courseId); } if(_dbConnString) { map.insert(<API key>, *_dbConnString); } if(!_stopCodePrefix.empty()) { map.insert(<API key>, _stopCodePrefix); } return map; } void <API key>::Importer_::<API key>( const util::ParametersMap& map ) { if(map.isDefined(<API key>)) try { _plannedDataSource = DataSourceTableSync::Get(map.get<RegistryKeyType>(<API key>), _env); } catch(<API key><DataSource>&) { throw Exception("No such planned data source"); } _courseId = map.getOptional<string>(PARAMETER_COURSE_ID); _dbConnString = map.getOptional<string>(<API key>); _stopCodePrefix = map.getDefault<string>(<API key>, ""); } db::DBTransaction <API key>::Importer_::_save() const { DBTransaction transaction; if(_courseId) { BOOST_FOREACH(ScheduledService* service, _services) { <API key>::Save(static_cast<JourneyPattern*>(service->getPath()), transaction); BOOST_FOREACH(LineStop* edge, static_cast<JourneyPattern*>(service->getPath())->getLineStops()) { LineStopTableSync::Save(edge, transaction); } <API key>::Save(service, transaction); } } else { BOOST_FOREACH(const Registry<JourneyPattern>::value_type& journeyPattern, _env.getRegistry<JourneyPattern>()) { <API key>::Save(journeyPattern.second.get(), transaction); } BOOST_FOREACH(Registry<LineStop>::value_type lineStop, _env.getRegistry<LineStop>()) { LineStopTableSync::Save(lineStop.second.get(), transaction); } BOOST_FOREACH(const Registry<ScheduledService>::value_type& service, _env.getRegistry<ScheduledService>()) { <API key>::Save(service.second.get(), transaction); } } return transaction; } } }
\file Contains the declaration of the class OrbitalViewerBase #ifndef ORBITALVIEWERBASE_H #define ORBITALVIEWERBASE_H // Forward class declarations & header files /////////////////////////////// // Qt forward class declarations class QHBoxLayout; class QTimer; // Xbrabo forward class declarations class ColorButton; class GLOrbitalView; class <API key>; class OrbitalThread; // Base class header file #include <qdialog.h> // class OrbitalViewerBase ///////////////////////////////////////////////// class OrbitalViewerBase : public QDialog { Q_OBJECT public: // constructor/destructor OrbitalViewerBase(QWidget* parent = 0, const char* name = 0, bool modal = FALSE, WFlags fl = 0);// constructor ~OrbitalViewerBase(); // destructor protected: void customEvent(QCustomEvent* e); // reimplemented to receive events from calcThread private slots: void update(); // updates the view with the values of the widgets void adjustL(int newN); // adjust the orbital quantum number to the region 1 - n-1 void adjustM(int newL); // adjust the angular momentum quantum number to the region -l - +l void updateColors(); // updates the view with new colors void updateTypeOptions(int type); // updates the options to correspond to the chosen type void cancelCalculation(); // stops calculating a new orbital private: // private member functions void finishCalculation(); // finished up a calculation // private member variables QHBoxLayout* BigLayout; ///< All encompassing horizontal layout. <API key>* options; ///< Shows the options. GLOrbitalView* view; ///< Shows the orbital. ColorButton* ColorButtonPositive; ///< The pushbutton for choosing the colour of the positive values. ColorButton* ColorButtonNegative; ///< The pushbutton for choosing the colour of the negative values. OrbitalThread* calcThread; ///< The thread doing the calculation. QTimer* timer; ///< Handles periodic updating of the view during a calculation. }; #endif
// ADOBE SYSTEMS INCORPORATED // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms #include "Module.h" #include "HostAPI.h" namespace XMP_PLUGIN { static bool <API key> ( const PluginAPIRef pluginAPIs ) { // these plugin APIs are mandatory to run an XMP file handler if ( pluginAPIs-><API key> && pluginAPIs->mSetHostAPIProc && pluginAPIs-><API key> && pluginAPIs-><API key> && pluginAPIs-><API key> && pluginAPIs-><API key> && pluginAPIs->mGetFileModDateProc && pluginAPIs->mCacheFileDataProc && pluginAPIs->mUpdateFileProc && pluginAPIs->mWriteTempFileProc ) { return true; } return false; } static bool <API key> ( const PluginAPIRef pluginAPIs ) { if ( <API key> ( pluginAPIs ) ) { if ( pluginAPIs-><API key> && pluginAPIs-><API key> ) { return true; } } return false; } static bool <API key> ( const PluginAPIRef pluginAPIs ) { if ( <API key> ( pluginAPIs ) ) { if ( pluginAPIs-><API key> ) { return true; } } return false; } static bool <API key> ( const PluginAPIRef pluginAPIs ) { // Note: This is the place where we can reject old plugins. // For example if we consider all functionality of // plugin API version 2 mandatory we can reject // plugin version 1 by returning false in case 1. switch ( pluginAPIs->mVersion ) { case 1: return <API key> ( pluginAPIs ); break; case 2: return <API key> ( pluginAPIs ); break; case 3: return <API key> ( pluginAPIs ); break; default: // The loaded plugin is newer than the host. // Only basic functionality to run the plugin is required. return <API key> ( pluginAPIs ); break; } } PluginAPIRef Module::getPluginAPIs() { // return ref. to Plugin API, load module if not yet loaded if ( !mPluginAPIs || mLoaded != kModuleLoaded ) { if ( !load() ) { XMP_Throw ( "Plugin API not available.", kXMPErr_Unavailable ); } } return mPluginAPIs; } bool Module::load() { XMP_AutoLock lock ( &mLoadingLock, kXMP_WriteLock ); return loadInternal(); } void Module::unload() { XMP_AutoLock lock (&mLoadingLock, kXMP_WriteLock); unloadInternal(); } void Module::unloadInternal() { WXMP_Error error; // terminate plugin if( mPluginAPIs != NULL ) { if( mPluginAPIs-><API key> ) { mPluginAPIs-><API key>( &error ); } delete mPluginAPIs; mPluginAPIs = NULL; } // unload plugin module if( mLoaded != kModuleNotLoaded ) { UnloadModule(mHandle, false); mHandle = NULL; if( mLoaded == kModuleLoaded ) { // Reset mLoaded to kModuleNotLoaded, if the module was loaded successfully. // Otherwise let it remain kModuleErrorOnLoad so that we won't try to load // it again if some other handler ask to do so. mLoaded = kModuleNotLoaded; } } CheckError( error ); } bool Module::loadInternal() { if( mLoaded == kModuleNotLoaded ) { const char * errorMsg = NULL; // load module mLoaded = kModuleErrorOnLoad; mHandle = LoadModule(mPath, false); if( mHandle != NULL ) { // get entry point function pointer <API key> InitializePlugin = reinterpret_cast<<API key>>( <API key>(mHandle, "InitializePlugin") ); // legacy entry point <API key> InitializePlugin2 = reinterpret_cast<<API key>>( <API key>(mHandle, "InitializePlugin2") ); if( InitializePlugin2 != NULL || InitializePlugin != NULL ) { std::string moduleID; <API key>(mHandle, "MODULE_IDENTIFIER", "txt", moduleID); mPluginAPIs = new PluginAPI(); memset( mPluginAPIs, 0, sizeof(PluginAPI) ); mPluginAPIs->mSize = sizeof(PluginAPI); mPluginAPIs->mVersion = XMP_PLUGIN_VERSION; // informational: the latest version that the host knows about WXMP_Error error; // initialize plugin by calling entry point function if( InitializePlugin2 != NULL ) { HostAPIRef hostAPI = PluginManager::getHostAPI( <API key> ); InitializePlugin2( moduleID.c_str(), hostAPI, mPluginAPIs, &error ); if ( error.mErrorID == kXMPErr_NoError ) { // check all function pointers are correct based on version numbers if( <API key>( mPluginAPIs ) ) { mLoaded = kModuleLoaded; } else { errorMsg = "Incompatible plugin API version."; } } else { errorMsg = "Plugin initialization failed."; } } else if( InitializePlugin != NULL ) { // initialize through legacy plugin entry point InitializePlugin( moduleID.c_str(), mPluginAPIs, &error ); if ( error.mErrorID == kXMPErr_NoError ) { // check all function pointers are correct based on version numbers bool compatibleAPIs = <API key>(mPluginAPIs); if ( compatibleAPIs ) { // set host API at plugin HostAPIRef hostAPI = PluginManager::getHostAPI( mPluginAPIs->mVersion ); mPluginAPIs->mSetHostAPIProc( hostAPI, &error ); if( error.mErrorID == kXMPErr_NoError ) { mLoaded = kModuleLoaded; } else { errorMsg = "Plugin API incomplete."; } } else { errorMsg = "Incompatible plugin API version."; } } else { errorMsg = "Plugin initialization failed."; } } } if( mLoaded != kModuleLoaded ) { // plugin wasn't loaded and initialized successfully, // so unload the module this->unloadInternal(); } } else { errorMsg = "Can't load module"; } if ( mLoaded != kModuleLoaded && errorMsg ) { // error occurred throw XMP_Error( <API key>, errorMsg); } } return ( mLoaded == kModuleLoaded ); } } //namespace XMP_PLUGIN
package storm.starter.trident.homework.state; import storm.trident.operation.TridentCollector; import storm.trident.state.BaseStateUpdater; import storm.trident.tuple.TridentTuple; import java.util.ArrayList; import java.util.List; public class TopKStateUpdater extends BaseStateUpdater<TopKState> { @Override public void updateState(TopKState topKState, List<TridentTuple> list, TridentCollector tridentCollector) { for(TridentTuple tuple : list) { // Gets all the space separated hashtags. String hashTags = tuple.getString(0); String[] tag = hashTags.split(" "); // Creates the list to be added to the state List<TopTweet> tweetList = new ArrayList<TopTweet>(); for(String t : tag) { if(t != null && t.trim().length() != 0) { TopTweet tt = new TopTweet(t, 1); tweetList.add(tt); } } // Adds the list to the state. topKState.add(tweetList); } } }
</div> <footer> <p>copyright <a href="mailto:pengmaradi@gmail.com">@Xiaoling Peng</a> <a href="0763363847">call me</a></p> </footer> </body> </html>
@charset "utf-8"; #smenu_srch .iText, #smenu_srch button { background-color: #002a00; } #login_btn svg.active, #login_window .idpwWrap .login, #sider_nav h3 a, #sider_nav ul.smenu_3rdlevel { background-color: #005500; } #sider_nav ul.smenu_3rdlevel li a { border-bottom: 3px solid #005500; } #sider_nav, #login_window .idpw input[type=text], #login_window .idpw input[type=password] { background-color: #007f00; } #sider_nav ul.smenu_2ndlevel li a { border-bottom: 4px solid #007f00; } a:link, a:visited { color: #00aa00; } #topheader, .dialog_tline { background-color: #00aa00; } #header_nav ul li a { border-bottom: 5px solid #00aa00; } a:active, a:hover { /* #55ff55 */ color: #55d455; } #header_nav ul li.active a { border-bottom: 5px solid #55ff55; } #sider_nav ul.smenu_2ndlevel li.active a { border-bottom: 4px solid #55ff55; } #sider_nav ul.smenu_3rdlevel li.active a { border-bottom: 3px solid #55ff55; } #topheader a:active, #topheader a:hover, #sider_nav a:active, #sider_nav a:hover, #login_window .idpwWrap .login:active, #login_window .idpwWrap .login:hover { color: #aaffaa; } #smenu_srch button:active svg .stro, #smenu_srch button:hover svg .stro, #login_close:active svg .stro, #login_close:hover svg .stro, #login_btn svg.active .stro { stroke: #aaffaa; } #login_btn svg.active .poly { fill: #aaffaa; }
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>ctas: /home/antonmx/work/projects/ctascmake/image/ Directory 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.3 --> <script type="text/javascript"> function hasClass(ele,cls) { return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')); } function addClass(ele,cls) { if (!this.hasClass(ele,cls)) ele.className += " "+cls; } function removeClass(ele,cls) { if (hasClass(ele,cls)) { var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)'); ele.className=ele.className.replace(reg,' '); } } function toggleVisibility(linkObj) { var base = linkObj.getAttribute('id'); var summary = document.getElementById(base + '-summary'); var content = document.getElementById(base + '-content'); var trigger = document.getElementById(base + '-trigger'); if ( hasClass(linkObj,'closed') ) { summary.style.display = 'none'; content.style.display = 'block'; trigger.src = 'open.png'; removeClass(linkObj,'closed'); addClass(linkObj,'opened'); } else if ( hasClass(linkObj,'opened') ) { summary.style.display = 'block'; content.style.display = 'none'; trigger.src = 'closed.png'; removeClass(linkObj,'opened'); addClass(linkObj,'closed'); } return false; } </script> <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">ctas&#160;<span id="projectnumber">0.5.2</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><a href="modules.html"><span>Modules</span></a></li> <li><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 id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="<API key>.html">image</a> </li> </ul> </div> </div> <div class="header"> <div class="headertitle"> <h1>image Directory Reference</h1> </div> </div> <div class="contents"> <table class="memberdecls"> <tr><td colspan="2"><h2><a name="subdirs"></a> Directories</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top">directory &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html">bin</a></td></tr> </table> </div> <hr class="footer"/><address class="footer"><small>Generated on Fri Apr 8 2011 16:06:01 for ctas by&#160; <a href="http: <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.3 </small></address> </body> </html>
<?php defined('GANTRY_VERSION') or die(); gantry_import('core.params.gantryparamoverride'); /** * @package gantry * @subpackage core.params */ class <API key> extends GantryParamOverride { function store(){ global $gantry; foreach($gantry->_setinsession as $session_var){ if ($gantry->_working_params[$session_var]['setby'] != 'menuitem') { if ($gantry->_working_params[$session_var]['value'] != $gantry->_working_params[$session_var]['sitebase'] && $gantry->_working_params[$session_var]['type'] != 'preset'){ $gantry->session->set($gantry->template_prefix.$gantry-><API key>."-".$session_var,$gantry->_working_params[$session_var]['value']); } else { $gantry->session->set($gantry->template_prefix.$this-><API key>."-".$session_var,null); } } } } function clean(){ global $gantry; foreach($gantry->_setinsession as $session_var){ $gantry->session->set($gantry->template_prefix.$this-><API key>."-".$session_var,null); } } function populate(){ global $gantry; // get any session param overrides and set to that // set preset values foreach($gantry->_preset_names as $param_name) { $session_param_name = $gantry->template_prefix.$gantry-><API key>."-".$param_name; if (in_array($param_name, $gantry->_setbysession) && $gantry->session->get($session_param_name)) { $param =& $gantry->_working_params[$param_name]; $session_value = $gantry->session->get($session_param_name); $<API key> = $gantry->presets[$param_name][$session_value]; foreach($<API key> as $<API key> => $<API key>) { if (array_key_exists($<API key>, $gantry->_working_params) && !is_null($<API key>)){ $gantry->_working_params[$<API key>]['value'] = $<API key>; $gantry->_working_params[$<API key>]['setby'] = 'session'; } } } } // set individual values foreach($gantry->_param_names as $param_name) { $session_param_name = $gantry->template_prefix.$gantry-><API key>."-".$param_name; if (in_array($param_name, $gantry->_setbysession) && $gantry->session->get($session_param_name)) { $param =& $gantry->_working_params[$param_name]; $session_value = $gantry->session->get($session_param_name); if (!is_null($session_value)){ $gantry->_working_params[$param['name']]['value'] = $session_value; $gantry->_working_params[$param['name']]['setby'] = 'session'; } } } } }
<?php /** * Shows basic event infos and countdowns. * * @param array $event_config The event configuration * @return string */ function <API key>($event_config) { if ($event_config == null) { return div('col-md-12 text-center', [ heading(sprintf(_('Welcome to the %s!'), '<span class="icon-icon_angel"></span> HELFERSYSTEM'), 2) ]); } $elements = []; if ($event_config['event_name'] != null) { $elements[] = div('col-sm-12 text-center', [ heading(sprintf( _('Welcome to the %s!'), $event_config['event_name'] . ' <span class="icon-icon_angel"></span> HELFERSYSTEM' ), 2) ]); } if ($event_config['buildup_start_date'] != null && time() < $event_config['buildup_start_date']) { $elements[] = div('col-sm-3 text-center hidden-xs', [ heading(_('Buildup starts'), 4), '<span class="moment-countdown text-big" data-timestamp="' . $event_config['buildup_start_date'] . '">%c</span>', '<small>' . date(_('Y-m-d'), $event_config['buildup_start_date']) . '</small>' ]); } if ($event_config['event_start_date'] != null && time() < $event_config['event_start_date']) { $elements[] = div('col-sm-3 text-center hidden-xs', [ heading(_('Event starts'), 4), '<span class="moment-countdown text-big" data-timestamp="' . $event_config['event_start_date'] . '">%c</span>', '<small>' . date(_('Y-m-d'), $event_config['event_start_date']) . '</small>' ]); } if ($event_config['event_end_date'] != null && time() < $event_config['event_end_date']) { $elements[] = div('col-sm-3 text-center hidden-xs', [ heading(_('Event ends'), 4), '<span class="moment-countdown text-big" data-timestamp="' . $event_config['event_end_date'] . '">%c</span>', '<small>' . date(_('Y-m-d'), $event_config['event_end_date']) . '</small>' ]); } if ($event_config['teardown_end_date'] != null && time() < $event_config['teardown_end_date']) { $elements[] = div('col-sm-3 text-center hidden-xs', [ heading(_('Teardown ends'), 4), '<span class="moment-countdown text-big" data-timestamp="' . $event_config['teardown_end_date'] . '">%c</span>', '<small>' . date(_('Y-m-d'), $event_config['teardown_end_date']) . '</small>' ]); } return join('', $elements); } /** * Converts event name and start+end date into a line of text. * * @param array $event_config * @return string */ function EventConfig_info($event_config) { if ($event_config == null) { return ''; } // Event name, start+end date are set if ( $event_config['event_name'] != null && $event_config['event_start_date'] != null && $event_config['event_end_date'] != null ) { return sprintf( _('%s, from %s to %s'), $event_config['event_name'], date(_('Y-m-d'), $event_config['event_start_date']), date(_('Y-m-d'), $event_config['event_end_date']) ); } // Event name, start date are set if ($event_config['event_name'] != null && $event_config['event_start_date'] != null) { return sprintf( _('%s, starting %s'), $event_config['event_name'], date(_('Y-m-d'), $event_config['event_start_date']) ); } // Event start+end date are set if ($event_config['event_start_date'] != null && $event_config['event_end_date'] != null) { return sprintf( _('Event from %s to %s'), date(_('Y-m-d'), $event_config['event_start_date']), date(_('Y-m-d'), $event_config['event_end_date']) ); } // Only event name is set if ($event_config['event_name'] != null) { return sprintf($event_config['event_name']); } return ''; } /** * Render edit page for event config. * * @param string $event_name The event name * @param string $event_welcome_msg The welcome message * @param int $buildup_start_date unix time stamp * @param int $event_start_date unix time stamp * @param int $event_end_date unix time stamp * @param int $teardown_end_date unix time stamp * @return string */ function <API key>( $event_name, $event_welcome_msg, $buildup_start_date, $event_start_date, $event_end_date, $teardown_end_date ) { return page_with_title(event_config_title(), [ msg(), form([ div('row', [ div('col-md-6', [ form_text('event_name', _('Event Name'), $event_name), form_info('', _('Event Name is shown on the start page.')), form_textarea('event_welcome_msg', _('Event Welcome Message'), $event_welcome_msg), form_info( '', _('Welcome message is shown after successful registration. You can use markdown.') ) ]), div('col-md-3 col-xs-6', [ form_date('buildup_start_date', _('Buildup date'), $buildup_start_date), form_date('event_start_date', _('Event start date'), $event_start_date) ]), div('col-md-3 col-xs-6', [ form_date('teardown_end_date', _('Teardown end date'), $teardown_end_date), form_date('event_end_date', _('Event end date'), $event_end_date) ]) ]), div('row', [ div('col-md-6', [ form_submit('submit', _('Save')) ]) ]) ]) ]); }
"""Module computes indentation for block It contains implementation of indenters, which are supported by katepart xml files """ import logging logger = logging.getLogger('qutepart') from PyQt4.QtGui import QTextCursor def _getSmartIndenter(indenterName, qpart, indenter): """Get indenter by name. Available indenters are none, normal, cstyle, haskell, lilypond, lisp, python, ruby, xml Indenter name is not case sensitive Raise KeyError if not found indentText is indentation, which shall be used. i.e. '\t' for tabs, ' ' for 4 space symbols """ indenterName = indenterName.lower() if indenterName in ('haskell', 'lilypond'): # not supported yet logger.warning('Smart indentation for %s not supported yet. But you could be a hero who implemented it' % indenterName) from qutepart.indenter.base import IndentAlgNormal as indenterClass elif 'none' == indenterName: from qutepart.indenter.base import IndentAlgBase as indenterClass elif 'normal' == indenterName: from qutepart.indenter.base import IndentAlgNormal as indenterClass elif 'cstyle' == indenterName: from qutepart.indenter.cstyle import IndentAlgCStyle as indenterClass elif 'python' == indenterName: from qutepart.indenter.python import IndentAlgPython as indenterClass elif 'ruby' == indenterName: from qutepart.indenter.ruby import IndentAlgRuby as indenterClass elif 'xml' == indenterName: from qutepart.indenter.xmlindent import IndentAlgXml as indenterClass elif 'haskell' == indenterName: from qutepart.indenter.haskell import IndenterHaskell as indenterClass elif 'lilypond' == indenterName: from qutepart.indenter.lilypond import IndenterLilypond as indenterClass elif 'lisp' == indenterName: from qutepart.indenter.lisp import IndentAlgLisp as indenterClass elif 'scheme' == indenterName: from qutepart.indenter.scheme import IndentAlgScheme as indenterClass else: raise KeyError("Indenter %s not found" % indenterName) return indenterClass(qpart, indenter) class Indenter: """Qutepart functionality, related to indentation Public attributes: width Indent width useTabs Indent uses Tabs (instead of spaces) """ <API key> = 4 <API key> = False def __init__(self, qpart): self._qpart = qpart self.width = self.<API key> self.useTabs = self.<API key> self._smartIndenter = _getSmartIndenter('normal', self._qpart, self) def setSyntax(self, syntax): """Choose smart indentation algorithm according to syntax""" self._smartIndenter = self.<API key>(syntax) def text(self): """Get indent text as \t or string of spaces """ if self.useTabs: return '\t' else: return ' ' * self.width def triggerCharacters(self): """Trigger characters for smart indentation""" return self._smartIndenter.TRIGGER_CHARACTERS def autoIndentBlock(self, block, char = '\n'): """Indent block after Enter pressed or trigger character typed """ cursor = QTextCursor(block) currentText = block.text() spaceAtStartLen = len(currentText) - len(currentText.lstrip()) currentIndent = currentText[:spaceAtStartLen] indent = self._smartIndenter.computeIndent(block, char) if indent is not None and indent != currentIndent: self._qpart.replaceText(block.position(), spaceAtStartLen, indent) def <API key>(self, increase, withSpace=False): """Tab or Space pressed and few blocks are selected, or Shift+Tab pressed Insert or remove text from the beginning of blocks """ def blockIndentation(block): text = block.text() return text[:len(text) - len(text.lstrip())] def cursorAtSpaceEnd(block): cursor = QTextCursor(block) cursor.setPosition(block.position() + len(blockIndentation(block))) return cursor def indentBlock(block): cursor = cursorAtSpaceEnd(block) cursor.insertText(' ' if withSpace else self.text()) def spacesCount(text): return len(text) - len(text.rstrip(' ')) def unIndentBlock(block): currentIndent = blockIndentation(block) if currentIndent.endswith('\t'): charsToRemove = 1 elif withSpace: charsToRemove = 1 if currentIndent else 0 else: if self.useTabs: charsToRemove = min(spacesCount(currentIndent), self.width) else: # spaces if currentIndent.endswith(self.text()): # remove indent level charsToRemove = self.width else: # remove all spaces charsToRemove = min(spacesCount(currentIndent), self.width) if charsToRemove: cursor = cursorAtSpaceEnd(block) cursor.setPosition(cursor.position() - charsToRemove, QTextCursor.KeepAnchor) cursor.removeSelectedText() cursor = self._qpart.textCursor() startBlock = self._qpart.document().findBlock(cursor.selectionStart()) endBlock = self._qpart.document().findBlock(cursor.selectionEnd()) # If end is positioned in the beginning of a block, do not indent this # block, since no text is selected in it (beginning of line) if endBlock.position()==cursor.selectionEnd(): endBlock=endBlock.previous() indentFunc = indentBlock if increase else unIndentBlock if startBlock != endBlock: # indent multiply lines stopBlock = endBlock.next() block = startBlock with self._qpart: while block != stopBlock: indentFunc(block) block = block.next() newCursor = QTextCursor(startBlock) newCursor.setPosition(endBlock.position() + len(endBlock.text()), QTextCursor.KeepAnchor) self._qpart.setTextCursor(newCursor) else: # indent 1 line indentFunc(startBlock) def <API key>(self): """Tab pressed and no selection. Insert text after cursor """ cursor = self._qpart.textCursor() def insertIndent(): if self.useTabs: cursor.insertText('\t') else: # indent to integer count of indents from line start charsToInsert = self.width - (len(self._qpart.textBeforeCursor()) % self.width) cursor.insertText(' ' * charsToInsert) if cursor.positionInBlock() == 0: # if no any indent - indent smartly block = cursor.block() self.autoIndentBlock(block, '') # if no smart indentation - just insert one indent if self._qpart.textBeforeCursor() == '': insertIndent() else: insertIndent() def <API key>(self): """Backspace pressed, unindent """ assert self._qpart.textBeforeCursor().endswith(self.text()) charsToRemove = len(self._qpart.textBeforeCursor()) % len(self.text()) if charsToRemove == 0: charsToRemove = len(self.text()) cursor = self._qpart.textCursor() cursor.setPosition(cursor.position() - charsToRemove, QTextCursor.KeepAnchor) cursor.removeSelectedText() def <API key>(self): """Indent current line or selected lines """ cursor = self._qpart.textCursor() startBlock = self._qpart.document().findBlock(cursor.selectionStart()) endBlock = self._qpart.document().findBlock(cursor.selectionEnd()) if startBlock != endBlock: # indent multiply lines stopBlock = endBlock.next() block = startBlock with self._qpart: while block != stopBlock: self.autoIndentBlock(block, '') block = block.next() else: # indent 1 line self.autoIndentBlock(startBlock, '') def <API key>(self, syntax): """Get indenter for syntax """ if syntax.indenter is not None: try: return _getSmartIndenter(syntax.indenter, self._qpart, self) except KeyError: logger.error("Indenter '%s' is not finished yet. But you can do it!" % syntax.indenter) try: return _getSmartIndenter(syntax.name, self._qpart, self) except KeyError: pass return _getSmartIndenter('normal', self._qpart, self)
<?php # Database Configuration define( 'DB_NAME', 'wp_promedia' ); define( 'DB_USER', 'promedia' ); define( 'DB_PASSWORD', '<API key>' ); define( 'DB_HOST', '127.0.0.1' ); define( 'DB_HOST_SLAVE', '127.0.0.1' ); define('DB_CHARSET', 'utf8'); define('DB_COLLATE', 'utf8_unicode_ci'); $table_prefix = 'wp_'; # Security Salts, Keys, Etc define('AUTH_KEY', 'a`F4guyG[^ Y}d c{idj5&MhTD&|JP[[]~@3:[oUZ0C+8}dUu9hqiW9ZJ-5c}6+|'); define('SECURE_AUTH_KEY', 'eU7MN1?7~|AT,pN|!qQ$3BhT%iYHi~}Uf%`R_eH#$I_XJy3utwjOa}-`Z8rP;eZ;'); define('LOGGED_IN_KEY', 'szAvG,^<>/so:#:-(6RKz~caq+*)lRek+o{44r$2?}?Qd.)taRY0+rd+d<6|nb>s'); define('NONCE_KEY', '0Sd#vgoYj|3 _{zHx+O!@bT*l13wu1=N+fNV]P7Cx|JzL_&=_5Kjs$y^P7?IEss+'); define('AUTH_SALT', 'vrQ2560/7/rdC)gXpr+&2;`w-RD%VyZwu+a5sV)!X<5s_Wq,7}S*7Q~vR|K(Lf*B'); define('SECURE_AUTH_SALT', 'wV^Lf;y6[zqv4!Bm8eZuE!u]k||b!mF]vAx|/)5,aQP`,Mav3SFC;2g`gL4*0F{R'); define('LOGGED_IN_SALT', '?|e&TXiXjP$H5#)*!6I+2]^w#?iL? G3H%pG[MvLgr|kT8+0?w&4BTX+nWnp57f`'); define('NONCE_SALT', '4~7piruf+MjyI%%H(U>r|GPuZDtb#EbJ|@ISBwf+V5+nzEzGNv>ihd#?#wpa+~/|'); # Localized Language Stuff define( 'WP_CACHE', TRUE ); define( 'WP_AUTO_UPDATE_CORE', false ); define( 'PWP_NAME', 'promedia' ); define( 'FS_METHOD', 'direct' ); define( 'FS_CHMOD_DIR', 0775 ); define( 'FS_CHMOD_FILE', 0664 ); define( 'PWP_ROOT_DIR', '/nas/wp' ); define( 'WPE_APIKEY', '<SHA1-like>' ); define( 'WPE_FOOTER_HTML', "" ); define( 'WPE_CLUSTER_ID', '1986' ); define( 'WPE_CLUSTER_TYPE', 'pod' ); define( 'WPE_ISP', true ); define( 'WPE_BPOD', false ); define( 'WPE_RO_FILESYSTEM', false ); define( 'WPE_LARGEFS_BUCKET', 'largefs.wpengine' ); define( 'WPE_LBMASTER_IP', '212.71.255.152' ); define( '<API key>', true ); define( 'DISALLOW_FILE_EDIT', FALSE ); define( 'DISALLOW_FILE_MODS', FALSE ); define( 'DISABLE_WP_CRON', false ); define( 'WPE_FORCE_SSL_LOGIN', false ); define( 'FORCE_SSL_LOGIN', false ); /*SSLSTART*/ if ( isset($_SERVER['HTTP_X_WPE_SSL']) && $_SERVER['HTTP_X_WPE_SSL'] ) $_SERVER['HTTPS'] = 'on'; /*SSLEND*/ define( 'WPE_EXTERNAL_URL', false ); define( 'WP_POST_REVISIONS', FALSE ); define( 'WPE_WHITELABEL', 'wpengine' ); define( '<API key>', false ); define( 'WPE_BETA_TESTER', false ); umask(0002); $wpe_cdn_uris=array ( ); $wpe_no_cdn_uris=array ( ); $wpe_content_regexs=array ( ); $wpe_all_domains=array ( 0 => 'promedia.wpengine.com', ); $wpe_varnish_servers=array ( 0 => 'pod-1986', ); $wpe_special_ips=array ( 0 => '212.71.255.152', ); $wpe_ec_servers=array ( ); $wpe_largefs=array ( ); $wpe_netdna_domains=array ( ); $<API key>=array ( ); $<API key>=array ( ); $wpe_domain_mappings=array ( ); $memcached_servers=array ( ); define( 'WPE_SFTP_PORT', 22 ); define('WPLANG',''); # WP Engine ID # WP Engine Settings # That's It. Pencils down if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); require_once(ABSPATH . 'wp-settings.php'); $_wpe_preamble_path = null; if(false){}
#ifndef _SS_CONSTS_HPP_ #define _SS_CONSTS_HPP_ #include "StrideSearchConfig.h" namespace StrideSearch { Meters per second to Kilometers per hour conversion factor static const Real MPS2KPH = 3.6; Knots to meters per second conversion factor static const Real KTS2MPS = 0.5144444; Nautical miles to kilometers conversion factor static const Real NM2KM = 1.852; Pi static constexpr Real PI = 3.<API key>; Radians to degrees conversion factor static constexpr Real RAD2DEG = 180.0 / PI; Degrees to radians conversion factor static constexpr Real DEG2RAD = PI / 180.0; Hours to days conversion factor static constexpr Real HOURS2DAYS = 1.0/24.0; Minutes to days conversion factor static constexpr Real MINUTES2DAYS = 1.0/24.0/60.0; Gravitational acceleration static constexpr Real G = 9.80616; Mean sea level radius of the Earth (meters) static constexpr Real EARTH_RADIUS_KM = 6371.220; static constexpr Real SQ_EARTH_RADIUS_KM = EARTH_RADIUS_KM*EARTH_RADIUS_KM; One sidereal day, in units of seconds static constexpr Real SIDEREAL_DAY_SEC = 24.0 * 3600.0; Rotational rate of Earth about its z-axis static constexpr Real EARTH_OMEGA_HZ = 2.0 * PI / SIDEREAL_DAY_SEC; Floating point zero static constexpr Real ZERO_TOL = 1.0e-11; } #endif
<?php define('NAVBAR_TITLE', 'Cuénteselo a un amigo'); define('HEADING_TITLE', 'Háblele a un amigo sobre \'%s\''); define('<API key>', 'Sus datos'); define('<API key>', 'Los datos de sus amigo'); define('<API key>', 'Su mensaje'); define('<API key>', 'Su nombre:'); define('<API key>', 'Su dirección e-mail:'); define('<API key>', 'Nombre de su amigo:'); define('<API key>', 'Dirección e-mail de su amigo:'); define('<API key>', 'Su e-mail acerca de <b>%s</b> ha sido correctamente enviado a <b>%s</b>.'); define('TEXT_EMAIL_SUBJECT', 'Tu amigo %s te ha recomendado este fantástico producto de %s'); define('TEXT_EMAIL_INTRO', '¡Hola %s!' . "\n\n" . 'Tu amigo, %s, cree que puedes estar interesado en %s de %s.'); define('TEXT_EMAIL_LINK', 'Para ver el producto pulsa en el siguiente enlace o bien copia y pega el enlace en tu navegador:' . "\n\n" . '%s'); // LINE ADDED: MOD - ARTICLE MANAGER define('<API key>', 'Para ver la noticia pulsa en el siguiente enlace o bien copia y pega el enlace en tu navegador:' . "\n\n" . '%s'); define('<API key>', 'Saludos,' . "\n\n" . '%s'); define('ERROR_TO_NAME', 'Error: Debe rellenar el nombre de tu amigo.'); define('ERROR_TO_ADDRESS', 'Error: La dirección e-mail de su amigo debe ser una dirección válida.'); define('ERROR_FROM_NAME', 'Error: Debes rellenar su nombre.'); define('ERROR_FROM_ADDRESS', 'Error: Su dirección e-mail debe ser una dirección válida.'); ?>
package eu.ttbox.geoping.ui.admob; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.InterstitialAd; import eu.ttbox.geoping.BuildConfig; import eu.ttbox.geoping.R; import eu.ttbox.geoping.core.AppConstants; public class AdmobHelper { private static final String TAG = "AdmobHelper"; public static AdView bindAdMobView(Activity context) { // Admob final View admob = context.findViewById(R.id.admob); final AdView adView = (AdView) context.findViewById(R.id.adView); if (isAddBlocked(context)) { Log.d(TAG, "### is Add Blocked adsContainer : " + admob); if (admob != null) { admob.setVisibility(View.GONE); Log.d(TAG, "### is Add Blocked adsContainer ==> GONE"); } } else { // Container Log.d(TAG, "### is Add Not Blocked adsContainer : " + admob); if (admob != null) { admob.setVisibility(View.VISIBLE); Log.d(TAG, "### is Add Not Blocked adsContainer ==> VISIBLE"); } } // Request Ad if (adView != null) { //adView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); // Listener adView.setAdListener(new AdListener() { public void onAdOpened() { Log.d(TAG, "### AdListener onAdOpened AdView"); } public void onAdLoaded() { Log.d(TAG, "### AdListener onAdLoaded AdView"); } public void onAdFailedToLoad(int errorcode) { if (admob!=null) { Log.d(TAG, "### AdListener onAdFailedToLoad ==> HIDE adsContainer : " + admob); admob.setVisibility(View.GONE); } switch (errorcode) { case AdRequest.<API key>: Log.d(TAG, " Log.d(TAG, " Log.d(TAG, " break; case AdRequest.<API key>: Log.d(TAG, " Log.d(TAG, " Log.d(TAG, " break; case AdRequest.<API key>: Log.d(TAG, " Log.d(TAG, " Log.d(TAG, " break; case AdRequest.ERROR_CODE_NO_FILL: Log.d(TAG, " Log.d(TAG, " Log.d(TAG, " break; default: Log.d(TAG, " Log.d(TAG, " Log.d(TAG, " } } }); // adView.setAdUnitId(context.getString(R.string.admob_key)); // adView.setAdSize(AdSize.SMART_BANNER); AdRequest.Builder adRequestBuilder = new AdRequest.Builder(); if (BuildConfig.DEBUG) { adRequestBuilder .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) .addTestDevice("<API key>"); } AdRequest adRequest = adRequestBuilder.build(); adView.loadAd(adRequest); Log.d(TAG, "### Load adRequest AdView"); } else { Log.e(TAG, "### Null AdView"); } return adView; } public static boolean isAddBlocked(Context context) { SharedPreferences sharedPreferences = PreferenceManager.<API key>(context); boolean isAddBlocked = sharedPreferences != null ? sharedPreferences.getBoolean(AppConstants.PREFS_ADD_BLOCKED, false) : false; return isAddBlocked; } // InterstitialAd public static class AppAdListener extends AdListener { InterstitialAd interstitial; public AppAdListener() { } public AppAdListener(InterstitialAd interstitial) { this.interstitial = interstitial; } @Override public void onAdLoaded() { Log.i(TAG, "### AdListener : onAdLoaded"); super.onAdLoaded(); interstitial.show(); } } public static InterstitialAd <API key>(Context context) { return <API key>(context, new AppAdListener()); } public static InterstitialAd <API key>(Context context, AppAdListener adListener) { final InterstitialAd interstitial = new InterstitialAd(context); interstitial.setAdUnitId(context.getString(R.string.admob_key)); // Add Listener adListener.interstitial = interstitial; interstitial.setAdListener(adListener); // Create ad request. AdRequest adRequest = new AdRequest.Builder().build(); // Begin loading your interstitial. interstitial.loadAd(adRequest); return interstitial; } }
#ifndef lgc_h #define lgc_h #include "lobject.h" #include "lstate.h" /* ** Collectable objects may have one of three colors: white, which ** means the object is not marked; gray, which means the ** object is marked, but its references may be not marked; and ** black, which means that the object and all its references are marked. ** The main invariant of the garbage collector, while marking objects, ** is that a black object can never point to a white one. Moreover, ** any gray object must be in a "gray list" (gray, grayagain, weak, ** allweak, ephemeron) so that it can be visited again before finishing ** the collection cycle. These lists have no meaning when the invariant ** is not being enforced (e.g., sweep phase). */ /* how much to allocate before next GC step */ #if !defined(GCSTEPSIZE) /* ~100 small strings */ #define GCSTEPSIZE (cast_int(100 * sizeof(TString))) #endif /* ** Possible states of the Garbage Collector */ #define GCSpropagate 0 #define GCSatomic 1 #define GCSsweepstring 2 #define GCSsweepudata 3 #define GCSsweep 4 #define GCSpause 5 #define issweepphase(g) \ (GCSsweepstring <= (g)->gcstate && (g)->gcstate <= GCSsweep) #define isgenerational(g) ((g)->gckind == KGC_GEN) /* ** macros to tell when main invariant (white objects cannot point to black ** ones) must be kept. During a non-generational collection, the sweep ** phase may break the invariant, as objects turned white may point to ** still-black objects. The invariant is restored when sweep ends and ** all objects are white again. During a generational collection, the ** invariant must be kept all times. */ #define keepinvariant(g) (isgenerational(g) || g->gcstate <= GCSatomic) /* ** Outside the collector, the state in generational mode is kept in ** 'propagate', so 'keepinvariant' is always true. */ #define keepinvariantout(g) \ check_exp(g->gcstate == GCSpropagate || !isgenerational(g), \ g->gcstate <= GCSatomic) /* ** some useful bit tricks */ #define resetbits(x,m) ((x) &= cast(lu_byte, ~(m))) #define setbits(x,m) ((x) |= (m)) #define testbits(x,m) ((x) & (m)) #define bitmask(b) (1<<(b)) #define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2)) #define l_setbit(x,b) setbits(x, bitmask(b)) #define resetbit(x,b) resetbits(x, bitmask(b)) #define testbit(x,b) testbits(x, bitmask(b)) /* Layout for bit use in `marked' field: */ #define WHITE0BIT 0 /* object is white (type 0) */ #define WHITE1BIT 1 /* object is white (type 1) */ #define BLACKBIT 2 /* object is black */ #define FINALIZEDBIT 3 /* object has been separated for finalization */ #define SEPARATED 4 /* object is in 'finobj' list or in 'tobefnz' */ #define FIXEDBIT 5 /* object is fixed (should not be collected) */ #define OLDBIT 6 /* object is old (only in generational mode) */ /* bit 7 is currently used by tests (luaL_checkmemory) */ #define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT) #define iswhite(x) testbits((x)->gch.marked, WHITEBITS) #define isblack(x) testbit((x)->gch.marked, BLACKBIT) #define isgray(x) /* neither white nor black */ \ (!testbits((x)->gch.marked, WHITEBITS | bitmask(BLACKBIT))) #define isold(x) testbit((x)->gch.marked, OLDBIT) /* MOVE OLD rule: whenever an object is moved to the beginning of a GC list, its old bit must be cleared */ #define resetoldbit(o) resetbit((o)->gch.marked, OLDBIT) #define otherwhite(g) (g->currentwhite ^ WHITEBITS) #define isdeadm(ow,m) (!(((m) ^ WHITEBITS) & (ow))) #define isdead(g,v) isdeadm(otherwhite(g), (v)->gch.marked) #define changewhite(x) ((x)->gch.marked ^= WHITEBITS) #define gray2black(x) l_setbit((x)->gch.marked, BLACKBIT) #define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x))) #define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS) #define luaC_condGC(L,c) \ {if (G(L)->GCdebt > 0) {c;}; condchangemem(L);} #define luaC_checkGC(L) luaC_condGC(L, luaC_step(L);) #define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \ luaC_barrier_(L,obj2gco(p),gcvalue(v)); } #define luaC_barrierback(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \ luaC_barrierback_(L,p); } #define luaC_objbarrier(L,p,o) \ { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \ luaC_barrier_(L,obj2gco(p),obj2gco(o)); } #define luaC_objbarrierback(L,p,o) \ { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) luaC_barrierback_(L,p); } #define luaC_barrierproto(L,p,c) \ { if (isblack(obj2gco(p))) luaC_barrierproto_(L,p,c); } LUAI_FUNC void luaC_freeallobjects(lua_State *L); LUAI_FUNC void luaC_step(lua_State *L); LUAI_FUNC void luaC_forcestep(lua_State *L); LUAI_FUNC void luaC_runtilstate(lua_State *L, int statesmask); LUAI_FUNC void luaC_fullgc(lua_State *L, int isemergency); LUAI_FUNC GCObject *luaC_newobj(lua_State *L, int tt, size_t sz, GCObject **list, int offset); LUAI_FUNC void luaC_barrier_(lua_State *L, GCObject *o, GCObject *v); LUAI_FUNC void luaC_barrierback_(lua_State *L, GCObject *o); LUAI_FUNC void luaC_barrierproto_(lua_State *L, Proto *p, Closure *c); LUAI_FUNC void luaC_checkfinalizer(lua_State *L, GCObject *o, Table *mt); LUAI_FUNC void <API key>(global_State *g, UpVal *uv); LUAI_FUNC void luaC_changemode(lua_State *L, int mode); #endif
package org.cohorte.utilities.security; /** * @author ogattaz * */ public class CXPassphraseBuilder { /** * @param aValue * @return * @throws <API key> * @throws <API key> */ public static IXPassphrase buildB64(final IXPassphrase aPassphrase) throws <API key>, <API key> { return new CXPassphraseB64(aPassphrase); } /** * @param aValue * @return * @throws <API key> * @throws <API key> */ public static IXPassphrase buildB64(final String aValue) throws <API key>, <API key> { return new CXPassphraseB64(aValue); } /** * @param aValue * @return * @throws <API key> * @throws <API key> */ public static IXPassphrase buildB64OBFRDM(final String aValue) throws <API key>, <API key> { return new CXPassphraseB64(new CXPassphraseOBF(new CXPassphraseRDM( aValue))); } /** * @param aValue * @return * @throws <API key> * @throws <API key> */ public static IXPassphrase buildOBF(final IXPassphrase aPassphrase) throws <API key>, <API key> { return new CXPassphraseOBF(aPassphrase); } /** * @param aValue * @return * @throws <API key> * @throws <API key> */ public static IXPassphrase buildOBF(final String aValue) throws <API key>, <API key> { return new CXPassphraseOBF(aValue); } /** * @param aPassphrase * @return * @throws <API key> * @throws <API key> */ public static IXPassphrase buildRDM(final IXPassphrase aPassphrase) throws <API key>, <API key> { return new CXPassphraseRDM(aPassphrase); } /** * @param aValue * @return * @throws <API key> * @throws <API key> */ public static IXPassphrase buildRDM(final String aValue) throws <API key>, <API key> { return new CXPassphraseRDM(aValue); } }
'''Manual check (not a discoverable unit test) for the key import, to identify problems with gnupg, gpg, gpg1, gpg2 and so on''' import os import shutil from gnupg import GPG def setup_keyring(keyring_name): '''Setup the keyring''' keyring_path = os.path.join("test", "outputdata", keyring_name) # Delete the entire keyring shutil.rmtree(keyring_path, ignore_errors=True) os.makedirs(keyring_path) gpg = GPG(gnupghome=keyring_path, gpgbinary="gpg") for key_name in ["key1_private", "key1_public"]: with open(os.path.join("test", "inputdata", key_name + ".txt"), "r") as keyfile: key_str = "".join(keyfile.readlines()) import_result = gpg.import_keys(key_str) print("Import result:", type(import_result)) print(import_result.__dict__) if import_result.count == 1 and len(set(import_result.fingerprints)) == 1: print("Got one import result") return gpg CRYPTO = setup_keyring("keyringtest") if CRYPTO: print("Ready", CRYPTO) KEY_LIST = CRYPTO.list_keys(False) NUM_KEYS = len(KEY_LIST) if KEY_LIST else 0 print("Number of public keys:", NUM_KEYS) if NUM_KEYS < 1: print("ERROR: Number of keys should be 1, not", NUM_KEYS) KEY_LIST = CRYPTO.list_keys(True) NUM_KEYS = len(KEY_LIST) if KEY_LIST else 0 print("Number of private keys:", NUM_KEYS) if NUM_KEYS < 1: print("ERROR: Number of keys should be 1, not", NUM_KEYS)
<html> <head> <title>case sensitivity on id</title> <style> #test { background-color: blue; } #TEST { background-color: pink; } </style> <body> <div id="test">Hello</div> <div id="TEST">Goodbye</div> </body> </html>
#!/usr/bin/python """ Since functions are function instances you can wrap them Allow you to - modify arguments - modify function - modify results """ call_count = 0 def count(func): def wrapper(*args, **kw): global call_count call_count += 1 return func(*args, **kw) return wrapper def hello(): print 'Invoked hello' hello = count(hello) ## Now decorating hello to increment call count hello() print call_count hello() print call_count def cwd_decorator(func): """ decorator to change cwd to directory containing rst for this function """ def wrapper(*args, **kw): cur_dir = os.getcwd() found = False for arg in sys.argv: if arg.endswith(".rst"): found = arg break if found: directory = os.path.dirname(arg) if directory: os.chdir(directory) data = func(*args, **kw) os.chdir(cur_dir) return data return wrapper """ Properties Call get/set methods via an instance attributes class C(object): def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.") from property.__doc__ """ import os def find_files(base_dir, recurse=True): """ yeild files found in base_dir """ for name in os.listdir(base_dir): filepath = os.path.join(base_dir, name) if os.path.isdir(filepath) and recurse: for child in find_files(filepath, recurse): yield child else: yield filepath
<?php // ini_set('display_errors','1'); function <API key>($catid) { global $wpdb,$<API key>; $product = $wpdb->get_row("SELECT * FROM `".<API key>."` WHERE `id`=$catid LIMIT 1",ARRAY_A); $output = ''; $output .= "<div class='editing_this_group form_table'>"; $output .= "<p>".str_replace("[categorisation]", htmlentities(stripslashes($product['name'])), <API key>)."</p>\n\r"; $output .= "<p><a href='' onclick='return showaddform()' class='add_category_link'><span>".str_replace("&quot;[categorisation]&quot;", "current", <API key>)."</span></a></p>"; $output .="<dl>\n\r"; $output .=" <dt>Display Category Shortcode: </dt>\n\r"; $output .=" <dd> [wpsc_products category_url_name='{$product['nice-name']}']</dd>\n\r"; $output .=" <dt>Display Category Template Tag: </dt>\n\r"; $output .=" <dd> &lt;?php echo <API key>(array('category_url_name'=>'{$product['nice-name']}')); ?&gt;</dd>\n\r"; $output .="</dl>\n\r"; //$output .= " [ <a href='#' onclick='return <API key>()'>".<API key>."</a> ]"; $output .= "</div>"; $output .= " <table class='category_forms'>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_NAME.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= "<input type='text' class='text' name='title' value='".htmlentities(stripslashes($product['name']), ENT_QUOTES, 'UTF-8')."' />"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= <API key>.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= "<textarea name='description' cols='40' rows='8' >".stripslashes($product['description'])."</textarea>"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= <API key>.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= <API key>($product['group_id'], $product['id'], $product['category_parent']); $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </tr>\n\r"; if ($product['display_type'] == 'grid') { $display_type1="selected='selected'"; } else if ($product['display_type'] == 'default') { $display_type2="selected='selected'"; } switch($product['display_type']) { case "default": $product_view1 = "selected ='selected'"; break; case "grid": if(function_exists('<API key>')) { $product_view3 = "selected ='selected'"; break; } case "list": if(function_exists('<API key>')) { $product_view2 = "selected ='selected'"; break; } default: $product_view0 = "selected ='selected'"; break; } $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= <API key>.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= "<input type='file' name='image' value='' />"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </tr>\n\r"; if(function_exists("getimagesize")) { if($product['image'] != '') { $imagepath = WPSC_CATEGORY_DIR . $product['image']; $imagetype = @getimagesize($imagepath); //previously exif_imagetype() $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_HEIGHT.":<input type='text' size='6' name='height' value='".$imagetype[1]."' /> ".TXT_WPSC_WIDTH.":<input type='text' size='6' name='width' value='".$imagetype[0]."' /><br /><span class='wpscsmall description'>$<API key></span><br />\n\r"; $output .= "<span class='wpscsmall description'>".<API key>."</span>\n\r"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; } else { $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_HEIGHT.":<input type='text' size='6' name='height' value='".get_option('<API key>')."' /> ".TXT_WPSC_WIDTH.":<input type='text' size='6' name='width' value='".get_option('product_image_width')."' /><br /><span class='wpscsmall description'>$<API key></span><br />\n\r"; $output .= "<span class='wpscsmall description'>".<API key>."</span>\n\r"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; } } $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= <API key>.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= "<input type='checkbox' name='deleteimage' value='1' />"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </tr>\n\r"; /* START OF TARGET MARKET SELECTION */ $countrylist = $wpdb->get_results("SELECT id,country,visible FROM `".<API key>."` ORDER BY country ASC ",ARRAY_A); $selectedCountries = $wpdb->get_col("SELECT countryid FROM `".<API key>."` WHERE categoryid=".$product['id']." AND visible= 1"); // exit('<pre>'.print_r($countrylist,true).'</pre><br /><pre>'.print_r($selectedCountries,true).'</pre>'); $output .= " <tr>\n\r"; $output .= " <td colspan='2'><h4>Target Market Restrictions</h4></td></tr><tr><td>&nbsp;</td></tr><tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_TM.":\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; if(@extension_loaded('suhosin')) { $output .= "<em>".__("The Target Markets feature has been disabled because you have the Suhosin PHP extension installed on this server. If you need to use the Target Markets feature then disable the suhosin extension, if you can not do this, you will need to contact your hosting provider. ",'wpsc')."</em>"; } else { $output .= "<span>Select: <a href='' class='wpsc_select_all'>All</a>&nbsp; <a href='' class='wpsc_select_none'>None</a></span><br />"; $output .= " <div id='resizeable' class='ui-widget-content multiple-select'>\n\r"; foreach($countrylist as $country){ if(in_array($country['id'], $selectedCountries)) /* if($country['visible'] == 1) */{ $output .= " <input type='checkbox' name='countrylist2[]' value='".$country['id']."' checked='".$country['visible']."' />".$country['country']."<br />\n\r"; }else{ $output .= " <input type='checkbox' name='countrylist2[]' value='".$country['id']."' />".$country['country']."<br />\n\r"; } } $output .= " </div><br /><br />"; $output .= " <span class='wpscsmall description'>Select the markets you are selling this category to.<span>\n\r"; } $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td colspan='2' class='<API key>'>\n\r"; $output .= " <h4>".<API key>."</h4>\n\r"; $output .= " <span class='small'>".<API key>."</span>\n\r"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= " ". <API key>.":\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= " <select name='display_type'>\n\r"; $output .= " <option value='' $product_view0 >".<API key>."</option>\n\r"; $output .= " <option value='default' $product_view1 >".TXT_WPSC_DEFAULT."</option>\n\r"; if(function_exists('<API key>')) { $output .= " <option value='list' ". $product_view2.">". TXT_WPSC_LIST."</option>\n\r"; } else { $output .= " <option value='list' disabled='disabled' ". $product_view2.">". TXT_WPSC_LIST."</option>\n\r"; } if(function_exists('<API key>')) { $output .= " <option value='grid' ". $product_view3.">". TXT_WPSC_GRID."</option>\n\r"; } else { $output .= " <option value='grid' disabled='disabled' ". $product_view3.">". TXT_WPSC_GRID."</option>\n\r"; } $output .= " </select>\n\r"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; if(function_exists("getimagesize")) { $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= <API key>.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_HEIGHT.": <input type='text' value='".$product['image_height']."' name='product_height' size='6'/> "; $output .= TXT_WPSC_WIDTH.": <input type='text' value='".$product['image_width']."' name='product_width' size='6'/> <br/>"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </tr>\n\r"; } $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= " </td>\n\r"; $output .= " <td class='last_row'>\n\r"; $output .= "<input type='hidden' name='prodid' value='".$product['id']."' />"; $output .= "<input type='hidden' name='submit_action' value='edit' />"; $output .= "<input class='button-primary' style='float:left;' type='submit' name='submit' value='".TXT_WPSC_EDIT_GROUP."' />"; $output .= "<a class='delete_button' href='".add_query_arg('deleteid', $product['id'], 'admin.php?page=wpsc-edit-groups')."' onclick=\"return conf();\" >".TXT_WPSC_DELETE."</a>"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </table>\n\r"; return $output; } function <API key>($variation_id) { global $wpdb,$<API key>; $variation_sql = "SELECT * FROM `".<API key>."` WHERE `id`='$variation_id' LIMIT 1"; $variation_data = $wpdb->get_results($variation_sql,ARRAY_A) ; $variation = $variation_data[0]; $output .= " <table class='category_forms' >\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_NAME.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= "<input type='text' class='text' name='title' value='".htmlentities(stripslashes($variation['name']), ENT_QUOTES, 'UTF-8')."' />"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= <API key>.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $<API key> = "SELECT * FROM `".<API key>."` WHERE `variation_id`='$variation_id' ORDER BY `id` ASC"; $variation_values = $wpdb->get_results($<API key>,ARRAY_A); $<API key> = count($variation_values); $output .= "<div id='<API key>'>"; $num = 0; foreach($variation_values as $variation_value) { $output .= "<span class='variation_value'>"; $output .= "<input type='text' class='text' name='variation_values[".$variation_value['id']."]' value='".htmlentities(stripslashes($variation_value['name']), ENT_QUOTES, 'UTF-8')."' />"; if($<API key> > 1) { $output .= " <a class='image_link' onclick='return <API key>(this,".$variation_value['id'].")' href='#'><img src='".WPSC_URL."/images/trash.gif' alt='".TXT_WPSC_DELETE."' title='".TXT_WPSC_DELETE."' /></a>"; } $output .= "<br />"; $output .= "</span>"; $num++; } $output .= "</div>"; $output .= "<a href='#' onclick='return add_variation_value(\"edit\")'>".TXT_WPSC_ADD."</a>"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= "<input type='hidden' name='prodid' value='".$variation['id']."' />"; $output .= "<input type='hidden' name='submit_action' value='edit' />"; $output .= "<input class='button' style='float:left;' type='submit' name='submit' value='".TXT_WPSC_EDIT."' />"; $output .= "<a class='button delete_button' href='admin.php?page=".WPSC_DIR_NAME."/display_variations.php&amp;deleteid=".$variation['id']."' onclick=\"return conf();\" >".TXT_WPSC_DELETE."</a>"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </table>\n\r"; return $output; } function coupon_edit_form($coupon) { $conditions = unserialize($coupon['condition']); $conditions = $conditions[0]; //exit('<pre>'.print_r($conditions, true).'</pre>'); $start_timestamp = strtotime($coupon['start']); $end_timestamp = strtotime($coupon['expiry']); $id = $coupon['id']; $output = ''; $output .= "<form name='edit_coupon' method='post' action='admin.php?page=".WPSC_DIR_NAME."/display-coupons.php'>\n\r"; $output .= " <input type='hidden' value='true' name='is_edit_coupon' />\n\r"; $output .= "<table class='add-coupon'>\n\r"; $output .= " <tr>\n\r"; $output .= " <th>".<API key>."</th>\n\r"; $output .= " <th>".TXT_WPSC_DISCOUNT."</th>\n\r"; $output .= " <th>".TXT_WPSC_START."</th>\n\r"; $output .= " <th>".TXT_WPSC_EXPIRY."</th>\n\r"; $output .= " <th>".TXT_WPSC_USE_ONCE."</th>\n\r"; $output .= " <th>".TXT_WPSC_ACTIVE."</th>\n\r"; $output .= " <th>".TXT_WPSC_PERTICKED."</th>\n\r"; $output .= " <th></th>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= " <input type='text' size='8' value='".$coupon['coupon_code']."' name='edit_coupon[".$id."][coupon_code]' />\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= " <input type='text' style='width:28px;' value='".$coupon['value']."' name=edit_coupon[".$id."][value]' />"; $output .= " <select style='width:20px;' name='edit_coupon[".$id."][is-percentage]'>"; $output .= " <option value='0' ".(($coupon['is-percentage'] == 0) ? "selected='true'" : '')." >$</option>\n\r"; $output .= " <option value='1' ".(($coupon['is-percentage'] == 1) ? "selected='true'" : '')." >%</option>\n\r"; $output .= " </select>\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $coupon_start = explode(" ",$coupon['start']); $output .= "<input type='text' class='pickdate' size='8' name='edit_coupon[".$id."][start]' value='{$coupon_start[0]}'>"; /* $output .= " <select name='edit_coupon[".$id."][start][day]'>\n\r"; for($i = 1; $i <=31; ++$i) { $selected = ''; if($i == date("d", $start_timestamp)) { $selected = "selected='true'"; } $output .= " <option $selected value='$i'>$i</option>"; } $output .= " </select>\n\r"; $output .= " <select name='edit_coupon[".$id."][start][month]'>\n\r"; for($i = 1; $i <=12; ++$i) { $selected = ''; if($i == (int)date("m", $start_timestamp)) { $selected = "selected='true'"; } $output .= " <option $selected value='$i'>".date("M",mktime(0, 0, 0, $i, 1, date("Y")))."</option>"; } $output .= " </select>\n\r"; $output .= " <select name='edit_coupon[".$id."][start][year]'>\n\r"; for($i = date("Y"); $i <= (date("Y") +12); ++$i) { $selected = ''; if($i == date("Y", $start_timestamp)) { $selected = "selected='true'"; } $output .= " <option $selected value='$i'>".$i."</option>"; } $output .= " </select>\n\r";*/ $output .= " </td>\n\r"; $output .= " <td>\n\r"; $coupon_expiry = explode(" ",$coupon['expiry']); $output .= "<input type='text' class='pickdate' size='8' name='edit_coupon[".$id."][expiry]' value='{$coupon_expiry[0]}'>"; /*$output .= " <select name='edit_coupon[".$id."][expiry][day]'>\n\r"; for($i = 1; $i <=31; ++$i) { $selected = ''; if($i == date("d", $end_timestamp)) { $selected = "selected='true'"; } $output .= " <option $selected value='$i'>$i</option>"; } $output .= " </select>\n\r"; $output .= " <select name='edit_coupon[".$id."][expiry][month]'>\n\r"; for($i = 1; $i <=12; ++$i) { $selected = ''; if($i == (int)date("m", $end_timestamp)) { $selected = "selected='true'"; } $output .= " <option $selected value='$i'>".date("M",mktime(0, 0, 0, $i, 1, date("Y")))."</option>"; } $output .= " </select>\n\r"; $output .= " <select name='edit_coupon[".$id."][expiry][year]'>\n\r"; for($i = date("Y"); $i <= (date("Y") +12); ++$i) { $selected = ''; if($i == (date("Y", $end_timestamp))) { $selected = "selected='true'"; } $output .= " <option $selected value='$i'>".$i."</option>\n\r"; } $output .= " </select>\n\r";*/ $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= " <input type='hidden' value='0' name='edit_coupon[".$id."][use-once]' />\n\r"; $output .= " <input type='checkbox' value='1' ".(($coupon['use-once'] == 1) ? "checked='checked'" : '')." name='edit_coupon[".$id."][use-once]' />\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= " <input type='hidden' value='0' name='edit_coupon[".$id."][active]' />\n\r"; $output .= " <input type='checkbox' value='1' ".(($coupon['active'] == 1) ? "checked='checked'" : '')." name='edit_coupon[".$id."][active]' />\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= " <input type='hidden' value='0' name='edit_coupon[".$id."][every_product]' />\n\r"; $output .= " <input type='checkbox' value='1' ".(($coupon['every_product'] == 1) ? "checked='checked'" : '')." name='edit_coupon[".$id."][every_product]' />\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= " <input type='hidden' value='".$id."' name='edit_coupon[".$id."][id]' />\n\r"; //$output .= " <input type='hidden' value='false' name='add_coupon' />\n\r"; $output .= " <input type='submit' value='".TXT_WPSC_SUBMIT."' name='edit_coupon[".$id."][submit_coupon]' />\n\r"; $output .= " <input type='submit' value='".TXT_WPSC_DELETE."' name='edit_coupon[".$id."][delete_coupon]' />\n\r"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; if($conditions != null){ $output .= "<tr>"; $output .= "<th>"; $output .= "Conditions"; $output .= "</th>"; $output .= "</tr>"; $output .= "<th>"; $output .= "Delete"; $output .= "</th>"; $output .= "<th>"; $output .= "Property"; $output .= "</th>"; $output .= "<th>"; $output .= "Logic"; $output .= "</th>"; $output .= "<th>"; $output .= "Value"; $output .= "</th>"; $output .= " </tr>\n\r"; $output .= "<tr>"; $output .= "<td>"; $output .= "<input type='hidden' name='coupon_id' value='".$id."' />"; $output .= "<input type='submit' value='Delete' name='delete_condition' />"; $output .= "</td>"; $output .= "<td>"; $output .= $conditions['property']; $output .= "</td>"; $output .= "<td>"; $output .= $conditions['logic']; $output .= "</td>"; $output .= "<td>"; $output .= $conditions['value']; $output .= "</td>"; $output .= "</tr>"; }elseif($conditions == null){ $output .= <API key>( $id); } ?> <! <tr><td colspan="8"> <div class="coupon_condition"> <div><img height="16" width="16" class="delete" alt="Delete" src="<?=WPSC_URL?>/images/cross.png"/></button> <select class="ruleprops" name="rules[property][]"> <option value="item_name" rel="order">Item name</option> <option value="item_quantity" rel="order">Item quantity</option> <option value="total_quantity" rel="order">Total quantity</option> <option value="subtotal_amount" rel="order">Subtotal amount</option> </select> <select name="rules[logic][]"> <option value="equal">Is equal to</option> <option value="greater">Is greater than</option> <option value="less">Is less than</option> <option value="contains">Contains</option> <option value="not_contain">Does not contain</option> <option value="begins">Begins with</option> <option value="ends">Ends with</option> </select> <span> <input type="text" name="rules[value][]"/> </span> <span> <button class="add" type="button"> <img height="16" width="16" alt="Add" src="<?=WPSC_URL?>/images/add.png"/> </button> </span> </div> </div> </tr> <?php $output .= "</table>\n\r"; $output .= "</form>\n\r"; echo $output; return $output; } function <API key>($id){ ?> <?php $output =' <input type="hidden" name="coupon_id" value="'.$id.'" /> <tr><td colspan="3"><b>Conditions</b></td></tr> <tr><td colspan="8"> <div class="coupon_condition"> <div> <select class="ruleprops" name="rules[property][]"> <option value="item_name" rel="order">Item name</option> <option value="item_quantity" rel="order">Item quantity</option> <option value="total_quantity" rel="order">Total quantity</option> <option value="subtotal_amount" rel="order">Subtotal amount</option> </select> <select name="rules[logic][]"> <option value="equal">Is equal to</option> <option value="greater">Is greater than</option> <option value="less">Is less than</option> <option value="contains">Contains</option> <option value="not_contain">Does not contain</option> <option value="begins">Begins with</option> <option value="ends">Ends with</option> </select> <span> <input type="text" name="rules[value][]"/> </span> <span> <input type="submit" value="add" name="submit_condition" /> </span> </div> </div> </tr> '; return $output; } function setting_button(){ $itemsFeedURL = "http: $next_url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']."?page=wpsc-edit-products"; $redirect_url = 'https: $redirect_url .= '&next='; $redirect_url .= urlencode($next_url); $redirect_url .= "&scope="; $redirect_url .= urlencode($itemsFeedURL); // $output.="<div><img src='".get_option('siteurl')."/wp-content/plugins/".WPSC_DIR_NAME."/images/settings_button.jpg' onclick='<API key>()'>"; $output.="<div style='float: right; margin-top: 0px; position: relative;'> | <a href='#' onclick='<API key>(); return false;' style='text-decoration: underline;'>".TXT_WPSC_SETTINGS." &raquo;</a>"; $output.="<span id='settings_button' style='width:180px;background-color:#f1f1f1;position:absolute; right: 10px; border:1px solid black; display:none;'>"; $output.="<ul class='settings_button'>"; $output.="<li><a href='admin.php?page=wpsc-settings'>".<API key>."</a></li>"; $output.="<li><a href='admin.php?page=wpsc-settings&amp;tab=gateway'>".<API key>."</a></li>"; $output.="<li><a href='admin.php?page=wpsc-settings&amp;tab=checkout'>".<API key>."</a></li>"; //$output.="<li><a href='?page=".WPSC_DIR_NAME."/instructions.php'>Help/Upgrade</a></li>"; //$output.="<li><a href='{$redirect_url}'>".<API key>."</a></li>"; $output.="</ul>"; // $output.="<div>Checkout Settings</div>"; $output.="</span>&emsp;&emsp;</div>"; return $output; } function wpsc_right_now() { global $wpdb,$<API key>; $year = date("Y"); $month = date("m"); $start_timestamp = mktime(0, 0, 0, $month, 1, $year); $end_timestamp = mktime(0, 0, 0, ($month+1), 0, $year); $replace_values[":productcount:"] = $wpdb->get_var("SELECT COUNT(*) FROM `".<API key>."` WHERE `active` IN ('1')"); $product_count = $wpdb->get_var("SELECT COUNT(*) FROM `".<API key>."` WHERE `active` IN ('1')"); $replace_values[":productcount:"] .= " ".(($replace_values[":productcount:"] == 1) ? <API key> : <API key>); $product_unit = (($replace_values[":productcount:"] == 1) ? <API key> : <API key>); $replace_values[":groupcount:"] = $wpdb->get_var("SELECT COUNT(*) FROM `".<API key>."` WHERE `active` IN ('1')"); $group_count = $wpdb->get_var("SELECT COUNT(*) FROM `".<API key>."` WHERE `active` IN ('1')"); $replace_values[":groupcount:"] .= " ".(($replace_values[":groupcount:"] == 1) ? <API key> : <API key>); $group_unit = (($replace_values[":groupcount:"] == 1) ? <API key> : <API key>); $replace_values[":salecount:"] = $wpdb->get_var("SELECT COUNT(*) FROM `".<API key>."` WHERE `date` BETWEEN '".$start_timestamp."' AND '".$end_timestamp."'"); $sales_count = $wpdb->get_var("SELECT COUNT(*) FROM `".<API key>."` WHERE `date` BETWEEN '".$start_timestamp."' AND '".$end_timestamp."'"); $replace_values[":salecount:"] .= " ".(($replace_values[":salecount:"] == 1) ? <API key> : <API key>); $sales_unit = (($replace_values[":salecount:"] == 1) ? <API key> : <API key>); $replace_values[":monthtotal:"] = <API key>(<API key>($start_timestamp, $end_timestamp),1); $replace_values[":overaltotal:"] = <API key>(<API key>(),1); $variation_count = $wpdb->get_var("SELECT COUNT(*) FROM `".<API key>."`"); $variation_unit = (($variation_count == 1) ? <API key> : <API key>); $replace_values[":pendingcount:"] = $wpdb->get_var("SELECT COUNT(*) FROM `".<API key>."` WHERE `processed` IN ('1')"); $pending_sales = $wpdb->get_var("SELECT COUNT(*) FROM `".<API key>."` WHERE `processed` IN ('1')"); $replace_values[":pendingcount:"] .= " " . (($replace_values[":pendingcount:"] == 1) ? <API key> : <API key>); $pending_sales_unit = (($replace_values[":pendingcount:"] == 1) ? <API key> : <API key>); $accept_sales = $wpdb->get_var("SELECT COUNT(*) FROM `".<API key>."` WHERE `processed` IN ('2' ,'3', '4')"); $accept_sales_unit = (($accept_sales == 1) ? <API key> : <API key>); $replace_values[":theme:"] = get_option('wpsc_selected_theme'); $replace_values[":versionnumber:"] = <API key>; if (function_exists('add_object_page')) { $output=""; $output.="<div id='dashboard_right_now' class='postbox'>"; $output.=" <h3 class='hndle'>"; $output.=" <span>".<API key>."</span>"; $output.=" <br class='clear'/>"; $output.=" </h3>"; $output .= "<div class='inside'>"; $output .= "<p class='sub'>".<API key>."</p>"; //$output.="<p class='youhave'>".<API key>."</p>"; $output .= "<div class='table'>"; $output .= "<table>"; $output .= "<tr class='first'>"; $output .= "<td class='first b'>"; $output .= "<a href='?page=wpsc-edit-products'>".$product_count."</a>"; $output .= "</td>"; $output .= "<td class='t'>"; $output .= ucfirst($product_unit); $output .= "</td>"; $output .= "<td class='b'>"; $output .= "<a href='?page=wpsc-sales-logs'>".$sales_count."</a>"; $output .= "</td>"; $output .= "<td class='last'>"; $output .= ucfirst($sales_unit); $output .= "</td>"; $output .= "</tr>"; $output .= "<tr>"; $output .= "<td class='first b'>"; $output .= "<a href='?page=wpsc-edit-groups'>".$group_count."</a>"; $output .= "</td>"; $output .= "<td class='t'>"; $output .= ucfirst($group_unit); $output .= "</td>"; $output .= "<td class='b'>"; $output .= "<a href='?page=wpsc-sales-logs'>".$pending_sales."</a>"; $output .= "</td>"; $output .= "<td class='last t waiting'>".TXT_WPSC_PENDING." "; $output .= ucfirst($pending_sales_unit); $output .= "</td>"; $output .= "</tr>"; $output .= "<tr>"; $output .= "<td class='first b'>"; $output .= "<a href='?page=<API key>'>".$variation_count."</a>"; $output .= "</td>"; $output .= "<td class='t'>"; $output .= ucfirst($variation_unit); $output .= "</td>"; $output .= "<td class='b'>"; $output .= "<a href='?page=wpsc-sales-logs'>".$accept_sales."</a>"; $output .= "</td>"; $output .= "<td class='last t approved'>".TXT_WPSC_CLOSED." "; $output .= ucfirst($accept_sales_unit); $output .= "</td>"; $output .= "</tr>"; $output .= "</table>"; $output .= "</div>"; $output .= "<div class='versions'>"; $output .= "<p><a class='button rbutton' href='admin.php?page=wpsc-edit-products'><strong>".<API key>."</strong></a>".<API key>."</p>"; $output .= "</div>"; $output .= "</div>"; $output.="</div>"; } else { $output=""; $output.="<div id='rightnow'>\n\r"; $output.=" <h3 class='reallynow'>\n\r"; $output.=" <a class='rbutton' href='admin.php?page=wpsc-edit-products'><strong>".<API key>."</strong></a>\n\r"; $output.=" <span>"._('Right Now')."</span>\n\r"; //$output.=" <br class='clear'/>\n\r"; $output.=" </h3>\n\r"; $output.="<p class='youhave'>".<API key>."</p>\n\r"; $output.=" <p class='youare'>\n\r"; $output.=" ".<API key>."\n\r"; //$output.=" <a class='rbutton' href='themes.php'>Change Theme</a>\n\r"; $output.=" </p>\n\r"; $output.="</div>\n\r"; $output.="<br />\n\r"; $output = str_replace(array_keys($replace_values), array_values($replace_values),$output); } return $output; } function wpsc_packing_slip($purchase_id) { global $wpdb; $purch_sql = "SELECT * FROM `".<API key>."` WHERE `id`='".$purchase_id."'"; $purch_data = $wpdb->get_row($purch_sql,ARRAY_A) ; //echo "<p style='padding-left: 5px;'><strong>".TXT_WPSC_DATE."</strong>:".date("jS M Y", $purch_data['date'])."</p>"; $cartsql = "SELECT * FROM `".<API key>."` WHERE `purchaseid`=".$purchase_id.""; $cart_log = $wpdb->get_results($cartsql,ARRAY_A) ; $j = 0; if($cart_log != null) { echo "<div class='packing_slip'>\n\r"; echo "<h2>".<API key>."</h2>\n\r"; echo "<strong>".TXT_WPSC_ORDER." #</strong> ".$purchase_id."<br /><br />\n\r"; echo "<table>\n\r"; $form_sql = "SELECT * FROM `".<API key>."` WHERE `log_id` = '".(int)$purchase_id."'"; $input_data = $wpdb->get_results($form_sql,ARRAY_A); foreach($input_data as $input_row) { $rekeyed_input[$input_row['form_id']] = $input_row; } if($input_data != null) { $form_data = $wpdb->get_results("SELECT * FROM `".<API key>."` WHERE `active` = '1'",ARRAY_A); foreach($form_data as $form_field) { switch($form_field['type']) { case 'country': $<API key> = $wpdb->get_var("SELECT COUNT(`regions`.`id`) FROM `".<API key>."` AS `regions` INNER JOIN `".<API key>."` AS `country` ON `country`.`id` = `regions`.`country_id` WHERE `country`.`isocode` IN('".$wpdb->escape( $purch_data['billing_country'])."')"); if(is_numeric($purch_data['shipping_region']) && ($<API key> > 0)) { echo " <tr><td>".__('State', 'wpsc').":</td><td>".wpsc_get_region($purch_data['shipping_region'])."</td></tr>\n\r"; } echo " <tr><td>".wp_kses($form_field['name'], array() ).":</td><td>".wpsc_get_country($purch_data['billing_country'])."</td></tr>\n\r"; break; case 'delivery_country': echo " <tr><td>".wp_kses($form_field['name'], array() ).":</td><td>".wpsc_get_country($purch_data['shipping_country'])."</td></tr>\n\r"; break; case 'heading': echo " <tr><td colspan='2'><strong>".wp_kses($form_field['name'], array() ).":</strong></td></tr>\n\r"; break; default: echo " <tr><td>".wp_kses($form_field['name'], array() ).":</td><td>".htmlentities(stripslashes($rekeyed_input[$form_field['id']]['value']), ENT_QUOTES)."</td></tr>\n\r"; break; } } } else { echo " <tr><td>".TXT_WPSC_NAME.":</td><td>".$purch_data['firstname']." ".$purch_data['lastname']."</td></tr>\n\r"; echo " <tr><td>".TXT_WPSC_ADDRESS.":</td><td>".$purch_data['address']."</td></tr>\n\r"; echo " <tr><td>".TXT_WPSC_PHONE.":</td><td>".$purch_data['phone']."</td></tr>\n\r"; echo " <tr><td>".TXT_WPSC_EMAIL.":</td><td>".$purch_data['email']."</td></tr>\n\r"; } if(get_option('payment_method') == 2) { $gateway_name = ''; foreach($GLOBALS['nzshpcrt_gateways'] as $gateway) { if($purch_data['gateway'] != 'testmode') { if($gateway['internalname'] == $purch_data['gateway'] ) { $gateway_name = $gateway['name']; } } else { $gateway_name = "Manual Payment"; } } } // echo " <tr><td colspan='2'></td></tr>\n\r"; // echo " <tr><td>".<API key>.":</td><td>".$gateway_name."</td></tr>\n\r"; // //echo " <tr><td>".<API key>.":</td><td>".$purch_data['id']."</td></tr>\n\r"; // echo " <tr><td>".<API key>.":</td><td>".$purch_data['find_us']."</td></tr>\n\r"; // $engrave_line = explode(",",$purch_data['engravetext']); // echo " <tr><td>".TXT_WPSC_ENGRAVE."</td><td></td></tr>\n\r"; // echo " <tr><td>".<API key>.":</td><td>".$engrave_line[0]."</td></tr>\n\r"; // echo " <tr><td>".<API key>.":</td><td>".$engrave_line[1]."</td></tr>\n\r"; // if($purch_data['transactid'] != '') { // echo " <tr><td>".TXT_WPSC_TXN_ID.":</td><td>".$purch_data['transactid']."</td></tr>\n\r"; echo "</table>\n\r"; echo "<table class='packing_slip'>"; echo "<tr>"; echo " <th>".TXT_WPSC_QUANTITY." </th>"; echo " <th>".TXT_WPSC_NAME."</th>"; echo " <th>".TXT_WPSC_PRICE." </th>"; echo " <th>".TXT_WPSC_SHIPPING." </th>"; echo '<th>Tax</th>'; echo '</tr>'; $endtotal = 0; $all_donations = true; $all_no_shipping = true; $file_link_list = array(); foreach($cart_log as $cart_row) { $alternate = ""; $j++; if(($j % 2) != 0) { $alternate = "class='alt'"; } $productsql= "SELECT * FROM `".<API key>."` WHERE `id`=".$cart_row['prodid'].""; $product_data = $wpdb->get_results($productsql,ARRAY_A); $variation_sql = "SELECT * FROM `".<API key>."` WHERE `cart_id`='".$cart_row['id']."'"; $variation_data = $wpdb->get_results($variation_sql,ARRAY_A); $variation_count = count($variation_data); if($variation_count > 1) { $variation_list = " ("; $i = 0; foreach($variation_data as $variation) { if($i > 0) { $variation_list .= ", "; } $value_id = $variation['value_id']; $value_data = $wpdb->get_results("SELECT * FROM `".<API key>."` WHERE `id`='".$value_id."' LIMIT 1",ARRAY_A); $variation_list .= $value_data[0]['name']; $i++; } $variation_list .= ")"; } else if($variation_count == 1) { $value_id = $variation_data[0]['value_id']; $value_data = $wpdb->get_results("SELECT * FROM `".<API key>."` WHERE `id`='".$value_id."' LIMIT 1",ARRAY_A); $variation_list = " (".$value_data[0]['name'].")"; } else { $variation_list = ''; } if($cart_row['donation'] != 1) { $all_donations = false; } if($cart_row['no_shipping'] != 1) { $shipping = $cart_row['pnp'] * $cart_row['quantity']; $total_shipping += $shipping; $all_no_shipping = false; } else { $shipping = 0; } $price = $cart_row['price'] * $cart_row['quantity']; $gst = $price - ($price / (1+($cart_row['gst'] / 100))); if($gst > 0) { $tax_per_item = $gst / $cart_row['quantity']; } echo "<tr $alternate>"; echo " <td>"; echo $cart_row['quantity']; echo " </td>"; echo " <td>"; echo $product_data[0]['name']; echo stripslashes($variation_list); echo " </td>"; echo " <td>"; echo <API key>( $price, 1); echo " </td>"; echo " <td>"; echo <API key>($shipping, 1); echo " </td>"; echo '<td>'; echo <API key>($cart_row['tax_charged'],1); echo '<td>'; echo '</tr>'; } echo "</table>"; echo "</div>\n\r"; } else { echo "<br />".<API key>; } } function <API key>() { } ?>
// oxygensizegrip.cpp // bottom right size grip for borderless windows // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include "oxygensizegrip.h" #include "oxygenbutton.h" #include "oxygenclient.h" #include <cassert> #include <QtGui/QPainter> #include <QtGui/QPolygon> #include <QtCore/QTimer> #include <QtGui/QX11Info> #include <X11/Xlib.h> namespace Oxygen { //<API key> SizeGrip::SizeGrip( Client* client ): QWidget(0), _client( client ) { setAttribute(Qt::<API key> ); <API key>( false ); // cursor setCursor( Qt::SizeFDiagCursor ); // size setFixedSize( QSize( GRIP_SIZE, GRIP_SIZE ) ); // mask QPolygon p; p << QPoint( 0, GRIP_SIZE ) << QPoint( GRIP_SIZE, 0 ) << QPoint( GRIP_SIZE, GRIP_SIZE ) << QPoint( 0, GRIP_SIZE ); setMask( QRegion( p ) ); // embed embed(); updatePosition(); // event filter client->widget()->installEventFilter( this ); // show show(); } //<API key> SizeGrip::~SizeGrip( void ) {} //<API key> void SizeGrip::activeChange( void ) { XMapRaised( QX11Info::display(), winId() ); } //<API key> void SizeGrip::embed( void ) { WId window_id = client().windowId(); if( client().isPreview() ) { setParent( client().widget() ); } else if( window_id ) { WId current = window_id; while( true ) { WId root, parent = 0; WId *children = 0L; uint child_count = 0; XQueryTree(QX11Info::display(), current, &root, &parent, &children, &child_count); if( parent && parent != root && parent != current ) current = parent; else break; } // reparent XReparentWindow( QX11Info::display(), winId(), current, 0, 0 ); } else { hide(); } } //<API key> bool SizeGrip::eventFilter( QObject*, QEvent* event ) { if ( event->type() == QEvent::Resize) updatePosition(); return false; } //<API key> void SizeGrip::paintEvent( QPaintEvent* ) { // get relevant colors QColor base( client().backgroundColor( this, palette(), client().isActive() ) ); QColor light( client().helper().calcDarkColor( base ) ); QColor dark( client().helper().calcDarkColor( base.darker(150) ) ); // create and configure painter QPainter painter(this); painter.setRenderHints(QPainter::Antialiasing ); painter.setPen( Qt::NoPen ); painter.setBrush( base ); // polygon QPolygon p; p << QPoint( 0, GRIP_SIZE ) << QPoint( GRIP_SIZE, 0 ) << QPoint( GRIP_SIZE, GRIP_SIZE ) << QPoint( 0, GRIP_SIZE ); painter.drawPolygon( p ); // diagonal border painter.setBrush( Qt::NoBrush ); painter.setPen( QPen( dark, 3 ) ); painter.drawLine( QPoint( 0, GRIP_SIZE ), QPoint( GRIP_SIZE, 0 ) ); // side borders painter.setPen( QPen( light, 1.5 ) ); painter.drawLine( QPoint( 1, GRIP_SIZE ), QPoint( GRIP_SIZE, GRIP_SIZE ) ); painter.drawLine( QPoint( GRIP_SIZE, 1 ), QPoint( GRIP_SIZE, GRIP_SIZE ) ); painter.end(); } //<API key> void SizeGrip::mousePressEvent( QMouseEvent* event ) { switch (event->button()) { case Qt::RightButton: { hide(); QTimer::singleShot(5000, this, SLOT(show())); break; } case Qt::MidButton: { hide(); break; } case Qt::LeftButton: if( rect().contains( event->pos() ) ) { // check client window id if( !client().windowId() ) break; client().widget()->setFocus(); if( client().decoration() ) { client().decoration()-><API key>( KDecorationDefines::ResizeOp ); } } break; default: break; } return; } //<API key> void SizeGrip::updatePosition( void ) { QPoint position( client().width() - GRIP_SIZE - OFFSET, client().height() - GRIP_SIZE - OFFSET ); if( client().isPreview() ) { position -= QPoint( client().layoutMetric( Client::LM_BorderRight )+ client().layoutMetric( Client::<API key> ), client().layoutMetric( Client::<API key> )+ client().layoutMetric( Client::LM_BorderBottom ) ); } else { position -= QPoint( client().layoutMetric( Client::LM_BorderRight ), client().layoutMetric( Client::LM_BorderBottom ) ); } move( position ); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace gokiTagDB { public class Settings { public static float[] zoomLevels = new float[7] { .25f, .50f, .75f, 1.0f, 1.25f, 1.5f, 2.0f }; public static int[] updateIntervals = new int[] { 15, 30, 100 }; private string fileFilter; public string FileFilter { get { return fileFilter; } set { fileFilter = value; } } private SortType sortType; public SortType SortType { get { return sortType; } set { sortType = value; } } private SelectionMode selectionMode; public SelectionMode SelectionMode { get { return selectionMode; } set { selectionMode = value; } } private int thumbnailWidth; public int ThumbnailWidth { get { return thumbnailWidth; } set { thumbnailWidth = value; } } private int thumbnailHeight; public int ThumbnailHeight { get { return thumbnailHeight; } set { thumbnailHeight = value; } } private int zoomIndex; public int ZoomIndex { get { return zoomIndex; } set { zoomIndex = value; } } private int updateInterval; public int UpdateInterval { get { return updateInterval; } set { updateInterval = value; } } private Padding panelPadding ; public Padding PanelPadding { get { return panelPadding; } set { panelPadding = value; } } private Padding entryMargin; public Padding EntryMargin { get { return entryMargin; } set { entryMargin = value; } } private Padding entryPadding; public Padding EntryPadding { get { return entryPadding; } set { entryPadding = value; } } private int borderSize; public int BorderSize { get { return borderSize; } set { borderSize = value; if (borderSize < 1) { borderSize = 1; } } } private long <API key>; public long <API key> { get { return <API key>; } set { <API key> = value; } } private int maximumSuggestions; public int MaximumSuggestions { get { return maximumSuggestions; } set { maximumSuggestions = value; } } private <API key> <API key>; public <API key> <API key> { get { return <API key>; } set { <API key> = value; } } public Settings() { FileFilter = @".*(\.jpeg|\.jpg|\.png|\.gif|\.bmp|\.webm)"; SortType = SortType.Location; SelectionMode = SelectionMode.Explorer; ThumbnailWidth = 200; ThumbnailHeight = 200; ZoomIndex = 3; UpdateInterval = updateIntervals[0]; PanelPadding = new Padding(2); EntryMargin = new Padding(1); EntryPadding = new Padding(1); BorderSize = 1; <API key> = 100000000; MaximumSuggestions = 10; <API key> = gokiTagDB.<API key>.Smart; } } }
using JBB.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JBB.DAL.EF { public class JBInitializer : System.Data.Entity.<API key><JBContext> { protected override void Seed(JBContext context) { //base.Seed(context); var companies = new List<Company> { new Company{Name="Haagi Mettals"}, new Company{Name="Morkels Manufacture Pty Ltd"} }; companies.ForEach(c => context.Companies.Add(c)); context.SaveChanges(); var offers = new List<Offer> { new Offer{Company=companies[0],ShortDescription="Motor Maintenance", LongDescription="A student is required to maintain electric motors for the companies manufacturing division."}, new Offer{Company=companies[0], ShortDescription="Quality Assurance", LongDescription="A student is required to test the diameter of the product. Tcl/Tk and basic electronic skills (soldering) required."}, new Offer{Company=companies[1], ShortDescription="Lathe Operator", LongDescription="Partime work to earn some extras cash by operating a lathe in our furniture workshop in Doornfontein."} }; offers.ForEach(o => context.Offers.Add(o)); context.SaveChanges(); } } }
{{#each this}} <dl> <dt>ID: {{this}}</dt> <dd><button data-sincro-id="{{this}}" type="button" class="btn btn-md btn-default <API key>"><span class="glyphicon glyphicon-send" data-sincro-id="{{this}}"></span></button></dd> {{/each}}
#ifndef __CCGLPROGRAM_H__ #define __CCGLPROGRAM_H__ #include <unordered_map> #include "base/ccMacros.h" #include "base/CCRef.h" #include "base/ccTypes.h" #include "platform/CCGL.h" #include "math/CCMath.h" NS_CC_BEGIN /** * @addtogroup shaders * @{ */ struct _hashUniformEntry; class GLProgram; typedef void (*GLInfoFunction)(GLuint program, GLenum pname, GLint* params); typedef void (*GLLogFunction) (GLuint program, GLsizei bufsize, GLsizei* length, GLchar* infolog); struct VertexAttrib { GLuint index; GLint size; GLenum type; std::string name; }; struct Uniform { GLint location; GLint size; GLenum type; std::string name; }; /** GLProgram Class that implements a glProgram @since v2.0.0 */ class CC_DLL GLProgram : public Ref { friend class GLProgramState; public: enum { <API key>, VERTEX_ATTRIB_COLOR, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, VERTEX_ATTRIB_MAX, // backward compatibility <API key> = <API key>, }; enum { UNIFORM_P_MATRIX, UNIFORM_MV_MATRIX, UNIFORM_MVP_MATRIX, UNIFORM_TIME, UNIFORM_SIN_TIME, UNIFORM_COS_TIME, UNIFORM_RANDOM01, UNIFORM_SAMPLER0, UNIFORM_SAMPLER1, UNIFORM_SAMPLER2, UNIFORM_SAMPLER3, UNIFORM_MAX, }; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* SHADER_3D_POSITION; static const char* <API key>; static const char* <API key>; // uniform names static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* UNIFORM_NAME_TIME; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; // Attribute names static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; static const char* <API key>; GLProgram(); virtual ~GLProgram(); /** Initializes the GLProgram with a vertex and fragment with bytes array * @js initWithString * @lua initWithString */ #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) /** Initializes the CCGLProgram with precompiled shader program */ static GLProgram* <API key>(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray); bool <API key>(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray); #endif /** Initializes the GLProgram with a vertex and fragment with bytes array * @js initWithString * @lua initWithString */ static GLProgram* <API key>(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray); bool initWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray); /** Initializes the GLProgram with a vertex and fragment with contents of filenames * @js init * @lua init */ static GLProgram* createWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename); bool initWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename); //void bindUniform(std::string uniformName, int value); Uniform* getUniform(const std::string& name); VertexAttrib* getVertexAttrib(const std::string& name); /** It will add a new attribute to the shader by calling <API key> */ void bindAttribLocation(const std::string& attributeName, GLuint index) const; /** calls glGetAttribLocation */ GLint getAttribLocation(const std::string& attributeName) const; /** calls <API key>() */ GLint getUniformLocation(const std::string& attributeName) const; /** links the glProgram */ bool link(); /** it will call glUseProgram() */ void use(); /** It will create 4 uniforms: - kUniformPMatrix - kUniformMVMatrix - kUniformMVPMatrix - GLProgram::UNIFORM_SAMPLER And it will bind "GLProgram::UNIFORM_SAMPLER" to 0 */ void updateUniforms(); /** calls retrieves the named uniform location for this shader program. */ GLint <API key>(const char* name) const; /** calls glUniform1i only if the values are different than the previous call for this same shader program. * @js <API key> * @lua <API key> */ void <API key>(GLint location, GLint i1); /** calls glUniform2i only if the values are different than the previous call for this same shader program. */ void <API key>(GLint location, GLint i1, GLint i2); /** calls glUniform3i only if the values are different than the previous call for this same shader program. */ void <API key>(GLint location, GLint i1, GLint i2, GLint i3); /** calls glUniform4i only if the values are different than the previous call for this same shader program. */ void <API key>(GLint location, GLint i1, GLint i2, GLint i3, GLint i4); /** calls glUniform2iv only if the values are different than the previous call for this same shader program. */ void <API key>(GLint location, GLint* ints, unsigned int numberOfArrays); /** calls glUniform3iv only if the values are different than the previous call for this same shader program. */ void <API key>(GLint location, GLint* ints, unsigned int numberOfArrays); /** calls glUniform4iv only if the values are different than the previous call for this same shader program. */ void <API key>(GLint location, GLint* ints, unsigned int numberOfArrays); /** calls glUniform1f only if the values are different than the previous call for this same shader program. * In js or lua,please use <API key> * @js NA */ void <API key>(GLint location, GLfloat f1); /** calls glUniform2f only if the values are different than the previous call for this same shader program. * In js or lua,please use <API key> * @js NA */ void <API key>(GLint location, GLfloat f1, GLfloat f2); /** calls glUniform3f only if the values are different than the previous call for this same shader program. * In js or lua,please use <API key> * @js NA */ void <API key>(GLint location, GLfloat f1, GLfloat f2, GLfloat f3); /** calls glUniform4f only if the values are different than the previous call for this same shader program. * In js or lua,please use <API key> * @js NA */ void <API key>(GLint location, GLfloat f1, GLfloat f2, GLfloat f3, GLfloat f4); /** calls glUniform2fv only if the values are different than the previous call for this same shader program. */ void <API key>(GLint location, const GLfloat* floats, unsigned int numberOfArrays); /** calls glUniform3fv only if the values are different than the previous call for this same shader program. */ void <API key>(GLint location, const GLfloat* floats, unsigned int numberOfArrays); /** calls glUniform4fv only if the values are different than the previous call for this same shader program. */ void <API key>(GLint location, const GLfloat* floats, unsigned int numberOfArrays); /** calls glUniformMatrix2fv only if the values are different than the previous call for this same shader program. */ void <API key>(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices); /** calls glUniformMatrix3fv only if the values are different than the previous call for this same shader program. */ void <API key>(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices); /** calls glUniformMatrix4fv only if the values are different than the previous call for this same shader program. */ void <API key>(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices); /** will update the builtin uniforms if they are different than the previous call for this same shader program. */ void <API key>(); void <API key>(const Mat4 &modelView); // Attribute /** returns the vertexShader error log */ std::string getVertexShaderLog() const; /** returns the fragmentShader error log */ std::string <API key>() const; /** returns the program error log */ std::string getProgramLog() const; // reload all shaders, this function is designed for android // when opengl context lost, so don't call it. void reset(); inline const GLuint getProgram() const { return _program; } // DEPRECATED <API key> bool <API key>(const GLchar* vertexByteArray, const GLchar* fragByteArray) { return initWithByteArrays(vertexByteArray, fragByteArray); } <API key> bool <API key>(const std::string &vertexFilename, const std::string& fragFilename) { return initWithFilenames(vertexFilename, fragFilename); } <API key> void addAttribute(const std::string &attributeName, GLuint index) const { return bindAttribLocation(attributeName, index); } protected: bool <API key>(GLint location, const GLvoid* data, unsigned int bytes); virtual std::string getDescription() const; void <API key>(); void parseVertexAttribs(); void parseUniforms(); bool compileShader(GLuint * shader, GLenum type, const GLchar* source); std::string logForOpenGLObject(GLuint object, GLInfoFunction infoFunc, GLLogFunction logFunc) const; GLuint _program; GLuint _vertShader; GLuint _fragShader; GLint _builtInUniforms[UNIFORM_MAX]; struct _hashUniformEntry* _hashForUniforms; bool _hasShaderCompiler; #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) std::string _shaderId; #endif struct flag_struct { unsigned int usesTime:1; unsigned int usesMVP:1; unsigned int usesMV:1; unsigned int usesP:1; unsigned int usesRandom:1; // handy way to initialize the bitfield flag_struct() { memset(this, 0, sizeof(*this)); } } _flags; std::unordered_map<std::string, Uniform> _userUniforms; std::unordered_map<std::string, VertexAttrib> _vertexAttribs; }; NS_CC_END #endif /* __CCGLPROGRAM_H__ */
package com.tachys.moneyshare.dataaccess.db.contracts; import android.provider.BaseColumns; public class SettlementContract { public SettlementContract() { } public static class SettlementEntry implements BaseColumns { public static final String TABLE_NAME = "settlement"; public static final String COLUMN_NAME_PAYERID = "payer"; public static final String COLUMN_NAME_PAYEEID = "payee"; public static final String COLUMN_NAME_AMOUNT = "amount"; } }
<?php namespace UmnLib\Core\XmlRecord; class NlmCatalog extends Record { // Must be an id type that uniquely identifies the record, // usually the record-creating organization's id. public static function primaryIdType() { return 'nlm'; } // Must return array( 'type' => $type, 'value' => $value ) pairs. public function ids() { if (!isset($this->ids)) { // output $ids = array(); $array = $this->asArray(); // TODO: Not sure this array key lookup will work with Titon... $nlmUniqueId = $array['NlmUniqueID']; $ids[] = array('type' => 'nlm', 'value' => $nlmUniqueId); if (array_key_exists('OtherID', $array)) { $otherIds = $array['OtherID']; if (!array_key_exists(0, $otherIds)) { $otherIds = array($otherIds); } foreach ($otherIds as $otherId) { if ('OCLC' == $otherId['attributes']['Source']) { $oclcId = trim($otherId['value']); // For some goofy reason, some of the OCLC ids are prefixed with 'ocm': $oclcId = preg_replace('/^ocm/', '', $oclcId); $ids[] = array('type' => 'oclc', 'value' => $oclcId); } } } $this->ids = $ids; } return $this->ids; } }
my_inf = float('Inf') print 99999999 > my_inf # False my_neg_inf = float('-Inf') print my_neg_inf < -99999999 # True
cmd_kernel/irq/handle.o := <API key> -Wp,-MD,kernel/irq/.handle.o.d -nostdinc -isystem /usr/lib/gcc-cross/arm-linux-gnueabi/4.7/include -Iinclude -I/home/benoit/kernel_android/32/es209ra/arch/arm/include -include include/linux/autoconf.h -D__KERNEL__ -mlittle-endian -Iarch/arm/mach-msm/include -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs -Os -marm -mabi=aapcs-linux -mno-thumb-interwork -funwind-tables -D__LINUX_ARM_ARCH__=7 -march=armv7-a -msoft-float -Uarm -Wframe-larger-than=2048 -fno-stack-protector -fomit-frame-pointer -g -<API key> -Wno-pointer-sign -fno-strict-overflow -fno-dwarf2-cfi-asm -fconserve-stack -D"KBUILD_STR(s)=\#s" -D"KBUILD_BASENAME=KBUILD_STR(handle)" -D"KBUILD_MODNAME=KBUILD_STR(handle)" -c -o kernel/irq/handle.o kernel/irq/handle.c deps_kernel/irq/handle.o := \ kernel/irq/handle.c \ $(wildcard include/config/smp.h) \ $(wildcard include/config/generic/hardirqs.h) \ $(wildcard include/config/sparse/irq.h) \ $(wildcard include/config/generic/hardirqs/no//do/irq.h) \ $(wildcard include/config/enable/warn/deprecated.h) \ include/linux/irq.h \ $(wildcard include/config/s390.h) \ $(wildcard include/config/irq/per/cpu.h) \ $(wildcard include/config/irq/release/method.h) \ $(wildcard include/config/intr/remap.h) \ $(wildcard include/config/generic/pending/irq.h) \ $(wildcard include/config/proc/fs.h) \ $(wildcard include/config/numa/irq/desc.h) \ $(wildcard include/config/cpumask/offstack.h) \ $(wildcard include/config/cpumasks/offstack.h) \ include/linux/smp.h \ $(wildcard include/config/use/generic/smp/helpers.h) \ $(wildcard include/config/debug/preempt.h) \ include/linux/errno.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/errno.h \ include/asm-generic/errno.h \ include/asm-generic/errno-base.h \ include/linux/types.h \ $(wildcard include/config/uid16.h) \ $(wildcard include/config/lbdaf.h) \ $(wildcard include/config/phys/addr/t/64bit.h) \ $(wildcard include/config/64bit.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/types.h \ include/asm-generic/int-ll64.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/bitsperlong.h \ include/asm-generic/bitsperlong.h \ include/linux/posix_types.h \ include/linux/stddef.h \ include/linux/compiler.h \ $(wildcard include/config/trace/branch/profiling.h) \ $(wildcard include/config/profile/all/branches.h) \ $(wildcard include/config/enable/must/check.h) \ include/linux/compiler-gcc.h \ $(wildcard include/config/arch/supports/optimized/inlining.h) \ $(wildcard include/config/optimize/inlining.h) \ include/linux/compiler-gcc4.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/posix_types.h \ include/linux/list.h \ $(wildcard include/config/debug/list.h) \ include/linux/poison.h \ include/linux/prefetch.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/processor.h \ $(wildcard include/config/mmu.h) \ $(wildcard include/config/cpu/32v6k.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/ptrace.h \ $(wildcard include/config/cpu/endian/be8.h) \ $(wildcard include/config/arm/thumb.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/hwcap.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/cache.h \ $(wildcard include/config/arm/l1/cache/shift.h) \ $(wildcard include/config/aeabi.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/system.h \ $(wildcard include/config/cpu/xsc3.h) \ $(wildcard include/config/cpu/fa526.h) \ $(wildcard include/config/arch/msm.h) \ $(wildcard include/config/cpu/sa1100.h) \ $(wildcard include/config/cpu/sa110.h) \ include/linux/linkage.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/linkage.h \ include/linux/irqflags.h \ $(wildcard include/config/trace/irqflags.h) \ $(wildcard include/config/irqsoff/tracer.h) \ $(wildcard include/config/preempt/tracer.h) \ $(wildcard include/config/trace/irqflags/support.h) \ $(wildcard include/config/x86.h) \ include/linux/typecheck.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/irqflags.h \ include/asm-generic/cmpxchg-local.h \ include/linux/cpumask.h \ $(wildcard include/config/hotplug/cpu.h) \ $(wildcard include/config/debug/per/cpu/maps.h) \ $(wildcard include/config/disable/obsolete/cpumask/functions.h) \ include/linux/kernel.h \ $(wildcard include/config/preempt/voluntary.h) \ $(wildcard include/config/debug/spinlock/sleep.h) \ $(wildcard include/config/prove/locking.h) \ $(wildcard include/config/printk.h) \ $(wildcard include/config/dynamic/debug.h) \ $(wildcard include/config/ring/buffer.h) \ $(wildcard include/config/tracing.h) \ $(wildcard include/config/numa.h) \ $(wildcard include/config/ftrace/mcount/record.h) \ /usr/lib/gcc-cross/arm-linux-gnueabi/4.7/include/stdarg.h \ include/linux/bitops.h \ $(wildcard include/config/generic/find/first/bit.h) \ $(wildcard include/config/generic/find/last/bit.h) \ $(wildcard include/config/generic/find/next/bit.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/bitops.h \ include/asm-generic/bitops/non-atomic.h \ include/asm-generic/bitops/fls64.h \ include/asm-generic/bitops/sched.h \ include/asm-generic/bitops/hweight.h \ include/asm-generic/bitops/lock.h \ include/linux/log2.h \ $(wildcard include/config/arch/has/ilog2/u32.h) \ $(wildcard include/config/arch/has/ilog2/u64.h) \ include/linux/ratelimit.h \ include/linux/param.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/param.h \ $(wildcard include/config/hz.h) \ include/linux/dynamic_debug.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/byteorder.h \ include/linux/byteorder/little_endian.h \ include/linux/swab.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/swab.h \ include/linux/byteorder/generic.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/bug.h \ $(wildcard include/config/bug.h) \ $(wildcard include/config/debug/bugverbose.h) \ include/asm-generic/bug.h \ $(wildcard include/config/generic/bug.h) \ $(wildcard include/config/generic/bug/relative/pointers.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/div64.h \ include/linux/threads.h \ $(wildcard include/config/nr/cpus.h) \ $(wildcard include/config/base/small.h) \ include/linux/bitmap.h \ include/linux/string.h \ $(wildcard include/config/binary/printf.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/string.h \ include/linux/cache.h \ $(wildcard include/config/arch/has/cache/line/size.h) \ include/linux/spinlock.h \ $(wildcard include/config/debug/spinlock.h) \ $(wildcard include/config/generic/lockbreak.h) \ $(wildcard include/config/preempt.h) \ $(wildcard include/config/debug/lock/alloc.h) \ include/linux/preempt.h \ $(wildcard include/config/preempt/notifiers.h) \ include/linux/thread_info.h \ $(wildcard include/config/compat.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/thread_info.h \ $(wildcard include/config/arm/thumbee.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/fpstate.h \ $(wildcard include/config/vfpv3.h) \ $(wildcard include/config/iwmmxt.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/domain.h \ $(wildcard include/config/verify/permission/fault.h) \ $(wildcard include/config/io/36.h) \ include/linux/stringify.h \ include/linux/bottom_half.h \ include/linux/spinlock_types.h \ include/linux/spinlock_types_up.h \ include/linux/lockdep.h \ $(wildcard include/config/lockdep.h) \ $(wildcard include/config/lock/stat.h) \ include/linux/spinlock_up.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/atomic.h \ include/asm-generic/atomic-long.h \ include/linux/spinlock_api_up.h \ include/linux/gfp.h \ $(wildcard include/config/kmemcheck.h) \ $(wildcard include/config/highmem.h) \ $(wildcard include/config/zone/dma.h) \ $(wildcard include/config/zone/dma32.h) \ $(wildcard include/config/debug/vm.h) \ include/linux/mmzone.h \ $(wildcard include/config/force/max/zoneorder.h) \ $(wildcard include/config/memory/hotplug.h) \ $(wildcard include/config/sparsemem.h) \ $(wildcard include/config/arch/populates/node/map.h) \ $(wildcard include/config/discontigmem.h) \ $(wildcard include/config/flat/node/mem/map.h) \ $(wildcard include/config/cgroup/mem/res/ctlr.h) \ $(wildcard include/config/have/memory/present.h) \ $(wildcard include/config/need/node/memmap/size.h) \ $(wildcard include/config/need/multiple/nodes.h) \ $(wildcard include/config/have/arch/early/pfn/to/nid.h) \ $(wildcard include/config/flatmem.h) \ $(wildcard include/config/sparsemem/extreme.h) \ $(wildcard include/config/nodes/span/other/nodes.h) \ $(wildcard include/config/holes/in/zone.h) \ $(wildcard include/config/arch/has/holes/memorymodel.h) \ include/linux/wait.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/current.h \ include/linux/numa.h \ $(wildcard include/config/nodes/shift.h) \ include/linux/init.h \ $(wildcard include/config/modules.h) \ $(wildcard include/config/hotplug.h) \ include/linux/seqlock.h \ include/linux/nodemask.h \ include/linux/pageblock-flags.h \ $(wildcard include/config/hugetlb/page.h) \ $(wildcard include/config/hugetlb/page/size/variable.h) \ include/linux/bounds.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/page.h \ $(wildcard include/config/cpu/copy/v3.h) \ $(wildcard include/config/cpu/copy/v4wt.h) \ $(wildcard include/config/cpu/copy/v4wb.h) \ $(wildcard include/config/cpu/copy/feroceon.h) \ $(wildcard include/config/cpu/copy/fa.h) \ $(wildcard include/config/cpu/xscale.h) \ $(wildcard include/config/cpu/copy/v6.h) \ $(wildcard include/config/memory/hotplug/sparse.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/glue.h \ $(wildcard include/config/cpu/arm610.h) \ $(wildcard include/config/cpu/arm710.h) \ $(wildcard include/config/cpu/abrt/lv4t.h) \ $(wildcard include/config/cpu/abrt/ev4.h) \ $(wildcard include/config/cpu/abrt/ev4t.h) \ $(wildcard include/config/cpu/abrt/ev5tj.h) \ $(wildcard include/config/cpu/abrt/ev5t.h) \ $(wildcard include/config/cpu/abrt/ev6.h) \ $(wildcard include/config/cpu/abrt/ev7.h) \ $(wildcard include/config/cpu/pabrt/legacy.h) \ $(wildcard include/config/cpu/pabrt/v6.h) \ $(wildcard include/config/cpu/pabrt/v7.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/memory.h \ $(wildcard include/config/page/offset.h) \ $(wildcard include/config/thumb2/kernel.h) \ $(wildcard include/config/dram/size.h) \ $(wildcard include/config/dram/base.h) \ include/linux/const.h \ arch/arm/mach-msm/include/mach/memory.h \ $(wildcard include/config/phys/offset.h) \ $(wildcard include/config/arch/msm7x30.h) \ $(wildcard include/config/vmsplit/3g.h) \ $(wildcard include/config/arch/msm/arm11.h) \ $(wildcard include/config/cache/l2x0.h) \ $(wildcard include/config/arch/msm/scorpion.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/sizes.h \ include/asm-generic/memory_model.h \ $(wildcard include/config/sparsemem/vmemmap.h) \ include/asm-generic/getorder.h \ include/linux/memory_hotplug.h \ $(wildcard include/config/have/arch/nodedata/extension.h) \ $(wildcard include/config/memory/hotremove.h) \ include/linux/notifier.h \ include/linux/mutex.h \ $(wildcard include/config/debug/mutexes.h) \ include/linux/rwsem.h \ $(wildcard include/config/rwsem/generic/spinlock.h) \ include/linux/rwsem-spinlock.h \ include/linux/srcu.h \ include/linux/topology.h \ $(wildcard include/config/sched/smt.h) \ $(wildcard include/config/sched/mc.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/topology.h \ include/asm-generic/topology.h \ include/linux/mmdebug.h \ $(wildcard include/config/debug/virtual.h) \ include/linux/irqreturn.h \ include/linux/irqnr.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/irq.h \ arch/arm/mach-msm/include/mach/irqs.h \ $(wildcard include/config/arch/qsd8x50.h) \ $(wildcard include/config/arch/msm8x60.h) \ arch/arm/mach-msm/include/mach/irqs-8x50.h \ arch/arm/mach-msm/include/mach/sirc.h \ $(wildcard include/config/msm/soc/rev/a.h) \ arch/arm/mach-msm/include/mach/msm_iomap.h \ arch/arm/mach-msm/include/mach/msm_iomap-8x50.h \ $(wildcard include/config/mach/es209ra.h) \ $(wildcard include/config/msm/debug/uart.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/irq_regs.h \ include/asm-generic/irq_regs.h \ include/linux/percpu.h \ $(wildcard include/config/have/legacy/per/cpu/area.h) \ $(wildcard include/config/need/per/cpu/embed/first/chunk.h) \ $(wildcard include/config/need/per/cpu/page/first/chunk.h) \ $(wildcard include/config/debug/kmemleak.h) \ $(wildcard include/config/have/setup/per/cpu/area.h) \ include/linux/slab.h \ $(wildcard include/config/slab/debug.h) \ $(wildcard include/config/debug/objects.h) \ $(wildcard include/config/slub.h) \ $(wildcard include/config/slob.h) \ $(wildcard include/config/debug/slab.h) \ include/linux/slob_def.h \ include/linux/pfn.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/percpu.h \ include/asm-generic/percpu.h \ include/linux/percpu-defs.h \ $(wildcard include/config/debug/force/weak/per/cpu.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/hw_irq.h \ include/linux/sched.h \ $(wildcard include/config/sched/debug.h) \ $(wildcard include/config/no/hz.h) \ $(wildcard include/config/detect/softlockup.h) \ $(wildcard include/config/detect/hung/task.h) \ $(wildcard include/config/core/dump/default/elf/headers.h) \ $(wildcard include/config/bsd/process/acct.h) \ $(wildcard include/config/taskstats.h) \ $(wildcard include/config/audit.h) \ $(wildcard include/config/inotify/user.h) \ $(wildcard include/config/epoll.h) \ $(wildcard include/config/posix/mqueue.h) \ $(wildcard include/config/keys.h) \ $(wildcard include/config/user/sched.h) \ $(wildcard include/config/sysfs.h) \ $(wildcard include/config/perf/events.h) \ $(wildcard include/config/schedstats.h) \ $(wildcard include/config/task/delay/acct.h) \ $(wildcard include/config/fair/group/sched.h) \ $(wildcard include/config/rt/group/sched.h) \ $(wildcard include/config/blk/dev/io/trace.h) \ $(wildcard include/config/tree/preempt/rcu.h) \ $(wildcard include/config/cc/stackprotector.h) \ $(wildcard include/config/sysvipc.h) \ $(wildcard include/config/auditsyscall.h) \ $(wildcard include/config/rt/mutexes.h) \ $(wildcard include/config/task/xacct.h) \ $(wildcard include/config/cpusets.h) \ $(wildcard include/config/cgroups.h) \ $(wildcard include/config/futex.h) \ $(wildcard include/config/fault/injection.h) \ $(wildcard include/config/latencytop.h) \ $(wildcard include/config/function/graph/tracer.h) \ $(wildcard include/config/have/unstable/sched/clock.h) \ $(wildcard include/config/stack/growsup.h) \ $(wildcard include/config/debug/stack/usage.h) \ $(wildcard include/config/group/sched.h) \ $(wildcard include/config/mm/owner.h) \ include/linux/capability.h \ $(wildcard include/config/security/file/capabilities.h) \ include/linux/timex.h \ include/linux/time.h \ $(wildcard include/config/arch/uses/gettimeoffset.h) \ include/linux/math64.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/timex.h \ arch/arm/mach-msm/include/mach/timex.h \ include/linux/jiffies.h \ include/linux/rbtree.h \ include/linux/mm_types.h \ $(wildcard include/config/split/ptlock/cpus.h) \ $(wildcard include/config/want/page/debug/flags.h) \ $(wildcard include/config/aio.h) \ $(wildcard include/config/mmu/notifier.h) \ include/linux/auxvec.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/auxvec.h \ include/linux/prio_tree.h \ include/linux/completion.h \ include/linux/page-debug-flags.h \ $(wildcard include/config/page/poisoning.h) \ $(wildcard include/config/page/debug/something/else.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/mmu.h \ $(wildcard include/config/cpu/has/asid.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/cputime.h \ include/asm-generic/cputime.h \ include/linux/sem.h \ include/linux/ipc.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/ipcbuf.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/sembuf.h \ include/linux/rcupdate.h \ $(wildcard include/config/tree/rcu.h) \ include/linux/rcutree.h \ include/linux/signal.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/signal.h \ include/asm-generic/signal-defs.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/sigcontext.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/siginfo.h \ include/asm-generic/siginfo.h \ include/linux/path.h \ include/linux/pid.h \ include/linux/proportions.h \ include/linux/percpu_counter.h \ include/linux/seccomp.h \ $(wildcard include/config/seccomp.h) \ include/linux/rculist.h \ include/linux/rtmutex.h \ $(wildcard include/config/debug/rt/mutexes.h) \ include/linux/plist.h \ $(wildcard include/config/debug/pi/list.h) \ include/linux/resource.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/resource.h \ include/asm-generic/resource.h \ include/linux/timer.h \ $(wildcard include/config/timer/stats.h) \ $(wildcard include/config/debug/objects/timers.h) \ include/linux/ktime.h \ $(wildcard include/config/ktime/scalar.h) \ include/linux/debugobjects.h \ $(wildcard include/config/debug/objects/free.h) \ include/linux/hrtimer.h \ $(wildcard include/config/high/res/timers.h) \ include/linux/task_io_accounting.h \ $(wildcard include/config/task/io/accounting.h) \ include/linux/kobject.h \ include/linux/sysfs.h \ include/linux/kref.h \ include/linux/latencytop.h \ include/linux/cred.h \ $(wildcard include/config/debug/credentials.h) \ $(wildcard include/config/security.h) \ include/linux/key.h \ $(wildcard include/config/sysctl.h) \ include/linux/sysctl.h \ include/linux/selinux.h \ $(wildcard include/config/security/selinux.h) \ include/linux/aio.h \ include/linux/workqueue.h \ include/linux/aio_abi.h \ include/linux/uio.h \ include/linux/module.h \ $(wildcard include/config/modversions.h) \ $(wildcard include/config/unused/symbols.h) \ $(wildcard include/config/kallsyms.h) \ $(wildcard include/config/tracepoints.h) \ $(wildcard include/config/event/tracing.h) \ $(wildcard include/config/module/unload.h) \ $(wildcard include/config/constructors.h) \ include/linux/stat.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/stat.h \ include/linux/kmod.h \ include/linux/elf.h \ include/linux/elf-em.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/elf.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/user.h \ include/linux/moduleparam.h \ $(wildcard include/config/alpha.h) \ $(wildcard include/config/ia64.h) \ $(wildcard include/config/ppc64.h) \ include/linux/tracepoint.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/local.h \ include/asm-generic/local.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/module.h \ $(wildcard include/config/arm/unwind.h) \ include/trace/events/module.h \ include/trace/define_trace.h \ include/linux/random.h \ include/linux/ioctl.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/ioctl.h \ include/asm-generic/ioctl.h \ include/linux/interrupt.h \ $(wildcard include/config/pm/sleep.h) \ $(wildcard include/config/generic/irq/probe.h) \ $(wildcard include/config/debug/shirq.h) \ include/linux/hardirq.h \ $(wildcard include/config/virt/cpu/accounting.h) \ include/linux/smp_lock.h \ $(wildcard include/config/lock/kernel.h) \ include/linux/ftrace_irq.h \ $(wildcard include/config/ftrace/nmi/enter.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/hardirq.h \ include/linux/irq_cpustat.h \ include/linux/kernel_stat.h \ include/linux/hash.h \ include/linux/bootmem.h \ $(wildcard include/config/crash/dump.h) \ $(wildcard include/config/have/arch/bootmem/node.h) \ $(wildcard include/config/have/arch/alloc/remap.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/dma.h \ $(wildcard include/config/isa/dma/api.h) \ $(wildcard include/config/pci.h) \ include/trace/events/irq.h \ kernel/irq/internals.h \ include/linux/kallsyms.h \ kernel/irq/handle.o: $(deps_kernel/irq/handle.o) $(deps_kernel/irq/handle.o):
#include "fix_rigid.h" #include <mpi.h> #include <cmath> #include <cstdlib> #include <cstring> #include "math_extra.h" #include "atom.h" #include "atom_vec_ellipsoid.h" #include "atom_vec_line.h" #include "atom_vec_tri.h" #include "domain.h" #include "update.h" #include "respa.h" #include "modify.h" #include "group.h" #include "comm.h" #include "random_mars.h" #include "force.h" #include "input.h" #include "variable.h" #include "math_const.h" #include "memory.h" #include "error.h" #include "rigid_const.h" using namespace LAMMPS_NS; using namespace FixConst; using namespace MathConst; using namespace RigidConst; FixRigid::FixRigid(LAMMPS *lmp, int narg, char **arg) : Fix(lmp, narg, arg), step_respa(NULL), inpfile(NULL), nrigid(NULL), mol2body(NULL), body2mol(NULL), body(NULL), displace(NULL), masstotal(NULL), xcm(NULL), vcm(NULL), fcm(NULL), inertia(NULL), ex_space(NULL), ey_space(NULL), ez_space(NULL), angmom(NULL), omega(NULL), torque(NULL), quat(NULL), imagebody(NULL), fflag(NULL), tflag(NULL), langextra(NULL), sum(NULL), all(NULL), remapflag(NULL), xcmimage(NULL), eflags(NULL), orient(NULL), dorient(NULL), id_dilate(NULL), id_gravity(NULL), random(NULL), avec_ellipsoid(NULL), avec_line(NULL), avec_tri(NULL) { int i,ibody; scalar_flag = 1; extscalar = 0; time_integrate = 1; rigid_flag = 1; virial_flag = 1; thermo_virial = 1; create_attribute = 1; dof_flag = 1; enforce2d_flag = 1; MPI_Comm_rank(world,&me); MPI_Comm_size(world,&nprocs); // perform initial allocation of atom-based arrays // register with Atom class extended = orientflag = dorientflag = 0; body = NULL; xcmimage = NULL; displace = NULL; eflags = NULL; orient = NULL; dorient = NULL; grow_arrays(atom->nmax); atom->add_callback(0); // parse args for rigid body specification // set nbody and body[i] for each atom if (narg < 4) error->all(FLERR,"Illegal fix rigid command"); int iarg; mol2body = NULL; body2mol = NULL; // single rigid body // nbody = 1 // all atoms in fix group are part of body if (strcmp(arg[3],"single") == 0) { rstyle = SINGLE; iarg = 4; nbody = 1; int *mask = atom->mask; int nlocal = atom->nlocal; for (i = 0; i < nlocal; i++) { body[i] = -1; if (mask[i] & groupbit) body[i] = 0; } // each molecule in fix group is a rigid body // maxmol = largest molecule ID // ncount = # of atoms in each molecule (have to sum across procs) // nbody = # of non-zero ncount values // use nall as incremented ptr to set body[] values for each atom } else if (strcmp(arg[3],"molecule") == 0 || strcmp(arg[3],"custom") == 0) { rstyle = MOLECULE; tagint *molecule; int *mask = atom->mask; int nlocal = atom->nlocal; int custom_flag = strcmp(arg[3],"custom") == 0; if (custom_flag) { if (narg < 5) error->all(FLERR,"Illegal fix rigid command"); // determine whether atom-style variable or atom property is used if (strstr(arg[4],"i_") == arg[4]) { int is_double=0; int custom_index = atom->find_custom(arg[4]+2,is_double); if (custom_index == -1) error->all(FLERR,"Fix rigid custom requires " "previously defined property/atom"); else if (is_double) error->all(FLERR,"Fix rigid custom requires " "integer-valued property/atom"); int minval = INT_MAX; int *value = atom->ivector[custom_index]; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) minval = MIN(minval,value[i]); int vmin = minval; MPI_Allreduce(&vmin,&minval,1,MPI_INT,MPI_MIN,world); molecule = new tagint[nlocal]; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) molecule[i] = (tagint)(value[i] - minval + 1); else molecule[i] = 0; } else if (strstr(arg[4],"v_") == arg[4]) { int ivariable = input->variable->find(arg[4]+2); if (ivariable < 0) error->all(FLERR,"Variable name for fix rigid custom does not exist"); if (input->variable->atomstyle(ivariable) == 0) error->all(FLERR,"Fix rigid custom variable is no atom-style variable"); double *value = new double[nlocal]; input->variable->compute_atom(ivariable,0,value,1,0); int minval = INT_MAX; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) minval = MIN(minval,(int)value[i]); int vmin = minval; MPI_Allreduce(&vmin,&minval,1,MPI_INT,MPI_MIN,world); molecule = new tagint[nlocal]; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) molecule[i] = (tagint)((tagint)value[i] - minval + 1); delete[] value; } else error->all(FLERR,"Unsupported fix rigid custom property"); } else { if (atom->molecule_flag == 0) error->all(FLERR,"Fix rigid molecule requires atom attribute molecule"); molecule = atom->molecule; } iarg = 4 + custom_flag; tagint maxmol_tag = -1; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) maxmol_tag = MAX(maxmol_tag,molecule[i]); tagint itmp; MPI_Allreduce(&maxmol_tag,&itmp,1,MPI_LMP_TAGINT,MPI_MAX,world); if (itmp+1 > MAXSMALLINT) error->all(FLERR,"Too many molecules for fix rigid"); maxmol = (int) itmp; int *ncount; memory->create(ncount,maxmol+1,"rigid:ncount"); for (i = 0; i <= maxmol; i++) ncount[i] = 0; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) ncount[molecule[i]]++; memory->create(mol2body,maxmol+1,"rigid:mol2body"); MPI_Allreduce(ncount,mol2body,maxmol+1,MPI_INT,MPI_SUM,world); nbody = 0; for (i = 0; i <= maxmol; i++) if (mol2body[i]) mol2body[i] = nbody++; else mol2body[i] = -1; memory->create(body2mol,nbody,"rigid:body2mol"); nbody = 0; for (i = 0; i <= maxmol; i++) if (mol2body[i] >= 0) body2mol[nbody++] = i; for (i = 0; i < nlocal; i++) { body[i] = -1; if (mask[i] & groupbit) body[i] = mol2body[molecule[i]]; } memory->destroy(ncount); if (custom_flag) delete [] molecule; // each listed group is a rigid body // check if all listed groups exist // an atom must belong to fix group and listed group to be in rigid body // error if atom belongs to more than 1 rigid body } else if (strcmp(arg[3],"group") == 0) { if (narg < 5) error->all(FLERR,"Illegal fix rigid command"); rstyle = GROUP; nbody = force->inumeric(FLERR,arg[4]); if (nbody <= 0) error->all(FLERR,"Illegal fix rigid command"); if (narg < 5+nbody) error->all(FLERR,"Illegal fix rigid command"); iarg = 5+nbody; int *igroups = new int[nbody]; for (ibody = 0; ibody < nbody; ibody++) { igroups[ibody] = group->find(arg[5+ibody]); if (igroups[ibody] == -1) error->all(FLERR,"Could not find fix rigid group ID"); } int *mask = atom->mask; int nlocal = atom->nlocal; int flag = 0; for (i = 0; i < nlocal; i++) { body[i] = -1; if (mask[i] & groupbit) for (ibody = 0; ibody < nbody; ibody++) if (mask[i] & group->bitmask[igroups[ibody]]) { if (body[i] >= 0) flag = 1; body[i] = ibody; } } int flagall; MPI_Allreduce(&flag,&flagall,1,MPI_INT,MPI_SUM,world); if (flagall) error->all(FLERR,"One or more atoms belong to multiple rigid bodies"); delete [] igroups; } else error->all(FLERR,"Illegal fix rigid command"); // error check on nbody if (nbody == 0) error->all(FLERR,"No rigid bodies defined"); // create all nbody-length arrays memory->create(nrigid,nbody,"rigid:nrigid"); memory->create(masstotal,nbody,"rigid:masstotal"); memory->create(xcm,nbody,3,"rigid:xcm"); memory->create(vcm,nbody,3,"rigid:vcm"); memory->create(fcm,nbody,3,"rigid:fcm"); memory->create(inertia,nbody,3,"rigid:inertia"); memory->create(ex_space,nbody,3,"rigid:ex_space"); memory->create(ey_space,nbody,3,"rigid:ey_space"); memory->create(ez_space,nbody,3,"rigid:ez_space"); memory->create(angmom,nbody,3,"rigid:angmom"); memory->create(omega,nbody,3,"rigid:omega"); memory->create(torque,nbody,3,"rigid:torque"); memory->create(quat,nbody,4,"rigid:quat"); memory->create(imagebody,nbody,"rigid:imagebody"); memory->create(fflag,nbody,3,"rigid:fflag"); memory->create(tflag,nbody,3,"rigid:tflag"); memory->create(langextra,nbody,6,"rigid:langextra"); memory->create(sum,nbody,6,"rigid:sum"); memory->create(all,nbody,6,"rigid:all"); memory->create(remapflag,nbody,4,"rigid:remapflag"); // initialize force/torque flags to default = 1.0 // for 2d: fz, tx, ty = 0.0 array_flag = 1; size_array_rows = nbody; size_array_cols = 15; global_freq = 1; extarray = 0; for (i = 0; i < nbody; i++) { fflag[i][0] = fflag[i][1] = fflag[i][2] = 1.0; tflag[i][0] = tflag[i][1] = tflag[i][2] = 1.0; if (domain->dimension == 2) fflag[i][2] = tflag[i][0] = tflag[i][1] = 0.0; } // number of linear rigid bodies is counted later nlinear = 0; // parse optional args int seed; langflag = 0; reinitflag = 1; tstat_flag = 0; pstat_flag = 0; allremap = 1; t_chain = 10; t_iter = 1; t_order = 3; p_chain = 10; inpfile = NULL; id_gravity = NULL; id_dilate = NULL; pcouple = NONE; pstyle = ANISO; dimension = domain->dimension; for (int i = 0; i < 3; i++) { p_start[i] = p_stop[i] = p_period[i] = 0.0; p_flag[i] = 0; } while (iarg < narg) { if (strcmp(arg[iarg],"force") == 0) { if (iarg+5 > narg) error->all(FLERR,"Illegal fix rigid command"); int mlo,mhi; force->bounds(FLERR,arg[iarg+1],nbody,mlo,mhi); double xflag,yflag,zflag; if (strcmp(arg[iarg+2],"off") == 0) xflag = 0.0; else if (strcmp(arg[iarg+2],"on") == 0) xflag = 1.0; else error->all(FLERR,"Illegal fix rigid command"); if (strcmp(arg[iarg+3],"off") == 0) yflag = 0.0; else if (strcmp(arg[iarg+3],"on") == 0) yflag = 1.0; else error->all(FLERR,"Illegal fix rigid command"); if (strcmp(arg[iarg+4],"off") == 0) zflag = 0.0; else if (strcmp(arg[iarg+4],"on") == 0) zflag = 1.0; else error->all(FLERR,"Illegal fix rigid command"); if (domain->dimension == 2 && zflag == 1.0) error->all(FLERR,"Fix rigid z force cannot be on for 2d simulation"); int count = 0; for (int m = mlo; m <= mhi; m++) { fflag[m-1][0] = xflag; fflag[m-1][1] = yflag; fflag[m-1][2] = zflag; count++; } if (count == 0) error->all(FLERR,"Illegal fix rigid command"); iarg += 5; } else if (strcmp(arg[iarg],"torque") == 0) { if (iarg+5 > narg) error->all(FLERR,"Illegal fix rigid command"); int mlo,mhi; force->bounds(FLERR,arg[iarg+1],nbody,mlo,mhi); double xflag,yflag,zflag; if (strcmp(arg[iarg+2],"off") == 0) xflag = 0.0; else if (strcmp(arg[iarg+2],"on") == 0) xflag = 1.0; else error->all(FLERR,"Illegal fix rigid command"); if (strcmp(arg[iarg+3],"off") == 0) yflag = 0.0; else if (strcmp(arg[iarg+3],"on") == 0) yflag = 1.0; else error->all(FLERR,"Illegal fix rigid command"); if (strcmp(arg[iarg+4],"off") == 0) zflag = 0.0; else if (strcmp(arg[iarg+4],"on") == 0) zflag = 1.0; else error->all(FLERR,"Illegal fix rigid command"); if (domain->dimension == 2 && (xflag == 1.0 || yflag == 1.0)) error->all(FLERR,"Fix rigid xy torque cannot be on for 2d simulation"); int count = 0; for (int m = mlo; m <= mhi; m++) { tflag[m-1][0] = xflag; tflag[m-1][1] = yflag; tflag[m-1][2] = zflag; count++; } if (count == 0) error->all(FLERR,"Illegal fix rigid command"); iarg += 5; } else if (strcmp(arg[iarg],"langevin") == 0) { if (iarg+5 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid") != 0 && strcmp(style,"rigid/nve") != 0 && strcmp(style,"rigid/omp") != 0 && strcmp(style,"rigid/nve/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); langflag = 1; t_start = force->numeric(FLERR,arg[iarg+1]); t_stop = force->numeric(FLERR,arg[iarg+2]); t_period = force->numeric(FLERR,arg[iarg+3]); seed = force->inumeric(FLERR,arg[iarg+4]); if (t_period <= 0.0) error->all(FLERR,"Fix rigid langevin period must be > 0.0"); if (seed <= 0) error->all(FLERR,"Illegal fix rigid command"); iarg += 5; } else if (strcmp(arg[iarg],"temp") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/nvt") != 0 && strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nvt/omp") != 0 && strcmp(style,"rigid/npt/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); tstat_flag = 1; t_start = force->numeric(FLERR,arg[iarg+1]); t_stop = force->numeric(FLERR,arg[iarg+2]); t_period = force->numeric(FLERR,arg[iarg+3]); iarg += 4; } else if (strcmp(arg[iarg],"iso") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 && strcmp(style,"rigid/npt/omp") != 0 && strcmp(style,"rigid/nph/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); pcouple = XYZ; p_start[0] = p_start[1] = p_start[2] = force->numeric(FLERR,arg[iarg+1]); p_stop[0] = p_stop[1] = p_stop[2] = force->numeric(FLERR,arg[iarg+2]); p_period[0] = p_period[1] = p_period[2] = force->numeric(FLERR,arg[iarg+3]); p_flag[0] = p_flag[1] = p_flag[2] = 1; if (dimension == 2) { p_start[2] = p_stop[2] = p_period[2] = 0.0; p_flag[2] = 0; } iarg += 4; } else if (strcmp(arg[iarg],"aniso") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 && strcmp(style,"rigid/npt/omp") != 0 && strcmp(style,"rigid/nph/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); p_start[0] = p_start[1] = p_start[2] = force->numeric(FLERR,arg[iarg+1]); p_stop[0] = p_stop[1] = p_stop[2] = force->numeric(FLERR,arg[iarg+2]); p_period[0] = p_period[1] = p_period[2] = force->numeric(FLERR,arg[iarg+3]); p_flag[0] = p_flag[1] = p_flag[2] = 1; if (dimension == 2) { p_start[2] = p_stop[2] = p_period[2] = 0.0; p_flag[2] = 0; } iarg += 4; } else if (strcmp(arg[iarg],"x") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 && strcmp(style,"rigid/npt/omp") != 0 && strcmp(style,"rigid/nph/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); p_start[0] = force->numeric(FLERR,arg[iarg+1]); p_stop[0] = force->numeric(FLERR,arg[iarg+2]); p_period[0] = force->numeric(FLERR,arg[iarg+3]); p_flag[0] = 1; iarg += 4; } else if (strcmp(arg[iarg],"y") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 && strcmp(style,"rigid/npt/omp") != 0 && strcmp(style,"rigid/nph/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); p_start[1] = force->numeric(FLERR,arg[iarg+1]); p_stop[1] = force->numeric(FLERR,arg[iarg+2]); p_period[1] = force->numeric(FLERR,arg[iarg+3]); p_flag[1] = 1; iarg += 4; } else if (strcmp(arg[iarg],"z") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 && strcmp(style,"rigid/npt/omp") != 0 && strcmp(style,"rigid/nph/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); p_start[2] = force->numeric(FLERR,arg[iarg+1]); p_stop[2] = force->numeric(FLERR,arg[iarg+2]); p_period[2] = force->numeric(FLERR,arg[iarg+3]); p_flag[2] = 1; iarg += 4; } else if (strcmp(arg[iarg],"couple") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(arg[iarg+1],"xyz") == 0) pcouple = XYZ; else if (strcmp(arg[iarg+1],"xy") == 0) pcouple = XY; else if (strcmp(arg[iarg+1],"yz") == 0) pcouple = YZ; else if (strcmp(arg[iarg+1],"xz") == 0) pcouple = XZ; else if (strcmp(arg[iarg+1],"none") == 0) pcouple = NONE; else error->all(FLERR,"Illegal fix rigid command"); iarg += 2; } else if (strcmp(arg[iarg],"dilate") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid npt/nph command"); if (strcmp(arg[iarg+1],"all") == 0) allremap = 1; else { allremap = 0; delete [] id_dilate; int n = strlen(arg[iarg+1]) + 1; id_dilate = new char[n]; strcpy(id_dilate,arg[iarg+1]); int idilate = group->find(id_dilate); if (idilate == -1) error->all(FLERR, "Fix rigid npt/nph dilate group ID does not exist"); } iarg += 2; } else if (strcmp(arg[iarg],"tparam") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/nvt") != 0 && strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nvt/omp") != 0 && strcmp(style,"rigid/npt/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); t_chain = force->inumeric(FLERR,arg[iarg+1]); t_iter = force->inumeric(FLERR,arg[iarg+2]); t_order = force->inumeric(FLERR,arg[iarg+3]); iarg += 4; } else if (strcmp(arg[iarg],"pchain") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 && strcmp(style,"rigid/npt/omp") != 0 && strcmp(style,"rigid/nph/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); p_chain = force->inumeric(FLERR,arg[iarg+1]); iarg += 2; } else if (strcmp(arg[iarg],"infile") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command"); delete [] inpfile; int n = strlen(arg[iarg+1]) + 1; inpfile = new char[n]; strcpy(inpfile,arg[iarg+1]); restart_file = 1; reinitflag = 0; iarg += 2; } else if (strcmp(arg[iarg],"reinit") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp("yes",arg[iarg+1]) == 0) reinitflag = 1; else if (strcmp("no",arg[iarg+1]) == 0) reinitflag = 0; else error->all(FLERR,"Illegal fix rigid command"); iarg += 2; } else if (strcmp(arg[iarg],"gravity") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command"); delete [] id_gravity; int n = strlen(arg[iarg+1]) + 1; id_gravity = new char[n]; strcpy(id_gravity,arg[iarg+1]); iarg += 2; } else error->all(FLERR,"Illegal fix rigid command"); } // set pstat_flag pstat_flag = 0; for (int i = 0; i < 3; i++) if (p_flag[i]) pstat_flag = 1; if (pcouple == XYZ || (dimension == 2 && pcouple == XY)) pstyle = ISO; else pstyle = ANISO; // initialize Marsaglia RNG with processor-unique seed if (langflag) random = new RanMars(lmp,seed + me); else random = NULL; // initialize vector output quantities in case accessed before run for (i = 0; i < nbody; i++) { xcm[i][0] = xcm[i][1] = xcm[i][2] = 0.0; vcm[i][0] = vcm[i][1] = vcm[i][2] = 0.0; fcm[i][0] = fcm[i][1] = fcm[i][2] = 0.0; torque[i][0] = torque[i][1] = torque[i][2] = 0.0; } // nrigid[n] = # of atoms in Nth rigid body // error if one or zero atoms int *ncount = new int[nbody]; for (ibody = 0; ibody < nbody; ibody++) ncount[ibody] = 0; int nlocal = atom->nlocal; for (i = 0; i < nlocal; i++) if (body[i] >= 0) ncount[body[i]]++; MPI_Allreduce(ncount,nrigid,nbody,MPI_INT,MPI_SUM,world); delete [] ncount; for (ibody = 0; ibody < nbody; ibody++) if (nrigid[ibody] <= 1) error->all(FLERR,"One or zero atoms in rigid body"); // wait to setup bodies until first init() using current atom properties setupflag = 0; // compute per body forces and torques at final_integrate() by default earlyflag = 0; // print statistics int nsum = 0; for (ibody = 0; ibody < nbody; ibody++) nsum += nrigid[ibody]; if (me == 0) { if (screen) fprintf(screen,"%d rigid bodies with %d atoms\n",nbody,nsum); if (logfile) fprintf(logfile,"%d rigid bodies with %d atoms\n",nbody,nsum); } } FixRigid::~FixRigid() { // unregister callbacks to this fix from Atom class atom->delete_callback(id,0); delete random; delete [] inpfile; delete [] id_dilate; delete [] id_gravity; memory->destroy(mol2body); memory->destroy(body2mol); // delete locally stored per-atom arrays memory->destroy(body); memory->destroy(xcmimage); memory->destroy(displace); memory->destroy(eflags); memory->destroy(orient); memory->destroy(dorient); // delete nbody-length arrays memory->destroy(nrigid); memory->destroy(masstotal); memory->destroy(xcm); memory->destroy(vcm); memory->destroy(fcm); memory->destroy(inertia); memory->destroy(ex_space); memory->destroy(ey_space); memory->destroy(ez_space); memory->destroy(angmom); memory->destroy(omega); memory->destroy(torque); memory->destroy(quat); memory->destroy(imagebody); memory->destroy(fflag); memory->destroy(tflag); memory->destroy(langextra); memory->destroy(sum); memory->destroy(all); memory->destroy(remapflag); } int FixRigid::setmask() { int mask = 0; mask |= INITIAL_INTEGRATE; mask |= FINAL_INTEGRATE; if (langflag) mask |= POST_FORCE; mask |= PRE_NEIGHBOR; mask |= <API key>; mask |= <API key>; return mask; } void FixRigid::init() { int i,ibody; triclinic = domain->triclinic; // atom style pointers to particles that store extra info avec_ellipsoid = (AtomVecEllipsoid *) atom->style_match("ellipsoid"); avec_line = (AtomVecLine *) atom->style_match("line"); avec_tri = (AtomVecTri *) atom->style_match("tri"); // warn if more than one rigid fix // if earlyflag, warn if any post-force fixes come after a rigid fix int count = 0; for (i = 0; i < modify->nfix; i++) if (modify->fix[i]->rigid_flag) count++; if (count > 1 && me == 0) error->warning(FLERR,"More than one fix rigid"); if (earlyflag) { int rflag = 0; for (i = 0; i < modify->nfix; i++) { if (modify->fix[i]->rigid_flag) rflag = 1; if (rflag && (modify->fmask[i] & POST_FORCE) && !modify->fix[i]->rigid_flag) { char str[128]; snprintf(str,128,"Fix %s alters forces after fix rigid", modify->fix[i]->id); error->warning(FLERR,str); } } } // warn if body properties are read from inpfile // and the gravity keyword is not set and a gravity fix exists // this could mean body particles are overlapped // and gravity is not applied correctly if (inpfile && !id_gravity) { for (i = 0; i < modify->nfix; i++) { if (strcmp(modify->fix[i]->style,"gravity") == 0) { if (comm->me == 0) error->warning(FLERR,"Gravity may not be correctly applied " "to rigid bodies if they consist of " "overlapped particles"); break; } } } // error if npt,nph fix comes before rigid fix for (i = 0; i < modify->nfix; i++) { if (strcmp(modify->fix[i]->style,"npt") == 0) break; if (strcmp(modify->fix[i]->style,"nph") == 0) break; } if (i < modify->nfix) { for (int j = i; j < modify->nfix; j++) if (strcmp(modify->fix[j]->style,"rigid") == 0) error->all(FLERR,"Rigid fix must come before NPT/NPH fix"); } // add gravity forces based on gravity vector from fix if (id_gravity) { int ifix = modify->find_fix(id_gravity); if (ifix < 0) error->all(FLERR,"Fix rigid cannot find fix gravity ID"); if (strcmp(modify->fix[ifix]->style,"gravity") != 0) error->all(FLERR,"Fix rigid gravity fix is invalid"); int tmp; gvec = (double *) modify->fix[ifix]->extract("gvec",tmp); } // timestep info dtv = update->dt; dtf = 0.5 * update->dt * force->ftm2v; dtq = 0.5 * update->dt; if (strstr(update->integrate_style,"respa")) step_respa = ((Respa *) update->integrate)->step; // setup rigid bodies, using current atom info. if reinitflag is not set, // do the initialization only once, b/c properties may not be re-computable // especially if overlapping particles. // do not do dynamic init if read body properties from inpfile. // this is b/c the inpfile defines the static and dynamic properties and may // not be computable if contain overlapping particles. // setup_bodies_static() reads inpfile itself if (reinitflag || !setupflag) { setup_bodies_static(); if (!inpfile) <API key>(); setupflag = 1; } // temperature scale factor double ndof = 0.0; for (ibody = 0; ibody < nbody; ibody++) { ndof += fflag[ibody][0] + fflag[ibody][1] + fflag[ibody][2]; ndof += tflag[ibody][0] + tflag[ibody][1] + tflag[ibody][2]; } ndof -= nlinear; if (ndof > 0.0) tfactor = force->mvv2e / (ndof * force->boltz); else tfactor = 0.0; } void FixRigid::setup_pre_neighbor() { pre_neighbor(); } void FixRigid::setup(int vflag) { int i,n,ibody; // fcm = force on center-of-mass of each rigid body double **f = atom->f; int nlocal = atom->nlocal; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; sum[ibody][0] += f[i][0]; sum[ibody][1] += f[i][1]; sum[ibody][2] += f[i][2]; } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); for (ibody = 0; ibody < nbody; ibody++) { fcm[ibody][0] = all[ibody][0]; fcm[ibody][1] = all[ibody][1]; fcm[ibody][2] = all[ibody][2]; } // torque = torque on each rigid body double **x = atom->x; double dx,dy,dz; double unwrap[3]; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; domain->unmap(x[i],xcmimage[i],unwrap); dx = unwrap[0] - xcm[ibody][0]; dy = unwrap[1] - xcm[ibody][1]; dz = unwrap[2] - xcm[ibody][2]; sum[ibody][0] += dy * f[i][2] - dz * f[i][1]; sum[ibody][1] += dz * f[i][0] - dx * f[i][2]; sum[ibody][2] += dx * f[i][1] - dy * f[i][0]; } // extended particles add their torque to torque of body if (extended) { double **torque_one = atom->torque; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (eflags[i] & TORQUE) { sum[ibody][0] += torque_one[i][0]; sum[ibody][1] += torque_one[i][1]; sum[ibody][2] += torque_one[i][2]; } } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); for (ibody = 0; ibody < nbody; ibody++) { torque[ibody][0] = all[ibody][0]; torque[ibody][1] = all[ibody][1]; torque[ibody][2] = all[ibody][2]; } // zero langextra in case Langevin thermostat not used // no point to calling post_force() here since langextra // is only added to fcm/torque in final_integrate() for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) langextra[ibody][i] = 0.0; // virial setup before call to set_v if (vflag) v_setup(vflag); else evflag = 0; // set velocities from angmom & omega for (ibody = 0; ibody < nbody; ibody++) MathExtra::angmom_to_omega(angmom[ibody],ex_space[ibody],ey_space[ibody], ez_space[ibody],inertia[ibody],omega[ibody]); set_v(); // guesstimate virial as 2x the set_v contribution if (vflag_global) for (n = 0; n < 6; n++) virial[n] *= 2.0; if (vflag_atom) { for (i = 0; i < nlocal; i++) for (n = 0; n < 6; n++) vatom[i][n] *= 2.0; } } void FixRigid::initial_integrate(int vflag) { double dtfm; for (int ibody = 0; ibody < nbody; ibody++) { // update vcm by 1/2 step dtfm = dtf / masstotal[ibody]; vcm[ibody][0] += dtfm * fcm[ibody][0] * fflag[ibody][0]; vcm[ibody][1] += dtfm * fcm[ibody][1] * fflag[ibody][1]; vcm[ibody][2] += dtfm * fcm[ibody][2] * fflag[ibody][2]; // update xcm by full step xcm[ibody][0] += dtv * vcm[ibody][0]; xcm[ibody][1] += dtv * vcm[ibody][1]; xcm[ibody][2] += dtv * vcm[ibody][2]; // update angular momentum by 1/2 step angmom[ibody][0] += dtf * torque[ibody][0] * tflag[ibody][0]; angmom[ibody][1] += dtf * torque[ibody][1] * tflag[ibody][1]; angmom[ibody][2] += dtf * torque[ibody][2] * tflag[ibody][2]; // compute omega at 1/2 step from angmom at 1/2 step and current q // update quaternion a full step via Richardson iteration // returns new normalized quaternion, also updated omega at 1/2 step // update ex,ey,ez to reflect new quaternion MathExtra::angmom_to_omega(angmom[ibody],ex_space[ibody],ey_space[ibody], ez_space[ibody],inertia[ibody],omega[ibody]); MathExtra::richardson(quat[ibody],angmom[ibody],omega[ibody], inertia[ibody],dtq); MathExtra::q_to_exyz(quat[ibody], ex_space[ibody],ey_space[ibody],ez_space[ibody]); } // virial setup before call to set_xv if (vflag) v_setup(vflag); else evflag = 0; // set coords/orient and velocity/rotation of atoms in rigid bodies // from quarternion and omega set_xv(); } void FixRigid::<API key>() { if (me == 0) { double gamma1,gamma2; double delta = update->ntimestep - update->beginstep; if (delta != 0.0) delta /= update->endstep - update->beginstep; t_target = t_start + delta * (t_stop-t_start); double tsqrt = sqrt(t_target); double boltz = force->boltz; double dt = update->dt; double mvv2e = force->mvv2e; double ftm2v = force->ftm2v; for (int i = 0; i < nbody; i++) { gamma1 = -masstotal[i] / t_period / ftm2v; gamma2 = sqrt(masstotal[i]) * tsqrt * sqrt(24.0*boltz/t_period/dt/mvv2e) / ftm2v; langextra[i][0] = gamma1*vcm[i][0] + gamma2*(random->uniform()-0.5); langextra[i][1] = gamma1*vcm[i][1] + gamma2*(random->uniform()-0.5); langextra[i][2] = gamma1*vcm[i][2] + gamma2*(random->uniform()-0.5); gamma1 = -1.0 / t_period / ftm2v; gamma2 = tsqrt * sqrt(24.0*boltz/t_period/dt/mvv2e) / ftm2v; langextra[i][3] = inertia[i][0]*gamma1*omega[i][0] + sqrt(inertia[i][0])*gamma2*(random->uniform()-0.5); langextra[i][4] = inertia[i][1]*gamma1*omega[i][1] + sqrt(inertia[i][1])*gamma2*(random->uniform()-0.5); langextra[i][5] = inertia[i][2]*gamma1*omega[i][2] + sqrt(inertia[i][2])*gamma2*(random->uniform()-0.5); } } MPI_Bcast(&langextra[0][0],6*nbody,MPI_DOUBLE,0,world); } void FixRigid::enforce2d() { for (int ibody = 0; ibody < nbody; ibody++) { xcm[ibody][2] = 0.0; vcm[ibody][2] = 0.0; fcm[ibody][2] = 0.0; torque[ibody][0] = 0.0; torque[ibody][1] = 0.0; angmom[ibody][0] = 0.0; angmom[ibody][1] = 0.0; omega[ibody][0] = 0.0; omega[ibody][1] = 0.0; if (langflag && langextra) { langextra[ibody][2] = 0.0; langextra[ibody][3] = 0.0; langextra[ibody][4] = 0.0; } } } void FixRigid::<API key>() { int i,ibody; // sum over atoms to get force and torque on rigid body double **x = atom->x; double **f = atom->f; int nlocal = atom->nlocal; double dx,dy,dz; double unwrap[3]; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; sum[ibody][0] += f[i][0]; sum[ibody][1] += f[i][1]; sum[ibody][2] += f[i][2]; domain->unmap(x[i],xcmimage[i],unwrap); dx = unwrap[0] - xcm[ibody][0]; dy = unwrap[1] - xcm[ibody][1]; dz = unwrap[2] - xcm[ibody][2]; sum[ibody][3] += dy*f[i][2] - dz*f[i][1]; sum[ibody][4] += dz*f[i][0] - dx*f[i][2]; sum[ibody][5] += dx*f[i][1] - dy*f[i][0]; } // extended particles add their torque to torque of body if (extended) { double **torque_one = atom->torque; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (eflags[i] & TORQUE) { sum[ibody][3] += torque_one[i][0]; sum[ibody][4] += torque_one[i][1]; sum[ibody][5] += torque_one[i][2]; } } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); // include Langevin thermostat forces for (ibody = 0; ibody < nbody; ibody++) { fcm[ibody][0] = all[ibody][0] + langextra[ibody][0]; fcm[ibody][1] = all[ibody][1] + langextra[ibody][1]; fcm[ibody][2] = all[ibody][2] + langextra[ibody][2]; torque[ibody][0] = all[ibody][3] + langextra[ibody][3]; torque[ibody][1] = all[ibody][4] + langextra[ibody][4]; torque[ibody][2] = all[ibody][5] + langextra[ibody][5]; } // add gravity force to COM of each body if (id_gravity) { for (ibody = 0; ibody < nbody; ibody++) { fcm[ibody][0] += gvec[0]*masstotal[ibody]; fcm[ibody][1] += gvec[1]*masstotal[ibody]; fcm[ibody][2] += gvec[2]*masstotal[ibody]; } } } void FixRigid::post_force(int /*vflag*/) { if (langflag) <API key>(); if (earlyflag) <API key>(); } void FixRigid::final_integrate() { int ibody; double dtfm; if (!earlyflag) <API key>(); // update vcm and angmom // fflag,tflag = 0 for some dimensions in 2d for (ibody = 0; ibody < nbody; ibody++) { // update vcm by 1/2 step dtfm = dtf / masstotal[ibody]; vcm[ibody][0] += dtfm * fcm[ibody][0] * fflag[ibody][0]; vcm[ibody][1] += dtfm * fcm[ibody][1] * fflag[ibody][1]; vcm[ibody][2] += dtfm * fcm[ibody][2] * fflag[ibody][2]; // update angular momentum by 1/2 step angmom[ibody][0] += dtf * torque[ibody][0] * tflag[ibody][0]; angmom[ibody][1] += dtf * torque[ibody][1] * tflag[ibody][1]; angmom[ibody][2] += dtf * torque[ibody][2] * tflag[ibody][2]; MathExtra::angmom_to_omega(angmom[ibody],ex_space[ibody],ey_space[ibody], ez_space[ibody],inertia[ibody],omega[ibody]); } // set velocity/rotation of atoms in rigid bodies // virial is already setup from initial_integrate set_v(); } void FixRigid::<API key>(int vflag, int ilevel, int /*iloop*/) { dtv = step_respa[ilevel]; dtf = 0.5 * step_respa[ilevel] * force->ftm2v; dtq = 0.5 * step_respa[ilevel]; if (ilevel == 0) initial_integrate(vflag); else final_integrate(); } void FixRigid::<API key>(int ilevel, int /*iloop*/) { dtf = 0.5 * step_respa[ilevel] * force->ftm2v; final_integrate(); } void FixRigid::pre_neighbor() { for (int ibody = 0; ibody < nbody; ibody++) domain->remap(xcm[ibody],imagebody[ibody]); image_shift(); } void FixRigid::image_shift() { int ibody; imageint tdim,bdim,xdim[3]; imageint *image = atom->image; int nlocal = atom->nlocal; for (int i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; tdim = image[i] & IMGMASK; bdim = imagebody[ibody] & IMGMASK; xdim[0] = IMGMAX + tdim - bdim; tdim = (image[i] >> IMGBITS) & IMGMASK; bdim = (imagebody[ibody] >> IMGBITS) & IMGMASK; xdim[1] = IMGMAX + tdim - bdim; tdim = image[i] >> IMG2BITS; bdim = imagebody[ibody] >> IMG2BITS; xdim[2] = IMGMAX + tdim - bdim; xcmimage[i] = (xdim[2] << IMG2BITS) | (xdim[1] << IMGBITS) | xdim[0]; } } int FixRigid::dof(int tgroup) { // cannot count DOF correctly unless setup_bodies_static() has been called if (!setupflag) { if (comm->me == 0) error->warning(FLERR,"Cannot count rigid body degrees-of-freedom " "before bodies are initialized"); return 0; } int tgroupbit = group->bitmask[tgroup]; // nall = # of point particles in each rigid body // mall = # of finite-size particles in each rigid body // particles must also be in temperature group int *mask = atom->mask; int nlocal = atom->nlocal; int *ncount = new int[nbody]; int *mcount = new int[nbody]; for (int ibody = 0; ibody < nbody; ibody++) ncount[ibody] = mcount[ibody] = 0; for (int i = 0; i < nlocal; i++) if (body[i] >= 0 && mask[i] & tgroupbit) { // do not count point particles or point dipoles as extended particles // a spheroid dipole will be counted as extended if (extended && (eflags[i] & ~(POINT | DIPOLE))) mcount[body[i]]++; else ncount[body[i]]++; } int *nall = new int[nbody]; int *mall = new int[nbody]; MPI_Allreduce(ncount,nall,nbody,MPI_INT,MPI_SUM,world); MPI_Allreduce(mcount,mall,nbody,MPI_INT,MPI_SUM,world); // warn if nall+mall != nrigid for any body included in temperature group int flag = 0; for (int ibody = 0; ibody < nbody; ibody++) { if (nall[ibody]+mall[ibody] > 0 && nall[ibody]+mall[ibody] != nrigid[ibody]) flag = 1; } if (flag && me == 0) error->warning(FLERR,"Computing temperature of portions of rigid bodies"); // remove appropriate DOFs for each rigid body wholly in temperature group // N = # of point particles in body // M = # of finite-size particles in body // 3d body has 3N + 6M dof to start with // 2d body has 2N + 3M dof to start with // 3d point-particle body with all non-zero I should have 6 dof, remove 3N-6 // 3d point-particle body (linear) with a 0 I should have 5 dof, remove 3N-5 // 2d point-particle body should have 3 dof, remove 2N-3 // 3d body with any finite-size M should have 6 dof, remove (3N+6M) - 6 // 2d body with any finite-size M should have 3 dof, remove (2N+3M) - 3 int n = 0; nlinear = 0; if (domain->dimension == 3) { for (int ibody = 0; ibody < nbody; ibody++) if (nall[ibody]+mall[ibody] == nrigid[ibody]) { n += 3*nall[ibody] + 6*mall[ibody] - 6; if (inertia[ibody][0] == 0.0 || inertia[ibody][1] == 0.0 || inertia[ibody][2] == 0.0) { n++; nlinear++; } } } else if (domain->dimension == 2) { for (int ibody = 0; ibody < nbody; ibody++) if (nall[ibody]+mall[ibody] == nrigid[ibody]) n += 2*nall[ibody] + 3*mall[ibody] - 3; } delete [] ncount; delete [] mcount; delete [] nall; delete [] mall; return n; } void FixRigid::deform(int flag) { if (flag == 0) for (int ibody = 0; ibody < nbody; ibody++) domain->x2lamda(xcm[ibody],xcm[ibody]); else for (int ibody = 0; ibody < nbody; ibody++) domain->lamda2x(xcm[ibody],xcm[ibody]); } void FixRigid::set_xv() { int ibody; int xbox,ybox,zbox; double x0,x1,x2,v0,v1,v2,fc0,fc1,fc2,massone; double xy,xz,yz; double ione[3],exone[3],eyone[3],ezone[3],vr[6],p[3][3]; double **x = atom->x; double **v = atom->v; double **f = atom->f; double *rmass = atom->rmass; double *mass = atom->mass; int *type = atom->type; int nlocal = atom->nlocal; double xprd = domain->xprd; double yprd = domain->yprd; double zprd = domain->zprd; if (triclinic) { xy = domain->xy; xz = domain->xz; yz = domain->yz; } // set x and v of each atom for (int i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; xbox = (xcmimage[i] & IMGMASK) - IMGMAX; ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX; // save old positions and velocities for virial if (evflag) { if (triclinic == 0) { x0 = x[i][0] + xbox*xprd; x1 = x[i][1] + ybox*yprd; x2 = x[i][2] + zbox*zprd; } else { x0 = x[i][0] + xbox*xprd + ybox*xy + zbox*xz; x1 = x[i][1] + ybox*yprd + zbox*yz; x2 = x[i][2] + zbox*zprd; } v0 = v[i][0]; v1 = v[i][1]; v2 = v[i][2]; } // x = displacement from center-of-mass, based on body orientation // v = vcm + omega around center-of-mass MathExtra::matvec(ex_space[ibody],ey_space[ibody], ez_space[ibody],displace[i],x[i]); v[i][0] = omega[ibody][1]*x[i][2] - omega[ibody][2]*x[i][1] + vcm[ibody][0]; v[i][1] = omega[ibody][2]*x[i][0] - omega[ibody][0]*x[i][2] + vcm[ibody][1]; v[i][2] = omega[ibody][0]*x[i][1] - omega[ibody][1]*x[i][0] + vcm[ibody][2]; // add center of mass to displacement // map back into periodic box via xbox,ybox,zbox // for triclinic, add in box tilt factors as well if (triclinic == 0) { x[i][0] += xcm[ibody][0] - xbox*xprd; x[i][1] += xcm[ibody][1] - ybox*yprd; x[i][2] += xcm[ibody][2] - zbox*zprd; } else { x[i][0] += xcm[ibody][0] - xbox*xprd - ybox*xy - zbox*xz; x[i][1] += xcm[ibody][1] - ybox*yprd - zbox*yz; x[i][2] += xcm[ibody][2] - zbox*zprd; } // virial = unwrapped coords dotted into body constraint force // body constraint force = implied force due to v change minus f external // assume f does not include forces internal to body // 1/2 factor b/c final_integrate contributes other half // assume per-atom contribution is due to constraint force on that atom if (evflag) { if (rmass) massone = rmass[i]; else massone = mass[type[i]]; fc0 = massone*(v[i][0] - v0)/dtf - f[i][0]; fc1 = massone*(v[i][1] - v1)/dtf - f[i][1]; fc2 = massone*(v[i][2] - v2)/dtf - f[i][2]; vr[0] = 0.5*x0*fc0; vr[1] = 0.5*x1*fc1; vr[2] = 0.5*x2*fc2; vr[3] = 0.5*x0*fc1; vr[4] = 0.5*x0*fc2; vr[5] = 0.5*x1*fc2; v_tally(1,&i,1.0,vr); } } // set orientation, omega, angmom of each extended particle if (extended) { double theta_body,theta; double *shape,*quatatom,*inertiaatom; AtomVecEllipsoid::Bonus *ebonus; if (avec_ellipsoid) ebonus = avec_ellipsoid->bonus; AtomVecLine::Bonus *lbonus; if (avec_line) lbonus = avec_line->bonus; AtomVecTri::Bonus *tbonus; if (avec_tri) tbonus = avec_tri->bonus; double **omega_one = atom->omega; double **angmom_one = atom->angmom; double **mu = atom->mu; int *ellipsoid = atom->ellipsoid; int *line = atom->line; int *tri = atom->tri; for (int i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (eflags[i] & SPHERE) { omega_one[i][0] = omega[ibody][0]; omega_one[i][1] = omega[ibody][1]; omega_one[i][2] = omega[ibody][2]; } else if (eflags[i] & ELLIPSOID) { shape = ebonus[ellipsoid[i]].shape; quatatom = ebonus[ellipsoid[i]].quat; MathExtra::quatquat(quat[ibody],orient[i],quatatom); MathExtra::qnormalize(quatatom); ione[0] = EINERTIA*rmass[i] * (shape[1]*shape[1] + shape[2]*shape[2]); ione[1] = EINERTIA*rmass[i] * (shape[0]*shape[0] + shape[2]*shape[2]); ione[2] = EINERTIA*rmass[i] * (shape[0]*shape[0] + shape[1]*shape[1]); MathExtra::q_to_exyz(quatatom,exone,eyone,ezone); MathExtra::omega_to_angmom(omega[ibody],exone,eyone,ezone,ione, angmom_one[i]); } else if (eflags[i] & LINE) { if (quat[ibody][3] >= 0.0) theta_body = 2.0*acos(quat[ibody][0]); else theta_body = -2.0*acos(quat[ibody][0]); theta = orient[i][0] + theta_body; while (theta <= -MY_PI) theta += MY_2PI; while (theta > MY_PI) theta -= MY_2PI; lbonus[line[i]].theta = theta; omega_one[i][0] = omega[ibody][0]; omega_one[i][1] = omega[ibody][1]; omega_one[i][2] = omega[ibody][2]; } else if (eflags[i] & TRIANGLE) { inertiaatom = tbonus[tri[i]].inertia; quatatom = tbonus[tri[i]].quat; MathExtra::quatquat(quat[ibody],orient[i],quatatom); MathExtra::qnormalize(quatatom); MathExtra::q_to_exyz(quatatom,exone,eyone,ezone); MathExtra::omega_to_angmom(omega[ibody],exone,eyone,ezone, inertiaatom,angmom_one[i]); } if (eflags[i] & DIPOLE) { MathExtra::quat_to_mat(quat[ibody],p); MathExtra::matvec(p,dorient[i],mu[i]); MathExtra::snormalize3(mu[i][3],mu[i],mu[i]); } } } } void FixRigid::set_v() { int xbox,ybox,zbox; double x0,x1,x2,v0,v1,v2,fc0,fc1,fc2,massone; double xy,xz,yz; double ione[3],exone[3],eyone[3],ezone[3],delta[3],vr[6]; double **x = atom->x; double **v = atom->v; double **f = atom->f; double *rmass = atom->rmass; double *mass = atom->mass; int *type = atom->type; int nlocal = atom->nlocal; double xprd = domain->xprd; double yprd = domain->yprd; double zprd = domain->zprd; if (triclinic) { xy = domain->xy; xz = domain->xz; yz = domain->yz; } // set v of each atom for (int i = 0; i < nlocal; i++) { if (body[i] < 0) continue; const int ibody = body[i]; MathExtra::matvec(ex_space[ibody],ey_space[ibody], ez_space[ibody],displace[i],delta); // save old velocities for virial if (evflag) { v0 = v[i][0]; v1 = v[i][1]; v2 = v[i][2]; } v[i][0] = omega[ibody][1]*delta[2] - omega[ibody][2]*delta[1] + vcm[ibody][0]; v[i][1] = omega[ibody][2]*delta[0] - omega[ibody][0]*delta[2] + vcm[ibody][1]; v[i][2] = omega[ibody][0]*delta[1] - omega[ibody][1]*delta[0] + vcm[ibody][2]; // virial = unwrapped coords dotted into body constraint force // body constraint force = implied force due to v change minus f external // assume f does not include forces internal to body // 1/2 factor b/c initial_integrate contributes other half // assume per-atom contribution is due to constraint force on that atom if (evflag) { if (rmass) massone = rmass[i]; else massone = mass[type[i]]; fc0 = massone*(v[i][0] - v0)/dtf - f[i][0]; fc1 = massone*(v[i][1] - v1)/dtf - f[i][1]; fc2 = massone*(v[i][2] - v2)/dtf - f[i][2]; xbox = (xcmimage[i] & IMGMASK) - IMGMAX; ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX; if (triclinic == 0) { x0 = x[i][0] + xbox*xprd; x1 = x[i][1] + ybox*yprd; x2 = x[i][2] + zbox*zprd; } else { x0 = x[i][0] + xbox*xprd + ybox*xy + zbox*xz; x1 = x[i][1] + ybox*yprd + zbox*yz; x2 = x[i][2] + zbox*zprd; } vr[0] = 0.5*x0*fc0; vr[1] = 0.5*x1*fc1; vr[2] = 0.5*x2*fc2; vr[3] = 0.5*x0*fc1; vr[4] = 0.5*x0*fc2; vr[5] = 0.5*x1*fc2; v_tally(1,&i,1.0,vr); } } // set omega, angmom of each extended particle if (extended) { double *shape,*quatatom,*inertiaatom; AtomVecEllipsoid::Bonus *ebonus; if (avec_ellipsoid) ebonus = avec_ellipsoid->bonus; AtomVecTri::Bonus *tbonus; if (avec_tri) tbonus = avec_tri->bonus; double **omega_one = atom->omega; double **angmom_one = atom->angmom; int *ellipsoid = atom->ellipsoid; int *tri = atom->tri; for (int i = 0; i < nlocal; i++) { if (body[i] < 0) continue; const int ibody = body[i]; if (eflags[i] & SPHERE) { omega_one[i][0] = omega[ibody][0]; omega_one[i][1] = omega[ibody][1]; omega_one[i][2] = omega[ibody][2]; } else if (eflags[i] & ELLIPSOID) { shape = ebonus[ellipsoid[i]].shape; quatatom = ebonus[ellipsoid[i]].quat; ione[0] = EINERTIA*rmass[i] * (shape[1]*shape[1] + shape[2]*shape[2]); ione[1] = EINERTIA*rmass[i] * (shape[0]*shape[0] + shape[2]*shape[2]); ione[2] = EINERTIA*rmass[i] * (shape[0]*shape[0] + shape[1]*shape[1]); MathExtra::q_to_exyz(quatatom,exone,eyone,ezone); MathExtra::omega_to_angmom(omega[ibody],exone,eyone,ezone,ione, angmom_one[i]); } else if (eflags[i] & LINE) { omega_one[i][0] = omega[ibody][0]; omega_one[i][1] = omega[ibody][1]; omega_one[i][2] = omega[ibody][2]; } else if (eflags[i] & TRIANGLE) { inertiaatom = tbonus[tri[i]].inertia; quatatom = tbonus[tri[i]].quat; MathExtra::q_to_exyz(quatatom,exone,eyone,ezone); MathExtra::omega_to_angmom(omega[ibody],exone,eyone,ezone, inertiaatom,angmom_one[i]); } } } } void FixRigid::setup_bodies_static() { int i,ibody; // extended = 1 if any particle in a rigid body is finite size // or has a dipole moment extended = orientflag = dorientflag = 0; AtomVecEllipsoid::Bonus *ebonus; if (avec_ellipsoid) ebonus = avec_ellipsoid->bonus; AtomVecLine::Bonus *lbonus; if (avec_line) lbonus = avec_line->bonus; AtomVecTri::Bonus *tbonus; if (avec_tri) tbonus = avec_tri->bonus; double **mu = atom->mu; double *radius = atom->radius; double *rmass = atom->rmass; double *mass = atom->mass; int *ellipsoid = atom->ellipsoid; int *line = atom->line; int *tri = atom->tri; int *type = atom->type; int nlocal = atom->nlocal; if (atom->radius_flag || atom->ellipsoid_flag || atom->line_flag || atom->tri_flag || atom->mu_flag) { int flag = 0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; if (radius && radius[i] > 0.0) flag = 1; if (ellipsoid && ellipsoid[i] >= 0) flag = 1; if (line && line[i] >= 0) flag = 1; if (tri && tri[i] >= 0) flag = 1; if (mu && mu[i][3] > 0.0) flag = 1; } MPI_Allreduce(&flag,&extended,1,MPI_INT,MPI_MAX,world); } // grow extended arrays and set extended flags for each particle // orientflag = 4 if any particle stores ellipsoid or tri orientation // orientflag = 1 if any particle stores line orientation // dorientflag = 1 if any particle stores dipole orientation if (extended) { if (atom->ellipsoid_flag) orientflag = 4; if (atom->line_flag) orientflag = 1; if (atom->tri_flag) orientflag = 4; if (atom->mu_flag) dorientflag = 1; grow_arrays(atom->nmax); for (i = 0; i < nlocal; i++) { eflags[i] = 0; if (body[i] < 0) continue; // set to POINT or SPHERE or ELLIPSOID or LINE if (radius && radius[i] > 0.0) { eflags[i] |= SPHERE; eflags[i] |= OMEGA; eflags[i] |= TORQUE; } else if (ellipsoid && ellipsoid[i] >= 0) { eflags[i] |= ELLIPSOID; eflags[i] |= ANGMOM; eflags[i] |= TORQUE; } else if (line && line[i] >= 0) { eflags[i] |= LINE; eflags[i] |= OMEGA; eflags[i] |= TORQUE; } else if (tri && tri[i] >= 0) { eflags[i] |= TRIANGLE; eflags[i] |= ANGMOM; eflags[i] |= TORQUE; } else eflags[i] |= POINT; // set DIPOLE if atom->mu and mu[3] > 0.0 if (atom->mu_flag && mu[i][3] > 0.0) eflags[i] |= DIPOLE; } } // set body xcmimage flags = true image flags imageint *image = atom->image; for (i = 0; i < nlocal; i++) if (body[i] >= 0) xcmimage[i] = image[i]; else xcmimage[i] = 0; // compute masstotal & center-of-mass of each rigid body // error if image flag is not 0 in a non-periodic dim double **x = atom->x; int *periodicity = domain->periodicity; double xprd = domain->xprd; double yprd = domain->yprd; double zprd = domain->zprd; double xy = domain->xy; double xz = domain->xz; double yz = domain->yz; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; int xbox,ybox,zbox; double massone,xunwrap,yunwrap,zunwrap; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; xbox = (xcmimage[i] & IMGMASK) - IMGMAX; ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; if ((xbox && !periodicity[0]) || (ybox && !periodicity[1]) || (zbox && !periodicity[2])) error->one(FLERR,"Fix rigid atom has non-zero image flag " "in a non-periodic dimension"); if (triclinic == 0) { xunwrap = x[i][0] + xbox*xprd; yunwrap = x[i][1] + ybox*yprd; zunwrap = x[i][2] + zbox*zprd; } else { xunwrap = x[i][0] + xbox*xprd + ybox*xy + zbox*xz; yunwrap = x[i][1] + ybox*yprd + zbox*yz; zunwrap = x[i][2] + zbox*zprd; } sum[ibody][0] += xunwrap * massone; sum[ibody][1] += yunwrap * massone; sum[ibody][2] += zunwrap * massone; sum[ibody][3] += massone; } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); for (ibody = 0; ibody < nbody; ibody++) { masstotal[ibody] = all[ibody][3]; xcm[ibody][0] = all[ibody][0]/masstotal[ibody]; xcm[ibody][1] = all[ibody][1]/masstotal[ibody]; xcm[ibody][2] = all[ibody][2]/masstotal[ibody]; } // set vcm, angmom = 0.0 in case inpfile is used // and doesn't overwrite all body's values // since <API key>() will not be called for (ibody = 0; ibody < nbody; ibody++) { vcm[ibody][0] = vcm[ibody][1] = vcm[ibody][2] = 0.0; angmom[ibody][0] = angmom[ibody][1] = angmom[ibody][2] = 0.0; } // set rigid body image flags to default values for (ibody = 0; ibody < nbody; ibody++) imagebody[ibody] = ((imageint) IMGMAX << IMG2BITS) | ((imageint) IMGMAX << IMGBITS) | IMGMAX; // overwrite masstotal, center-of-mass, image flags with file values // inbody[i] = 0/1 if Ith rigid body is initialized by file int *inbody; if (inpfile) { memory->create(inbody,nbody,"rigid:inbody"); for (ibody = 0; ibody < nbody; ibody++) inbody[ibody] = 0; readfile(0,masstotal,xcm,vcm,angmom,imagebody,inbody); } // remap the xcm of each body back into simulation box // and reset body and atom xcmimage flags via pre_neighbor() pre_neighbor(); // compute 6 moments of inertia of each body in Cartesian reference frame // dx,dy,dz = coords relative to center-of-mass // symmetric 3x3 inertia tensor stored in Voigt notation as 6-vector double dx,dy,dz; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; xbox = (xcmimage[i] & IMGMASK) - IMGMAX; ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX; if (triclinic == 0) { xunwrap = x[i][0] + xbox*xprd; yunwrap = x[i][1] + ybox*yprd; zunwrap = x[i][2] + zbox*zprd; } else { xunwrap = x[i][0] + xbox*xprd + ybox*xy + zbox*xz; yunwrap = x[i][1] + ybox*yprd + zbox*yz; zunwrap = x[i][2] + zbox*zprd; } dx = xunwrap - xcm[ibody][0]; dy = yunwrap - xcm[ibody][1]; dz = zunwrap - xcm[ibody][2]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; sum[ibody][0] += massone * (dy*dy + dz*dz); sum[ibody][1] += massone * (dx*dx + dz*dz); sum[ibody][2] += massone * (dx*dx + dy*dy); sum[ibody][3] -= massone * dy*dz; sum[ibody][4] -= massone * dx*dz; sum[ibody][5] -= massone * dx*dy; } // extended particles may contribute extra terms to moments of inertia if (extended) { double ivec[6]; double *shape,*quatatom,*inertiaatom; double length,theta; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; if (eflags[i] & SPHERE) { sum[ibody][0] += SINERTIA*massone * radius[i]*radius[i]; sum[ibody][1] += SINERTIA*massone * radius[i]*radius[i]; sum[ibody][2] += SINERTIA*massone * radius[i]*radius[i]; } else if (eflags[i] & ELLIPSOID) { shape = ebonus[ellipsoid[i]].shape; quatatom = ebonus[ellipsoid[i]].quat; MathExtra::inertia_ellipsoid(shape,quatatom,massone,ivec); sum[ibody][0] += ivec[0]; sum[ibody][1] += ivec[1]; sum[ibody][2] += ivec[2]; sum[ibody][3] += ivec[3]; sum[ibody][4] += ivec[4]; sum[ibody][5] += ivec[5]; } else if (eflags[i] & LINE) { length = lbonus[line[i]].length; theta = lbonus[line[i]].theta; MathExtra::inertia_line(length,theta,massone,ivec); sum[ibody][0] += ivec[0]; sum[ibody][1] += ivec[1]; sum[ibody][2] += ivec[2]; sum[ibody][3] += ivec[3]; sum[ibody][4] += ivec[4]; sum[ibody][5] += ivec[5]; } else if (eflags[i] & TRIANGLE) { inertiaatom = tbonus[tri[i]].inertia; quatatom = tbonus[tri[i]].quat; MathExtra::inertia_triangle(inertiaatom,quatatom,massone,ivec); sum[ibody][0] += ivec[0]; sum[ibody][1] += ivec[1]; sum[ibody][2] += ivec[2]; sum[ibody][3] += ivec[3]; sum[ibody][4] += ivec[4]; sum[ibody][5] += ivec[5]; } } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); // overwrite Cartesian inertia tensor with file values if (inpfile) readfile(1,NULL,all,NULL,NULL,NULL,inbody); // diagonalize inertia tensor for each body via Jacobi rotations // inertia = 3 eigenvalues = principal moments of inertia // evectors and exzy_space = 3 evectors = principal axes of rigid body int ierror; double cross[3]; double tensor[3][3],evectors[3][3]; for (ibody = 0; ibody < nbody; ibody++) { tensor[0][0] = all[ibody][0]; tensor[1][1] = all[ibody][1]; tensor[2][2] = all[ibody][2]; tensor[1][2] = tensor[2][1] = all[ibody][3]; tensor[0][2] = tensor[2][0] = all[ibody][4]; tensor[0][1] = tensor[1][0] = all[ibody][5]; ierror = MathExtra::jacobi(tensor,inertia[ibody],evectors); if (ierror) error->all(FLERR, "Insufficient Jacobi rotations for rigid body"); ex_space[ibody][0] = evectors[0][0]; ex_space[ibody][1] = evectors[1][0]; ex_space[ibody][2] = evectors[2][0]; ey_space[ibody][0] = evectors[0][1]; ey_space[ibody][1] = evectors[1][1]; ey_space[ibody][2] = evectors[2][1]; ez_space[ibody][0] = evectors[0][2]; ez_space[ibody][1] = evectors[1][2]; ez_space[ibody][2] = evectors[2][2]; // if any principal moment < scaled EPSILON, set to 0.0 double max; max = MAX(inertia[ibody][0],inertia[ibody][1]); max = MAX(max,inertia[ibody][2]); if (inertia[ibody][0] < EPSILON*max) inertia[ibody][0] = 0.0; if (inertia[ibody][1] < EPSILON*max) inertia[ibody][1] = 0.0; if (inertia[ibody][2] < EPSILON*max) inertia[ibody][2] = 0.0; // enforce 3 evectors as a right-handed coordinate system // flip 3rd vector if needed MathExtra::cross3(ex_space[ibody],ey_space[ibody],cross); if (MathExtra::dot3(cross,ez_space[ibody]) < 0.0) MathExtra::negate3(ez_space[ibody]); // create initial quaternion MathExtra::exyz_to_q(ex_space[ibody],ey_space[ibody],ez_space[ibody], quat[ibody]); } // displace = initial atom coords in basis of principal axes // set displace = 0.0 for atoms not in any rigid body // for extended particles, set their orientation wrt to rigid body double qc[4],delta[3]; double *quatatom; double theta_body; for (i = 0; i < nlocal; i++) { if (body[i] < 0) { displace[i][0] = displace[i][1] = displace[i][2] = 0.0; continue; } ibody = body[i]; xbox = (xcmimage[i] & IMGMASK) - IMGMAX; ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX; if (triclinic == 0) { xunwrap = x[i][0] + xbox*xprd; yunwrap = x[i][1] + ybox*yprd; zunwrap = x[i][2] + zbox*zprd; } else { xunwrap = x[i][0] + xbox*xprd + ybox*xy + zbox*xz; yunwrap = x[i][1] + ybox*yprd + zbox*yz; zunwrap = x[i][2] + zbox*zprd; } delta[0] = xunwrap - xcm[ibody][0]; delta[1] = yunwrap - xcm[ibody][1]; delta[2] = zunwrap - xcm[ibody][2]; MathExtra::transpose_matvec(ex_space[ibody],ey_space[ibody], ez_space[ibody],delta,displace[i]); if (extended) { if (eflags[i] & ELLIPSOID) { quatatom = ebonus[ellipsoid[i]].quat; MathExtra::qconjugate(quat[ibody],qc); MathExtra::quatquat(qc,quatatom,orient[i]); MathExtra::qnormalize(orient[i]); } else if (eflags[i] & LINE) { if (quat[ibody][3] >= 0.0) theta_body = 2.0*acos(quat[ibody][0]); else theta_body = -2.0*acos(quat[ibody][0]); orient[i][0] = lbonus[line[i]].theta - theta_body; while (orient[i][0] <= -MY_PI) orient[i][0] += MY_2PI; while (orient[i][0] > MY_PI) orient[i][0] -= MY_2PI; if (orientflag == 4) orient[i][1] = orient[i][2] = orient[i][3] = 0.0; } else if (eflags[i] & TRIANGLE) { quatatom = tbonus[tri[i]].quat; MathExtra::qconjugate(quat[ibody],qc); MathExtra::quatquat(qc,quatatom,orient[i]); MathExtra::qnormalize(orient[i]); } else if (orientflag == 4) { orient[i][0] = orient[i][1] = orient[i][2] = orient[i][3] = 0.0; } else if (orientflag == 1) orient[i][0] = 0.0; if (eflags[i] & DIPOLE) { MathExtra::transpose_matvec(ex_space[ibody],ey_space[ibody], ez_space[ibody],mu[i],dorient[i]); MathExtra::snormalize3(mu[i][3],dorient[i],dorient[i]); } else if (dorientflag) dorient[i][0] = dorient[i][1] = dorient[i][2] = 0.0; } } // test for valid principal moments & axes // recompute moments of inertia around new axes // 3 diagonal moments should equal principal moments // 3 off-diagonal moments should be 0.0 // extended particles may contribute extra terms to moments of inertia for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; sum[ibody][0] += massone * (displace[i][1]*displace[i][1] + displace[i][2]*displace[i][2]); sum[ibody][1] += massone * (displace[i][0]*displace[i][0] + displace[i][2]*displace[i][2]); sum[ibody][2] += massone * (displace[i][0]*displace[i][0] + displace[i][1]*displace[i][1]); sum[ibody][3] -= massone * displace[i][1]*displace[i][2]; sum[ibody][4] -= massone * displace[i][0]*displace[i][2]; sum[ibody][5] -= massone * displace[i][0]*displace[i][1]; } if (extended) { double ivec[6]; double *shape,*inertiaatom; double length; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; if (eflags[i] & SPHERE) { sum[ibody][0] += SINERTIA*massone * radius[i]*radius[i]; sum[ibody][1] += SINERTIA*massone * radius[i]*radius[i]; sum[ibody][2] += SINERTIA*massone * radius[i]*radius[i]; } else if (eflags[i] & ELLIPSOID) { shape = ebonus[ellipsoid[i]].shape; MathExtra::inertia_ellipsoid(shape,orient[i],massone,ivec); sum[ibody][0] += ivec[0]; sum[ibody][1] += ivec[1]; sum[ibody][2] += ivec[2]; sum[ibody][3] += ivec[3]; sum[ibody][4] += ivec[4]; sum[ibody][5] += ivec[5]; } else if (eflags[i] & LINE) { length = lbonus[line[i]].length; MathExtra::inertia_line(length,orient[i][0],massone,ivec); sum[ibody][0] += ivec[0]; sum[ibody][1] += ivec[1]; sum[ibody][2] += ivec[2]; sum[ibody][3] += ivec[3]; sum[ibody][4] += ivec[4]; sum[ibody][5] += ivec[5]; } else if (eflags[i] & TRIANGLE) { inertiaatom = tbonus[tri[i]].inertia; MathExtra::inertia_triangle(inertiaatom,orient[i],massone,ivec); sum[ibody][0] += ivec[0]; sum[ibody][1] += ivec[1]; sum[ibody][2] += ivec[2]; sum[ibody][3] += ivec[3]; sum[ibody][4] += ivec[4]; sum[ibody][5] += ivec[5]; } } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); // error check that re-computed moments of inertia match diagonalized ones // do not do test for bodies with params read from inpfile double norm; for (ibody = 0; ibody < nbody; ibody++) { if (inpfile && inbody[ibody]) continue; if (inertia[ibody][0] == 0.0) { if (fabs(all[ibody][0]) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } else { if (fabs((all[ibody][0]-inertia[ibody][0])/inertia[ibody][0]) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } if (inertia[ibody][1] == 0.0) { if (fabs(all[ibody][1]) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } else { if (fabs((all[ibody][1]-inertia[ibody][1])/inertia[ibody][1]) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } if (inertia[ibody][2] == 0.0) { if (fabs(all[ibody][2]) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } else { if (fabs((all[ibody][2]-inertia[ibody][2])/inertia[ibody][2]) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } norm = (inertia[ibody][0] + inertia[ibody][1] + inertia[ibody][2]) / 3.0; if (fabs(all[ibody][3]/norm) > TOLERANCE || fabs(all[ibody][4]/norm) > TOLERANCE || fabs(all[ibody][5]/norm) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } if (inpfile) memory->destroy(inbody); } void FixRigid::<API key>() { int i,ibody; double massone,radone; // vcm = velocity of center-of-mass of each rigid body // angmom = angular momentum of each rigid body double **x = atom->x; double **v = atom->v; double *rmass = atom->rmass; double *mass = atom->mass; int *type = atom->type; int nlocal = atom->nlocal; double dx,dy,dz; double unwrap[3]; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; sum[ibody][0] += v[i][0] * massone; sum[ibody][1] += v[i][1] * massone; sum[ibody][2] += v[i][2] * massone; domain->unmap(x[i],xcmimage[i],unwrap); dx = unwrap[0] - xcm[ibody][0]; dy = unwrap[1] - xcm[ibody][1]; dz = unwrap[2] - xcm[ibody][2]; sum[ibody][3] += dy * massone*v[i][2] - dz * massone*v[i][1]; sum[ibody][4] += dz * massone*v[i][0] - dx * massone*v[i][2]; sum[ibody][5] += dx * massone*v[i][1] - dy * massone*v[i][0]; } // extended particles add their rotation to angmom of body if (extended) { AtomVecLine::Bonus *lbonus; if (avec_line) lbonus = avec_line->bonus; double **omega_one = atom->omega; double **angmom_one = atom->angmom; double *radius = atom->radius; int *line = atom->line; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (eflags[i] & OMEGA) { if (eflags[i] & SPHERE) { radone = radius[i]; sum[ibody][3] += SINERTIA*rmass[i] * radone*radone * omega_one[i][0]; sum[ibody][4] += SINERTIA*rmass[i] * radone*radone * omega_one[i][1]; sum[ibody][5] += SINERTIA*rmass[i] * radone*radone * omega_one[i][2]; } else if (eflags[i] & LINE) { radone = lbonus[line[i]].length; sum[ibody][5] += LINERTIA*rmass[i] * radone*radone * omega_one[i][2]; } } if (eflags[i] & ANGMOM) { sum[ibody][3] += angmom_one[i][0]; sum[ibody][4] += angmom_one[i][1]; sum[ibody][5] += angmom_one[i][2]; } } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); // normalize velocity of COM for (ibody = 0; ibody < nbody; ibody++) { vcm[ibody][0] = all[ibody][0]/masstotal[ibody]; vcm[ibody][1] = all[ibody][1]/masstotal[ibody]; vcm[ibody][2] = all[ibody][2]/masstotal[ibody]; angmom[ibody][0] = all[ibody][3]; angmom[ibody][1] = all[ibody][4]; angmom[ibody][2] = all[ibody][5]; } } void FixRigid::readfile(int which, double *vec, double **array1, double **array2, double **array3, imageint *ivec, int *inbody) { int j,nchunk,id,eofflag,xbox,ybox,zbox; int nlines; FILE *fp; char *eof,*start,*next,*buf; char line[MAXLINE]; if (me == 0) { fp = fopen(inpfile,"r"); if (fp == NULL) { char str[128]; snprintf(str,128,"Cannot open fix rigid inpfile %s",inpfile); error->one(FLERR,str); } while (1) { eof = fgets(line,MAXLINE,fp); if (eof == NULL) error->one(FLERR,"Unexpected end of fix rigid file"); start = &line[strspn(line," \t\n\v\f\r")]; if (*start != '\0' && *start != '#') break; } sscanf(line,"%d",&nlines); } MPI_Bcast(&nlines,1,MPI_INT,0,world); if (nlines == 0) error->all(FLERR,"Fix rigid file has no lines"); char *buffer = new char[CHUNK*MAXLINE]; char **values = new char*[ATTRIBUTE_PERBODY]; int nread = 0; while (nread < nlines) { nchunk = MIN(nlines-nread,CHUNK); eofflag = comm-><API key>(fp,nchunk,MAXLINE,buffer); if (eofflag) error->all(FLERR,"Unexpected end of fix rigid file"); buf = buffer; next = strchr(buf,'\n'); *next = '\0'; int nwords = atom->count_words(buf); *next = '\n'; if (nwords != ATTRIBUTE_PERBODY) error->all(FLERR,"Incorrect rigid body format in fix rigid file"); // loop over lines of rigid body attributes // tokenize the line into values // id = rigid body ID // use ID as-is for SINGLE, as mol-ID for MOLECULE, as-is for GROUP // for which = 0, store all but inertia in vecs and arrays // for which = 1, store inertia tensor array, invert 3,4,5 values to Voigt for (int i = 0; i < nchunk; i++) { next = strchr(buf,'\n'); values[0] = strtok(buf," \t\n\r\f"); for (j = 1; j < nwords; j++) values[j] = strtok(NULL," \t\n\r\f"); id = atoi(values[0]); if (rstyle == MOLECULE) { if (id <= 0 || id > maxmol) error->all(FLERR,"Invalid rigid body ID in fix rigid file"); id = mol2body[id]; } else id if (id < 0 || id >= nbody) error->all(FLERR,"Invalid rigid body ID in fix rigid file"); inbody[id] = 1; if (which == 0) { vec[id] = atof(values[1]); array1[id][0] = atof(values[2]); array1[id][1] = atof(values[3]); array1[id][2] = atof(values[4]); array2[id][0] = atof(values[11]); array2[id][1] = atof(values[12]); array2[id][2] = atof(values[13]); array3[id][0] = atof(values[14]); array3[id][1] = atof(values[15]); array3[id][2] = atof(values[16]); xbox = atoi(values[17]); ybox = atoi(values[18]); zbox = atoi(values[19]); ivec[id] = ((imageint) (xbox + IMGMAX) & IMGMASK) | (((imageint) (ybox + IMGMAX) & IMGMASK) << IMGBITS) | (((imageint) (zbox + IMGMAX) & IMGMASK) << IMG2BITS); } else { array1[id][0] = atof(values[5]); array1[id][1] = atof(values[6]); array1[id][2] = atof(values[7]); array1[id][3] = atof(values[10]); array1[id][4] = atof(values[9]); array1[id][5] = atof(values[8]); } buf = next + 1; } nread += nchunk; } if (me == 0) fclose(fp); delete [] buffer; delete [] values; } void FixRigid::write_restart_file(char *file) { if (me) return; char outfile[128]; snprintf(outfile,128,"%s.rigid",file); FILE *fp = fopen(outfile,"w"); if (fp == NULL) { char str[192]; snprintf(str,192,"Cannot open fix rigid restart file %s",outfile); error->one(FLERR,str); } fprintf(fp,"# fix rigid mass, COM, inertia tensor info for " "%d bodies on timestep " BIGINT_FORMAT "\n\n", nbody,update->ntimestep); fprintf(fp,"%d\n",nbody); // compute I tensor against xyz axes from diagonalized I and current quat // Ispace = P Idiag P_transpose // P is stored column-wise in exyz_space int xbox,ybox,zbox; double p[3][3],pdiag[3][3],ispace[3][3]; int id; for (int i = 0; i < nbody; i++) { if (rstyle == SINGLE || rstyle == GROUP) id = i; else id = body2mol[i]; MathExtra::col2mat(ex_space[i],ey_space[i],ez_space[i],p); MathExtra::times3_diag(p,inertia[i],pdiag); MathExtra::times3_transpose(pdiag,p,ispace); xbox = (imagebody[i] & IMGMASK) - IMGMAX; ybox = (imagebody[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (imagebody[i] >> IMG2BITS) - IMGMAX; fprintf(fp,"%d %-1.16e %-1.16e %-1.16e %-1.16e " "%-1.16e %-1.16e %-1.16e %-1.16e %-1.16e %-1.16e " "%-1.16e %-1.16e %-1.16e %-1.16e %-1.16e %-1.16e " "%d %d %d\n", id,masstotal[i],xcm[i][0],xcm[i][1],xcm[i][2], ispace[0][0],ispace[1][1],ispace[2][2], ispace[0][1],ispace[0][2],ispace[1][2], vcm[i][0],vcm[i][1],vcm[i][2], angmom[i][0],angmom[i][1],angmom[i][2], xbox,ybox,zbox); } fclose(fp); } double FixRigid::memory_usage() { int nmax = atom->nmax; double bytes = nmax * sizeof(int); bytes += nmax * sizeof(imageint); bytes += nmax*3 * sizeof(double); bytes += maxvatom*6 * sizeof(double); // vatom if (extended) { bytes += nmax * sizeof(int); if (orientflag) bytes = nmax*orientflag * sizeof(double); if (dorientflag) bytes = nmax*3 * sizeof(double); } return bytes; } void FixRigid::grow_arrays(int nmax) { memory->grow(body,nmax,"rigid:body"); memory->grow(xcmimage,nmax,"rigid:xcmimage"); memory->grow(displace,nmax,3,"rigid:displace"); if (extended) { memory->grow(eflags,nmax,"rigid:eflags"); if (orientflag) memory->grow(orient,nmax,orientflag,"rigid:orient"); if (dorientflag) memory->grow(dorient,nmax,3,"rigid:dorient"); } // check for regrow of vatom // must be done whether per-atom virial is accumulated on this step or not // b/c this is only time grow_array() may be called // need to regrow b/c vatom is calculated before and after atom migration if (nmax > maxvatom) { maxvatom = atom->nmax; memory->grow(vatom,maxvatom,6,"fix:vatom"); } } void FixRigid::copy_arrays(int i, int j, int /*delflag*/) { body[j] = body[i]; xcmimage[j] = xcmimage[i]; displace[j][0] = displace[i][0]; displace[j][1] = displace[i][1]; displace[j][2] = displace[i][2]; if (extended) { eflags[j] = eflags[i]; for (int k = 0; k < orientflag; k++) orient[j][k] = orient[i][k]; if (dorientflag) { dorient[j][0] = dorient[i][0]; dorient[j][1] = dorient[i][1]; dorient[j][2] = dorient[i][2]; } } // must also copy vatom if per-atom virial calculated on this timestep // since vatom is calculated before and after atom migration if (vflag_atom) for (int k = 0; k < 6; k++) vatom[j][k] = vatom[i][k]; } void FixRigid::set_arrays(int i) { body[i] = -1; xcmimage[i] = 0; displace[i][0] = 0.0; displace[i][1] = 0.0; displace[i][2] = 0.0; // must also zero vatom if per-atom virial calculated on this timestep // since vatom is calculated before and after atom migration if (vflag_atom) for (int k = 0; k < 6; k++) vatom[i][k] = 0.0; } int FixRigid::pack_exchange(int i, double *buf) { buf[0] = ubuf(body[i]).d; buf[1] = ubuf(xcmimage[i]).d; buf[2] = displace[i][0]; buf[3] = displace[i][1]; buf[4] = displace[i][2]; if (!extended) return 5; int m = 5; buf[m++] = eflags[i]; for (int j = 0; j < orientflag; j++) buf[m++] = orient[i][j]; if (dorientflag) { buf[m++] = dorient[i][0]; buf[m++] = dorient[i][1]; buf[m++] = dorient[i][2]; } // must also pack vatom if per-atom virial calculated on this timestep // since vatom is calculated before and after atom migration if (vflag_atom) for (int k = 0; k < 6; k++) buf[m++] = vatom[i][k]; return m; } int FixRigid::unpack_exchange(int nlocal, double *buf) { body[nlocal] = (int) ubuf(buf[0]).i; xcmimage[nlocal] = (imageint) ubuf(buf[1]).i; displace[nlocal][0] = buf[2]; displace[nlocal][1] = buf[3]; displace[nlocal][2] = buf[4]; if (!extended) return 5; int m = 5; eflags[nlocal] = static_cast<int> (buf[m++]); for (int j = 0; j < orientflag; j++) orient[nlocal][j] = buf[m++]; if (dorientflag) { dorient[nlocal][0] = buf[m++]; dorient[nlocal][1] = buf[m++]; dorient[nlocal][2] = buf[m++]; } // must also unpack vatom if per-atom virial calculated on this timestep // since vatom is calculated before and after atom migration if (vflag_atom) for (int k = 0; k < 6; k++) vatom[nlocal][k] = buf[m++]; return m; } void FixRigid::reset_dt() { dtv = update->dt; dtf = 0.5 * update->dt * force->ftm2v; dtq = 0.5 * update->dt; } void FixRigid::zero_momentum() { for (int ibody = 0; ibody < nbody; ibody++) vcm[ibody][0] = vcm[ibody][1] = vcm[ibody][2] = 0.0; evflag = 0; set_v(); } void FixRigid::zero_rotation() { for (int ibody = 0; ibody < nbody; ibody++) { angmom[ibody][0] = angmom[ibody][1] = angmom[ibody][2] = 0.0; omega[ibody][0] = omega[ibody][1] = omega[ibody][2] = 0.0; } evflag = 0; set_v(); } int FixRigid::modify_param(int narg, char **arg) { if (strcmp(arg[0],"bodyforces") == 0) { if (narg < 2) error->all(FLERR,"Illegal fix_modify command"); if (strcmp(arg[1],"early") == 0) earlyflag = 1; else if (strcmp(arg[1],"late") == 0) earlyflag = 0; else error->all(FLERR,"Illegal fix_modify command"); // reset fix mask // must do here and not in init, // since modify.cpp::init() uses fix masks before calling fix::init() for (int i = 0; i < modify->nfix; i++) if (strcmp(modify->fix[i]->id,id) == 0) { if (earlyflag) modify->fmask[i] |= POST_FORCE; else if (!langflag) modify->fmask[i] &= ~POST_FORCE; break; } return 2; } return 0; } double FixRigid::compute_scalar() { double wbody[3],rot[3][3]; double t = 0.0; for (int i = 0; i < nbody; i++) { t += masstotal[i] * (fflag[i][0]*vcm[i][0]*vcm[i][0] + fflag[i][1]*vcm[i][1]*vcm[i][1] + fflag[i][2]*vcm[i][2]*vcm[i][2]); // wbody = angular velocity in body frame MathExtra::quat_to_mat(quat[i],rot); MathExtra::transpose_matvec(rot,angmom[i],wbody); if (inertia[i][0] == 0.0) wbody[0] = 0.0; else wbody[0] /= inertia[i][0]; if (inertia[i][1] == 0.0) wbody[1] = 0.0; else wbody[1] /= inertia[i][1]; if (inertia[i][2] == 0.0) wbody[2] = 0.0; else wbody[2] /= inertia[i][2]; t += tflag[i][0]*inertia[i][0]*wbody[0]*wbody[0] + tflag[i][1]*inertia[i][1]*wbody[1]*wbody[1] + tflag[i][2]*inertia[i][2]*wbody[2]*wbody[2]; } t *= tfactor; return t; } void *FixRigid::extract(const char *str, int &dim) { if (strcmp(str,"body") == 0) { dim = 1; return body; } if (strcmp(str,"masstotal") == 0) { dim = 1; return masstotal; } if (strcmp(str,"t_target") == 0) { dim = 0; return &t_target; } return NULL; } double FixRigid::extract_ke() { double ke = 0.0; for (int i = 0; i < nbody; i++) ke += masstotal[i] * (vcm[i][0]*vcm[i][0] + vcm[i][1]*vcm[i][1] + vcm[i][2]*vcm[i][2]); return 0.5*ke; } double FixRigid::extract_erotational() { double wbody[3],rot[3][3]; double erotate = 0.0; for (int i = 0; i < nbody; i++) { // wbody = angular velocity in body frame MathExtra::quat_to_mat(quat[i],rot); MathExtra::transpose_matvec(rot,angmom[i],wbody); if (inertia[i][0] == 0.0) wbody[0] = 0.0; else wbody[0] /= inertia[i][0]; if (inertia[i][1] == 0.0) wbody[1] = 0.0; else wbody[1] /= inertia[i][1]; if (inertia[i][2] == 0.0) wbody[2] = 0.0; else wbody[2] /= inertia[i][2]; erotate += inertia[i][0]*wbody[0]*wbody[0] + inertia[i][1]*wbody[1]*wbody[1] + inertia[i][2]*wbody[2]*wbody[2]; } return 0.5*erotate; } double FixRigid::compute_array(int i, int j) { if (j < 3) return xcm[i][j]; if (j < 6) return vcm[i][j-3]; if (j < 9) return fcm[i][j-6]; if (j < 12) return torque[i][j-9]; if (j == 12) return (imagebody[i] & IMGMASK) - IMGMAX; if (j == 13) return (imagebody[i] >> IMGBITS & IMGMASK) - IMGMAX; return (imagebody[i] >> IMG2BITS) - IMGMAX; }
// <summary> // Defines the ResourceList type. // </summary> namespace TW.Resfit.Core { using System.Collections.Generic; using System.Linq; using TW.Resfit.Framework; public class ResourceList : ListDecoratorBase<Resource> { public ResourceList() { } public ResourceList(IEnumerable<Resource> resources) : this() { this.Items.AddRange(resources); } <summary> Gets the underlying Items collection. It is just a proxy for the protected Items property. Its only purpose is to make the code read easier. </summary> public ICollection<Resource> Resources { get { return this.Items; } } public ResourceList Clone(ResourceFilter filter = null) { if (filter == null) { filter = ResourceFilter.NoFilter; } var clonedList = new ResourceList(); foreach (var resource in this.Where(resource => filter.IsMatch(resource))) { clonedList.Add(new Resource(resource)); } return clonedList; } public void Merge(ResourceList <API key>) { foreach (var resource in <API key>) { if (this.All(x => x.Key != resource.Key)) { this.Add(new Resource(resource)); } } } public ResourceList <API key>() { var newList = new ResourceList(); foreach (var resource in this) { var newResource = new Resource(resource); foreach (var transform in resource.Transforms) { newResource = transform.Transform(resource); } if (newResource != null) { newList.Add(newResource); } } return newList; } } }
package mnm.mcpackager.gui; import java.io.File; import javax.swing.filechooser.FileFilter; public class JarFilter extends FileFilter { @Override public boolean accept(File f) { if (f.isDirectory()) return true; return getExtension(f).equalsIgnoreCase("jar"); } @Override public String getDescription() { return "Jar Archives"; } private String getExtension(File f) { String ext = null; String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) ext = s.substring(i + 1).toLowerCase(); return ext; } }
#ifndef NCMPCPP_MENU_H #define NCMPCPP_MENU_H #include <boost/iterator/transform_iterator.hpp> #include <boost/range/detail/any_iterator.hpp> #include <cassert> #include <functional> #include <iterator> #include <memory> #include <set> #include "curses/formatted_color.h" #include "curses/strbuffer.h" #include "curses/window.h" #include "utility/const.h" namespace NC { struct List { struct Properties { enum Type { None = 0, Selectable = (1 << 0), Selected = (1 << 1), Inactive = (1 << 2), Separator = (1 << 3) }; Properties(Type properties = Selectable) : m_properties(properties) { } void setSelectable(bool is_selectable) { if (is_selectable) m_properties |= Selectable; else m_properties &= ~(Selectable | Selected); } void setSelected(bool is_selected) { if (!isSelectable()) return; if (is_selected) m_properties |= Selected; else m_properties &= ~Selected; } void setInactive(bool is_inactive) { if (is_inactive) m_properties |= Inactive; else m_properties &= ~Inactive; } void setSeparator(bool is_separator) { if (is_separator) m_properties |= Separator; else m_properties &= ~Separator; } bool isSelectable() const { return m_properties & Selectable; } bool isSelected() const { return m_properties & Selected; } bool isInactive() const { return m_properties & Inactive; } bool isSeparator() const { return m_properties & Separator; } private: unsigned m_properties; }; template <typename ValueT> using PropertiesIterator = boost::range_detail::any_iterator< ValueT, boost::<API key>, ValueT &, std::ptrdiff_t >; typedef PropertiesIterator<Properties> Iterator; typedef PropertiesIterator<const Properties> ConstIterator; virtual ~List() { } virtual bool empty() const = 0; virtual size_t size() const = 0; virtual size_t choice() const = 0; virtual void highlight(size_t pos) = 0; virtual Iterator currentP() = 0; virtual ConstIterator currentP() const = 0; virtual Iterator beginP() = 0; virtual ConstIterator beginP() const = 0; virtual Iterator endP() = 0; virtual ConstIterator endP() const = 0; }; inline List::Properties::Type operator|(List::Properties::Type lhs, List::Properties::Type rhs) { return List::Properties::Type(unsigned(lhs) | unsigned(rhs)); } inline List::Properties::Type &operator|=(List::Properties::Type &lhs, List::Properties::Type rhs) { lhs = lhs | rhs; return lhs; } inline List::Properties::Type operator&(List::Properties::Type lhs, List::Properties::Type rhs) { return List::Properties::Type(unsigned(lhs) & unsigned(rhs)); } inline List::Properties::Type &operator&=(List::Properties::Type &lhs, List::Properties::Type rhs) { lhs = lhs & rhs; return lhs; } // for range-based for loop inline List::Iterator begin(List &list) { return list.beginP(); } inline List::ConstIterator begin(const List &list) { return list.beginP(); } inline List::Iterator end(List &list) { return list.endP(); } inline List::ConstIterator end(const List &list) { return list.endP(); } Generic menu capable of holding any std::vector compatible values. template <typename ItemT> struct Menu: Window, List { struct Item { friend struct Menu<ItemT>; typedef ItemT Type; Item() : m_impl(std::make_shared<std::tuple<ItemT, Properties>>()) { } template <typename ValueT, typename PropertiesT> Item(ValueT &&value_, PropertiesT properties_) : m_impl( std::make_shared<std::tuple<ItemT, List::Properties>>( std::forward<ValueT>(value_), std::forward<PropertiesT>(properties_))) { } ItemT &value() { return std::get<0>(*m_impl); } const ItemT &value() const { return std::get<0>(*m_impl); } Properties &properties() { return std::get<1>(*m_impl); } const Properties &properties() const { return std::get<1>(*m_impl); } // Forward methods to List::Properties. void setSelectable(bool is_selectable) { properties().setSelectable(is_selectable); } void setSelected (bool is_selected) { properties().setSelected(is_selected); } void setInactive (bool is_inactive) { properties().setInactive(is_inactive); } void setSeparator (bool is_separator) { properties().setSeparator(is_separator); } bool isSelectable() const { return properties().isSelectable(); } bool isSelected() const { return properties().isSelected(); } bool isInactive() const { return properties().isInactive(); } bool isSeparator() const { return properties().isSeparator(); } // Make a deep copy of Item. Item copy() const { return Item(value(), properties()); } private: template <Const const_> struct ExtractProperties { typedef ExtractProperties type; typedef typename std::conditional< const_ == Const::Yes, const Properties, Properties>::type Properties_; typedef typename std::conditional< const_ == Const::Yes, const Item, Item>::type Item_; Properties_ &operator()(Item_ &i) const { return i.properties(); } }; template <Const const_> struct ExtractValue { typedef ExtractValue type; typedef typename std::conditional< const_ == Const::Yes, const ItemT, ItemT>::type Value_; typedef typename std::conditional< const_ == Const::Yes, const Item, Item>::type Item_; Value_ &operator()(Item_ &i) const { return i.value(); } }; static Item mkSeparator() { Item item; item.setSelectable(false); item.setSeparator(true); return item; } std::shared_ptr<std::tuple<ItemT, Properties>> m_impl; }; typedef typename std::vector<Item>::iterator Iterator; typedef typename std::vector<Item>::const_iterator ConstIterator; typedef std::reverse_iterator<Iterator> ReverseIterator; typedef std::reverse_iterator<ConstIterator> <API key>; typedef boost::transform_iterator< typename Item::template ExtractValue<Const::No>, Iterator> ValueIterator; typedef boost::transform_iterator< typename Item::template ExtractValue<Const::Yes>, ConstIterator> ConstValueIterator; typedef std::reverse_iterator<ValueIterator> <API key>; typedef std::reverse_iterator<ConstValueIterator> <API key>; typedef boost::transform_iterator< typename Item::template ExtractProperties<Const::No>, Iterator> PropertiesIterator; typedef boost::transform_iterator< typename Item::template ExtractProperties<Const::Yes>, ConstIterator> <API key>; // For compliance with boost utilities. typedef Iterator iterator; typedef ConstIterator const_iterator; Function helper prototype used to display each option on the screen. If not set by setItemDisplayer(), menu won't display anything. @see setItemDisplayer() typedef std::function<void(Menu<ItemT> &)> ItemDisplayer; typedef std::function<bool(const Item &)> FilterPredicate; Menu(); Menu(size_t startx, size_t starty, size_t width, size_t height, const std::string &title, Color color, Border border); Menu(const Menu &rhs); Menu(Menu &&rhs); Menu &operator=(Menu rhs); Sets helper function that is responsible for displaying items @param ptr function pointer that matches the ItemDisplayer prototype template <typename ItemDisplayerT> void setItemDisplayer(ItemDisplayerT &&displayer); Resizes the list to given size (adequate to std::vector::resize()) @param size requested size void resizeList(size_t new_size); Adds a new option to list void addItem(ItemT item, Properties::Type properties = Properties::Selectable); Adds separator to list void addSeparator(); Inserts a new option to the list at given position void insertItem(size_t pos, ItemT item, Properties::Type properties = Properties::Selectable); Inserts separator to list at given position @param pos initial position of inserted separator void insertSeparator(size_t pos); Moves the highlighted position to the given line of window @param y Y position of menu window to be highlighted @return true if the position is reachable, false otherwise bool Goto(size_t y); Checks if list is empty @return true if list is empty, false otherwise virtual bool empty() const override { return m_items->empty(); } @return size of the list virtual size_t size() const override { return m_items->size(); } @return currently highlighted position virtual size_t choice() const override; Highlights given position @param pos position to be highlighted virtual void highlight(size_t position) override; Refreshes the menu window @see Window::refresh() virtual void refresh() override; Scrolls by given amount of lines @param where indicated where exactly one wants to go @see Window::scroll() virtual void scroll(Scroll where) override; Cleares all options, used filters etc. It doesn't reset highlighted position though. @see reset() virtual void clear() override; Sets highlighted position to 0 void reset(); Apply filter predicate to items in the menu and show the ones for which it returned true. template <typename PredicateT> void applyFilter(PredicateT &&pred); Reapply previously applied filter. void reapplyFilter(); Get current filter predicate. template <typename TargetT> const TargetT *filterPredicate() const; Clear results of applyFilter and show all items. void clearFilter(); @return true if menu is filtered. bool isFiltered() const { return m_items == &m_filtered_items; } Show all items. void showAllItems() { m_items = &m_all_items; } Show filtered items. void showFilteredItems() { m_items = &m_filtered_items; } Sets prefix, that is put before each selected item to indicate its selection Note that the passed variable is not deleted along with menu object. @param b pointer to buffer that contains the prefix void setSelectedPrefix(const Buffer &b) { m_selected_prefix = b; } Sets suffix, that is put after each selected item to indicate its selection Note that the passed variable is not deleted along with menu object. @param b pointer to buffer that contains the suffix void setSelectedSuffix(const Buffer &b) { m_selected_suffix = b; } void setHighlightPrefix(const Buffer &b) { m_highlight_prefix = b; } void setHighlightSuffix(const Buffer &b) { m_highlight_suffix = b; } const Buffer &highlightPrefix() const { return m_highlight_prefix; } const Buffer &highlightSuffix() const { return m_highlight_suffix; } @return state of highlighting bool isHighlighted() { return m_highlight_enabled; } Turns on/off highlighting @param state state of hihglighting void setHighlighting(bool state) { m_highlight_enabled = state; } Turns on/off cyclic scrolling @param state state of cyclic scrolling void cyclicScrolling(bool state) { <API key> = state; } Turns on/off centered cursor @param state state of centered cursor void centeredCursor(bool state) { m_autocenter_cursor = state; } @return currently drawn item. The result is defined only within drawing function that is called by refresh() @see refresh() ConstIterator drawn() const { return begin() + m_drawn_position; } @param pos requested position @return reference to item at given position @throw std::out_of_range if given position is out of range Menu<ItemT>::Item &at(size_t pos) { return m_items->at(pos); } @param pos requested position @return const reference to item at given position @throw std::out_of_range if given position is out of range const Menu<ItemT>::Item &at(size_t pos) const { return m_items->at(pos); } @param pos requested position @return const reference to item at given position const Menu<ItemT>::Item &operator[](size_t pos) const { return (*m_items)[pos]; } @param pos requested position @return const reference to item at given position Menu<ItemT>::Item &operator[](size_t pos) { return (*m_items)[pos]; } Iterator current() { return Iterator(m_items->begin() + m_highlight); } ConstIterator current() const { return ConstIterator(m_items->begin() + m_highlight); } ReverseIterator rcurrent() { if (empty()) return rend(); else return ReverseIterator(++current()); } <API key> rcurrent() const { if (empty()) return rend(); else return <API key>(++current()); } ValueIterator currentV() { return ValueIterator(m_items->begin() + m_highlight); } ConstValueIterator currentV() const { return ConstValueIterator(m_items->begin() + m_highlight); } <API key> rcurrentV() { if (empty()) return rendV(); else return <API key>(++currentV()); } <API key> rcurrentV() const { if (empty()) return rendV(); else return <API key>(++currentV()); } Iterator begin() { return Iterator(m_items->begin()); } ConstIterator begin() const { return ConstIterator(m_items->begin()); } Iterator end() { return Iterator(m_items->end()); } ConstIterator end() const { return ConstIterator(m_items->end()); } ReverseIterator rbegin() { return ReverseIterator(end()); } <API key> rbegin() const { return <API key>(end()); } ReverseIterator rend() { return ReverseIterator(begin()); } <API key> rend() const { return <API key>(begin()); } ValueIterator beginV() { return ValueIterator(begin()); } ConstValueIterator beginV() const { return ConstValueIterator(begin()); } ValueIterator endV() { return ValueIterator(end()); } ConstValueIterator endV() const { return ConstValueIterator(end()); } <API key> rbeginV() { return <API key>(endV()); } <API key> rbeginV() const { return <API key>(endV()); } <API key> rendV() { return <API key>(beginV()); } <API key> rendV() const { return <API key>(beginV()); } virtual List::Iterator currentP() override { return List::Iterator(PropertiesIterator(m_items->begin() + m_highlight)); } virtual List::ConstIterator currentP() const override { return List::ConstIterator(<API key>(m_items->begin() + m_highlight)); } virtual List::Iterator beginP() override { return List::Iterator(PropertiesIterator(m_items->begin())); } virtual List::ConstIterator beginP() const override { return List::ConstIterator(<API key>(m_items->begin())); } virtual List::Iterator endP() override { return List::Iterator(PropertiesIterator(m_items->end())); } virtual List::ConstIterator endP() const override { return List::ConstIterator(<API key>(m_items->end())); } private: bool isHighlightable(size_t pos) { return !(*m_items)[pos].isSeparator() && !(*m_items)[pos].isInactive(); } ItemDisplayer m_item_displayer; FilterPredicate m_filter_predicate; std::vector<Item> *m_items; std::vector<Item> m_all_items; std::vector<Item> m_filtered_items; size_t m_beginning; size_t m_highlight; bool m_highlight_enabled; bool <API key>; bool m_autocenter_cursor; size_t m_drawn_position; Buffer m_highlight_prefix; Buffer m_highlight_suffix; Buffer m_selected_prefix; Buffer m_selected_suffix; }; } #endif // NCMPCPP_MENU_H
package calliope.handler.post; import calliope.Connector; import calliope.exception.AeseException; import calliope.handler.post.importer.*; import calliope.constants.Formats; import calliope.importer.Archive; import calliope.constants.Config; import calliope.json.JSONDocument; import calliope.constants.Database; import calliope.constants.Params; import calliope.constants.JSONKeys; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * Handle import of a set of XML files from a tool like mmpupload. * @author desmond 23-7-2012 */ public class <API key> extends AeseImportHandler { public void handle( HttpServletRequest request, HttpServletResponse response, String urn ) throws AeseException { try { if (ServletFileUpload.isMultipartContent(request) ) { parseImportParams( request ); Archive cortex = new Archive(docID.getWork(), docID.getAuthor(),Formats.MVD_TEXT,encoding); Archive corcode = new Archive(docID.getWork(), docID.getAuthor(),Formats.MVD_STIL,encoding); cortex.setStyle( style ); corcode.setStyle( style ); StageOne stage1 = new StageOne( files ); log.append( stage1.process(cortex,corcode) ); if ( stage1.hasFiles() ) { String suffix = ""; StageTwo stage2 = new StageTwo( stage1, false ); stage2.setEncoding( encoding ); log.append( stage2.process(cortex,corcode) ); StageThreeXML stage3Xml = new StageThreeXML( stage2, style, dict, hhExceptions ); stage3Xml.setStripConfig( getConfig(Config.stripper, stripperName) ); stage3Xml.setSplitConfig( getConfig(Config.splitter, splitterName) ); if ( stage3Xml.hasTEI() ) { ArrayList<File> notes = stage3Xml.getNotes(); if ( notes.size()> 0 ) { Archive nCorTex = new Archive(docID.getWork(), docID.getAuthor(),Formats.MVD_TEXT,encoding); nCorTex.setStyle( style ); Archive nCorCode = new Archive(docID.getWork(), docID.getAuthor(),Formats.MVD_STIL,encoding); StageThreeXML s3notes = new StageThreeXML( style,dict, hhExceptions); s3notes.setStripConfig( getConfig(Config.stripper, stripperName) ); s3notes.setSplitConfig( getConfig(Config.splitter, splitterName) ); for ( int j=0;j<notes.size();j++ ) s3notes.add(notes.get(j)); log.append( s3notes.process(nCorTex,nCorCode) ); addToDBase(nCorTex, "cortex", "notes" ); addToDBase( nCorCode, "corcode", "notes" ); // differentiate base from notes suffix = "base"; } if ( xslt == null ) xslt = Params.XSLT_DEFAULT; String transform = getConfig(Config.xslt,xslt); JSONDocument jDoc = JSONDocument.internalise( transform ); stage3Xml.setTransform( (String) jDoc.get(JSONKeys.BODY) ); } log.append( stage3Xml.process(cortex,corcode) ); addToDBase( cortex, "cortex", suffix ); addToDBase( corcode, "corcode", suffix ); // now get the json docs and add them at the right docid // Connector.getConnection().putToDb( Database.CORTEX, // docID.get(), cortex.toMVD("cortex") ); // log.append( cortex.getLog() ); // String fullAddress = docID.get()+"/"+Formats.DEFAULT; // log.append( Connector.getConnection().putToDb( // Database.CORCODE,fullAddress, corcode.toMVD("corcode")) ); // log.append( corcode.getLog() ); } response.setContentType("text/html;charset=UTF-8"); response.getWriter().println( wrapLog() ); } } catch ( Exception e ) { throw new AeseException( e ); } } }
#if HAVE_CONFIG_H #include "config.h" #endif #include <pthread.h> #include <errno.h> int <API key>( pthread_attr_t *attr, const struct sched_param *param ) { if ( !attr || !attr->is_initialized || !param ) return EINVAL; attr->schedparam = *param; return 0; }
#include <QRegExp> #include <QString> #include <QStringList> #include "shortener.h" #include "network-if.h" namespace chronicon { Shortener::Shortener (QObject *parent) :QObject (parent), network (0) { } void Shortener::SetNetwork (NetworkIF * net) { network = net; connect (network, SIGNAL (ShortenReply (QUuid, QString, QString, bool)), this, SLOT (CatchShortening (QUuid, QString, QString, bool))); } void Shortener::ShortenHttp (QString status, bool & wait) { if (network == 0) { emit DoneShortening (status); return; } QRegExp regular ("(https?: status.append (" "); QStringList linkList; QStringList wholeList; int where (0), offset(0), lenSub(0); QString link, beforeLink; while ((where = regular.indexIn (status,offset)) > 0) { lenSub = regular.matchedLength(); beforeLink = status.mid (offset, where - offset); link = regular.cap(0); if ((!link.contains ("bit.ly")) && (!link.contains ("twitpic.com")) && (link.length() > QString("http://bit.ly/12345678").length())) { linkList << link; } wholeList << beforeLink; wholeList << link; offset = where + lenSub; } wholeList << status.mid (offset, -1); shortenTag = QUuid::createUuid(); if (linkList.isEmpty ()) { wait = false; } else { messageParts[shortenTag] = wholeList; linkParts [shortenTag] = linkList; network->ShortenHttp (shortenTag,linkList); wait = true; } } void Shortener::CatchShortening (QUuid tag, QString shortUrl, QString longUrl, bool good) { replace the longUrl with shortUrl in the messageParts[tag] // remove the longUrl from the linkParts[tag] // if the linkParts[tag] is empty, we have replaced all the links // so send append all the messageParts[tag] and finish the message if (messageParts.find(tag) == messageParts.end()) { return; // extra, perhaps duplicates in original, or not for me } if (linkParts.find(tag) == linkParts.end()) { return; } QStringList::iterator chase; for (chase = messageParts[tag].begin(); chase != messageParts[tag].end(); chase++) { if (*chase == longUrl) { *chase = shortUrl; } } linkParts[tag].removeAll (longUrl); if (linkParts[tag].isEmpty()) { QString message = messageParts[tag].join (QString()); emit DoneShortening (message); messageParts.erase (tag); } } } // namespace
<?php require_once("../../config.php"); require_once("lib.php"); require_once($CFG->libdir.'/gradelib.php'); $id = required_param('id', PARAM_INT); // course if (! $course = get_record("course", "id", $id)) { error("Course ID is incorrect"); } <API key>($course); add_to_log($course->id, "assignment", "view all", "index.php?id=$course->id", ""); $strassignments = get_string("modulenameplural", "assignment"); $strassignment = get_string("modulename", "assignment"); $strassignmenttype = get_string("assignmenttype", "assignment"); $strweek = get_string("week"); $strtopic = get_string("topic"); $strname = get_string("name"); $strduedate = get_string("duedate", "assignment"); $strsubmitted = get_string("submitted", "assignment"); $strgrade = get_string("grade"); $navlinks = array(); $navlinks[] = array('name' => $strassignments, 'link' => '', 'type' => 'activity'); $navigation = build_navigation($navlinks); print_header_simple($strassignments, "", $navigation, "", "", true, "", navmenu($course)); if (!$cms = <API key>('assignment', $course->id, 'm.assignmenttype, m.timedue')) { notice(get_string('noassignments', 'assignment'), "../../course/view.php?id=$course->id"); die; } $timenow = time(); $table = new object; if ($course->format == "weeks") { $table->head = array ($strweek, $strname, $strassignmenttype, $strduedate, $strsubmitted, $strgrade); $table->align = array ("center", "left", "left", "left", "right"); } else if ($course->format == "topics") { $table->head = array ($strtopic, $strname, $strassignmenttype, $strduedate, $strsubmitted, $strgrade); $table->align = array ("center", "left", "left", "left", "right"); } else { $table->head = array ($strname, $strassignmenttype, $strduedate, $strsubmitted, $strgrade); $table->align = array ("left", "left", "left", "right"); } $currentsection = ""; $types = assignment_types(); $modinfo = get_fast_modinfo($course); foreach ($modinfo->instances['assignment'] as $cm) { if (!$cm->uservisible) { continue; } $cm->timedue = $cms[$cm->id]->timedue; $cm->assignmenttype = $cms[$cm->id]->assignmenttype; $cm->idnumber = get_field('course_modules', 'idnumber', 'id', $cm->id); //hack //Show dimmed if the mod is hidden $class = $cm->visible ? '' : 'class="dimmed"'; $link = "<a $class href=\"view.php?id=$cm->id\">".format_string($cm->name)."</a>"; $printsection = ""; if ($cm->sectionnum !== $currentsection) { if ($cm->sectionnum) { $printsection = $cm->sectionnum; } if ($currentsection !== "") { $table->data[] = 'hr'; } $currentsection = $cm->sectionnum; } if (!file_exists($CFG->dirroot.'/mod/assignment/type/'.$cm->assignmenttype.'/assignment.class.php')) { continue; } require_once ($CFG->dirroot.'/mod/assignment/type/'.$cm->assignmenttype.'/assignment.class.php'); $assignmentclass = 'assignment_'.$cm->assignmenttype; $assignmentinstance = new $assignmentclass($cm->id, NULL, $cm, $course); $submitted = $assignmentinstance->submittedlink(true); $grading_info = grade_get_grades($course->id, 'mod', 'assignment', $cm->instance, $USER->id); if (isset($grading_info->items[0]) && !$grading_info->items[0]->grades[$USER->id]->hidden ) { $grade = $grading_info->items[0]->grades[$USER->id]->str_grade; } else { $grade = '-'; } $type = $types[$cm->assignmenttype]; $due = $cm->timedue ? userdate($cm->timedue) : '-'; if ($course->format == "weeks" or $course->format == "topics") { $table->data[] = array ($printsection, $link, $type, $due, $submitted, $grade); } else { $table->data[] = array ($link, $type, $due, $submitted, $grade); } } echo "<br />"; print_table($table); print_footer($course); ?>
void RedboxFactory::add (Addr addr, ActionType t) { switch (t) { case ActionType::RD8 : return add_read (addr, 1); case ActionType::RD16 : return add_read (addr, 2); case ActionType::RD32 : return add_read (addr, 4); case ActionType::RD64 : return add_read (addr, 8); case ActionType::WR8 : return add_write (addr, 1); case ActionType::WR16 : return add_write (addr, 2); case ActionType::WR32 : return add_write (addr, 4); case ActionType::WR64 : return add_write (addr, 8); default : SHOW (t, "d"); ASSERT (0); } } void RedboxFactory::add_read (Addr addr, unsigned size) { ASSERT (size); read_regions.emplace_back (addr, size); } void RedboxFactory::add_write (Addr addr, unsigned size) { ASSERT (size); write_regions.emplace_back (addr, size); } void RedboxFactory::clear () { read_regions.clear (); write_regions.clear (); } Redbox *RedboxFactory::create () { Redbox *b; // Special case: we return a null pointer if both memory pools are empty. // In this case the event will continue being labelled by a null pointer // rather than a pointer to a Redbox. This is useful during the data race // detection in DataRaceAnalysis::find_data_races(), because that way we // don't even need to look inside of the red box to see if it has events, the // event will straightfowardly be discarde for DR detection if (read_regions.empty() and write_regions.empty()) return nullptr; // allocate a new Redbox and keep the pointer to it, we are the container b = new Redbox (); boxes.push_back (b); // compress the lists of memory areas compress (read_regions); compress (write_regions); // copy them to the new redbox b->readpool = read_regions; b->writepool = write_regions; #ifdef CONFIG_DEBUG if (verb_debug) b->dump (); // this will assert that the memory pools are a sorted sequence of disjoint // memory areas b->readpool.assertt (); b->writepool.assertt (); #endif // restart the internal arrays read_regions.clear (); write_regions.clear (); ASSERT (empty()); return b; } void RedboxFactory::compress (MemoryPool::Container &regions) { unsigned i, j; size_t s; // nothing to do if we have no regions; code below assumes we have at least 1 if (regions.empty ()) return; // sort the memory regions by increasing value of lower bound struct compare { bool operator() (const MemoryRegion<Addr> &a, const MemoryRegion<Addr> &b) { return a.lower < b.lower; } } cmp; std::sort (regions.begin(), regions.end(), cmp); // compress regions s = regions.size (); breakme (); for (i = 0, j = 1; j < s; ++j) { ASSERT (i < j); ASSERT (regions[i].lower <= regions[j].lower); // if the next region's lower bound is below i's region upper bound, we can // extend i's range if (regions[i].upper >= regions[j].lower) { regions[i].upper = std::max (regions[i].upper, regions[j].upper); } else { // otherwise there is a gap betwen interval i and interval j, so we // need to create a new interval at offset i+1, only if i+1 != j ++i; if (i != j) { // copy j into i regions[i] = regions[j]; } } } DEBUG ("redbox-factory: compressed %zu regions into %u", regions.size(), i+1); regions.resize (i + 1); }
** // * ClassName: MainTest.java //package com.ojdbc.sql.test; //import java.sql.Connection; //import java.sql.SQLException; //import com.ojdbc.sql.ConnectionObject; //import com.ojdbc.sql.DataBase; //import com.ojdbc.sql.DataBaseEnum; //import com.ojdbc.sql.DataBaseManager; //import com.ojdbc.sql.SQLResultSet; //import com.ojdbc.sql.connection.<API key>; //import com.ojdbc.sql.connection.<API key>; //import com.ojdbc.sql.connection.<API key>; //import com.ojdbc.sql.connection.<API key>; ** // * Description: // * Log: //public class MainTest { // /** // * @param args // * @throws SQLException // */ // public static void main(String[] args) throws SQLException { // // TODO Auto-generated method stub // ConnectionObject conn; // <API key> sqlite = new <API key>(); // String dataBaseURL = "jdbc:sqlite://E:/shaogaige/iNote/iNoteRun/data/iNoteData.note"; // String userName = ""; // String passWord = ""; // conn = sqlite.createConnection(dataBaseURL, userName, passWord); // System.out.println(conn.getMetaData().getURL()); // DataBase database = new DataBase(conn); // SQLResultSet rs =database.exeSQLSelect("select * from noteinfo"); // System.out.println(rs.getRowNum()); // <API key> mongo = new <API key>(); // dataBaseURL = "jdbc:mongo://172.15.103.42:10001/geoglobe"; // userName = "data"; // passWord = "data"; // conn = mongo.createConnection(dataBaseURL, userName, passWord); // System.out.println(conn.getMetaData().getURL()); // <API key> mysql = new <API key>(); // dataBaseURL = "jdbc:mysql://172.15.103.42:3306/geoglobe"; // userName = "root"; // passWord = "root"; // conn = mysql.createConnection(dataBaseURL, userName, passWord); // System.out.println(conn.getMetaData().getURL()); // <API key> oracle = new <API key>(); // dataBaseURL = "jdbc:oracle:thin:@172.15.103.43:1521:geoglobe"; // userName = "autotest"; // passWord = "autotest"; // conn = oracle.createConnection(dataBaseURL, userName, passWord); // System.out.println(conn.getMetaData().getURL()); // DataBaseManager.getDataBase(DataBaseEnum.ORACLE, "", "", "");
// This file is part of VideoPad. // VideoPad is free software; you can redistribute it and/or modify // (at your option) any later version. // VideoPad is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with VideoPad; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #pragma once #include "CaptureDevice.h" class CAudioCaptureDevice : public CCaptureDevice { public: CAudioCaptureDevice(); // init capture device by given COM object ID HRESULT Create( CString szID ); const DWORD& <API key>(); const WORD& <API key>(); const WORD& <API key>(); const DWORD& GetSamplesPerSec(); const WORD& GetBitsPerSample(); const WORD& GetChannels(); void <API key>( DWORD nSamplesPerSec ); void <API key>( WORD wBitsPerSample ); void <API key>( WORD nChannels ); // these functions are used by CAudioGraph to set // the current audio format information of the graph // and the device void <API key>( DWORD nSamplesPerSec ); void <API key>( WORD wBitsPerSample ); void SetAudioChannels( WORD nChannels ); private: DWORD <API key>; WORD <API key>; WORD <API key>; DWORD m_nSamplesPerSec; WORD m_wBitsPerSample; WORD m_nChannels; };
'use strict'; angular.module('eshttp') .filter('unixtostr', function() { return function(str){ var dt; dt = Date.create(str * 1000).format('{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}'); if (dt == "Invalid Date") { return 'N/A'; } else { return dt; } }; });
#include "thanks.h" // EternityProject Public message START: - To the "developers" like franciscofranco: Are you able to work on your own? Also, if you want to badly copy my commits, can you at least give credits to the proprietary of the commit you're copying? We're an opensource community, we do this for free... but we also are satisfacted of the TIME WE LOSE on the things we do. We want to work with everyone that wants to. We publish our sources. We give you all everything we do. And you? Instead of copying someone else's work, try to lose time on your own at least sorting the not working commits (yeah, I knew someone was copying my work and I've committed some fakes). You did that badly. The EternityProject Team Manager & Main Developer, --kholk // EternityProject Public message END
<?php namespace PHPExiftool\Driver\Tag\Microsoft; use PHPExiftool\Driver\AbstractTag; class Duration extends AbstractTag { protected $Id = 'mixed'; protected $Name = 'Duration'; protected $FullName = 'Microsoft::Xtra'; protected $GroupName = 'Microsoft'; protected $g0 = 'QuickTime'; protected $g1 = 'Microsoft'; protected $g2 = 'Video'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Duration'; }
#ifndef <API key> #define <API key> #include "../CppTest/cpptest.h" #include "../Raple/Headers/Stack.h" #ifdef _MSC_VER #pragma warning (disable: 4290) #endif using Raple::Stack; using Raple::<API key>; using Raple::<API key>; namespace RapleTests { class StackTests : public Test::Suite { public: StackTests() { addTest(StackTests::SizeTest); addTest(StackTests::PushAndPopTest); addTest(StackTests::<API key>); addTest(StackTests::<API key>); } private: void SizeTest() { Stack<int> s; assertEquals(0, s.Size()); s.Push(1); s.Push(2); assertEquals(2, s.Size()); s.Pop(); assertEquals(1, s.Size()); s.Pop(); assertEquals(0, s.Size()); } void PushAndPopTest() { Stack<int> s; s.Push(1); s.Push(2); s.Push(3); assertEquals(3, s.Pop()); assertEquals(2, s.Pop()); assertEquals(1, s.Pop()); } void <API key>() { Stack<int> s(2); s.Push(1); s.Push(2); try { s.Push(3); } catch (<API key> ex) { assert(true); return; } assert(false); } void <API key>() { Stack<int> s; try { s.Pop(); } catch (<API key> ex) { assert(true); return; } assert(false); } }; } #endif //<API key>
# Install script for directory: /home/hscore # Set the install prefix IF(NOT DEFINED <API key>) SET(<API key> "/home/root/hswow") ENDIF(NOT DEFINED <API key>) STRING(REGEX REPLACE "/$" "" <API key> "${<API key>}") # Set the install configuration name. IF(NOT DEFINED <API key>) IF(BUILD_TYPE) STRING(REGEX REPLACE "^[^A-Za-z0-9_]+" "" <API key> "${BUILD_TYPE}") ELSE(BUILD_TYPE) SET(<API key> "Release") ENDIF(BUILD_TYPE) MESSAGE(STATUS "Install configuration: \"${<API key>}\"") ENDIF(NOT DEFINED <API key>) # Set the component getting installed. IF(NOT <API key>) IF(COMPONENT) MESSAGE(STATUS "Install component: \"${COMPONENT}\"") SET(<API key> "${COMPONENT}") ELSE(COMPONENT) SET(<API key>) ENDIF(COMPONENT) ENDIF(NOT <API key>) IF(NOT DEFINED <API key>) SET(<API key> "1") ENDIF(NOT DEFINED <API key>) IF(NOT <API key>) # Include the install script for each subdirectory. INCLUDE("/home/hscore/src/dep/cmake_install.cmake") INCLUDE("/home/hscore/src/src/cmake_install.cmake") ENDIF(NOT <API key>) IF(<API key>) SET(<API key> "install_manifest_${<API key>}.txt") ELSE(<API key>) SET(<API key> "install_manifest.txt") ENDIF(<API key>) FILE(WRITE "/home/hscore/src/${<API key>}" "") FOREACH(file ${<API key>}) FILE(APPEND "/home/hscore/src/${<API key>}" "${file}\n") ENDFOREACH(file)
#ifndef <API key> #define <API key> #include <qwidget.h> //Added by qt3to4: #include <Q3GridLayout> #include <list> #include <q3frame.h> #include <qlayout.h> #include <qlabel.h> class Control; class MetaGear; class GearControl; class ControlPanel : public QWidget { public: ControlPanel(QWidget *<API key>, MetaGear *parentMetagear); ~ControlPanel(); Control *addControl(GearControl* gear); void addControlPanel(ControlPanel* controlPanel); QWidget *mainWidget(){return _mainFrame;} private: std::list<Control*> _controls; std::list<ControlPanel*> _controlPanels; MetaGear *_parentMetaGear; Q3Frame *_mainFrame; Q3GridLayout *_mainLayout; QLabel *_labelName; }; #endif
CKEDITOR.plugins.setLang( 'colordialog', 'en-gb', { clear: 'Clear', highlight: 'Highlight', options: 'Colour Options', selected: 'Selected Colour', title: 'Select colour' } );
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title></title> <link rel="stylesheet" href="../layui/css/layui.css"> <link type="text/css" rel="styleSheet" href="../style/common.css"> </link> <link type="text/css" rel="styleSheet" href="../style/siteList.css"> </link> <script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.min.js"></script> <script src="https://cdn.bootcss.com/echarts/4.2.1-rc.2/echarts.min.js"></script> <script type="text/javascript" src="../theme/purple-passion.js"></script> <script type="text/javascript" src="../js/iconfont.js"></script> <script type="text/javascript" src="../layui/layui.js"></script> <script src="../js/template-web.js"></script> <script type="text/javascript" src="../js/common.js"></script> <script type="text/javascript" src="../js/siteList.js"></script> <script> var whdef = 100 / 1920;// 1920,100PX var wH = window.innerHeight; var wW = window.innerWidth; var rem = wW * whdef;// ,FONT-SIZE $('html').css('font-size', rem + "px"); layui.use(['form'], function () { var form = layui.form; }); </script> </head> <body> <div class="nav" id='nav'> <a href="./index.html"></a> <a href="./management.html"></a> <a href="./warnMonitor.html"></a> <svg class="icon navLockIcon" aria-hidden="true" id="lockBtn"> <use xlink:href="#icon-lock-line"></use> </svg> </div> <div class="siderWrap" id="siderWrap" data-visible='false'> <div class="siderBtn" id="siderBtn"> <svg class="icon siderBtnIcon" aria-hidden="true"> <use xlink:href="#icon-zuojiantou"></use> </svg> </div> <div class="sider" id="sider"> <div class="clearfix"> <div class="siderHeader"></div> <div class="siderGeoBtn" id="siderGeoBtn"></div> </div> <div class="searchBox"> <svg class="baiyanIcon menuIcon" aria-hidden="true"> <use xlink:href="#icon-caidan"></use> </svg> <input class="searchInput" placeholder="" /> <svg class="baiyanIcon searchIcon" aria-hidden="true"> <use xlink:href="#icon-xiazai17"></use> </svg> </div> <h5 class="title2 mgt35"></h5> <div class="dashLine"></div> <div class="dataStatistics"> <div class="digit_set"></div> <div class="digit_set"></div> <div class="digit_set"></div> <div class="digit_set set_last"></div> </div> <div class="siteNumWrapper clearfix"> <div>123</div> <div>123</div> <div>123</div> </div> <h5 class="title2 mgt17">3</h5> <div class="dashLine"></div> <div class="warningBox clearfix"> <div> <span></span> <span>3</span> </div> <div> <span></span> <span>3</span> </div> <div> <span></span> <span>3</span> </div> </div> <div class="mgt17"> <h5 class="title2"></h5> <span class="oneyear">2018</span> <span class="twoyear">2019</span> </div> <div class="dashLine"></div> <div id="barCharts1"></div> <h5 class="title2 mgt17"></h5> <div class="dashLine"></div> <div id="pieCharts1"></div> </div> </div> <!-- LNG --> <div id="lngBtn" data-show="false"> <div id="lngBtnHidden">LNG</div> <div id="lngBtnShow"> <svg class="icon shouqiIcon" aria-hidden="true"> <use xlink:href="#icon-zuojiantou"></use> </svg> <a class="btn private" href="./siteList.html"></a> <a class="btn private"></a> <a class="btn default"></a> </div> </div> <div class="siteList"> <div class="siteItemBox"> <div class="siteItem"> <div class="imgWrap"> <img src="../images/demo.jpg" /> </div> <div class="clearfix info"> <div class="name"></div> <div class="success"> <img src="../images/chenggong.png"/> <span>80%</span> </div> <div class="error"> <img src="../images/shibai.png"/> <span>80%</span> </div> </div> </div> </div> </div> </body> <script type="text/html" id="tpl1"> {{each list}} <div class="siteItemBox"> <div class="siteItem"> <div class="imgWrap"> <img src="../images/demo.jpg" /> </div> <div class="clearfix info"> <div class="name"></div> <div class="success"> <img src="../images/chenggong.png"/> <span>80%</span> </div> <div class="error"> <img src="../images/shibai.png"/> <span>80%</span> </div> </div> </div> </div> {{/each}} </script> </html>
{% load i18n %} <ul class="nav nav-tabs"> <li id="tab-basic"> <a href="{% url 'settings:basic-setting' %}" class="text-center"><i class="fa fa-cubes"></i> {% trans 'Basic setting' %}</a> </li> <li id="tab-email" > <a href="{% url 'settings:email-setting' %}" class="text-center"><i class="fa fa-envelope"></i> {% trans 'Email setting' %} </a> </li> <li id="tab-email-content" > <a href="{% url 'settings:<API key>' %}" class="text-center"><i class="fa fa-file-text"></i> {% trans 'Email content setting' %} </a> </li> <li id="tab-ldap"> <a href="{% url 'settings:ldap-setting' %}" class="text-center"><i class="fa fa-archive"></i> {% trans 'LDAP setting' %} </a> </li> <li id="tab-terminal"> <a href="{% url 'settings:terminal-setting' %}" class="text-center"><i class="fa fa-hdd-o"></i> {% trans 'Terminal setting' %} </a> </li> <li id="tab-security"> <a href="{% url 'settings:security-setting' %}" class="text-center"><i class="fa fa-lock"></i> {% trans 'Security setting' %} </a> </li> </ul> <script> $(document).ready(function () { var path = location.pathname; if (path.endsWith('/')) { path = path.substring(0, path.length-1) } var pathList = path.split('/'); var tabId = pathList[pathList.length-1]; if (tabId === "settings") { tabId = "basic" } tabId = "#tab-" + tabId; $(tabId).addClass("active") }) </script>
<?php if(!defined('kernel_entry') || !kernel_entry) die('Not A Valid Entry Point'); require_once('include/data/cls_table_view_base.php'); class <API key> extends cls_table_view_base { private $<API key> = null; function __construct() { $a = func_get_args(); $i = func_num_args(); if (method_exists($this,$f="__construct".$i)) { <API key>(array($this,$f),$a); } } public function query($search_values,$limit,$offset) { require_once('include/data/table_factory/cls_table_factory.php'); $<API key> = cls_table_factory::<API key>(); $<API key> = $<API key>-><API key>($this->get_db_manager(),$this->get_application(),$search_values,$limit,$offset,false); $result_array = array(); foreach($<API key> as $drupal_registry) { $drupal_registry_id = $drupal_registry->get_id(); $result_array[$drupal_registry_id]['drupal_registry.name'] = $drupal_registry->get_name(); $result_array[$drupal_registry_id]['drupal_registry.type'] = $drupal_registry->get_type(); $result_array[$drupal_registry_id]['drupal_registry.filename'] = $drupal_registry->get_filename(); $result_array[$drupal_registry_id]['drupal_registry.module'] = $drupal_registry->get_module(); $result_array[$drupal_registry_id]['drupal_registry.weight'] = $drupal_registry->get_weight(); $result_array[$drupal_registry_id]['drupal_registry.id'] = $drupal_registry->get_id(); } return $result_array; } public function <API key>() { if (!is_null($this-><API key>)) return $this-><API key>; { $this-><API key> = array(); $this-><API key>['drupal_registry.name']['type'] = 'varchar'; $this-><API key>['drupal_registry.type']['type'] = 'varchar'; $this-><API key>['drupal_registry.filename']['type'] = 'varchar'; $this-><API key>['drupal_registry.module']['type'] = 'varchar'; $this-><API key>['drupal_registry.weight']['type'] = 'int4'; $this-><API key>['drupal_registry.id']['type'] = 'uuid'; } return $this-><API key>; } } ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>CHAI3D: /home/seb/workspace/chai3d-2.0.0/src/scenegraph/CGenericObject.h File 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.5.5 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> </div> <div class="contents"> <h1>/home/seb/workspace/chai3d-2.0.0/src/scenegraph/CGenericObject.h File Reference</h1><b> Scenegraph </b> <br> Base Class. <a href="#_details">More...</a> <p> <code>#include &quot;<a class="el" href="_c_maths_8h-source.html">math/CMaths.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="<API key>.html">graphics/CDraw3D.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_color_8h-source.html">graphics/CColor.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="<API key>.html">graphics/CMacrosGL.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="<API key>.html">graphics/CMaterial.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="<API key>.html">graphics/CTexture2D.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="<API key>.html">collisions/CCollisionBasics.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="<API key>.html">forces/CInteractionBasics.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="<API key>.html">effects/CGenericEffect.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="<API key>.html">extras/CGenericType.h</a>&quot;</code><br> <code>#include &lt;typeinfo&gt;</code><br> <code>#include &lt;vector&gt;</code><br> <code>#include &lt;list&gt;</code><br> <p> <a href="<API key>.html">Go to the source code of this file.</a><table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> <tr><td colspan="2"><br><h2>Classes</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html">cGenericObject</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">This class is the root of basically every render-able object in CHAI. It defines a reference frame (position and rotation) and virtual methods for rendering, which are overloaded by useful subclasses. <br> . <a href="<API key>.html#_details">More...</a><br></td></tr> <tr><td colspan="2"><br><h2>Enumerations</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">enum &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">chai_render_modes</a> { <b><API key></b> = 0, <b><API key></b>, <b><API key></b>, <b><API key></b> }</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Constants that define specific rendering passes (see cCamera.cpp). <br></td></tr> </table> <hr><a name="_details"></a><h2>Detailed Description</h2> <b> Scenegraph </b> <br> Base Class. <p> </div> <font size=-2><br><hr><b>CHAI3D 2.0.0 documentation</b><br>Please address any questions to <a href="mailto:support@chai3d.org">support@chai3d.org</a><br> (C) 2003-2009 - <a href="http: All Rights Reserved.
// This program is free software; you can redistribute it and/or modify it // by the Free Software Foundation. You may not use, modify or distribute // This program is distributed in the hope that it will be useful, but // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // rule_profiler.cc author Joel Cornett <jocornet@cisco.com> #include "rule_profiler.h" #if HAVE_CONFIG_H #include "config.h" #endif #include <algorithm> #include <functional> #include <iostream> #include <sstream> #include <vector> #include "detection/detection_options.h" #include "detection/treenodes.h" #include "hash/sfghash.h" #include "main/snort_config.h" #include "main/thread_config.h" #include "parser/parser.h" #include "target_based/snort_protocols.h" #include "profiler_printer.h" #include "<API key>.h" #include "rule_profiler_defs.h" #ifdef UNIT_TEST #include "catch/catch.hpp" #endif #define s_rule_table_title "Rule Profile Statistics" static inline OtnState& operator+=(OtnState& lhs, const OtnState& rhs) { lhs.elapsed += rhs.elapsed; lhs.elapsed_match += rhs.elapsed_match; lhs.checks += rhs.checks; lhs.matches += rhs.matches; lhs.alerts += rhs.alerts; return lhs; } namespace rule_stats { static const StatsTable::Field fields[] = { { "#", 5, '\0', 0, std::ios_base::left }, { "gid", 6, '\0', 0, std::ios_base::fmtflags() }, { "sid", 6, '\0', 0, std::ios_base::fmtflags() }, { "rev", 4, '\0', 0, std::ios_base::fmtflags() }, { "checks", 7, '\0', 0, std::ios_base::fmtflags() }, { "matches", 8, '\0', 0, std::ios_base::fmtflags() }, { "alerts", 7, '\0', 0, std::ios_base::fmtflags() }, { "time (us)", 10, '\0', 0, std::ios_base::fmtflags() }, { "avg/check", 10, '\0', 1, std::ios_base::fmtflags() }, { "avg/match", 10, '\0', 1, std::ios_base::fmtflags() }, { "avg/non-match", 14, '\0', 1, std::ios_base::fmtflags() }, { "timeouts", 9, '\0', 0, std::ios_base::fmtflags() }, { "suspends", 9, '\0', 0, std::ios_base::fmtflags() }, { nullptr, 0, '\0', 0, std::ios_base::fmtflags() } }; struct View { OtnState state; SigInfo sig_info; hr_duration elapsed() const { return state.elapsed; } hr_duration elapsed_match() const { return state.elapsed_match; } hr_duration elapsed_no_match() const { return elapsed() - elapsed_match(); } uint64_t checks() const { return state.checks; } uint64_t matches() const { return state.matches; } uint64_t no_matches() const { return checks() - matches(); } uint64_t alerts() const { return state.alerts; } uint64_t timeouts() const { return state.latency_timeouts; } uint64_t suspends() const { return state.latency_suspends; } hr_duration time_per(hr_duration d, uint64_t v) const { if ( v == 0 ) return 0_ticks; return hr_duration(d.count() / v); } hr_duration avg_match() const { return time_per(elapsed_match(), matches()); } hr_duration avg_no_match() const { return time_per(elapsed_no_match(), no_matches()); } hr_duration avg_check() const { return time_per(elapsed(), checks()); } View(const OtnState& otn_state, const SigInfo* si = nullptr) : state(otn_state) { if ( si ) // FIXIT-L J does sig_info need to be initialized otherwise? sig_info = *si; } }; static const ProfilerSorter<View> sorters[] = { { "", nullptr }, { "checks", [](const View& lhs, const View& rhs) { return lhs.checks() >= rhs.checks(); } }, { "avg_check", [](const View& lhs, const View& rhs) { return lhs.avg_check() >= rhs.avg_check(); } }, { "total_time", [](const View& lhs, const View& rhs) { return lhs.elapsed().count() >= rhs.elapsed().count(); } }, { "matches", [](const View& lhs, const View& rhs) { return lhs.matches() >= rhs.matches(); } }, { "no_matches", [](const View& lhs, const View& rhs) { return lhs.no_matches() >= rhs.no_matches(); } }, { "avg_match", [](const View& lhs, const View& rhs) { return lhs.avg_match() >= rhs.avg_match(); } }, { "avg_no_match", [](const View& lhs, const View& rhs) { return lhs.avg_no_match() >= rhs.avg_no_match(); } } }; static void <API key>(OtnState* states) { for ( unsigned i = 1; i < ThreadConfig::get_instance_max(); ++i ) states[0] += states[i]; } static std::vector<View> build_entries() { assert(snort_conf); <API key>(snort_conf-><API key>); auto* otn_map = snort_conf->otn_map; std::vector<View> entries; for ( auto* h = sfghash_findfirst(otn_map); h; h = sfghash_findnext(otn_map) ) { auto* otn = static_cast<OptTreeNode*>(h->data); assert(otn); auto* states = otn->state; <API key>(states); auto& state = states[0]; if ( !state ) continue; // FIXIT-L J should we assert(otn->sigInfo)? entries.emplace_back(state, &otn->sigInfo); } return entries; } // FIXIT-L J logic duplicated from ProfilerPrinter static void print_single_entry(const View& v, unsigned n) { using std::chrono::duration_cast; using std::chrono::microseconds; std::ostringstream ss; { StatsTable table(fields, ss); table << StatsTable::ROW; table << n; // table << v.sig_info.generator; // gid table << v.sig_info.id; // sid table << v.sig_info.rev; // rev table << v.checks(); // checks table << v.matches(); // matches table << v.alerts(); // alerts table << duration_cast<microseconds>(v.elapsed()).count(); // time table << duration_cast<microseconds>(v.avg_check()).count(); // avg/check table << duration_cast<microseconds>(v.avg_match()).count(); // avg/match table << duration_cast<microseconds>(v.avg_no_match()).count(); // avg/non-match table << v.timeouts(); table << v.suspends(); } LogMessage("%s", ss.str().c_str()); } // FIXIT-L J logic duplicated from ProfilerPrinter static void print_entries(std::vector<View>& entries, ProfilerSorter<View> sort, unsigned count) { std::ostringstream ss; { StatsTable table(fields, ss); table << StatsTable::SEP; table << s_rule_table_title; if ( count ) table << " (worst " << count; else table << " (all"; if ( sort ) table << ", sorted by " << sort.name; table << ")\n"; table << StatsTable::HEADER; } LogMessage("%s", ss.str().c_str()); if ( !count || count > entries.size() ) count = entries.size(); if ( sort ) std::partial_sort(entries.begin(), entries.begin() + count, entries.end(), sort); for ( unsigned i = 0; i < count; ++i ) print_single_entry(entries[i], i + 1); } } void <API key>(const RuleProfilerConfig& config) { if ( !config.show ) return; auto entries = rule_stats::build_entries(); // if there aren't any eval'd rules, don't sort or print if ( entries.empty() ) return; auto sort = rule_stats::sorters[config.sort]; // FIXIT-L J do we eventually want to be able print rule totals, too? print_entries(entries, sort, config.count); } void <API key>() { assert(snort_conf); auto* otn_map = snort_conf->otn_map; for ( auto* h = sfghash_findfirst(otn_map); h; h = sfghash_findnext(otn_map) ) { auto* otn = static_cast<OptTreeNode*>(h->data); assert(otn); auto* rtn = getRtnFromOtn(otn); if ( !rtn || !is_network_protocol(rtn->proto) ) continue; for ( unsigned i = 0; i < ThreadConfig::get_instance_max(); ++i ) { auto& state = otn->state[i]; state = OtnState(); } } } void RuleContext::stop(bool match) { if ( finished ) return; finished = true; stats.update(sw.get(), match); } #ifdef UNIT_TEST namespace { using RuleEntryVector = std::vector<rule_stats::View>; using RuleStatsVector = std::vector<OtnState>; } // anonymous namespace static inline bool operator==(const RuleEntryVector& lhs, const RuleStatsVector& rhs) { if ( lhs.size() != rhs.size() ) return false; for ( unsigned i = 0; i < lhs.size(); ++i ) if ( lhs[i].state != rhs[i] ) return false; return true; } static inline OtnState make_otn_state( hr_duration elapsed, hr_duration elapsed_match, uint64_t checks, uint64_t matches) { OtnState state; state.elapsed = elapsed; state.elapsed_match = elapsed_match; state.checks = checks; state.matches = matches; return state; } static inline rule_stats::View make_rule_entry( hr_duration elapsed, hr_duration elapsed_match, uint64_t checks, uint64_t matches) { return { make_otn_state(elapsed, elapsed_match, checks, matches), nullptr }; } static void avoid_optimization() { for ( int i = 0; i < 1024; ++i ); } TEST_CASE( "otn state", "[profiler][rule_profiler]" ) { OtnState state_a; state_a.elapsed = 1_ticks; state_a.elapsed_match = 2_ticks; state_a.elapsed_no_match = 2_ticks; state_a.checks = 1; state_a.matches = 2; state_a.noalerts = 3; state_a.alerts = 4; SECTION( "incremental addition" ) { OtnState state_b; state_b.elapsed = 4_ticks; state_b.elapsed_match = 5_ticks; state_b.elapsed_no_match = 6_ticks; state_b.checks = 5; state_b.matches = 6; state_b.noalerts = 7; state_b.alerts = 8; state_a += state_b; CHECK( state_a.elapsed == 5_ticks ); CHECK( state_a.elapsed_match == 7_ticks ); CHECK( state_a.checks == 6 ); CHECK( state_a.matches == 8 ); CHECK( state_a.alerts == 12 ); } SECTION( "reset" ) { state_a = OtnState(); CHECK( state_a.elapsed == 0_ticks ); CHECK( state_a.elapsed_match == 0_ticks ); CHECK( state_a.checks == 0 ); CHECK( state_a.matches == 0 ); CHECK( state_a.alerts == 0 ); } SECTION( "bool()" ) { CHECK( state_a ); OtnState state_c = OtnState(); CHECK_FALSE( state_c ); state_c.elapsed = 1_ticks; CHECK( state_c ); state_c.elapsed = 0_ticks; state_c.checks = 1; CHECK( state_c ); } } TEST_CASE( "rule entry", "[profiler][rule_profiler]" ) { SigInfo sig_info; auto entry = make_rule_entry(3_ticks, 2_ticks, 3, 2); entry.state.alerts = 77; entry.state.latency_timeouts = 5; entry.state.latency_suspends = 2; SECTION( "copy assignment" ) { auto copy = entry; CHECK( copy.sig_info.generator == entry.sig_info.generator ); CHECK( copy.sig_info.id == entry.sig_info.id ); CHECK( copy.sig_info.rev == entry.sig_info.rev ); CHECK( copy.state == entry.state ); } SECTION( "copy construction" ) { rule_stats::View copy(entry); CHECK( copy.sig_info.generator == entry.sig_info.generator ); CHECK( copy.sig_info.id == entry.sig_info.id ); CHECK( copy.sig_info.rev == entry.sig_info.rev ); CHECK( copy.state == entry.state ); } SECTION( "elapsed" ) { CHECK( entry.elapsed() == 3_ticks ); } SECTION( "elapsed_match" ) { CHECK( entry.elapsed_match() == 2_ticks ); } SECTION( "elapsed_no_match" ) { CHECK( entry.elapsed_no_match() == 1_ticks ); } SECTION( "checks" ) { CHECK( entry.checks() == 3 ); } SECTION( "matches" ) { CHECK( entry.matches() == 2 ); } SECTION( "no_matches" ) { CHECK( entry.no_matches() == 1 ); } SECTION( "alerts" ) { CHECK( entry.alerts() == 77 ); } SECTION( "timeouts" ) { CHECK( entry.timeouts() == 5 ); } SECTION( "suspends" ) { CHECK( entry.suspends() == 2 ); } SECTION( "avg_match" ) { auto ticks = entry.avg_match(); INFO( ticks.count() << " == " << (1_ticks).count() ); CHECK( ticks == 1_ticks ); } SECTION( "avg_no_match" ) { auto ticks = entry.avg_no_match(); INFO( ticks.count() << " == " << (1_ticks).count() ); CHECK( ticks == 1_ticks ); } SECTION( "avg_check" ) { auto ticks = entry.avg_check(); INFO( ticks.count() << " == " << (1_ticks).count() ); CHECK( ticks == 1_ticks ); } } TEST_CASE( "rule profiler sorting", "[profiler][rule_profiler]" ) { using Sort = RuleProfilerConfig::Sort; SECTION( "checks" ) { RuleEntryVector entries { make_rule_entry(0_ticks, 0_ticks, 0, 0), make_rule_entry(0_ticks, 0_ticks, 1, 0), make_rule_entry(0_ticks, 0_ticks, 2, 0) }; RuleStatsVector expected { make_otn_state(0_ticks, 0_ticks, 2, 0), make_otn_state(0_ticks, 0_ticks, 1, 0), make_otn_state(0_ticks, 0_ticks, 0, 0) }; const auto& sorter = rule_stats::sorters[Sort::SORT_CHECKS]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } SECTION( "avg_check" ) { RuleEntryVector entries { make_rule_entry(2_ticks, 0_ticks, 2, 0), make_rule_entry(8_ticks, 0_ticks, 4, 0), make_rule_entry(4_ticks, 0_ticks, 1, 0) }; RuleStatsVector expected { make_otn_state(4_ticks, 0_ticks, 1, 0), make_otn_state(8_ticks, 0_ticks, 4, 0), make_otn_state(2_ticks, 0_ticks, 2, 0) }; const auto& sorter = rule_stats::sorters[Sort::SORT_AVG_CHECK]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } SECTION( "total_time" ) { RuleEntryVector entries { make_rule_entry(0_ticks, 0_ticks, 0, 0), make_rule_entry(1_ticks, 0_ticks, 0, 0), make_rule_entry(2_ticks, 0_ticks, 0, 0) }; RuleStatsVector expected { make_otn_state(2_ticks, 0_ticks, 0, 0), make_otn_state(1_ticks, 0_ticks, 0, 0), make_otn_state(0_ticks, 0_ticks, 0, 0) }; const auto& sorter = rule_stats::sorters[Sort::SORT_TOTAL_TIME]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } SECTION( "matches" ) { RuleEntryVector entries { make_rule_entry(0_ticks, 0_ticks, 0, 0), make_rule_entry(0_ticks, 0_ticks, 0, 1), make_rule_entry(0_ticks, 0_ticks, 0, 2) }; RuleStatsVector expected { make_otn_state(0_ticks, 0_ticks, 0, 2), make_otn_state(0_ticks, 0_ticks, 0, 1), make_otn_state(0_ticks, 0_ticks, 0, 0) }; const auto& sorter = rule_stats::sorters[Sort::SORT_MATCHES]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } SECTION( "no matches" ) { RuleEntryVector entries { make_rule_entry(0_ticks, 0_ticks, 4, 3), make_rule_entry(0_ticks, 0_ticks, 3, 1), make_rule_entry(0_ticks, 0_ticks, 4, 1) }; RuleStatsVector expected { make_otn_state(0_ticks, 0_ticks, 4, 1), make_otn_state(0_ticks, 0_ticks, 3, 1), make_otn_state(0_ticks, 0_ticks, 4, 3) }; const auto& sorter = rule_stats::sorters[Sort::SORT_NO_MATCHES]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } SECTION( "avg match" ) { RuleEntryVector entries { make_rule_entry(4_ticks, 0_ticks, 0, 2), make_rule_entry(6_ticks, 0_ticks, 0, 2), make_rule_entry(8_ticks, 0_ticks, 0, 2) }; RuleStatsVector expected { make_otn_state(8_ticks, 0_ticks, 0, 2), make_otn_state(6_ticks, 0_ticks, 0, 2), make_otn_state(4_ticks, 0_ticks, 0, 2) }; const auto& sorter = rule_stats::sorters[Sort::SORT_AVG_MATCH]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } SECTION( "avg no match" ) { RuleEntryVector entries { make_rule_entry(4_ticks, 0_ticks, 6, 2), make_rule_entry(6_ticks, 0_ticks, 5, 2), make_rule_entry(8_ticks, 0_ticks, 2, 0) }; RuleStatsVector expected { make_otn_state(8_ticks, 0_ticks, 2, 0), make_otn_state(6_ticks, 0_ticks, 5, 2), make_otn_state(4_ticks, 0_ticks, 6, 2) }; const auto& sorter = rule_stats::sorters[Sort::SORT_AVG_NO_MATCH]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } } TEST_CASE( "rule profiler time context", "[profiler][rule_profiler]" ) { dot_node_state_t stats; stats.elapsed = 0_ticks; stats.checks = 0; stats.elapsed_match = 0_ticks; SECTION( "automatically updates stats" ) { { RuleContext ctx(stats); avoid_optimization(); } INFO( "elapsed: " << stats.elapsed.count() ); CHECK( stats.elapsed > 0_ticks ); CHECK( stats.checks == 1 ); INFO( "elapsed_match: " << stats.elapsed_match.count() ); CHECK( stats.elapsed_match == 0_ticks ); } SECTION( "explicitly calling stop" ) { dot_node_state_t save; SECTION( "stop(true)" ) { { RuleContext ctx(stats); avoid_optimization(); ctx.stop(true); INFO( "elapsed: " << stats.elapsed.count() ); CHECK( stats.elapsed > 0_ticks ); CHECK( stats.checks == 1 ); CHECK( stats.elapsed_match == stats.elapsed ); save = stats; } } SECTION( "stop(false)" ) { { RuleContext ctx(stats); avoid_optimization(); ctx.stop(false); INFO( "elapsed: " << stats.elapsed.count() ); CHECK( stats.elapsed > 0_ticks ); CHECK( stats.checks == 1 ); CHECK( stats.elapsed_match == 0_ticks ); save = stats; } } INFO( "elapsed: " << stats.elapsed.count() ); CHECK( stats.elapsed == save.elapsed ); CHECK( stats.elapsed_match == save.elapsed_match ); CHECK( stats.checks == save.checks ); } } #endif
// This program is free software; you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // messy scheme interface #include <unistd.h> #include <sys/time.h> #include <time.h> #include "scheme.h" #include "scheme-private.h" // starwisp stuff ////////////////////////// #ifdef ANDROID_NDK #include <android/log.h> #endif #include "engine/engine.h" #include "engine/shader.h" #include "core/geometry.h" #include "core/osc.h" #include "fluxa/graph.h" #include "fluxa/time.h" #include "audio.h" graph *m_audio_graph = NULL; audio_device *m_audio_device = NULL; char *starwisp_data = NULL; #ifdef USE_SQLITE #include "core/db_container.h" db_container the_db_container; #include "core/idmap.h" idmap the_idmap; #endif pointer scheme_interface(scheme *sc, enum scheme_opcodes op) { switch (op) { ////////// FLUXUS case OP_ALOG: #ifdef ANDROID_NDK __android_log_print(ANDROID_LOG_INFO, "starwisp", string_value(car(sc->args))); #endif s_return(sc,sc->F); case OP_SEND: if (is_string(car(sc->args))) { if (starwisp_data!=NULL) { #ifdef ANDROID_NDK __android_log_print(ANDROID_LOG_INFO, "starwisp", "deleting starwisp data: something is wrong!"); #endif free(starwisp_data); } starwisp_data=strdup(string_value(car(sc->args))); } s_return(sc,sc->F); case OP_OPEN_DB: { #ifdef USE_SQLITE if (is_string(car(sc->args))) { the_db_container.add(string_value(car(sc->args)), new db(string_value(car(sc->args)))); s_return(sc,sc->T); } #endif s_return(sc,sc->F); } case OP_EXEC_DB: { #ifdef USE_SQLITE if (is_string(car(sc->args)) && is_string(cadr(sc->args))) { db *d=the_db_container.get(string_value(car(sc->args))); if (d!=NULL) { s_return(sc,db_exec(sc,d)); } } #endif s_return(sc,sc->F); } case OP_INSERT_DB: { #ifdef USE_SQLITE if (is_string(car(sc->args)) && is_string(cadr(sc->args))) { db *d=the_db_container.get(string_value(car(sc->args))); if (d!=NULL) { db_exec(sc,d); s_return(sc,mk_integer(sc,d->last_rowid())); } } #endif s_return(sc,sc->F); } /* case OP_INSERT_BLOB_DB: { #ifndef FLX_RPI if (is_string(car(sc->args)) && is_string(caddr(sc->args)) && is_string(cadddr(sc->args)) && is_string(caddddr(sc->args)) && is_string(cadddddr(sc->args))) { db *d=the_db_container.get(string_value(car(sc->args))); if (d!=NULL) { db_exec(sc,d); s_return(sc,mk_integer(sc,d->last_rowid())); } } #endif s_return(sc,sc->F); } */ case OP_STATUS_DB: { #ifdef USE_SQLITE if (is_string(car(sc->args))) { s_return(sc,mk_string(sc,the_db_container.status())); } #endif s_return(sc,sc->F); } case OP_TIME: { timeval t; // stop valgrind complaining t.tv_sec=0; t.tv_usec=0; gettimeofday(&t,NULL); s_return(sc,cons(sc,mk_integer(sc,t.tv_sec), cons(sc,mk_integer(sc,t.tv_usec),sc->NIL))); } case OP_NTP_TIME: { spiralcore::time t; t.set_to_now(); s_return(sc,cons(sc,mk_integer(sc,t.seconds), cons(sc,mk_integer(sc,t.fraction),sc->NIL))); } case OP_NTP_TIME_ADD: { spiralcore::time t(ivalue(car(car(sc->args))), ivalue(cadr(car(sc->args)))); t+=rvalue(cadr(sc->args)); s_return(sc,cons(sc,mk_integer(sc,t.seconds), cons(sc,mk_integer(sc,t.fraction),sc->NIL))); } case OP_NTP_TIME_DIFF: { spiralcore::time t(ivalue(car(car(sc->args))), ivalue(cadr(car(sc->args)))); spiralcore::time t2(ivalue(car(cadr(sc->args))), ivalue(cadr(cadr(sc->args)))); s_return(sc,mk_real(sc,t.get_difference(t2))); } case OP_NTP_TIME_GTR: { spiralcore::time t(ivalue(car(car(sc->args))), ivalue(cadr(car(sc->args)))); spiralcore::time t2(ivalue(car(cadr(sc->args))), ivalue(cadr(cadr(sc->args)))); if (t>t2) s_return(sc,sc->T); else s_return(sc,sc->F); } case OP_DATETIME: { timeval t; // stop valgrind complaining t.tv_sec=0; t.tv_usec=0; gettimeofday(&t,NULL); struct tm *now = gmtime((time_t *)&t.tv_sec); /* note: now->tm_year is the number of years SINCE 1900. On the year 2000, this will be 100 not 0. Do a man gmtime for more information */ s_return(sc,cons(sc,mk_integer(sc,now->tm_year + 1900), cons(sc,mk_integer(sc,now->tm_mon + 1), cons(sc,mk_integer(sc,now->tm_mday), cons(sc,mk_integer(sc,now->tm_hour), cons(sc,mk_integer(sc,now->tm_min), cons(sc,mk_integer(sc,now->tm_sec), sc->NIL))))))); } #ifdef USE_SQLITE case OP_ID_MAP_ADD: { the_idmap.add( string_value(car(sc->args)), ivalue(cadr(sc->args))); s_return(sc,sc->F); } case OP_ID_MAP_GET: { s_return( sc,mk_integer(sc,the_idmap.get( string_value(car(sc->args))))); } #endif ///////////////// fluxa ///////////////////////////////////////// case OP_SYNTH_INIT: { // name,buf,sr,synths m_audio_device = new audio_device(string_value(car(sc->args)), ivalue(cadr(sc->args)), ivalue(caddr(sc->args)), ivalue(cadddr(sc->args))); m_audio_graph = new graph(ivalue(caddddr(sc->args)),ivalue(caddr(sc->args))); m_audio_device->start_graph(m_audio_graph); s_return(sc,sc->F); } break; case OP_AUDIO_CHECK: { m_audio_device->check_audio(); s_return(sc,sc->F); } break; case OP_SYNTH_RECORD: { m_audio_device->start_recording(string_value(car(sc->args))); s_return(sc,sc->F); } break; case OP_AUDIO_EQ: { m_audio_device->m_left_eq.set_low(rvalue(car(sc->args))); m_audio_device->m_right_eq.set_low(rvalue(car(sc->args))); m_audio_device->m_left_eq.set_mid(rvalue(cadr(sc->args))); m_audio_device->m_right_eq.set_mid(rvalue(cadr(sc->args))); m_audio_device->m_left_eq.set_high(rvalue(caddr(sc->args))); m_audio_device->m_right_eq.set_high(rvalue(caddr(sc->args))); s_return(sc,sc->F); } break; case OP_AUDIO_COMP: { m_audio_device->m_left_comp.set_attack(rvalue(car(sc->args))); m_audio_device->m_right_comp.set_attack(rvalue(car(sc->args))); m_audio_device->m_left_comp.set_release(rvalue(cadr(sc->args))); m_audio_device->m_right_comp.set_release(rvalue(cadr(sc->args))); m_audio_device->m_left_comp.set_threshold(rvalue(caddr(sc->args))); m_audio_device->m_right_comp.set_threshold(rvalue(caddr(sc->args))); m_audio_device->m_left_comp.set_slope(rvalue(cadddr(sc->args))); m_audio_device->m_right_comp.set_slope(rvalue(cadddr(sc->args))); s_return(sc,sc->F); } break; case OP_SYNTH_CRT: { m_audio_graph ->create(ivalue(car(sc->args)), (graph::node_type)(ivalue(cadr(sc->args))), rvalue(caddr(sc->args))); s_return(sc,sc->F); } break; case OP_SYNTH_CON: { m_audio_graph ->connect(ivalue(car(sc->args)), ivalue(cadr(sc->args)), ivalue(caddr(sc->args))); s_return(sc,sc->F); } break; case OP_SYNTH_PLY: { m_audio_graph ->play(ivalue(car(sc->args)), ivalue(cadr(sc->args)), ivalue(caddr(sc->args)), rvalue(cadddr(sc->args))); s_return(sc,sc->F); } break; case OP_SLEEP: { usleep(ivalue(car(sc->args))); s_return(sc,sc->F); } break; case OP_FMOD: { s_return(sc,mk_real(sc,fmod(rvalue(car(sc->args)),rvalue(cadr(sc->args))))); } break; case OP_OSC_SEND: { const char *url=string_value(car(sc->args)); const char *name=string_value(cadr(sc->args)); const char *types=string_value(caddr(sc->args)); pointer data=cadddr(sc->args); // figure out size of the data packet u32 data_size=0; for (u32 i=0; i<strlen(types); ++i) { switch(types[i]) { case 'f': data_size+=sizeof(float); break; case 'i': data_size+=sizeof(int); break; case 'l': data_size+=sizeof(long long); break; case 's': data_size+=strlen(string_value(list_ref(sc,data,i)))+1; break; } } // build data packet char *packet = new char[data_size]; u32 data_pos=0; for (u32 i=0; i<strlen(types); ++i) { switch(types[i]) { case 'f': { float v=rvalue(list_ref(sc,data,i)); memcpy(packet+data_pos,&v,sizeof(float)); data_pos+=sizeof(float); } break; case 'i': { int v=ivalue(list_ref(sc,data,i)); memcpy(packet+data_pos,&v,sizeof(int)); data_pos+=sizeof(int); } break; case 'l': /*float v=ivalue(list_ref(sc,data,i)); memcpy(packet+data_pos,&v,sizeof(float)); data_pos+=sizeof(long long); */ break; case 's': { char *str=string_value(list_ref(sc,data,i)); memcpy(packet+data_pos,str,strlen(str)); data_pos+=strlen(string_value(list_ref(sc,data,i))); packet[data_pos]=0; // null terminator data_pos++; } break; } } network_osc::send(url,name,types,packet,data_size); delete[] packet; s_return(sc,sc->F); } break; ///////////////// fluxus ///////////////////////////////////////// case OP_PUSH: engine::get()->push(); s_return(sc,sc->F); case OP_POP: engine::get()->pop(); s_return(sc,sc->F); case OP_GRAB: engine::get()->grab(ivalue(car(sc->args))); s_return(sc,sc->F); case OP_UNGRAB: engine::get()->ungrab(); s_return(sc,sc->F); case OP_PARENT: engine::get()->parent(ivalue(car(sc->args))); s_return(sc,sc->F); case OP_LOCK_CAMERA: engine::get()->lock_camera(ivalue(car(sc->args))); s_return(sc,sc->F); case OP_IDENTITY: engine::get()->identity(); s_return(sc,sc->F); case OP_TRANSLATE: engine::get()->translate(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2))); s_return(sc,sc->F); case OP_SCALE: if (!is_vector(car(sc->args))) // uniform scale with one arg { engine::get()->scale(rvalue(car(sc->args)), rvalue(car(sc->args)), rvalue(car(sc->args))); } else { engine::get()->scale(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2))); } s_return(sc,sc->F); case OP_ROTATE: engine::get()->rotate(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2))); s_return(sc,sc->F); case OP_AIM: engine::get()->aim(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2)), rvalue(vector_elem(cadr(sc->args),0)), rvalue(vector_elem(cadr(sc->args),1)), rvalue(vector_elem(cadr(sc->args),2))); s_return(sc,sc->F); case OP_CONCAT: { mat44 t = mat44(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2)), rvalue(vector_elem(car(sc->args),3)), rvalue(vector_elem(car(sc->args),4)), rvalue(vector_elem(car(sc->args),5)), rvalue(vector_elem(car(sc->args),6)), rvalue(vector_elem(car(sc->args),7)), rvalue(vector_elem(car(sc->args),8)), rvalue(vector_elem(car(sc->args),9)), rvalue(vector_elem(car(sc->args),10)), rvalue(vector_elem(car(sc->args),11)), rvalue(vector_elem(car(sc->args),12)), rvalue(vector_elem(car(sc->args),13)), rvalue(vector_elem(car(sc->args),14)), rvalue(vector_elem(car(sc->args),15))); t.transpose(); engine::get()->concat(t); s_return(sc,sc->F); } case OP_COLOUR: engine::get()->colour(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2)), rvalue(vector_elem(car(sc->args),3))); s_return(sc,sc->F); case OP_HINT: { u32 h=ivalue(car(sc->args)); switch (h) { case 0: engine::get()->hint(HINT_NONE); break; case 1: engine::get()->hint(HINT_SOLID); break; case 2: engine::get()->hint(HINT_WIRE); break; case 3: engine::get()->hint(HINT_NORMAL); break; case 4: engine::get()->hint(HINT_POINTS); break; case 5: engine::get()->hint(HINT_AALIAS); break; case 6: engine::get()->hint(HINT_BOUND); break; case 7: engine::get()->hint(HINT_UNLIT); break; case 8: engine::get()->hint(HINT_VERTCOLS); break; case 9: engine::get()->hint(HINT_ORIGIN); break; case 10: engine::get()->hint(HINT_CAST_SHADOW); break; case 11: engine::get()->hint(HINT_IGNORE_DEPTH); break; case 12: engine::get()->hint(HINT_DEPTH_SORT); break; case 13: engine::get()->hint(HINT_LAZY_PARENT); break; case 14: engine::get()->hint(HINT_CULL_CCW); break; case 15: engine::get()->hint(HINT_WIRE_STIPPLED); break; case 16: engine::get()->hint(HINT_SPHERE_MAP); break; case 17: engine::get()->hint(HINT_FRUSTUM_CULL); break; case 18: engine::get()->hint(HINT_NORMALISE); break; case 19: engine::get()->hint(HINT_NOBLEND); break; case 20: engine::get()->hint(HINT_NOZWRITE); break; } s_return(sc,sc->F); } case OP_DESTROY: engine::get()->destroy(rvalue(car(sc->args))); s_return(sc,sc->F); case OP_LINE_WIDTH: engine::get()->line_width(rvalue(car(sc->args))); s_return(sc,sc->F); case OP_TEXTURE: engine::get()->texture(rvalue(car(sc->args))); s_return(sc,sc->F); case OP_SHADER: engine::get()->set_shader(string_value(car(sc->args)), string_value(cadr(sc->args))); s_return(sc,sc->F); case OP_SHADER_SET: { shader *shader = engine::get()->get_current_shader(); shader->apply(); char *name = string_value(car(sc->args)); pointer arg=cadr(sc->args); if (is_vector(arg)) { switch (ivalue(arg)) { case 3: { vec3 vec(rvalue(vector_elem(arg,0)), rvalue(vector_elem(arg,1)), rvalue(vector_elem(arg,2))); shader->set_vector(name,vec); } break; case 16: { mat44 mat(rvalue(vector_elem(arg,0)), rvalue(vector_elem(arg,1)), rvalue(vector_elem(arg,2)), rvalue(vector_elem(arg,3)), rvalue(vector_elem(arg,4)), rvalue(vector_elem(arg,5)), rvalue(vector_elem(arg,6)), rvalue(vector_elem(arg,7)), rvalue(vector_elem(arg,8)), rvalue(vector_elem(arg,9)), rvalue(vector_elem(arg,10)), rvalue(vector_elem(arg,11)), rvalue(vector_elem(arg,12)), rvalue(vector_elem(arg,13)), rvalue(vector_elem(arg,14)), rvalue(vector_elem(arg,15))); shader->set_matrix(name,mat); } break; } } else { if (is_number(arg)) { if (num_is_integer(arg)) { shader->set_int(name,ivalue(arg)); } else { shader->set_float(name,rvalue(arg)); } } } shader->unapply(); s_return(sc,sc->F); } case OP_LOAD_TEXTURE: s_return(sc,mk_integer(sc,engine::get()->get_texture(string_value(car(sc->args))))); case OP_DRAW_INSTANCE: engine::get()->draw_instance(ivalue(car(sc->args))); s_return(sc,sc->F); case OP_BUILD_CUBE: s_return(sc,mk_integer(sc,engine::get()->build_cube())); case OP_LOAD_OBJ: s_return(sc,mk_integer(sc,engine::get()->load_obj(string_value(car(sc->args))))); case OP_RAW_OBJ: s_return(sc,mk_integer(sc,engine::get()->raw_obj(string_value(car(sc->args))))); case OP_BUILD_TEXT: s_return(sc,mk_integer(sc,engine::get()->build_text( string_value(car(sc->args))))); case OP_BUILD_JELLYFISH: s_return(sc,mk_integer(sc,engine::get()->build_jellyfish(ivalue(car(sc->args))))); case OP_BUILD_INSTANCE: s_return(sc,mk_integer(sc,engine::get()->build_instance(ivalue(car(sc->args))))); case OP_BUILD_POLYGONS: s_return(sc,mk_integer(sc,engine::get()->build_polygons( ivalue(car(sc->args)), ivalue(cadr(sc->args)) ))); case OP_GET_TRANSFORM: { flx_real *m=&(engine::get()->get_transform()->m[0][0]); pointer v=mk_vector(sc,16); int i=0; for (i=0; i<16; i++) { set_vector_elem(v,i,mk_real(sc,m[i])); } s_return(sc,v); } case <API key>: { mat44 mat=engine::get()-><API key>(); flx_real *m=&(mat.m[0][0]); pointer v=mk_vector(sc,16); int i=0; for (i=0; i<16; i++) { set_vector_elem(v,i,mk_real(sc,m[i])); } s_return(sc,v); } case <API key>: { flx_real *m=&(engine::get()-><API key>()->m[0][0]); pointer v=mk_vector(sc,16); int i=0; for (i=0; i<16; i++) { set_vector_elem(v,i,mk_real(sc,m[i])); } s_return(sc,v); } case OP_GET_SCREEN_SIZE: { unsigned int *s=engine::get()->get_screensize(); pointer v=mk_vector(sc,2); set_vector_elem(v,0,mk_real(sc,s[0])); set_vector_elem(v,1,mk_real(sc,s[1])); s_return(sc,v); } case OP_APPLY_TRANSFORM: engine::get()->apply_transform(); s_return(sc,sc->F); case OP_CLEAR: engine::get()->clear(); s_return(sc,sc->F); case OP_CLEAR_COLOUR: engine::get()->clear_colour(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2)), rvalue(vector_elem(car(sc->args),3))); s_return(sc,sc->F); case OP_PDATA_SIZE: s_return(sc,mk_integer(sc,engine::get()->pdata_size())); case OP_PDATA_ADD: engine::get()->pdata_add(string_value(car(sc->args))); s_return(sc,sc->F); case OP_PDATA_REF: { vec3* vec=engine::get()->pdata_get(string_value(car(sc->args)), ivalue(cadr(sc->args))); pointer v=mk_vector(sc,3); if (vec) { set_vector_elem(v,0,mk_real(sc,vec->x)); set_vector_elem(v,1,mk_real(sc,vec->y)); set_vector_elem(v,2,mk_real(sc,vec->z)); } s_return(sc,v); } case OP_PDATA_SET: { vec3 vec(rvalue(vector_elem(caddr(sc->args),0)), rvalue(vector_elem(caddr(sc->args),1)), rvalue(vector_elem(caddr(sc->args),2))); engine::get()->pdata_set(string_value(car(sc->args)), ivalue(cadr(sc->args)), vec); s_return(sc,sc->F); } case OP_SET_TEXT: { engine::get()->text_set(string_value(car(sc->args))); s_return(sc,sc->F); } case OP_TEXT_PARAMS: { engine::get()->text_params(string_value(list_ref(sc,sc->args,0)), rvalue(list_ref(sc,sc->args,1)), rvalue(list_ref(sc,sc->args,2)), ivalue(list_ref(sc,sc->args,3)), ivalue(list_ref(sc,sc->args,4)), rvalue(list_ref(sc,sc->args,5)), rvalue(list_ref(sc,sc->args,6)), rvalue(list_ref(sc,sc->args,7)), rvalue(list_ref(sc,sc->args,8)), rvalue(list_ref(sc,sc->args,9)), rvalue(list_ref(sc,sc->args,10))); s_return(sc,sc->F); } case OP_RECALC_BB: { engine::get()->recalc_bb(); s_return(sc,sc->F); } case <API key>: { vec3 pvec(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2))); s_return(sc,mk_integer(sc,engine::get()->bb_point_intersect(pvec,rvalue(cadr(sc->args))))); } case <API key>: { vec3 svec(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2))); vec3 evec(rvalue(vector_elem(cadr(sc->args),0)), rvalue(vector_elem(cadr(sc->args),1)), rvalue(vector_elem(cadr(sc->args),2))); bb::list *points=engine::get()->geo_line_intersect(svec,evec); if (points!=NULL) { pointer list=sc->NIL; intersect_point *p=static_cast<intersect_point*>(points->m_head); while (p!=NULL) { list=cons(sc,mk_real(sc,p->m_t),list); pointer blend=sc->NIL; intersect_point::blend *b= static_cast<intersect_point::blend*> (p->m_blends.m_head); while (b!=NULL) { pointer v=mk_vector(sc,3); set_vector_elem(v,0,mk_real(sc,b->m_blend.x)); set_vector_elem(v,1,mk_real(sc,b->m_blend.y)); set_vector_elem(v,2,mk_real(sc,b->m_blend.z)); pointer l=sc->NIL; l=cons(sc,mk_string(sc,b->m_name),v); blend=cons(sc,l,blend); b=static_cast<intersect_point::blend*>(b->m_next); } list=cons(sc,blend,list); p=static_cast<intersect_point*>(p->m_next); } s_return(sc,list); } s_return(sc,sc->F); } case <API key>: { vec3 svec(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2))); vec3 evec(rvalue(vector_elem(cadr(sc->args),0)), rvalue(vector_elem(cadr(sc->args),1)), rvalue(vector_elem(cadr(sc->args),2))); s_return(sc,mk_integer(sc,engine::get()->get_line_intersect(svec,evec))); } case OP_MINVERSE: { mat44 inm; int i=0; for (i=0; i<16; i++) { inm.arr()[i]=rvalue(vector_elem(car(sc->args),i)); } inm=inm.inverse(); pointer v=mk_vector(sc,16); for (i=0; i<16; i++) { set_vector_elem(v,i,mk_real(sc,inm.arr()[i])); } s_return(sc,v); } case OP_BITWISE_IOR: { s_return(sc,mk_integer(sc, ivalue(car(sc->args))| ivalue(cadr(sc->args))| ivalue(caddr(sc->args)) )); } case OP_BLEND_MODE: { u32 src = GL_SRC_ALPHA; u32 dst = <API key>; u32 s = ivalue(car(sc->args)); u32 d = ivalue(cadr(sc->args)); if (s==0) src=GL_ZERO; else if (s==1) src=GL_ONE; else if (s==2) src=GL_DST_COLOR; else if (s==3) src=<API key>; else if (s==4) src=GL_SRC_ALPHA; else if (s==5) src=<API key>; else if (s==6) src=GL_DST_ALPHA; else if (s==7) src=<API key>; else if (s==8) src=<API key>; if (d==0) dst=GL_ZERO; else if (d==1) dst=GL_ONE; else if (d==9) dst=GL_SRC_COLOR; else if (d==10) dst=<API key>; else if (d==4) dst=GL_SRC_ALPHA; else if (d==5) dst=<API key>; else if (d==6) dst=GL_DST_ALPHA; else if (d==7) dst=<API key>; engine::get()->blend_mode(src,dst); s_return(sc,sc->F); } default: snprintf(sc->strbuff,STRBUFFSIZE,"%d: illegal operator", sc->op); Error_0(sc,sc->strbuff); } }
#include "jni.h" #include "jni_util.h" #include "jvm.h" #include "jlong.h" #include <dlfcn.h> #include <errno.h> #include <sys/acl.h> #include "<API key>.h" static void throwUnixException(JNIEnv* env, int errnum) { jobject x = JNU_NewObjectByName(env, "sun/nio/fs/UnixException", "(I)V", errnum); if (x != NULL) { (*env)->Throw(env, x); } } JNIEXPORT void JNICALL <API key>(JNIEnv *env, jclass clazz) { } JNIEXPORT jint JNICALL <API key>(JNIEnv* env, jclass this, jint fd, jint cmd, jint nentries, jlong address) { void* aclbufp = jlong_to_ptr(address); int n = -1; n = facl((int)fd, (int)cmd, (int)nentries, aclbufp); if (n == -1) { throwUnixException(env, errno); } return (jint)n; }
#include "TreeFactory.h" #include "RobotFactory.h" #include "Robot.h" #include "kinematic/Tree.h" #include "kinematic/Enums.h" #include <vector> #include <list> using namespace matrices; using namespace manip_core::enums; using namespace manip_core::enums::robot; namespace factories { const Vector3 unitx(1, 0, 0); const Vector3 unity(0, 1, 0); const Vector3 unitz(0, 0, 1); const Vector3 unit1(sqrt(14.0)/8.0, 1.0/8.0, 7.0/8.0); const Vector3 zero(0,0,0); struct RobotFactoryPimpl{ RobotFactoryPimpl() { // NOTHING } ~RobotFactoryPimpl() { // NOTHING } // TODO Joint that do not move Robot* CreateHuman(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::Human); Tree* rightLeg = treeFact_.CreateTree( RightLeg, Vector3(0.0, -0.2, 0.1), 0); Tree* leftLeg = treeFact_.CreateTree( LeftLeg, Vector3(0.0, 0.2 , 0.1), 1); Tree* rightArm = treeFact_.CreateTree( RightArm, Vector3(0.0, -0.4, 1.3), 2); Tree* leftArm = treeFact_.CreateTree( LeftArm, Vector3(0.0, 0.4, 1.3), 3); //rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 ); //leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 ); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 1); res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateHumanEscalade(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::HumanEscalade); Tree* rightLeg = treeFact_.CreateTree( RightLegEscalade, Vector3(0.0, -0.2, 0.1), 0); Tree* leftLeg = treeFact_.CreateTree( LeftLegEscalade, Vector3(0.0, 0.2 , 0.1), 1); Tree* rightArm = treeFact_.CreateTree( RightArmEscalade, Vector3(0.0, -0.4, 1.3), 2); Tree* leftArm = treeFact_.CreateTree( LeftArmEscalade, Vector3(0.0, 0.4, 1.3), 3); //rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 ); //leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 ); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 1); res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateHumanCanap(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::HumanCanap); Tree* rightLeg = treeFact_.CreateTree( RightLegCanap, Vector3(0.0, -0.2, 0.1), 0); Tree* leftLeg = treeFact_.CreateTree( LeftLegCanap, Vector3(0.0, 0.2 , 0.1), 1); Tree* rightArm = treeFact_.CreateTree( RightArmCanap, Vector3(0.0, -0.4, 1.3), 2); Tree* leftArm = treeFact_.CreateTree( LeftArmCanap, Vector3(0.0, 0.4, 1.3), 3); //rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 ); //leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 ); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 1); res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateHumanCrouch(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorsoCrouch, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::Human); Tree* rightLeg = treeFact_.CreateTree( RightLegCrouch, Vector3(0.1, -0.2, 0.), 0); Tree* leftLeg = treeFact_.CreateTree( LeftLegCrouch, Vector3(0.1, 0.2 , 0.), 1); Tree* rightArm = treeFact_.CreateTree( RightArmCrouch, Vector3(1.3, -0.4, 0.), 2); Tree* leftArm = treeFact_.CreateTree( LeftArmCrouch, Vector3(1.3, 0.4, 0.), 3); //rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 ); //leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 ); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(rightArm, matrices::Vector3(1.2,0,0), 1); res->AddTree(leftArm, matrices::Vector3(1.2,0,0), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* <API key>(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorsoCrouch180, Vector3(0, 0., 0), 4), manip_core::enums::robot::Human); Tree* rightLeg = treeFact_.CreateTree( RightLegCrouch180, Vector3(0.1, -0.2, 0.), 0); Tree* leftLeg = treeFact_.CreateTree( LeftLegCrouch180, Vector3(0.1, 0.2 , 0.), 1); Tree* rightArm = treeFact_.CreateTree( RightArmCrouch180, Vector3(1.3, -0.4, 0.), 2); Tree* leftArm = treeFact_.CreateTree( LeftArmCrouch180, Vector3(1.3, 0.4, 0.), 3); //rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 ); //leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 ); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(rightArm, matrices::Vector3(1.2,0,0), 1); res->AddTree(leftArm, matrices::Vector3(1.2,0,0), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateHumanWalk(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::HumanWalk); Tree* rightLeg = treeFact_.CreateTree( RightLegWalk, Vector3(0.0, -0.2, 0.1), 0); Tree* leftLeg = treeFact_.CreateTree( LeftLegWalk, Vector3(0.0, 0.2 , 0.1), 1); Tree* rightArm = treeFact_.CreateTree( RightArm, Vector3(0.0, -0.4, 1.3), 2); Tree* leftArm = treeFact_.CreateTree( LeftArm, Vector3(0.0, 0.4, 1.3), 3); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 1); res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateHumanEllipse(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 1), manip_core::enums::robot::HumanEllipse); //Tree* rightLeg = treeFact_.CreateTree( RightLegWalk, Vector3(0.0, -0.2, 0.1), 0); //Tree* leftLeg = treeFact_.CreateTree( LeftLegWalk, Vector3(0.0, 0.2 , 0.1), 1); Tree* rightArm = treeFact_.CreateTree( RightArmEllipse, Vector3(0.0, -0.4, 1.3), 0); //Tree* leftArm = treeFact_.CreateTree( LeftArm, Vector3(0.0, 0.4, 1.3), 3); /*res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0);*/ res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 0); //res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateQuadruped(const Matrix4& robotBasis) const { // TODO Remove order neccessity to create ids ... Robot* res = new Robot(robotBasis, treeFact_.CreateTree( QuadrupedTorso, Vector3(0.0, 0., 0.0), 4), manip_core::enums::robot::Quadruped); factories::TreeFactory factory; Tree* rightLeg = treeFact_.CreateTree( QuadrupedLegRight, Vector3(-1.2, -0.25, -0.1), 0); Tree* leftLeg = treeFact_.CreateTree( QuadrupedLegLeft, Vector3(-1.2, 0.25 , -0.1), 1); Tree* leftArm = treeFact_.CreateTree( QuadrupedLegLeft, Vector3(0.3, 0.25 , -0.1), 2); Tree* rightArm = treeFact_.CreateTree( QuadrupedLegRight, Vector3(0.3, -0.25, -0.1), 3); res->AddTree(rightLeg, matrices::Vector3(-1.2,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(-1.2,0,0), 0); res->AddTree(leftArm, matrices::Vector3(0.3,0,0), 1); res->AddTree(rightArm, matrices::Vector3(0.3,0,0), 1); /*rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3(-0.3, 0, -1.3))); leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.5, 0, -1.3))); rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.3, 0, -1.3)));*/ rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.4))); leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.4, 0, -1.4))); leftArm->LockTarget (matrix4TimesVect3(res->ToWorldCoordinates(), leftArm->GetPosition() + Vector3( -0.4, 0, -1.4))); return res; } Robot* CreateQuadrupedDown(const Matrix4& robotBasis) const { // TODO Remove order neccessity to create ids ... Robot* res = new Robot(robotBasis, treeFact_.CreateTree( QuadrupedTorso, Vector3(0.0, 0., 0.0), 4), manip_core::enums::robot::Quadruped); factories::TreeFactory factory; Tree* rightLeg = treeFact_.CreateTree( <API key>, Vector3(0.0, -0.25, -0.1), 0); Tree* leftLeg = treeFact_.CreateTree( <API key>, Vector3(0.0, 0.25 , -0.1), 1); Tree* leftArm = treeFact_.CreateTree( <API key>, Vector3(1.5, 0.25 , -0.1), 2); Tree* rightArm = treeFact_.CreateTree( <API key>, Vector3(1.5, -0.25, -0.1), 3); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftArm, matrices::Vector3(1.5,0,0), 1); res->AddTree(rightArm, matrices::Vector3(1.5,0,0), 1); /*rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3(-0.3, 0, -1.3))); leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.5, 0, -1.3))); rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.3, 0, -1.3)));*/ rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.4))); leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.4, 0, -1.4))); leftArm->LockTarget (matrix4TimesVect3(res->ToWorldCoordinates(), leftArm->GetPosition() + Vector3( -0.4, 0, -1.4))); return res; } Robot* CreateSpider(const Matrix4& robotBasis) const { // TODO Remove order neccessity to create ids ... Robot* res = new Robot(robotBasis, treeFact_.CreateTree( SpiderTorso, Vector3(0.0, 0., 0.0), 8), manip_core::enums::robot::Spider); factories::TreeFactory factory; Vector3 zeroAngle(0.25, 0, 0); Tree* t1 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 0); Tree* t2 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 1); Tree* t3 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 2); Tree* t4 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 3); Tree* t5 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 4); Tree* t6 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 5); Tree* t7 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 6); Tree* t8 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 7); matrices::Vector3 position(0,0,0); res->AddTree(t1,position, 1); res->AddTree(t2,position, 1); res->AddTree(t3,position, 1); res->AddTree(t4,position, 1); res->AddTree(t5,position, 1); res->AddTree(t6,position, 1); res->AddTree(t7,position, 1); res->AddTree(t8,position, 1); /*rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3(-0.3, 0, -1.3))); leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.5, 0, -1.3))); rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.3, 0, -1.3)));*/ /*rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.4))); leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.4, 0, -1.4))); leftArm->LockTarget (matrix4TimesVect3(res->ToWorldCoordinates(), leftArm->GetPosition() + Vector3( -0.4, 0, -1.4)));*/ return res; } Robot* CreateSpiderRace(const Matrix4& robotBasis) const { // TODO Remove order neccessity to create ids ... Robot* res = new Robot(robotBasis, treeFact_.CreateTree( SpiderTorsoRace, Vector3(0.0, 0., 0.0), 4), manip_core::enums::robot::SpiderRace); factories::TreeFactory factory; Vector3 zeroAngle(0.25, 0, 0); Tree* t1 = treeFact_.CreateTree( SpiderLegRace, zeroAngle, 0); Tree* t2 = treeFact_.CreateTree( SpiderLegRace, zeroAngle, 1); Tree* t3 = treeFact_.CreateTree( SpiderLegRace, zeroAngle, 2); Tree* t4 = treeFact_.CreateTree( SpiderLegRace, zeroAngle, 3); matrices::Vector3 position(0,0,0); res->AddTree(t1,position, 1); res->AddTree(t2,position, 1); res->AddTree(t3,position, 1); res->AddTree(t4,position, 1); return res; } Robot* CreateSpiderSix(const Matrix4& robotBasis) const { // TODO Remove order neccessity to create ids ... Robot* res = new Robot(robotBasis, treeFact_.CreateTree( SpiderTorsoRace, Vector3(0.0, 0., 0.0), 4), manip_core::enums::robot::SpiderSix); factories::TreeFactory factory; Vector3 zeroAngle(0.25, 0, 0); Tree* t1 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 0); Tree* t2 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 1); Tree* t3 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 2); Tree* t4 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 3); Tree* t5 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 4); Tree* t6 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 5); matrices::Vector3 position(0,0,0); res->AddTree(t1,position, 1); res->AddTree(t2,position, 1); res->AddTree(t3,position, 1); res->AddTree(t4,position, 1); res->AddTree(t5,position, 1); res->AddTree(t6,position, 1); return res; } TreeFactory treeFact_; }; } using namespace factories; RobotFactory::RobotFactory() : pImpl_(new RobotFactoryPimpl()) { // NOTHING } RobotFactory::~RobotFactory() { // NOTHING } Robot* RobotFactory::CreateRobot(const eRobots robots, const Matrix4& robotBasis) const { switch (robots) { case Human: { return pImpl_->CreateHuman(robotBasis); } case HumanWalk: { return pImpl_->CreateHumanWalk(robotBasis); } case HumanEscalade: { return pImpl_->CreateHumanEscalade(robotBasis); } case HumanCanap: { return pImpl_->CreateHumanCanap(robotBasis); } case HumanEllipse: { return pImpl_->CreateHumanEllipse(robotBasis); } case Quadruped: { return pImpl_->CreateQuadruped(robotBasis); } case QuadrupedDown: { return pImpl_->CreateQuadrupedDown(robotBasis); } case Spider: { return pImpl_->CreateSpider(robotBasis); } case SpiderSix: { return pImpl_->CreateSpiderSix(robotBasis); } case SpiderRace: { return pImpl_->CreateSpiderRace(robotBasis); } case HumanCrouch: { return pImpl_->CreateHumanCrouch(robotBasis); } case HumanCrouch180: { return pImpl_-><API key>(robotBasis); } default: throw(std::exception()); } } /* bool IsSpine(const joint_def_t* root) { const std::string headTag("head"); std::string taf(root->tag); return (root->nbChildren_ == 0) ? (taf == headTag) : IsSpine(root->children[0]); } const joint_def_t* RetrieveSpine(std::list<const joint_def_t*>& trees) { for(std::list<const joint_def_t*>::const_iterator it = trees.begin(); it!= trees.end(); ++it) { if(IsSpine(*it)) { const joint_def_t* res = (*it); trees.remove(*it); return res; } } return 0; } void GetTrees(const joint_def_t* root, std::list<const joint_def_t*>& trees) { if(root->is_simple() && !root->is_locked()) { trees.push_back(root); } else { for(unsigned int i = 0; i < root->nbChildren_; ++i) { GetTrees(root->children[i], trees); } } } #include "Pi.h" #include "kinematic/Com.h" #include "kinematic/Joint.h" #include "kinematic/Tree.h" Joint* GetLast(Tree* tree) { Joint* j = tree->GetRoot(); while(j) { if(j->pChild_) j = j->pChild_; else return j; } return 0; } void ReadOneJointDef(matrices::Vector3 root, const joint_def_t* jointDef, Tree* tree, const ComFactory& comFact_) { const Vector3 unitx(1, 0, 0); const Vector3 unity(0, 1, 0); const Vector3 unitz(0, 0, 1); const Vector3 vectors []= {unitx, unity, unitz}; Joint* previous = GetLast(tree); matrices::Vector3 attach(jointDef->offset[0], jointDef->offset[1], jointDef->offset[2]); attach += root; bool lastIsEffector = jointDef->nbChildren_ == 0; for(int i = 0; i < 3; ++ i) { Joint* j = new Joint(attach, vectors[i], (lastIsEffector && i == 2) ? EFFECTOR : JOINT, comFact_.CreateCom(None) , RADIAN(jointDef->minAngleValues[i]), RADIAN(jointDef->maxAngleValues[i]), RADIAN(jointDef->defaultAngleValues[i]), rotation::eRotation(i)); if(previous) { tree->InsertChild(previous, j); } else { tree->InsertRoot(j); } previous = j; } if(!lastIsEffector) ReadOneJointDef(attach, jointDef->children[0], tree, comFact_); } Tree* MakeTree(const joint_def_t* root, unsigned int& id) { assert(root->is_simple()); const ComFactory comFact; Tree* tree = new Tree(id++); const joint_def_t* current_joint = root; matrices::Vector3 attach(0,0,0); ReadOneJointDef(attach, root, tree, comFact); return tree; } Robot* RobotFactory::CreateRobot(const joint_def_t& joint, const Matrix4& robotBasis) const { std::list<const joint_def_t*> trees; GetTrees(&joint, trees); const joint_def_t * spine = RetrieveSpine(trees); unsigned int id = 0; unsigned int torsoIndex = trees.size(); Robot* res = new Robot(robotBasis, MakeTree(spine, torsoIndex)); for(std::list<const joint_def_t*>::const_iterator it = trees.begin(); it!= trees.end(); ++it) { matrices::Vector3 offset((*it)->offset[0], (*it)->offset[1], (*it)->offset[2]); res->AddTree( MakeTree((*it), id), offset, 0); // TODO find good column joint for rendering } return res; }*/
<!DOCTYPE html> <html lang="en"> <head> <?php Copyright 2015 Luna Claudio,Rebolloso Leandro. //This file is part of ARSoftware. //ARSoftware is free software; you can redistribute it and/or //as published by the Free Software Foundation; either version 2 //ARSoftware is distributed in the hope that it will be useful, //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //along with this program; if not, write to the Free Software //Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ?> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>ARSoftware</title> <?php include_once($_SERVER["DOCUMENT_ROOT"]."/arsoftware/utiles/headerAdmin.php"); include_once($docRootSitio."modelo/Administrador.php"); $limit=15; if(is_numeric($_GET['pagina']) && $_GET['pagina']>=1){ $offset = ($_GET['pagina']-1) * $limit; } else{ $offset=0; } #Orden por defecto if(!isset($_GET['campoOrder']) && !isset($_GET['order']) ){ $order = "DESC"; } else{ $campoOrder = $_GET['campoOrder']; $order = $_GET['order']; } #incluyo clases include_once($docRootSitio."modelo/Marca.php"); #nuevo objeto $mar1 = new Marca(); $adm1 = new Administrador(); $usuario = $_SESSION["nombreUsuario"]; $mar1->setNombreUsuario($usuario); $_marcas = $mar1->listarMarcas($offset,$limit,$campoOrder,$order); $_nombre = $adm1-><API key>($usuario); #getCantRegistros $cantRegistros = $mar1->getCantRegistros(); $cantPaginas = ceil($cantRegistros/$limit); ?> <!-- Bootstrap Core CSS --> <link href="<?php echo $httpHostSitio?>plantilla/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="<?php echo $httpHostSitio?>plantilla/css/sb-admin.css" rel="stylesheet"> <!-- Morris Charts CSS --> <link href="<?php echo $httpHostSitio?>plantilla/css/plugins/morris.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="<?php echo $httpHostSitio?>plantilla/font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <script src="<?php echo $httpHostSitio?>jquery/jquery-1.11.1.js"></script> <script src="<?php echo $httpHostSitio?>plantilla/js/bootstrap.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file: <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif] </head> <body> <div id="wrapper"> <!-- Navigation --> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <div onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/administradores/<API key>.php')"; style="height: 52px; width:225px; max-width: 100%; background: #FFFFFF; background-image: url(<?php echo $httpHostSitio?>plantilla/imagenes/logotipoe.png);"></div> </div> <ul class="nav navbar-right top-nav"> <li class="dropdown"> <a href="<API key>.php" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-user"></i> <?php echo $_nombre['nombre'].' '.$_nombre['apellido']?> <b class="caret"></b></a> <ul class="dropdown-menu"> <li> <a href="<?php echo $httpHostSitio?>utiles/ctrlLogout.php"><i class="fa fa-fw fa-power-off"></i> Salir</a> </li> </ul> </li> </ul> <!-- Sidebar Menu Items - These collapse to the responsive navigation menu on small screens --> <div class="collapse navbar-collapse navbar-ex1-collapse"> <?php include_once($docRootSitio."utiles/menuAdministradorAR.php");?> </div> <!-- /.navbar-collapse --> </nav> <div id="page-wrapper"> <div class="container-fluid"> </div> <div class="row"> <div class="col-lg-12"> <h1 class="page-header"> Marcas Netbooks </h1> <ol class="breadcrumb"> <li class="active"> <i class="fa fa-dashboard"></i> Marcas Netbooks </li> </ol> </div> </div> <?php if($_GET['insert']==1){?> <div class="alert alert-success"> <strong>La Marca Se Agrego Exitosamente.</strong> </div> <?php }?> <?php if($_GET['update']==1){?> <div class="alert alert-success"> <strong>La Marca Se Modificó Exitosamente.</strong> </div> <?php }?> <?php if($_GET['delete']==1){?> <div class="alert alert-success"> <strong>La Marca Se Elimino Exitosamente.</strong> </div> <?php }?> <p> <button type="button" class="btn btn-primary" onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/netescuela/listarNetbooks.php')" > Remanente Netbook</button> <button type="button" class="btn btn-success" onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/prestamo/listarPrestamos.php')" > Prestamos Netbook</button> <button type="button" class="btn btn-warning" onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/marcas/listarMarcas.php')" > Marcas Netbooks</button> <button type="button" class="btn btn-danger" onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/marcas/agregarMarca.php')" > Agregar Marca Netbooks</button> </p> <?php if(!isset($_GET['order']) || $_GET['order']=="DESC"){ $order = "ASC"; } else{ $order = "DESC"; } if(count($_marcas)){?> <table class="table table-bordered table-hover table-striped"> <tr> <td> <center><b>Nombre</b></center> </td> <td> <center><b>Acciones</b></center> </td> </tr> <?php for($i=1;$i<=count($_marcas);$i++){ if($i%2==0){ $class="class='alt'"; $classTh="class='specalt'"; } else{ $class=""; $classTh="class='spec'"; } ?> <tr> <td> <center><?php echo $_marcas[$i]['nombre']?></center> </td> <td> <div id="celdaAcciones"> <center><form method="post" action="modificarMarca.php"> <input type="hidden" name="Marca" value="<?php echo $_marcas[$i]['id']?>"> <input type="submit" value="Editar" class="btn btn-primary"> </form></center> </div> <div id="celdaAcciones"> <center><form method="post" action="eliminarMarca.php"> <input type="hidden" name="Marca" value="<?php echo $_marcas[$i]['id']?>"> <input type="submit" value="Eliminar" class="btn btn-success" onclick="return confirm('¿Está seguro que desea eliminar la siguiente marca <?php echo $_marcas[$i]['nombre']?>?');"> </form></center> </div> </td> </tr> <?php }?> </table> <div id="paginacion"> <?php if(!is_numeric($_GET['pagina']) || $_GET['pagina']<=1){ $_GET['pagina'] = 1; } else{ $paginaAnterior=$_GET['pagina']-1; if(isset($_GET['campoOrder']) && isset($_GET['order'])){ $campoOrder = $_GET['campoOrder'];+ $order = $_GET['order']; $criteriosOrder = "&campoOrder=$campoOrder&order=$order"; } ?> <a href="listarMarcas.php?pagina=<?php echo $paginaAnterior?><?php echo $criteriosOrder?>">Anterior</a> <?php }?> Página <?php echo $_GET['pagina']?>/<?php echo $cantPaginas?> de <?php echo $cantRegistros?> registros <?php if($_GET['pagina']<$cantPaginas){ $paginaSiguiente=$_GET['pagina']+1; if(isset($_GET['campoOrder']) && isset($_GET['order'])){ $campoOrder = $_GET['campoOrder'];+ $order = $_GET['order']; $criteriosOrder = "&campoOrder=$campoOrder&order=$order"; } ?> <a href="listarMarcas.php?pagina=<?php echo $paginaSiguiente?><?php echo $criteriosOrder?>">Siguiente</a> <?php }?> </div> <?php } else{?> <div class="alert alert-info"> <center><strong>Aviso! </strong> No existen marcas de netbooks cargadas.</center> </div> <?php }?> </div> <!-- /#page-wrapper --> <!-- /#wrapper --> <!-- jQuery Version 1.11.0 --> <script src="js/jquery-1.11.0.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Morris Charts JavaScript --> <script src="js/plugins/morris/raphael.min.js"></script> <script src="js/plugins/morris/morris.min.js"></script> <script src="js/plugins/morris/morris-data.js"></script> </body> </html>
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ #define RG_MODULE_STRING "[TrackButtons]" #include "TrackButtons.h" #include "TrackLabel.h" #include "TrackVUMeter.h" #include "misc/Debug.h" #include "misc/Strings.h" #include "base/AudioPluginInstance.h" #include "base/Composition.h" #include "base/Device.h" #include "base/Instrument.h" #include "base/<API key>.h" #include "base/MidiProgram.h" #include "base/Studio.h" #include "base/Track.h" #include "commands/segment/RenameTrackCommand.h" #include "document/RosegardenDocument.h" #include "document/CommandHistory.h" #include "gui/application/<API key>.h" #include "gui/general/GUIPalette.h" #include "gui/general/IconLoader.h" #include "gui/seqmanager/SequenceManager.h" #include "gui/widgets/LedButton.h" #include "sound/AudioFileManager.h" #include "sound/ControlBlock.h" #include "sound/PluginIdentifier.h" #include "sequencer/RosegardenSequencer.h" #include <QApplication> #include <QLayout> #include <QMessageBox> #include <QCursor> #include <QFrame> #include <QIcon> #include <QLabel> #include <QObject> #include <QPixmap> #include <QMenu> #include <QSignalMapper> #include <QString> #include <QTimer> #include <QWidget> #include <QStackedWidget> #include <QToolTip> namespace Rosegarden { // Constants const int TrackButtons::m_borderGap = 1; const int TrackButtons::m_buttonGap = 8; const int TrackButtons::m_vuWidth = 20; const int TrackButtons::m_vuSpacing = 2; TrackButtons::TrackButtons(RosegardenDocument* doc, int trackCellHeight, int trackLabelWidth, bool showTrackLabels, int overallHeight, QWidget* parent) : QFrame(parent), m_doc(doc), m_layout(new QVBoxLayout(this)), m_recordSigMapper(new QSignalMapper(this)), m_muteSigMapper(new QSignalMapper(this)), m_soloSigMapper(new QSignalMapper(this)), m_clickedSigMapper(new QSignalMapper(this)), m_instListSigMapper(new QSignalMapper(this)), m_tracks(doc->getComposition().getNbTracks()), // m_offset(4), m_cellSize(trackCellHeight), m_trackLabelWidth(trackLabelWidth), m_popupTrackPos(0), m_lastSelected(-1) { setFrameStyle(Plain); QPalette pal = palette(); pal.setColor(backgroundRole(), QColor(0xDD, 0xDD, 0xDD)); pal.setColor(foregroundRole(), Qt::black); setPalette(pal); // when we create the widget, what are we looking at? if (showTrackLabels) { m_labelDisplayMode = TrackLabel::ShowTrack; } else { m_labelDisplayMode = TrackLabel::ShowInstrument; } m_layout->setMargin(0); // Set the spacing between vertical elements m_layout->setSpacing(m_borderGap); // Now draw the buttons and labels and meters makeButtons(); m_layout->addStretch(20); connect(m_recordSigMapper, SIGNAL(mapped(int)), this, SLOT(slotToggleRecord(int))); connect(m_muteSigMapper, SIGNAL(mapped(int)), this, SLOT(slotToggleMute(int))); connect(m_soloSigMapper, SIGNAL(mapped(int)), this, SLOT(slotToggleSolo(int))); // connect signal mappers connect(m_instListSigMapper, SIGNAL(mapped(int)), this, SLOT(slotInstrumentMenu(int))); connect(m_clickedSigMapper, SIGNAL(mapped(int)), this, SLOT(slotTrackSelected(int))); // We have to force the height for the moment setMinimumHeight(overallHeight); m_doc->getComposition().addObserver(this); // We do not care about documentChanged() because if the // document is changing, we are going away. A new TrackButtons // is created for each new document. //connect(<API key>::self(), // SIGNAL(documentChanged(RosegardenDocument *)), // SLOT(slotNewDocument(RosegardenDocument *))); } TrackButtons::~TrackButtons() { // CRASH! Probably m_doc is gone... // Probably don't need to disconnect as we only go away when the // doc and composition do. shared_ptr would help here. // m_doc->getComposition().removeObserver(this); } void TrackButtons::updateUI(Track *track) { if (!track) return; int pos = track->getPosition(); if (pos < 0 || pos >= m_tracks) return; QFrame *hbox = m_trackHBoxes.at(pos); if (track->isArchived()) { // Go with the dark gray background. QPalette palette = hbox->palette(); palette.setColor(hbox->backgroundRole(), QColor(0x88, 0x88, 0x88)); hbox->setPalette(palette); } else { // Go with the parent's background color. QColor parentBackground = palette().color(backgroundRole()); QPalette palette = hbox->palette(); palette.setColor(hbox->backgroundRole(), parentBackground); hbox->setPalette(palette); } if (track->isMuted()) { m_muteLeds[pos]->off(); } else { m_muteLeds[pos]->on(); } Instrument *ins = m_doc->getStudio().getInstrumentById(track->getInstrument()); m_recordLeds[pos]->setColor(getRecordLedColour(ins)); // Note: setRecord() used to be used to do this. But that would // set the track in the composition to record as well as setting // the button on the UI. This seems better and works fine. bool recording = m_doc->getComposition().isTrackRecording(track->getId()); setRecordButton(pos, recording); // ??? An Led::setState(bool) would be handy. m_soloLeds[pos]->setState(track->isSolo() ? Led::On : Led::Off); TrackLabel *label = m_trackLabels[pos]; if (!label) return; // In case the tracks have been moved around, update the mapping. label->setId(track->getId()); setButtonMapping(label, track->getId()); label->setPosition(pos); if (track->getLabel() == "") { if (ins && ins->getType() == Instrument::Audio) { label->setTrackName(tr("<untitled audio>")); } else { label->setTrackName(tr("<untitled>")); } } else { label->setTrackName(strtoqstr(track->getLabel())); label->setShortName(strtoqstr(track->getShortLabel())); } initInstrumentNames(ins, label); label->updateLabel(); } void TrackButtons::makeButtons() { if (!m_doc) return; //RG_DEBUG << "makeButtons()"; // Create a horizontal box filled with widgets for each track for (int i = 0; i < m_tracks; ++i) { Track *track = m_doc->getComposition().getTrackByPosition(i); if (!track) continue; QFrame *trackHBox = makeButton(track); if (trackHBox) { trackHBox->setObjectName("TrackButtonFrame"); m_layout->addWidget(trackHBox); m_trackHBoxes.push_back(trackHBox); } } populateButtons(); } void TrackButtons::setButtonMapping(TrackLabel* trackLabel, TrackId trackId) { m_clickedSigMapper->setMapping(trackLabel, trackId); m_instListSigMapper->setMapping(trackLabel, trackId); } void TrackButtons::initInstrumentNames(Instrument *ins, TrackLabel *label) { if (!label) return; if (ins) { label->setPresentationName(ins-><API key>()); if (ins->sendsProgramChange()) { label-><API key>( QObject::tr(ins->getProgramName().c_str())); } else { label-><API key>(""); } } else { label->setPresentationName(tr("<no instrument>")); } } void TrackButtons::populateButtons() { //RG_DEBUG << "populateButtons()"; // For each track, copy info from Track object to the widgets for (int i = 0; i < m_tracks; ++i) { Track *track = m_doc->getComposition().getTrackByPosition(i); if (!track) continue; updateUI(track); } } void TrackButtons::slotToggleMute(int pos) { //RG_DEBUG << "TrackButtons::slotToggleMute( position =" << pos << ")"; if (!m_doc) return; if (pos < 0 || pos >= m_tracks) return; Composition &comp = m_doc->getComposition(); Track *track = comp.getTrackByPosition(pos); if (!track) return; // Toggle the mute state track->setMuted(!track->isMuted()); // Notify observers comp.notifyTrackChanged(track); m_doc-><API key>(); } void TrackButtons::toggleSolo() { if (!m_doc) return; Composition &comp = m_doc->getComposition(); int pos = comp.<API key>(comp.getSelectedTrack()); if (pos == -1) return; slotToggleSolo(pos); } void TrackButtons::slotToggleSolo(int pos) { //RG_DEBUG << "slotToggleSolo( position =" << pos << ")"; if (!m_doc) return; if (pos < 0 || pos >= m_tracks) return; Composition &comp = m_doc->getComposition(); Track *track = comp.getTrackByPosition(pos); if (!track) return; bool state = !track->isSolo(); // If we're setting solo on this track and shift isn't being held down, // clear solo on all tracks (canceling mode). If shift is being held // down, multiple tracks can be put into solo (latching mode). if (state && QApplication::keyboardModifiers() != Qt::ShiftModifier) { // For each track for (int i = 0; i < m_tracks; ++i) { // Except the one that is being toggled. if (i == pos) continue; Track *track2 = comp.getTrackByPosition(i); if (!track2) continue; if (track2->isSolo()) { // Clear solo track2->setSolo(false); comp.notifyTrackChanged(track2); } } } // Toggle the solo state track->setSolo(state); // Notify observers comp.notifyTrackChanged(track); m_doc-><API key>(); } void TrackButtons::removeButtons(int position) { //RG_DEBUG << "removeButtons() - deleting track button at position:" << position; if (position < 0 || position >= m_tracks) { RG_DEBUG << "%%%%%%%%% BIG PROBLEM : TrackButtons::removeButtons() was passed a non-existing index\n"; return; } std::vector<TrackLabel*>::iterator tit = m_trackLabels.begin(); tit += position; m_trackLabels.erase(tit); std::vector<TrackVUMeter*>::iterator vit = m_trackMeters.begin(); vit += position; m_trackMeters.erase(vit); std::vector<LedButton*>::iterator mit = m_muteLeds.begin(); mit += position; m_muteLeds.erase(mit); mit = m_recordLeds.begin(); mit += position; m_recordLeds.erase(mit); m_soloLeds.erase(m_soloLeds.begin() + position); // Delete all child widgets (button, led, label...) delete m_trackHBoxes[position]; m_trackHBoxes[position] = nullptr; std::vector<QFrame*>::iterator it = m_trackHBoxes.begin(); it += position; m_trackHBoxes.erase(it); } void TrackButtons::slotUpdateTracks() { //RG_DEBUG << "slotUpdateTracks()"; #if 0 static QTime t; RG_DEBUG << " elapsed: " << t.restart(); #endif if (!m_doc) return; Composition &comp = m_doc->getComposition(); const int newNbTracks = comp.getNbTracks(); if (newNbTracks < 0) { RG_WARNING << "slotUpdateTracks(): WARNING: New number of tracks was negative:" << newNbTracks; return; } //RG_DEBUG << "TrackButtons::slotUpdateTracks > newNbTracks = " << newNbTracks; // If a track or tracks were deleted if (newNbTracks < m_tracks) { // For each deleted track, remove a button from the end. for (int i = m_tracks; i > newNbTracks; --i) removeButtons(i - 1); } else if (newNbTracks > m_tracks) { // if added // For each added track for (int i = m_tracks; i < newNbTracks; ++i) { Track *track = m_doc->getComposition().getTrackByPosition(i); if (track) { // Make a new button QFrame *trackHBox = makeButton(track); if (trackHBox) { trackHBox->show(); // Add the new button to the layout. m_layout->insertWidget(i, trackHBox); m_trackHBoxes.push_back(trackHBox); } } else RG_DEBUG << "TrackButtons::slotUpdateTracks - can't find TrackId for position " << i; } } m_tracks = newNbTracks; if (m_tracks != (int)m_trackHBoxes.size()) RG_DEBUG << "WARNING TrackButtons::slotUpdateTracks(): m_trackHBoxes.size() != m_tracks"; if (m_tracks != (int)m_trackLabels.size()) RG_DEBUG << "WARNING TrackButtons::slotUpdateTracks(): m_trackLabels.size() != m_tracks"; // For each track for (int i = 0; i < m_tracks; ++i) { Track *track = comp.getTrackByPosition(i); if (!track) continue; // Track height can change when the user moves segments around and // they overlap. m_trackHBoxes[i]->setMinimumSize(labelWidth(), trackHeight(track->getId())); m_trackHBoxes[i]->setFixedHeight(trackHeight(track->getId())); } populateButtons(); // This is necessary to update the widgets's sizeHint to reflect any change in child widget sizes // Make the TrackButtons QFrame big enough to hold all the track buttons. // Some may have grown taller due to segments that overlap. // Note: This appears to no longer be needed. But it doesn't hurt. adjustSize(); } void TrackButtons::slotToggleRecord(int position) { //RG_DEBUG << "TrackButtons::slotToggleRecord(" << position << ")"; if (position < 0 || position >= m_tracks) return; if (!m_doc) return; Composition &comp = m_doc->getComposition(); Track *track = comp.getTrackByPosition(position); if (!track) return; // Toggle bool state = !comp.isTrackRecording(track->getId()); // Update the Track comp.setTrackRecording(track->getId(), state); comp.notifyTrackChanged(track); m_doc->checkAudioPath(track); } void TrackButtons::setRecordButton(int position, bool record) { if (position < 0 || position >= m_tracks) return; m_recordLeds[position]->setState(record ? Led::On : Led::Off); } void TrackButtons::selectTrack(int position) { if (position < 0 || position >= m_tracks) return; // No sense doing anything if the selection isn't changing if (position == m_lastSelected) return; // Unselect the previously selected if (m_lastSelected >= 0 && m_lastSelected < m_tracks) { m_trackLabels[m_lastSelected]->setSelected(false); } // Select the newly selected m_trackLabels[position]->setSelected(true); m_lastSelected = position; } #if 0 // unused std::vector<int> TrackButtons::<API key>() { std::vector<int> retList; for (int i = 0; i < m_trackLabels.size(); ++i) { if (m_trackLabels[i]->isSelected()) retList.push_back(i); } return retList; } #endif void TrackButtons::slotRenameTrack(QString longLabel, QString shortLabel, TrackId trackId) { if (!m_doc) return; Track *track = m_doc->getComposition().getTrackById(trackId); if (!track) return; TrackLabel *label = m_trackLabels[track->getPosition()]; // If neither label is changing, skip it if (label->getTrackName() == longLabel && QString::fromStdString(track->getShortLabel()) == shortLabel) return; // Rename the track CommandHistory::getInstance()->addCommand( new RenameTrackCommand(&m_doc->getComposition(), trackId, longLabel, shortLabel)); } void TrackButtons::slotSetTrackMeter(float value, int position) { if (position < 0 || position >= m_tracks) return; m_trackMeters[position]->setLevel(value); } void TrackButtons::<API key>(float value, InstrumentId id) { Composition &comp = m_doc->getComposition(); for (int i = 0; i < m_tracks; ++i) { Track *track = comp.getTrackByPosition(i); if (track && track->getInstrument() == id) { m_trackMeters[i]->setLevel(value); } } } void TrackButtons::slotInstrumentMenu(int trackId) { //RG_DEBUG << "TrackButtons::slotInstrumentMenu( trackId =" << trackId << ")"; Composition &comp = m_doc->getComposition(); const int position = comp.getTrackById(trackId)->getPosition(); Track *track = comp.getTrackByPosition(position); Instrument *instrument = nullptr; if (track != nullptr) { instrument = m_doc->getStudio().getInstrumentById( track->getInstrument()); } // E.g. "General MIDI Device m_trackLabels[position]-><API key>(true); m_trackLabels[position]->updateLabel(); // Yes, well as we might've changed the Device name in the // Device/Bank dialog then we reload the whole menu here. QMenu instrumentPopup(this); <API key>(instrument, &instrumentPopup); // Store the popup item position for <API key>(). m_popupTrackPos = position; instrumentPopup.exec(QCursor::pos()); // Turn off the presentation name m_trackLabels[position]-><API key>(false); m_trackLabels[position]->updateLabel(); } // ??? Break this stuff off into an InstrumentPopup class. This class is too // big. void TrackButtons::<API key>(Instrument *thisTrackInstr, QMenu* instrumentPopup) { // pixmaps for icons to show connection states as variously colored boxes // ??? Factor out the icon-related stuff to make this routine clearer. // getIcon(Instrument *) would be ideal, but might not be easy. // getIcon(Device *) would also be needed. static QPixmap connectedPixmap, unconnectedPixmap, connectedUsedPixmap, <API key>, <API key>, <API key>; static bool havePixmaps = false; if (!havePixmaps) { IconLoader il; connectedPixmap = il.loadPixmap("connected"); connectedUsedPixmap = il.loadPixmap("connected-used"); <API key> = il.loadPixmap("connected-selected"); unconnectedPixmap = il.loadPixmap("unconnected"); <API key> = il.loadPixmap("unconnected-used"); <API key> = il.loadPixmap("<API key>"); havePixmaps = true; } Composition &comp = m_doc->getComposition(); // clear the popup instrumentPopup->clear(); QMenu *currentSubMenu = nullptr; // position index int count = 0; int currentDevId = -1; // Get the list Studio &studio = m_doc->getStudio(); InstrumentList list = studio.<API key>(); // For each instrument for (InstrumentList::iterator it = list.begin(); it != list.end(); ++it) { if (!(*it)) continue; // sanity check // get the Localized instrument name, with the string hackery performed // in Instrument QString iname((*it)-><API key>()); // translate the program name // Note we are converting the string from std to Q back to std then to // C. This is obviously ridiculous, but the fact that we have programName // here at all makes me think it exists as some kind of necessary hack // to coax tr() into behaving nicely. I decided to change it as little // as possible to get it to compile, and not refactor this down to the // simplest way to call tr() on a C string. QString programName(strtoqstr((*it)->getProgramName())); programName = QObject::tr(programName.toStdString().c_str()); Device *device = (*it)->getDevice(); DeviceId devId = device->getId(); bool connectedIcon = false; // Determine the proper program name and whether it is connected if ((*it)->getType() == Instrument::SoftSynth) { programName = ""; AudioPluginInstance *plugin = (*it)->getPlugin(Instrument::<API key>); if (plugin) { // we don't translate any plugin program names or other texts programName = strtoqstr(plugin->getDisplayName()); connectedIcon = (plugin->getIdentifier() != ""); } } else if ((*it)->getType() == Instrument::Audio) { connectedIcon = true; } else { QString conn = RosegardenSequencer::getInstance()-> getConnection(devId); connectedIcon = (conn != ""); } // These two are for selecting the correct icon to display. bool instrUsedByMe = false; bool instrUsedByAnyone = false; if (thisTrackInstr && thisTrackInstr->getId() == (*it)->getId()) { instrUsedByMe = true; instrUsedByAnyone = true; } // If we have switched to a new device, we'll create a new submenu if (devId != (DeviceId)(currentDevId)) { currentDevId = int(devId); // For selecting the correct icon to display. bool deviceUsedByAnyone = false; if (instrUsedByMe) deviceUsedByAnyone = true; else { for (Composition::trackcontainer::iterator tit = comp.getTracks().begin(); tit != comp.getTracks().end(); ++tit) { if (tit->second->getInstrument() == (*it)->getId()) { instrUsedByAnyone = true; deviceUsedByAnyone = true; break; } Instrument *instr = studio.getInstrumentById(tit->second->getInstrument()); if (instr && (instr->getDevice()->getId() == devId)) { deviceUsedByAnyone = true; } } } QIcon icon (connectedIcon ? (deviceUsedByAnyone ? connectedUsedPixmap : connectedPixmap) : (deviceUsedByAnyone ? <API key> : unconnectedPixmap)); // Create a submenu for this device QMenu *subMenu = new QMenu(instrumentPopup); subMenu->setMouseTracking(true); subMenu->setIcon(icon); // Not needed so long as <API key> is false. //subMenu->menuAction()-><API key>(true); // Menu title QString deviceName = QObject::tr(device->getName().c_str()); subMenu->setTitle(deviceName); // QObject name subMenu->setObjectName(deviceName); // Add the submenu to the popup menu instrumentPopup->addMenu(subMenu); // Connect the submenu to <API key>() connect(subMenu, SIGNAL(triggered(QAction*)), this, SLOT(<API key>(QAction*))); currentSubMenu = subMenu; } else if (!instrUsedByMe) { // Search the tracks to see if anyone else is using this // instrument for (Composition::trackcontainer::iterator tit = comp.getTracks().begin(); tit != comp.getTracks().end(); ++tit) { if (tit->second->getInstrument() == (*it)->getId()) { instrUsedByAnyone = true; break; } } } QIcon icon (connectedIcon ? (instrUsedByAnyone ? instrUsedByMe ? <API key> : connectedUsedPixmap : connectedPixmap) : (instrUsedByAnyone ? instrUsedByMe ? <API key> : <API key> : unconnectedPixmap)); // Create an action for this instrument QAction* action = new QAction(instrumentPopup); action->setIcon(icon); // Not needed so long as <API key> is false. //action-><API key>(true); // Action text if (programName != "") iname += " (" + programName + ")"; action->setText(iname); // Item index used to find the proper instrument once the user makes // a selection from the menu. action->setData(QVariant(count)); // QObject object name. action->setObjectName(iname + QString(count)); // Add the action to the current submenu if (currentSubMenu) currentSubMenu->addAction(action); // Next item index count++; } } void TrackButtons::<API key>(QAction* action) { // The action data field has the instrument index. <API key>(action->data().toInt()); } void TrackButtons::selectInstrument(Track *track, Instrument *instrument) { // Inform the rest of the system of the instrument change. // ??? This routine needs to go for two reasons: // 1. TrackParameterBox calls this. UI to UI connections should be // avoided. It would be better to copy/paste this over to TPB // to avoid the connection. But then we have double-maintenance. // See reason 2. // 2. The UI shouldn't know so much about the other objects in the // system. The following updates should be done by their // respective objects. // A "TrackStaticSignals::instrumentChanged(Track *, Instrument *)" // notification is probably the best way to get rid of this routine. // It could be emitted from Track::setInstrument(). Normally emitting // from setters is bad, but in this case, it is necessary. We need // to know about every single change when it occurs. // Then <API key> (new class to avoid deriving // ControlBlock from QObject), <API key> (new class to // handle signals for all Instrument instances), and // SequenceManager (already derives from QObject, might want to // consider a new <API key> to avoid additional // dependency on QObject) can connect and do what needs to be done in // response. Rationale for this over doc modified is that we // can't simply refresh everything (Instrument::sendChannelSetup() // sends out data), and it is expensive to detect what has actually // changed (we would have to cache the Track->Instrument mapping and // check it for changes). const TrackId trackId = track->getId(); ControlBlock::getInstance()-> <API key>(trackId, instrument->getId()); // Make sure the Device is in sync with the Instrument's settings. instrument->sendChannelSetup(); // In case the sequencer is currently playing, we need to regenerate // all the events with the new channel number. Composition &comp = m_doc->getComposition(); SequenceManager *sequenceManager = m_doc->getSequenceManager(); // For each segment in the composition for (Composition::iterator i = comp.begin(); i != comp.end(); ++i) { Segment *segment = (*i); // If this Segment is on this Track, let SequenceManager know // that the Instrument has changed. // Segments on this track are now playing on a new // instrument, so they're no longer ready (making them // ready is done just-in-time elsewhere), nor is thru // channel ready. if (segment->getTrack() == trackId) sequenceManager-><API key>(segment); } } void TrackButtons::<API key>(int instrumentIndex) { //RG_DEBUG << "<API key>(): instrumentIndex =" << instrumentIndex; Instrument *instrument = m_doc->getStudio().<API key>(instrumentIndex); //RG_DEBUG << "<API key>(): instrument " << inst; if (!instrument) { RG_WARNING << "<API key>(): WARNING: Can't find Instrument"; return; } Composition &comp = m_doc->getComposition(); Track *track = comp.getTrackByPosition(m_popupTrackPos); if (!track) { RG_WARNING << "<API key>(): WARNING: Can't find Track"; return; } // No change? Bail. if (instrument->getId() == track->getInstrument()) return; // Select the new instrument for the track. // ??? This sends a trackChanged() notification. It shouldn't. We should // send one here. track->setInstrument(instrument->getId()); // ??? This is what we should do. //comp.notifyTrackChanged(track); m_doc-><API key>(); // Notify IPB, ControlBlock, and SequenceManager. selectInstrument(track, instrument); } void TrackButtons::<API key>(TrackLabel::DisplayMode mode) { // Set new mode m_labelDisplayMode = mode; // For each track, set the display mode and update. for (int i = 0; i < m_tracks; i++) { m_trackLabels[i]->setDisplayMode(mode); m_trackLabels[i]->updateLabel(); } } void TrackButtons::<API key>() { //RG_DEBUG << "<API key>()"; Composition &comp = m_doc->getComposition(); for (int i = 0; i < m_tracks; i++) { updateUI(comp.getTrackByPosition(i)); } } #if 0 void TrackButtons::slotLabelSelected(int position) { Track *track = m_doc->getComposition().getTrackByPosition(position); if (track) { emit trackSelected(track->getId()); } } #endif void TrackButtons::<API key>(TrackId trackId, int instrumentIndex) { //RG_DEBUG << "TrackButtons::<API key>( trackId =" << trackId << ", instrumentIndex =" << instrumentIndex << ")"; // Set the position for <API key>(). // ??? This isn't good. Should have a selectTrack() that takes the // track position and the instrument index. <API key>() // could call it. m_popupTrackPos = m_doc->getComposition().getTrackById(trackId)->getPosition(); <API key>(instrumentIndex); } int TrackButtons::labelWidth() { return m_trackLabelWidth - ((m_cellSize - m_buttonGap) * 2 + m_vuSpacing * 2 + m_vuWidth); } int TrackButtons::trackHeight(TrackId trackId) { int multiple = m_doc-> getComposition().<API key>(trackId); if (multiple == 0) multiple = 1; return m_cellSize * multiple - m_borderGap; } QFrame* TrackButtons::makeButton(Track *track) { if (track == nullptr) return nullptr; TrackId trackId = track->getId(); QFrame *trackHBox = new QFrame(this); QHBoxLayout *hblayout = new QHBoxLayout(trackHBox); trackHBox->setLayout(hblayout); hblayout->setMargin(0); hblayout->setSpacing(0); trackHBox->setMinimumSize(labelWidth(), trackHeight(trackId)); trackHBox->setFixedHeight(trackHeight(trackId)); trackHBox->setFrameShape(QFrame::StyledPanel); trackHBox->setFrameShadow(QFrame::Raised); // We will be changing the background color, so turn on auto-fill. trackHBox-><API key>(true); // Insert a little gap hblayout->addSpacing(m_vuSpacing); TrackVUMeter *vuMeter = new TrackVUMeter(trackHBox, VUMeter::PeakHold, m_vuWidth, m_buttonGap, track->getPosition()); m_trackMeters.push_back(vuMeter); hblayout->addWidget(vuMeter); // Insert a little gap hblayout->addSpacing(m_vuSpacing); LedButton *mute = new LedButton( GUIPalette::getColour(GUIPalette::MuteTrackLED), trackHBox); mute->setToolTip(tr("Mute track")); hblayout->addWidget(mute); connect(mute, SIGNAL(stateChanged(bool)), m_muteSigMapper, SLOT(map())); m_muteSigMapper->setMapping(mute, track->getPosition()); m_muteLeds.push_back(mute); mute->setFixedSize(m_cellSize - m_buttonGap, m_cellSize - m_buttonGap); Rosegarden::Instrument *ins = m_doc->getStudio().getInstrumentById(track->getInstrument()); LedButton *record = new LedButton(getRecordLedColour(ins), trackHBox); record->setToolTip(tr("Record on this track")); hblayout->addWidget(record); connect(record, SIGNAL(stateChanged(bool)), m_recordSigMapper, SLOT(map())); m_recordSigMapper->setMapping(record, track->getPosition()); m_recordLeds.push_back(record); record->setFixedSize(m_cellSize - m_buttonGap, m_cellSize - m_buttonGap); LedButton *solo = new LedButton( GUIPalette::getColour(GUIPalette::SoloTrackLED), trackHBox); solo->setToolTip(tr("Solo track")); hblayout->addWidget(solo); connect(solo, SIGNAL(stateChanged(bool)), m_soloSigMapper, SLOT(map())); m_soloSigMapper->setMapping(solo, track->getPosition()); m_soloLeds.push_back(solo); solo->setFixedSize(m_cellSize - m_buttonGap, m_cellSize - m_buttonGap); TrackLabel *trackLabel = new TrackLabel(trackId, track->getPosition(), trackHBox); hblayout->addWidget(trackLabel); hblayout->addSpacing(m_vuSpacing); trackLabel->setDisplayMode(m_labelDisplayMode); trackLabel->setFixedSize(labelWidth(), m_cellSize - m_buttonGap); trackLabel->setFixedHeight(m_cellSize - m_buttonGap); trackLabel->setIndent(7); connect(trackLabel, &TrackLabel::renameTrack, this, &TrackButtons::slotRenameTrack); m_trackLabels.push_back(trackLabel); // Connect it setButtonMapping(trackLabel, trackId); connect(trackLabel, SIGNAL(<API key>()), m_instListSigMapper, SLOT(map())); connect(trackLabel, SIGNAL(clicked()), m_clickedSigMapper, SLOT(map())); return trackHBox; } QColor TrackButtons::getRecordLedColour(Instrument *ins) { if (!ins) return Qt::white; switch (ins->getType()) { case Instrument::Audio: return GUIPalette::getColour(GUIPalette::RecordAudioTrackLED); case Instrument::SoftSynth: return GUIPalette::getColour(GUIPalette::<API key>); case Instrument::Midi: return GUIPalette::getColour(GUIPalette::RecordMIDITrackLED); case Instrument::InvalidInstrument: default: RG_DEBUG << "TrackButtons::slotUpdateTracks() - invalid instrument type, this is probably a BUG!"; return Qt::green; } } void TrackButtons::tracksAdded(const Composition *, std::vector<TrackId> &/*trackIds*/) { //RG_DEBUG << "TrackButtons::tracksAdded()"; // ??? This is a bit heavy-handed as it just adds a track button, then // recreates all the track buttons. We might be able to just add the // one that is needed. slotUpdateTracks(); } void TrackButtons::trackChanged(const Composition *, Track* track) { //RG_DEBUG << "trackChanged()"; //RG_DEBUG << " Position:" << track->getPosition(); //RG_DEBUG << " Armed:" << track->isArmed(); updateUI(track); } void TrackButtons::tracksDeleted(const Composition *, std::vector<TrackId> &/*trackIds*/) { //RG_DEBUG << "TrackButtons::tracksDeleted()"; // ??? This is a bit heavy-handed as it just deletes a track button, // then recreates all the track buttons. We might be able to just // delete the one that is going away. slotUpdateTracks(); } void TrackButtons::<API key>(const Composition *, TrackId trackId) { //RG_DEBUG << "TrackButtons::<API key>()" << trackId; Track *track = m_doc->getComposition().getTrackById(trackId); selectTrack(track->getPosition()); } void TrackButtons::segmentRemoved(const Composition *, Segment *) { // If recording causes the track heights to change, this makes sure // they go back if needed when recording stops. slotUpdateTracks(); } void TrackButtons::slotTrackSelected(int trackId) { // Select the track. m_doc->getComposition().setSelectedTrack(trackId); // Old notification mechanism // ??? This should be replaced with <API key>() below. m_doc->getComposition().<API key>(trackId); // Older mechanism. Keeping this until we can completely replace it // with <API key>() below. emit trackSelected(trackId); // New notification mechanism. // This should replace all others. m_doc-><API key>(); } void TrackButtons::<API key>(bool) { // Full and immediate update. // ??? Note that updates probably happen elsewhere. This will result // in duplicate updates. All other updates should be removed and // this should be the only update. slotUpdateTracks(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Navigation; namespace SupCarLocator.ViewModel { class PageViewModelBase : BaseViewModel { protected NavigationContext NavigationContext; protected NavigationService NavigationService; public virtual void OnNavigatedTo(NavigationContext navigationContext, NavigationService navigationService) { NavigationContext = navigationContext; NavigationService = navigationService; } } }
/* * Ring initialization rules: * 1. Each segment is initialized to zero, except for link TRBs. * 2. Ring cycle state = 0. This represents Producer Cycle State (PCS) or * Consumer Cycle State (CCS), depending on ring function. * 3. Enqueue pointer = dequeue pointer = address of first TRB in the segment. * * Ring behavior rules: * 1. A ring is empty if enqueue == dequeue. This means there will always be at * least one free TRB in the ring. This is useful if you want to turn that * into a link TRB and expand the ring. * 2. When incrementing an enqueue or dequeue pointer, if the next TRB is a * link TRB, then load the pointer with the address in the link TRB. If the * link TRB had its toggle bit set, you may need to update the ring cycle * state (see cycle bit rules). You may have to do this multiple times * until you reach a non-link TRB. * 3. A ring is full if enqueue++ (for the definition of increment above) * equals the dequeue pointer. * * Cycle bit rules: * 1. When a consumer increments a dequeue pointer and encounters a toggle bit * in a link TRB, it must toggle the ring cycle state. * 2. When a producer increments an enqueue pointer and encounters a toggle bit * in a link TRB, it must toggle the ring cycle state. * * Producer rules: * 1. Check if ring is full before you enqueue. * 2. Write the ring cycle state to the cycle bit in the TRB you're enqueuing. * Update enqueue pointer between each write (which may update the ring * cycle state). * 3. Notify consumer. If SW is producer, it rings the doorbell for command * and endpoint rings. If HC is the producer for the event ring, * and it generates an interrupt according to interrupt modulation rules. * * Consumer rules: * 1. Check if TRB belongs to you. If the cycle bit == your ring cycle state, * the TRB is owned by the consumer. * 2. Update dequeue pointer (which may update the ring cycle state) and * continue processing TRBs until you reach a TRB which is not owned by you. * 3. Notify the producer. SW is the consumer for the event ring, and it * updates event ring dequeue pointer. HC is the consumer for the command and * endpoint rings; it generates events on the event ring for these. */ #include <linux/scatterlist.h> #include <linux/slab.h> #include "xhci.h" static int <API key>(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev, struct xhci_event_cmd *event); /* * Returns zero if the TRB isn't in this segment, otherwise it returns the DMA * address of the TRB. */ dma_addr_t <API key>(struct xhci_segment *seg, union xhci_trb *trb) { unsigned long segment_offset; if (!seg || !trb || trb < seg->trbs) return 0; /* offset in TRBs */ segment_offset = trb - seg->trbs; if (segment_offset > TRBS_PER_SEGMENT) return 0; return seg->dma + (segment_offset * sizeof(*trb)); } /* Does this link TRB point to the first segment in a ring, * or was the previous TRB the last TRB on the last segment in the ERST? */ static bool <API key>(struct xhci_hcd *xhci, struct xhci_ring *ring, struct xhci_segment *seg, union xhci_trb *trb) { if (ring == xhci->event_ring) return (trb == &seg->trbs[TRBS_PER_SEGMENT]) && (seg->next == xhci->event_ring->first_seg); else return le32_to_cpu(trb->link.control) & LINK_TOGGLE; } /* Is this TRB a link TRB or was the last TRB the last TRB in this event ring * segment? I.e. would the updated event TRB pointer step off the end of the * event seg? */ static int last_trb(struct xhci_hcd *xhci, struct xhci_ring *ring, struct xhci_segment *seg, union xhci_trb *trb) { if (ring == xhci->event_ring) return trb == &seg->trbs[TRBS_PER_SEGMENT]; else return TRB_TYPE_LINK_LE32(trb->link.control); } static int enqueue_is_link_trb(struct xhci_ring *ring) { struct xhci_link_trb *link = &ring->enqueue->link; return TRB_TYPE_LINK_LE32(link->control); } /* Updates trb to point to the next TRB in the ring, and updates seg if the next * TRB is in a new segment. This does not skip over link TRBs, and it does not * effect the ring dequeue or enqueue pointers. */ static void next_trb(struct xhci_hcd *xhci, struct xhci_ring *ring, struct xhci_segment **seg, union xhci_trb **trb) { if (last_trb(xhci, ring, *seg, *trb)) { *seg = (*seg)->next; *trb = ((*seg)->trbs); } else { (*trb)++; } } /* * See Cycle bit rules. SW is the consumer for the event ring only. * Don't make a ring full of link TRBs. That would be dumb and this would loop. */ static void inc_deq(struct xhci_hcd *xhci, struct xhci_ring *ring) { union xhci_trb *next; unsigned long long addr; ring->deq_updates++; /* If this is not event ring, there is one more usable TRB */ if (ring->type != TYPE_EVENT && !last_trb(xhci, ring, ring->deq_seg, ring->dequeue)) ring->num_trbs_free++; next = ++(ring->dequeue); /* Update the dequeue pointer further if that was a link TRB or we're at * the end of an event ring segment (which doesn't have link TRBS) */ while (last_trb(xhci, ring, ring->deq_seg, next)) { if (ring->type == TYPE_EVENT && <API key>(xhci, ring, ring->deq_seg, next)) { ring->cycle_state = (ring->cycle_state ? 0 : 1); } ring->deq_seg = ring->deq_seg->next; ring->dequeue = ring->deq_seg->trbs; next = ring->dequeue; } addr = (unsigned long long) <API key>(ring->deq_seg, ring->dequeue); } /* * See Cycle bit rules. SW is the consumer for the event ring only. * Don't make a ring full of link TRBs. That would be dumb and this would loop. * * If we've just enqueued a TRB that is in the middle of a TD (meaning the * chain bit is set), then set the chain bit in all the following link TRBs. * If we've enqueued the last TRB in a TD, make sure the following link TRBs * have their chain bit cleared (so that each Link TRB is a separate TD). * * Section 6.4.4.1 of the 0.95 spec says link TRBs cannot have the chain bit * set, but other sections talk about dealing with the chain bit set. This was * fixed in the 0.96 specification errata, but we have to assume that all 0.95 * xHCI hardware can't handle the chain bit being cleared on a link TRB. * * @more_trbs_coming: Will you enqueue more TRBs before calling * prepare_transfer()? */ static void inc_enq(struct xhci_hcd *xhci, struct xhci_ring *ring, bool more_trbs_coming) { u32 chain; union xhci_trb *next; unsigned long long addr; chain = le32_to_cpu(ring->enqueue->generic.field[3]) & TRB_CHAIN; /* If this is not event ring, there is one less usable TRB */ if (ring->type != TYPE_EVENT && !last_trb(xhci, ring, ring->enq_seg, ring->enqueue)) ring->num_trbs_free next = ++(ring->enqueue); ring->enq_updates++; /* Update the dequeue pointer further if that was a link TRB or we're at * the end of an event ring segment (which doesn't have link TRBS) */ while (last_trb(xhci, ring, ring->enq_seg, next)) { if (ring->type != TYPE_EVENT) { /* * If the caller doesn't plan on enqueueing more * TDs before ringing the doorbell, then we * don't want to give the link TRB to the * hardware just yet. We'll give the link TRB * back in prepare_ring() just before we enqueue * the TD at the top of the ring. */ if (!chain && !more_trbs_coming) break; /* If we're not dealing with 0.95 hardware or * isoc rings on AMD 0.96 host, * carry over the chain bit of the previous TRB * (which may mean the chain bit is cleared). */ if (!(ring->type == TYPE_ISOC && (xhci->quirks & XHCI_AMD_0x96_HOST)) && !xhci_link_trb_quirk(xhci)) { next->link.control &= cpu_to_le32(~TRB_CHAIN); next->link.control |= cpu_to_le32(chain); } /* Give this link TRB to the hardware */ wmb(); next->link.control ^= cpu_to_le32(TRB_CYCLE); /* Toggle the cycle bit after the last ring segment. */ if (<API key>(xhci, ring, ring->enq_seg, next)) { ring->cycle_state = (ring->cycle_state ? 0 : 1); } } ring->enq_seg = ring->enq_seg->next; ring->enqueue = ring->enq_seg->trbs; next = ring->enqueue; } addr = (unsigned long long) <API key>(ring->enq_seg, ring->enqueue); } /* * Check to see if there's room to enqueue num_trbs on the ring and make sure * enqueue pointer will not advance into dequeue segment. See rules above. */ static inline int room_on_ring(struct xhci_hcd *xhci, struct xhci_ring *ring, unsigned int num_trbs) { int num_trbs_in_deq_seg; if (ring->num_trbs_free < num_trbs) return 0; if (ring->type != TYPE_COMMAND && ring->type != TYPE_EVENT) { num_trbs_in_deq_seg = ring->dequeue - ring->deq_seg->trbs; if (ring->num_trbs_free < num_trbs + num_trbs_in_deq_seg) return 0; } return 1; } /* Ring the host controller doorbell after placing a command on the ring */ void xhci_ring_cmd_db(struct xhci_hcd *xhci) { xhci_dbg(xhci, "// Ding dong!\n"); xhci_writel(xhci, DB_VALUE_HOST, &xhci->dba->doorbell[0]); /* Flush PCI posted writes */ xhci_readl(xhci, &xhci->dba->doorbell[0]); } void <API key>(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id) { __le32 __iomem *db_addr = &xhci->dba->doorbell[slot_id]; struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index]; unsigned int ep_state = ep->ep_state; /* Don't ring the doorbell for this endpoint if there are pending * cancellations because we don't want to interrupt processing. * We don't want to restart any stream rings if there's a set dequeue * pointer command pending because the device can choose to start any * stream once the endpoint is on the HW schedule. * FIXME - check all the stream rings for pending cancellations. */ if ((ep_state & EP_HALT_PENDING) || (ep_state & SET_DEQ_PENDING) || (ep_state & EP_HALTED)) return; xhci_writel(xhci, DB_VALUE(ep_index, stream_id), db_addr); /* The CPU has better things to do at this point than wait for a * write-posting flush. It'll get there soon enough. */ } /* Ring the doorbell for any rings with pending URBs */ static void <API key>(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index) { unsigned int stream_id; struct xhci_virt_ep *ep; ep = &xhci->devs[slot_id]->eps[ep_index]; /* A ring has pending URBs if its TD list is not empty */ if (!(ep->ep_state & EP_HAS_STREAMS)) { if (!(list_empty(&ep->ring->td_list))) <API key>(xhci, slot_id, ep_index, 0); return; } for (stream_id = 1; stream_id < ep->stream_info->num_streams; stream_id++) { struct xhci_stream_info *stream_info = ep->stream_info; if (!list_empty(&stream_info->stream_rings[stream_id]->td_list)) <API key>(xhci, slot_id, ep_index, stream_id); } } /* * Find the segment that trb is in. Start searching in start_seg. * If we must move past a segment that has a link TRB with a toggle cycle state * bit set, then we will toggle the value pointed at by cycle_state. */ static struct xhci_segment *find_trb_seg( struct xhci_segment *start_seg, union xhci_trb *trb, int *cycle_state) { struct xhci_segment *cur_seg = start_seg; struct xhci_generic_trb *generic_trb; while (cur_seg->trbs > trb || &cur_seg->trbs[TRBS_PER_SEGMENT - 1] < trb) { generic_trb = &cur_seg->trbs[TRBS_PER_SEGMENT - 1].generic; if (generic_trb->field[3] & cpu_to_le32(LINK_TOGGLE)) *cycle_state ^= 0x1; cur_seg = cur_seg->next; if (cur_seg == start_seg) /* Looped over the entire list. Oops! */ return NULL; } return cur_seg; } static struct xhci_ring *<API key>(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id) { struct xhci_virt_ep *ep; ep = &xhci->devs[slot_id]->eps[ep_index]; /* Common case: no streams */ if (!(ep->ep_state & EP_HAS_STREAMS)) return ep->ring; if (stream_id == 0) { xhci_warn(xhci, "WARN: Slot ID %u, ep index %u has streams, " "but URB has no stream ID.\n", slot_id, ep_index); return NULL; } if (stream_id < ep->stream_info->num_streams) return ep->stream_info->stream_rings[stream_id]; xhci_warn(xhci, "WARN: Slot ID %u, ep index %u has " "stream IDs 1 to %u allocated, " "but stream ID %u is requested.\n", slot_id, ep_index, ep->stream_info->num_streams - 1, stream_id); return NULL; } /* Get the right ring for the given URB. * If the endpoint supports streams, boundary check the URB's stream ID. * If the endpoint doesn't support streams, return the singular endpoint ring. */ static struct xhci_ring *<API key>(struct xhci_hcd *xhci, struct urb *urb) { return <API key>(xhci, urb->dev->slot_id, <API key>(&urb->ep->desc), urb->stream_id); } /* * Move the xHC's endpoint ring dequeue pointer past cur_td. * Record the new state of the xHC's endpoint ring dequeue segment, * dequeue pointer, and new consumer cycle state in state. * Update our internal representation of the ring's dequeue pointer. * * We do this in three jumps: * - First we update our new ring state to be the same as when the xHC stopped. * - Then we traverse the ring to find the segment that contains * the last TRB in the TD. We toggle the xHC's new cycle state when we pass * any link TRBs with the toggle cycle bit set. * - Finally we move the dequeue state one TRB further, toggling the cycle bit * if we've moved it past a link TRB with the toggle cycle bit set. * * Some of the uses of xhci_generic_trb are grotty, but if they're done * with correct __le32 accesses they should work fine. Only users of this are * in here. */ void <API key>(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_td *cur_td, struct xhci_dequeue_state *state) { struct xhci_virt_device *dev = xhci->devs[slot_id]; struct xhci_ring *ep_ring; struct xhci_generic_trb *trb; struct xhci_ep_ctx *ep_ctx; dma_addr_t addr; ep_ring = <API key>(xhci, slot_id, ep_index, stream_id); if (!ep_ring) { xhci_warn(xhci, "WARN can't find new dequeue state " "for invalid stream ID %u.\n", stream_id); return; } state->new_cycle_state = 0; xhci_dbg(xhci, "Finding segment containing stopped TRB.\n"); state->new_deq_seg = find_trb_seg(cur_td->start_seg, dev->eps[ep_index].stopped_trb, &state->new_cycle_state); if (!state->new_deq_seg) { WARN_ON(1); return; } /* Dig out the cycle state saved by the xHC during the stop ep cmd */ xhci_dbg(xhci, "Finding endpoint context\n"); ep_ctx = xhci_get_ep_ctx(xhci, dev->out_ctx, ep_index); state->new_cycle_state = 0x1 & le64_to_cpu(ep_ctx->deq); state->new_deq_ptr = cur_td->last_trb; xhci_dbg(xhci, "Finding segment containing last TRB in TD.\n"); state->new_deq_seg = find_trb_seg(state->new_deq_seg, state->new_deq_ptr, &state->new_cycle_state); if (!state->new_deq_seg) { WARN_ON(1); return; } trb = &state->new_deq_ptr->generic; if (TRB_TYPE_LINK_LE32(trb->field[3]) && (trb->field[3] & cpu_to_le32(LINK_TOGGLE))) state->new_cycle_state ^= 0x1; next_trb(xhci, ep_ring, &state->new_deq_seg, &state->new_deq_ptr); /* * If there is only one segment in a ring, find_trb_seg()'s while loop * will not run, and it will return before it has a chance to see if it * needs to toggle the cycle bit. It can't tell if the stalled transfer * ended just before the link TRB on a one-segment ring, or if the TD * wrapped around the top of the ring, because it doesn't have the TD in * question. Look for the one-segment case where stalled TRB's address * is greater than the new dequeue pointer address. */ if (ep_ring->first_seg == ep_ring->first_seg->next && state->new_deq_ptr < dev->eps[ep_index].stopped_trb) state->new_cycle_state ^= 0x1; xhci_dbg(xhci, "Cycle state = 0x%x\n", state->new_cycle_state); /* Don't update the ring cycle state for the producer (us). */ xhci_dbg(xhci, "New dequeue segment = %p (virtual)\n", state->new_deq_seg); addr = <API key>(state->new_deq_seg, state->new_deq_ptr); xhci_dbg(xhci, "New dequeue pointer = 0x%llx (DMA)\n", (unsigned long long) addr); } /* flip_cycle means flip the cycle bit of all but the first and last TRB. * (The last TRB actually points to the ring enqueue pointer, which is not part * of this TD.) This is used to remove partially enqueued isoc TDs from a ring. */ static void td_to_noop(struct xhci_hcd *xhci, struct xhci_ring *ep_ring, struct xhci_td *cur_td, bool flip_cycle) { struct xhci_segment *cur_seg; union xhci_trb *cur_trb; for (cur_seg = cur_td->start_seg, cur_trb = cur_td->first_trb; true; next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) { if (TRB_TYPE_LINK_LE32(cur_trb->generic.field[3])) { /* Unchain any chained Link TRBs, but * leave the pointers intact. */ cur_trb->generic.field[3] &= cpu_to_le32(~TRB_CHAIN); /* Flip the cycle bit (link TRBs can't be the first * or last TRB). */ if (flip_cycle) cur_trb->generic.field[3] ^= cpu_to_le32(TRB_CYCLE); xhci_dbg(xhci, "Cancel (unchain) link TRB\n"); xhci_dbg(xhci, "Address = %p (0x%llx dma); " "in seg %p (0x%llx dma)\n", cur_trb, (unsigned long long)<API key>(cur_seg, cur_trb), cur_seg, (unsigned long long)cur_seg->dma); } else { cur_trb->generic.field[0] = 0; cur_trb->generic.field[1] = 0; cur_trb->generic.field[2] = 0; /* Preserve only the cycle bit of this TRB */ cur_trb->generic.field[3] &= cpu_to_le32(TRB_CYCLE); /* Flip the cycle bit except on the first or last TRB */ if (flip_cycle && cur_trb != cur_td->first_trb && cur_trb != cur_td->last_trb) cur_trb->generic.field[3] ^= cpu_to_le32(TRB_CYCLE); cur_trb->generic.field[3] |= cpu_to_le32( TRB_TYPE(TRB_TR_NOOP)); xhci_dbg(xhci, "TRB to noop at offset 0x%llx\n", (unsigned long long) <API key>(cur_seg, cur_trb)); } if (cur_trb == cur_td->last_trb) break; } } static int queue_set_tr_deq(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_segment *deq_seg, union xhci_trb *deq_ptr, u32 cycle_state); void <API key>(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_dequeue_state *deq_state) { struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index]; xhci_dbg(xhci, "Set TR Deq Ptr cmd, new deq seg = %p (0x%llx dma), " "new deq ptr = %p (0x%llx dma), new cycle = %u\n", deq_state->new_deq_seg, (unsigned long long)deq_state->new_deq_seg->dma, deq_state->new_deq_ptr, (unsigned long long)<API key>(deq_state->new_deq_seg, deq_state->new_deq_ptr), deq_state->new_cycle_state); queue_set_tr_deq(xhci, slot_id, ep_index, stream_id, deq_state->new_deq_seg, deq_state->new_deq_ptr, (u32) deq_state->new_cycle_state); /* Stop the TD queueing code from ringing the doorbell until * this command completes. The HC won't set the dequeue pointer * if the ring is running, and ringing the doorbell starts the * ring running. */ ep->ep_state |= SET_DEQ_PENDING; } static void <API key>(struct xhci_hcd *xhci, struct xhci_virt_ep *ep) { ep->ep_state &= ~EP_HALT_PENDING; /* Can't del_timer_sync in interrupt, so we attempt to cancel. If the * timer is running on another CPU, we don't decrement stop_cmds_pending * (since we didn't successfully stop the watchdog timer). */ if (del_timer(&ep->stop_cmd_timer)) ep->stop_cmds_pending } /* Must be called with xhci->lock held in interrupt context */ static void <API key>(struct xhci_hcd *xhci, struct xhci_td *cur_td, int status, char *adjective) { struct usb_hcd *hcd; struct urb *urb; struct urb_priv *urb_priv; urb = cur_td->urb; urb_priv = urb->hcpriv; urb_priv->td_cnt++; hcd = bus_to_hcd(urb->dev->bus); /* Only giveback urb when this is the last td in urb */ if (urb_priv->td_cnt == urb_priv->length) { if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) { xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) { if (xhci->quirks & XHCI_AMD_PLL_FIX) <API key>(); } } <API key>(hcd, urb); spin_unlock(&xhci->lock); <API key>(hcd, urb, status); xhci_urb_free_priv(xhci, urb_priv); spin_lock(&xhci->lock); } } /* * When we get a command completion for a Stop Endpoint Command, we need to * unlink any cancelled TDs from the ring. There are two ways to do that: * * 1. If the HW was in the middle of processing the TD that needs to be * cancelled, then we must move the ring's dequeue pointer past the last TRB * in the TD with a Set Dequeue Pointer Command. * 2. Otherwise, we turn all the TRBs in the TD into No-op TRBs (with the chain * bit cleared) so that the HW will skip over them. */ static void <API key>(struct xhci_hcd *xhci, union xhci_trb *trb, struct xhci_event_cmd *event) { unsigned int slot_id; unsigned int ep_index; struct xhci_virt_device *virt_dev; struct xhci_ring *ep_ring; struct xhci_virt_ep *ep; struct list_head *entry; struct xhci_td *cur_td = NULL; struct xhci_td *last_unlinked_td; struct xhci_dequeue_state deq_state; if (unlikely(TRB_TO_SUSPEND_PORT( le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3])))) { slot_id = TRB_TO_SLOT_ID( le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3])); virt_dev = xhci->devs[slot_id]; if (virt_dev) <API key>(xhci, virt_dev, event); else xhci_warn(xhci, "Stop endpoint command " "completion for disabled slot %u\n", slot_id); return; } memset(&deq_state, 0, sizeof(deq_state)); slot_id = TRB_TO_SLOT_ID(le32_to_cpu(trb->generic.field[3])); ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3])); ep = &xhci->devs[slot_id]->eps[ep_index]; if (list_empty(&ep->cancelled_td_list)) { <API key>(xhci, ep); ep->stopped_td = NULL; ep->stopped_trb = NULL; <API key>(xhci, slot_id, ep_index); return; } /* Fix up the ep ring first, so HW stops executing cancelled TDs. * We have the xHCI lock, so nothing can modify this list until we drop * it. We're also in the event handler, so we can't get re-interrupted * if another Stop Endpoint command completes */ list_for_each(entry, &ep->cancelled_td_list) { cur_td = list_entry(entry, struct xhci_td, cancelled_td_list); xhci_dbg(xhci, "Removing canceled TD starting at 0x%llx (dma).\n", (unsigned long long)<API key>( cur_td->start_seg, cur_td->first_trb)); ep_ring = <API key>(xhci, cur_td->urb); if (!ep_ring) { /* This shouldn't happen unless a driver is mucking * with the stream ID after submission. This will * leave the TD on the hardware ring, and the hardware * will try to execute it, and may access a buffer * that has already been freed. In the best case, the * hardware will execute it, and the event handler will * ignore the completion event for that TD, since it was * removed from the td_list for that endpoint. In * short, don't muck with the stream ID after * submission. */ xhci_warn(xhci, "WARN Cancelled URB %p " "has invalid stream ID %u.\n", cur_td->urb, cur_td->urb->stream_id); goto remove_finished_td; } /* * If we stopped on the TD we need to cancel, then we have to * move the xHC endpoint ring dequeue pointer past this TD. */ if (cur_td == ep->stopped_td) <API key>(xhci, slot_id, ep_index, cur_td->urb->stream_id, cur_td, &deq_state); else td_to_noop(xhci, ep_ring, cur_td, false); remove_finished_td: /* * The event handler won't see a completion for this TD anymore, * so remove it from the endpoint ring's TD list. Keep it in * the cancelled TD list for URB completion later. */ list_del_init(&cur_td->td_list); } last_unlinked_td = cur_td; <API key>(xhci, ep); /* If necessary, queue a Set Transfer Ring Dequeue Pointer command */ if (deq_state.new_deq_ptr && deq_state.new_deq_seg) { <API key>(xhci, slot_id, ep_index, ep->stopped_td->urb->stream_id, &deq_state); xhci_ring_cmd_db(xhci); } else { /* Otherwise ring the doorbell(s) to restart queued transfers */ <API key>(xhci, slot_id, ep_index); } ep->stopped_td = NULL; ep->stopped_trb = NULL; /* * Drop the lock and complete the URBs in the cancelled TD list. * New TDs to be cancelled might be added to the end of the list before * we can complete all the URBs for the TDs we already unlinked. * So stop when we've completed the URB for the last TD we unlinked. */ do { cur_td = list_entry(ep->cancelled_td_list.next, struct xhci_td, cancelled_td_list); list_del_init(&cur_td->cancelled_td_list); /* Clean up the cancelled URB */ /* Doesn't matter what we pass for status, since the core will * just overwrite it (because the URB has been unlinked). */ <API key>(xhci, cur_td, 0, "cancelled"); /* Stop processing the cancelled list if the watchdog timer is * running. */ if (xhci->xhc_state & XHCI_STATE_DYING) return; } while (cur_td != last_unlinked_td); /* Return to the event handler with xhci->lock re-acquired */ } /* Watchdog timer function for when a stop endpoint command fails to complete. * In this case, we assume the host controller is broken or dying or dead. The * host may still be completing some other events, so we have to be careful to * let the event ring handler and the URB dequeueing/enqueueing functions know * through xhci->state. * * The timer may also fire if the host takes a very long time to respond to the * command, and the stop endpoint command completion handler cannot delete the * timer before the timer function is called. Another endpoint cancellation may * sneak in before the timer function can grab the lock, and that may queue * another stop endpoint command and add the timer back. So we cannot use a * simple flag to say whether there is a pending stop endpoint command for a * particular endpoint. * * Instead we use a combination of that flag and a counter for the number of * pending stop endpoint commands. If the timer is the tail end of the last * stop endpoint command, and the endpoint's command is still pending, we assume * the host is dying. */ void <API key>(unsigned long arg) { struct xhci_hcd *xhci; struct xhci_virt_ep *ep; struct xhci_virt_ep *temp_ep; struct xhci_ring *ring; struct xhci_td *cur_td; int ret, i, j; unsigned long flags; ep = (struct xhci_virt_ep *) arg; xhci = ep->xhci; spin_lock_irqsave(&xhci->lock, flags); ep->stop_cmds_pending if (xhci->xhc_state & XHCI_STATE_DYING) { xhci_dbg(xhci, "Stop EP timer ran, but another timer marked " "xHCI as DYING, exiting.\n"); <API key>(&xhci->lock, flags); return; } if (!(ep->stop_cmds_pending == 0 && (ep->ep_state & EP_HALT_PENDING))) { xhci_dbg(xhci, "Stop EP timer ran, but no command pending, " "exiting.\n"); <API key>(&xhci->lock, flags); return; } xhci_warn(xhci, "xHCI host not responding to stop endpoint command.\n"); xhci_warn(xhci, "Assuming host is dying, halting host.\n"); /* Oops, HC is dead or dying or at least not responding to the stop * endpoint command. */ xhci->xhc_state |= XHCI_STATE_DYING; /* Disable interrupts from the host controller and start halting it */ xhci_quiesce(xhci); <API key>(&xhci->lock, flags); ret = xhci_halt(xhci); spin_lock_irqsave(&xhci->lock, flags); if (ret < 0) { /* This is bad; the host is not responding to commands and it's * not allowing itself to be halted. At least interrupts are * disabled. If we call usb_hc_died(), it will attempt to * disconnect all device drivers under this host. Those * disconnect() methods will wait for all URBs to be unlinked, * so we must complete them. */ xhci_warn(xhci, "Non-responsive xHCI host is not halting.\n"); xhci_warn(xhci, "Completing active URBs anyway.\n"); /* We could turn all TDs on the rings to no-ops. This won't * help if the host has cached part of the ring, and is slow if * we want to preserve the cycle bit. Skip it and hope the host * doesn't touch the memory. */ } for (i = 0; i < MAX_HC_SLOTS; i++) { if (!xhci->devs[i]) continue; for (j = 0; j < 31; j++) { temp_ep = &xhci->devs[i]->eps[j]; ring = temp_ep->ring; if (!ring) continue; xhci_dbg(xhci, "Killing URBs for slot ID %u, " "ep index %u\n", i, j); while (!list_empty(&ring->td_list)) { cur_td = list_first_entry(&ring->td_list, struct xhci_td, td_list); list_del_init(&cur_td->td_list); if (!list_empty(&cur_td->cancelled_td_list)) list_del_init(&cur_td->cancelled_td_list); <API key>(xhci, cur_td, -ESHUTDOWN, "killed"); } while (!list_empty(&temp_ep->cancelled_td_list)) { cur_td = list_first_entry( &temp_ep->cancelled_td_list, struct xhci_td, cancelled_td_list); list_del_init(&cur_td->cancelled_td_list); <API key>(xhci, cur_td, -ESHUTDOWN, "killed"); } } } <API key>(&xhci->lock, flags); xhci_dbg(xhci, "Calling usb_hc_died()\n"); usb_hc_died(xhci_to_hcd(xhci)->primary_hcd); xhci_dbg(xhci, "xHCI host controller is dead.\n"); } static void <API key>(struct xhci_hcd *xhci, struct xhci_virt_device *dev, struct xhci_ring *ep_ring, unsigned int ep_index) { union xhci_trb *dequeue_temp; int num_trbs_free_temp; bool revert = false; num_trbs_free_temp = ep_ring->num_trbs_free; dequeue_temp = ep_ring->dequeue; while (ep_ring->dequeue != dev->eps[ep_index].queued_deq_ptr) { /* We have more usable TRBs */ ep_ring->num_trbs_free++; ep_ring->dequeue++; if (last_trb(xhci, ep_ring, ep_ring->deq_seg, ep_ring->dequeue)) { if (ep_ring->dequeue == dev->eps[ep_index].queued_deq_ptr) break; ep_ring->deq_seg = ep_ring->deq_seg->next; ep_ring->dequeue = ep_ring->deq_seg->trbs; } if (ep_ring->dequeue == dequeue_temp) { revert = true; break; } } if (revert) { xhci_dbg(xhci, "Unable to find new dequeue pointer\n"); ep_ring->num_trbs_free = num_trbs_free_temp; } } /* * When we get a completion for a Set Transfer Ring Dequeue Pointer command, * we need to clear the set deq pending flag in the endpoint ring state, so that * the TD queueing code can ring the doorbell again. We also need to ring the * endpoint doorbell to restart the ring, but only if there aren't more * cancellations pending. */ static void <API key>(struct xhci_hcd *xhci, struct xhci_event_cmd *event, union xhci_trb *trb) { unsigned int slot_id; unsigned int ep_index; unsigned int stream_id; struct xhci_ring *ep_ring; struct xhci_virt_device *dev; struct xhci_ep_ctx *ep_ctx; struct xhci_slot_ctx *slot_ctx; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(trb->generic.field[3])); ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3])); stream_id = TRB_TO_STREAM_ID(le32_to_cpu(trb->generic.field[2])); dev = xhci->devs[slot_id]; ep_ring = <API key>(dev, ep_index, stream_id); if (!ep_ring) { xhci_warn(xhci, "WARN Set TR deq ptr command for " "freed stream ID %u\n", stream_id); /* XXX: Harmless??? */ dev->eps[ep_index].ep_state &= ~SET_DEQ_PENDING; return; } ep_ctx = xhci_get_ep_ctx(xhci, dev->out_ctx, ep_index); slot_ctx = xhci_get_slot_ctx(xhci, dev->out_ctx); if (GET_COMP_CODE(le32_to_cpu(event->status)) != COMP_SUCCESS) { unsigned int ep_state; unsigned int slot_state; switch (GET_COMP_CODE(le32_to_cpu(event->status))) { case COMP_TRB_ERR: xhci_warn(xhci, "WARN Set TR Deq Ptr cmd invalid because " "of stream ID configuration\n"); break; case COMP_CTX_STATE: xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed due " "to incorrect slot or ep state.\n"); ep_state = le32_to_cpu(ep_ctx->ep_info); ep_state &= EP_STATE_MASK; slot_state = le32_to_cpu(slot_ctx->dev_state); slot_state = GET_SLOT_STATE(slot_state); xhci_dbg(xhci, "Slot state = %u, EP state = %u\n", slot_state, ep_state); break; case COMP_EBADSLT: xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed because " "slot %u was not enabled.\n", slot_id); break; default: xhci_warn(xhci, "WARN Set TR Deq Ptr cmd with unknown " "completion code of %u.\n", GET_COMP_CODE(le32_to_cpu(event->status))); break; } /* OK what do we do now? The endpoint state is hosed, and we * should never get to this point if the synchronization between * queueing, and endpoint state are correct. This might happen * if the device gets disconnected after we've finished * cancelling URBs, which might not be an error... */ } else { xhci_dbg(xhci, "Successful Set TR Deq Ptr cmd, deq = @%08llx\n", le64_to_cpu(ep_ctx->deq)); if (<API key>(dev->eps[ep_index].queued_deq_seg, dev->eps[ep_index].queued_deq_ptr) == (le64_to_cpu(ep_ctx->deq) & ~(EP_CTX_CYCLE_MASK))) { /* Update the ring's dequeue segment and dequeue pointer * to reflect the new position. */ <API key>(xhci, dev, ep_ring, ep_index); } else { xhci_warn(xhci, "Mismatch between completed Set TR Deq " "Ptr command & xHCI internal state.\n"); xhci_warn(xhci, "ep deq seg = %p, deq ptr = %p\n", dev->eps[ep_index].queued_deq_seg, dev->eps[ep_index].queued_deq_ptr); } } dev->eps[ep_index].ep_state &= ~SET_DEQ_PENDING; dev->eps[ep_index].queued_deq_seg = NULL; dev->eps[ep_index].queued_deq_ptr = NULL; /* Restart any rings with pending URBs */ <API key>(xhci, slot_id, ep_index); } static void <API key>(struct xhci_hcd *xhci, struct xhci_event_cmd *event, union xhci_trb *trb) { int slot_id; unsigned int ep_index; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(trb->generic.field[3])); ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3])); /* This command will only fail if the endpoint wasn't halted, * but we don't care. */ xhci_dbg(xhci, "Ignoring reset ep completion code of %u\n", GET_COMP_CODE(le32_to_cpu(event->status))); /* HW with the reset endpoint quirk needs to have a configure endpoint * command complete before the endpoint can be used. Queue that here * because the HW can't handle two commands being queued in a row. */ if (xhci->quirks & XHCI_RESET_EP_QUIRK) { xhci_dbg(xhci, "Queueing configure endpoint command\n"); <API key>(xhci, xhci->devs[slot_id]->in_ctx->dma, slot_id, false); xhci_ring_cmd_db(xhci); } else { /* Clear our internal halted state and restart the ring(s) */ xhci->devs[slot_id]->eps[ep_index].ep_state &= ~EP_HALTED; <API key>(xhci, slot_id, ep_index); } } /* Check to see if a command in the device's command queue matches this one. * Signal the completion or free the command, and return 1. Return 0 if the * completed command isn't at the head of the command list. */ static int <API key>(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev, struct xhci_event_cmd *event) { struct xhci_command *command; if (list_empty(&virt_dev->cmd_list)) return 0; command = list_entry(virt_dev->cmd_list.next, struct xhci_command, cmd_list); if (xhci->cmd_ring->dequeue != command->command_trb) return 0; command->status = GET_COMP_CODE(le32_to_cpu(event->status)); list_del(&command->cmd_list); if (command->completion) complete(command->completion); else xhci_free_command(xhci, command); return 1; } static void <API key>(struct xhci_hcd *xhci, struct xhci_event_cmd *event) { int slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags)); u64 cmd_dma; dma_addr_t cmd_dequeue_dma; struct <API key> *ctrl_ctx; struct xhci_virt_device *virt_dev; unsigned int ep_index; struct xhci_ring *ep_ring; unsigned int ep_state; cmd_dma = le64_to_cpu(event->cmd_trb); cmd_dequeue_dma = <API key>(xhci->cmd_ring->deq_seg, xhci->cmd_ring->dequeue); /* Is the command ring deq ptr out of sync with the deq seg ptr? */ if (cmd_dequeue_dma == 0) { xhci->error_bitmask |= 1 << 4; return; } /* Does the DMA address match our internal dequeue pointer address? */ if (cmd_dma != (u64) cmd_dequeue_dma) { xhci->error_bitmask |= 1 << 5; return; } switch (le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3]) & TRB_TYPE_BITMASK) { case TRB_TYPE(TRB_ENABLE_SLOT): if (GET_COMP_CODE(le32_to_cpu(event->status)) == COMP_SUCCESS) xhci->slot_id = slot_id; else xhci->slot_id = 0; complete(&xhci->addr_dev); break; case TRB_TYPE(TRB_DISABLE_SLOT): if (xhci->devs[slot_id]) { if (xhci->quirks & XHCI_EP_LIMIT_QUIRK) /* Delete default control endpoint resources */ <API key>(xhci, xhci->devs[slot_id], true); <API key>(xhci, slot_id); } break; case TRB_TYPE(TRB_CONFIG_EP): virt_dev = xhci->devs[slot_id]; if (<API key>(xhci, virt_dev, event)) break; /* * Configure endpoint commands can come from the USB core * configuration or alt setting changes, or because the HW * needed an extra configure endpoint command after a reset * endpoint command or streams were being configured. * If the command was for a halted endpoint, the xHCI driver * is not waiting on the configure endpoint command. */ ctrl_ctx = <API key>(xhci, virt_dev->in_ctx); /* Input ctx add_flags are the endpoint index plus one */ ep_index = <API key>(le32_to_cpu(ctrl_ctx->add_flags)) - 1; /* A usb_set_interface() call directly after clearing a halted * condition may race on this quirky hardware. Not worth * worrying about, since this is prototype hardware. Not sure * if this will work for streams, but streams support was * untested on this prototype. */ if (xhci->quirks & XHCI_RESET_EP_QUIRK && ep_index != (unsigned int) -1 && le32_to_cpu(ctrl_ctx->add_flags) - SLOT_FLAG == le32_to_cpu(ctrl_ctx->drop_flags)) { ep_ring = xhci->devs[slot_id]->eps[ep_index].ring; ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state; if (!(ep_state & EP_HALTED)) goto bandwidth_change; xhci_dbg(xhci, "Completed config ep cmd - " "last ep index = %d, state = %d\n", ep_index, ep_state); /* Clear internal halted state and restart ring(s) */ xhci->devs[slot_id]->eps[ep_index].ep_state &= ~EP_HALTED; <API key>(xhci, slot_id, ep_index); break; } bandwidth_change: xhci_dbg(xhci, "Completed config ep cmd\n"); xhci->devs[slot_id]->cmd_status = GET_COMP_CODE(le32_to_cpu(event->status)); complete(&xhci->devs[slot_id]->cmd_completion); break; case TRB_TYPE(TRB_EVAL_CONTEXT): virt_dev = xhci->devs[slot_id]; if (<API key>(xhci, virt_dev, event)) break; xhci->devs[slot_id]->cmd_status = GET_COMP_CODE(le32_to_cpu(event->status)); complete(&xhci->devs[slot_id]->cmd_completion); break; case TRB_TYPE(TRB_ADDR_DEV): xhci->devs[slot_id]->cmd_status = GET_COMP_CODE(le32_to_cpu(event->status)); complete(&xhci->addr_dev); break; case TRB_TYPE(TRB_STOP_RING): <API key>(xhci, xhci->cmd_ring->dequeue, event); break; case TRB_TYPE(TRB_SET_DEQ): <API key>(xhci, event, xhci->cmd_ring->dequeue); break; case TRB_TYPE(TRB_CMD_NOOP): break; case TRB_TYPE(TRB_RESET_EP): <API key>(xhci, event, xhci->cmd_ring->dequeue); break; case TRB_TYPE(TRB_RESET_DEV): xhci_dbg(xhci, "Completed reset device command.\n"); slot_id = TRB_TO_SLOT_ID( le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3])); virt_dev = xhci->devs[slot_id]; if (virt_dev) <API key>(xhci, virt_dev, event); else xhci_warn(xhci, "Reset device command completion " "for disabled slot %u\n", slot_id); break; case TRB_TYPE(TRB_NEC_GET_FW): if (!(xhci->quirks & XHCI_NEC_HOST)) { xhci->error_bitmask |= 1 << 6; break; } xhci_dbg(xhci, "NEC firmware version %2x.%02x\n", NEC_FW_MAJOR(le32_to_cpu(event->status)), NEC_FW_MINOR(le32_to_cpu(event->status))); break; default: /* Skip over unknown commands on the event ring */ xhci->error_bitmask |= 1 << 6; break; } inc_deq(xhci, xhci->cmd_ring); } static void handle_vendor_event(struct xhci_hcd *xhci, union xhci_trb *event) { u32 trb_type; trb_type = TRB_FIELD_TO_TYPE(le32_to_cpu(event->generic.field[3])); xhci_dbg(xhci, "Vendor specific event TRB type = %u\n", trb_type); if (trb_type == TRB_NEC_CMD_COMP && (xhci->quirks & XHCI_NEC_HOST)) <API key>(xhci, &event->event_cmd); } /* @port_id: the one-based port ID from the hardware (indexed from array of all * port registers -- USB 3.0 and USB 2.0). * * Returns a zero-based port number, which is suitable for indexing into each of * the split roothubs' port arrays and bus state arrays. * Add one to it in order to call <API key>. */ static unsigned int <API key>(struct usb_hcd *hcd, struct xhci_hcd *xhci, u32 port_id) { unsigned int i; unsigned int <API key> = 0; /* port_id from the hardware is 1-based, but port_array[], usb3_ports[], * and usb2_ports are 0-based indexes. Count the number of similar * speed ports, up to 1 port before this port. */ for (i = 0; i < (port_id - 1); i++) { u8 port_speed = xhci->port_array[i]; /* * Skip ports that don't have known speeds, or have duplicate * Extended Capabilities port speed entries. */ if (port_speed == 0 || port_speed == DUPLICATE_ENTRY) continue; /* * USB 3.0 ports are always under a USB 3.0 hub. USB 2.0 and * 1.1 ports are under the USB 2.0 hub. If the port speed * matches the device speed, it's a similar speed port. */ if ((port_speed == 0x03) == (hcd->speed == HCD_USB3)) <API key>++; } return <API key>; } static void <API key>(struct xhci_hcd *xhci, union xhci_trb *event) { u32 slot_id; struct usb_device *udev; slot_id = TRB_TO_SLOT_ID(event->generic.field[3]); if (!xhci->devs[slot_id]) { xhci_warn(xhci, "Device Notification event for " "unused slot %u\n", slot_id); return; } xhci_dbg(xhci, "Device Wake Notification event for slot ID %u\n", slot_id); udev = xhci->devs[slot_id]->udev; if (udev && udev->parent) <API key>(udev->parent, udev->portnum); } static void handle_port_status(struct xhci_hcd *xhci, union xhci_trb *event) { struct usb_hcd *hcd; u32 port_id; u32 temp, temp1; int max_ports; int slot_id; unsigned int faked_port_index; u8 major_revision; struct xhci_bus_state *bus_state; __le32 __iomem **port_array; bool bogus_port_status = false; /* Port status change events always have a successful completion code */ if (GET_COMP_CODE(le32_to_cpu(event->generic.field[2])) != COMP_SUCCESS) { xhci_warn(xhci, "WARN: xHC returned failed port status event\n"); xhci->error_bitmask |= 1 << 8; } port_id = GET_PORT_ID(le32_to_cpu(event->generic.field[0])); xhci_dbg(xhci, "Port Status Change Event for port %d\n", port_id); max_ports = HCS_MAX_PORTS(xhci->hcs_params1); if ((port_id <= 0) || (port_id > max_ports)) { xhci_warn(xhci, "Invalid port id %d\n", port_id); bogus_port_status = true; goto cleanup; } /* Figure out which usb_hcd this port is attached to: * is it a USB 3.0 port or a USB 2.0/1.1 port? */ major_revision = xhci->port_array[port_id - 1]; if (major_revision == 0) { xhci_warn(xhci, "Event for port %u not in " "Extended Capabilities, ignoring.\n", port_id); bogus_port_status = true; goto cleanup; } if (major_revision == DUPLICATE_ENTRY) { xhci_warn(xhci, "Event for port %u duplicated in" "Extended Capabilities, ignoring.\n", port_id); bogus_port_status = true; goto cleanup; } /* * Hardware port IDs reported by a Port Status Change Event include USB * 3.0 and USB 2.0 ports. We want to check if the port has reported a * resume event, but we first need to translate the hardware port ID * into the index into the ports on the correct split roothub, and the * correct bus_state structure. */ /* Find the right roothub. */ hcd = xhci_to_hcd(xhci); if ((major_revision == 0x03) != (hcd->speed == HCD_USB3)) hcd = xhci->shared_hcd; bus_state = &xhci->bus_state[hcd_index(hcd)]; if (hcd->speed == HCD_USB3) port_array = xhci->usb3_ports; else port_array = xhci->usb2_ports; /* Find the faked port hub number */ faked_port_index = <API key>(hcd, xhci, port_id); temp = xhci_readl(xhci, port_array[faked_port_index]); if (hcd->state == HC_STATE_SUSPENDED) { xhci_dbg(xhci, "resume root hub\n"); <API key>(hcd); } if ((temp & PORT_PLC) && (temp & PORT_PLS_MASK) == XDEV_RESUME) { xhci_dbg(xhci, "port resume event for port %d\n", port_id); temp1 = xhci_readl(xhci, &xhci->op_regs->command); if (!(temp1 & CMD_RUN)) { xhci_warn(xhci, "xHC is not running.\n"); goto cleanup; } if (DEV_SUPERSPEED(temp)) { xhci_dbg(xhci, "remote wake SS port %d\n", port_id); /* Set a flag to say the port signaled remote wakeup, * so we can tell the difference between the end of * device and host initiated resume. */ bus_state->port_remote_wakeup |= 1 << faked_port_index; <API key>(xhci, port_array, faked_port_index, PORT_PLC); xhci_set_link_state(xhci, port_array, faked_port_index, XDEV_U0); /* Need to wait until the next link state change * indicates the device is actually in U0. */ bogus_port_status = true; goto cleanup; } else { xhci_dbg(xhci, "resume HS port %d\n", port_id); bus_state->resume_done[faked_port_index] = jiffies + msecs_to_jiffies(20); mod_timer(&hcd->rh_timer, bus_state->resume_done[faked_port_index]); /* Do the rest in GetPortStatus */ } } if ((temp & PORT_PLC) && (temp & PORT_PLS_MASK) == XDEV_U0 && DEV_SUPERSPEED(temp)) { xhci_dbg(xhci, "resume SS port %d finished\n", port_id); /* We've just brought the device into U0 through either the * Resume state after a device remote wakeup, or through the * U3Exit state after a host-initiated resume. If it's a device * initiated remote wake, don't pass up the link state change, * so the roothub behavior is consistent with external * USB 3.0 hub behavior. */ slot_id = <API key>(hcd, xhci, faked_port_index + 1); if (slot_id && xhci->devs[slot_id]) xhci_ring_device(xhci, slot_id); if (bus_state->port_remote_wakeup && (1 << faked_port_index)) { bus_state->port_remote_wakeup &= ~(1 << faked_port_index); <API key>(xhci, port_array, faked_port_index, PORT_PLC); <API key>(hcd->self.root_hub, faked_port_index + 1); bogus_port_status = true; goto cleanup; } } if (hcd->speed != HCD_USB3) <API key>(xhci, port_array, faked_port_index, PORT_PLC); cleanup: /* Update event ring dequeue pointer before dropping the lock */ inc_deq(xhci, xhci->event_ring); /* Don't make the USB core poll the roothub if we got a bad port status * change event. Besides, at that point we can't tell which roothub * (USB 2.0 or USB 3.0) to kick. */ if (bogus_port_status) return; spin_unlock(&xhci->lock); /* Pass this up to the core */ <API key>(hcd); spin_lock(&xhci->lock); } /* * This TD is defined by the TRBs starting at start_trb in start_seg and ending * at end_trb, which may be in another segment. If the suspect DMA address is a * TRB in this TD, this function returns that TRB's segment. Otherwise it * returns 0. */ struct xhci_segment *trb_in_td(struct xhci_segment *start_seg, union xhci_trb *start_trb, union xhci_trb *end_trb, dma_addr_t suspect_dma) { dma_addr_t start_dma; dma_addr_t end_seg_dma; dma_addr_t end_trb_dma; struct xhci_segment *cur_seg; start_dma = <API key>(start_seg, start_trb); cur_seg = start_seg; do { if (start_dma == 0) return NULL; /* We may get an event for a Link TRB in the middle of a TD */ end_seg_dma = <API key>(cur_seg, &cur_seg->trbs[TRBS_PER_SEGMENT - 1]); /* If the end TRB isn't in this segment, this is set to 0 */ end_trb_dma = <API key>(cur_seg, end_trb); if (end_trb_dma > 0) { /* The end TRB is in this segment, so suspect should be here */ if (start_dma <= end_trb_dma) { if (suspect_dma >= start_dma && suspect_dma <= end_trb_dma) return cur_seg; } else { /* Case for one segment with * a TD wrapped around to the top */ if ((suspect_dma >= start_dma && suspect_dma <= end_seg_dma) || (suspect_dma >= cur_seg->dma && suspect_dma <= end_trb_dma)) return cur_seg; } return NULL; } else { /* Might still be somewhere in this segment */ if (suspect_dma >= start_dma && suspect_dma <= end_seg_dma) return cur_seg; } cur_seg = cur_seg->next; start_dma = <API key>(cur_seg, &cur_seg->trbs[0]); } while (cur_seg != start_seg); return NULL; } static void <API key>(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_td *td, union xhci_trb *event_trb) { struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index]; ep->ep_state |= EP_HALTED; ep->stopped_td = td; ep->stopped_trb = event_trb; ep->stopped_stream = stream_id; xhci_queue_reset_ep(xhci, slot_id, ep_index); <API key>(xhci, td->urb->dev, ep_index); ep->stopped_td = NULL; ep->stopped_trb = NULL; ep->stopped_stream = 0; xhci_ring_cmd_db(xhci); } /* Check if an error has halted the endpoint ring. The class driver will * cleanup the halt for a non-default control endpoint if we indicate a stall. * However, a babble and other errors also halt the endpoint ring, and the class * driver won't clear the halt in that case, so we need to issue a Set Transfer * Ring Dequeue Pointer command manually. */ static int <API key>(struct xhci_hcd *xhci, struct xhci_ep_ctx *ep_ctx, unsigned int trb_comp_code) { /* TRB completion codes that may require a manual halt cleanup */ if (trb_comp_code == COMP_TX_ERR || trb_comp_code == COMP_BABBLE || trb_comp_code == COMP_SPLIT_ERR) /* The 0.96 spec says a babbling control endpoint * is not halted. The 0.96 spec says it is. Some HW * claims to be 0.95 compliant, but it halts the control * endpoint anyway. Check if a babble halted the * endpoint. */ if ((ep_ctx->ep_info & cpu_to_le32(EP_STATE_MASK)) == cpu_to_le32(EP_STATE_HALTED)) return 1; return 0; } int <API key>(struct xhci_hcd *xhci, unsigned int trb_comp_code) { if (trb_comp_code >= 224 && trb_comp_code <= 255) { /* Vendor defined "informational" completion code, * treat as not-an-error. */ xhci_dbg(xhci, "Vendor defined info completion code %u\n", trb_comp_code); xhci_dbg(xhci, "Treating code as success.\n"); return 1; } return 0; } /* * Finish the td processing, remove the td from td list; * Return 1 if the urb can be given back. */ static int finish_td(struct xhci_hcd *xhci, struct xhci_td *td, union xhci_trb *event_trb, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status, bool skip) { struct xhci_virt_device *xdev; struct xhci_ring *ep_ring; unsigned int slot_id; int ep_index; struct urb *urb = NULL; struct xhci_ep_ctx *ep_ctx; int ret = 0; struct urb_priv *urb_priv; u32 trb_comp_code; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags)); xdev = xhci->devs[slot_id]; ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1; ep_ring = <API key>(ep, le64_to_cpu(event->buffer)); ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); if (skip) goto td_cleanup; if (trb_comp_code == COMP_STOP_INVAL || trb_comp_code == COMP_STOP) { /* The Endpoint Stop Command completion will take care of any * stopped TDs. A stopped TD may be restarted, so don't update * the ring dequeue pointer or take this TD off any lists yet. */ ep->stopped_td = td; ep->stopped_trb = event_trb; return 0; } else { if (trb_comp_code == COMP_STALL) { /* The transfer is completed from the driver's * perspective, but we need to issue a set dequeue * command for this stalled endpoint to move the dequeue * pointer past the TD. We can't do that here because * the halt condition must be cleared first. Let the * USB class driver clear the stall later. */ ep->stopped_td = td; ep->stopped_trb = event_trb; ep->stopped_stream = ep_ring->stream_id; } else if (<API key>(xhci, ep_ctx, trb_comp_code)) { /* Other types of errors halt the endpoint, but the * class driver doesn't call usb_reset_endpoint() unless * the error is -EPIPE. Clear the halted status in the * xHCI hardware manually. */ <API key>(xhci, slot_id, ep_index, ep_ring->stream_id, td, event_trb); } else { /* Update ring dequeue pointer */ while (ep_ring->dequeue != td->last_trb) inc_deq(xhci, ep_ring); inc_deq(xhci, ep_ring); } td_cleanup: /* Clean up the endpoint's TD list */ urb = td->urb; urb_priv = urb->hcpriv; /* Do one last check of the actual transfer length. * If the host controller said we transferred more data than * the buffer length, urb->actual_length will be a very big * number (since it's unsigned). Play it safe and say we didn't * transfer anything. */ if (urb->actual_length > urb-><API key>) { xhci_warn(xhci, "URB transfer length is wrong, " "xHC issue? req. len = %u, " "act. len = %u\n", urb-><API key>, urb->actual_length); urb->actual_length = 0; if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; } list_del_init(&td->td_list); /* Was this TD slated to be cancelled but completed anyway? */ if (!list_empty(&td->cancelled_td_list)) list_del_init(&td->cancelled_td_list); urb_priv->td_cnt++; /* Giveback the urb when all the tds are completed */ if (urb_priv->td_cnt == urb_priv->length) { ret = 1; if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) { xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) { if (xhci->quirks & XHCI_AMD_PLL_FIX) <API key>(); } } } } return ret; } /* * Process control tds, update urb status and actual_length. */ static int process_ctrl_td(struct xhci_hcd *xhci, struct xhci_td *td, union xhci_trb *event_trb, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status) { struct xhci_virt_device *xdev; struct xhci_ring *ep_ring; unsigned int slot_id; int ep_index; struct xhci_ep_ctx *ep_ctx; u32 trb_comp_code; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags)); xdev = xhci->devs[slot_id]; ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1; ep_ring = <API key>(ep, le64_to_cpu(event->buffer)); ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); switch (trb_comp_code) { case COMP_SUCCESS: if (event_trb == ep_ring->dequeue) { xhci_warn(xhci, "WARN: Success on ctrl setup TRB " "without IOC set??\n"); *status = -ESHUTDOWN; } else if (event_trb != td->last_trb) { xhci_warn(xhci, "WARN: Success on ctrl data TRB " "without IOC set??\n"); *status = -ESHUTDOWN; } else { *status = 0; } break; case COMP_SHORT_TX: if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; break; case COMP_STOP_INVAL: case COMP_STOP: return finish_td(xhci, td, event_trb, event, ep, status, false); default: if (!<API key>(xhci, ep_ctx, trb_comp_code)) break; xhci_dbg(xhci, "TRB error code %u, " "halted endpoint index = %u\n", trb_comp_code, ep_index); /* else fall through */ case COMP_STALL: /* Did we transfer part of the data (middle) phase? */ if (event_trb != ep_ring->dequeue && event_trb != td->last_trb) td->urb->actual_length = td->urb-><API key> - TRB_LEN(le32_to_cpu(event->transfer_len)); else td->urb->actual_length = 0; <API key>(xhci, slot_id, ep_index, 0, td, event_trb); return finish_td(xhci, td, event_trb, event, ep, status, true); } /* * Did we transfer any data, despite the errors that might have * happened? I.e. did we get past the setup stage? */ if (event_trb != ep_ring->dequeue) { /* The event was for the status stage */ if (event_trb == td->last_trb) { if (td->urb->actual_length != 0) { /* Don't overwrite a previously set error code */ if ((*status == -EINPROGRESS || *status == 0) && (td->urb->transfer_flags & URB_SHORT_NOT_OK)) /* Did we already see a short data * stage? */ *status = -EREMOTEIO; } else { td->urb->actual_length = td->urb-><API key>; } } else { /* Maybe the event was for the data stage? */ td->urb->actual_length = td->urb-><API key> - TRB_LEN(le32_to_cpu(event->transfer_len)); xhci_dbg(xhci, "Waiting for status " "stage event\n"); return 0; } } return finish_td(xhci, td, event_trb, event, ep, status, false); } /* * Process isochronous tds, update urb packet status and actual_length. */ static int process_isoc_td(struct xhci_hcd *xhci, struct xhci_td *td, union xhci_trb *event_trb, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status) { struct xhci_ring *ep_ring; struct urb_priv *urb_priv; int idx; int len = 0; union xhci_trb *cur_trb; struct xhci_segment *cur_seg; struct <API key> *frame; u32 trb_comp_code; bool skip_td = false; ep_ring = <API key>(ep, le64_to_cpu(event->buffer)); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); urb_priv = td->urb->hcpriv; idx = urb_priv->td_cnt; frame = &td->urb->iso_frame_desc[idx]; /* handle completion code */ switch (trb_comp_code) { case COMP_SUCCESS: frame->status = 0; break; case COMP_SHORT_TX: frame->status = td->urb->transfer_flags & URB_SHORT_NOT_OK ? -EREMOTEIO : 0; break; case COMP_BW_OVER: frame->status = -ECOMM; skip_td = true; break; case COMP_BUFF_OVER: case COMP_BABBLE: frame->status = -EOVERFLOW; skip_td = true; break; case COMP_DEV_ERR: case COMP_STALL: frame->status = -EPROTO; skip_td = true; break; case COMP_STOP: case COMP_STOP_INVAL: break; default: frame->status = -1; break; } if (trb_comp_code == COMP_SUCCESS || skip_td) { frame->actual_length = frame->length; td->urb->actual_length += frame->length; } else { for (cur_trb = ep_ring->dequeue, cur_seg = ep_ring->deq_seg; cur_trb != event_trb; next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) { if (!TRB_TYPE_NOOP_LE32(cur_trb->generic.field[3]) && !TRB_TYPE_LINK_LE32(cur_trb->generic.field[3])) len += TRB_LEN(le32_to_cpu(cur_trb->generic.field[2])); } len += TRB_LEN(le32_to_cpu(cur_trb->generic.field[2])) - TRB_LEN(le32_to_cpu(event->transfer_len)); if (trb_comp_code != COMP_STOP_INVAL) { frame->actual_length = len; td->urb->actual_length += len; } } return finish_td(xhci, td, event_trb, event, ep, status, false); } static int skip_isoc_td(struct xhci_hcd *xhci, struct xhci_td *td, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status) { struct xhci_ring *ep_ring; struct urb_priv *urb_priv; struct <API key> *frame; int idx; ep_ring = <API key>(ep, le64_to_cpu(event->buffer)); urb_priv = td->urb->hcpriv; idx = urb_priv->td_cnt; frame = &td->urb->iso_frame_desc[idx]; /* The transfer is partly done. */ frame->status = -EXDEV; /* calc actual length */ frame->actual_length = 0; /* Update ring dequeue pointer */ while (ep_ring->dequeue != td->last_trb) inc_deq(xhci, ep_ring); inc_deq(xhci, ep_ring); return finish_td(xhci, td, NULL, event, ep, status, true); } /* * Process bulk and interrupt tds, update urb status and actual_length. */ static int <API key>(struct xhci_hcd *xhci, struct xhci_td *td, union xhci_trb *event_trb, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status) { struct xhci_ring *ep_ring; union xhci_trb *cur_trb; struct xhci_segment *cur_seg; u32 trb_comp_code; ep_ring = <API key>(ep, le64_to_cpu(event->buffer)); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); switch (trb_comp_code) { case COMP_SUCCESS: /* Double check that the HW transferred everything. */ if (event_trb != td->last_trb) { xhci_warn(xhci, "WARN Successful completion " "on short TX\n"); if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; } else { *status = 0; } break; case COMP_SHORT_TX: if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; break; default: /* Others already handled above */ break; } if (trb_comp_code == COMP_SHORT_TX) xhci_dbg(xhci, "ep %#x - asked for %d bytes, " "%d bytes untransferred\n", td->urb->ep->desc.bEndpointAddress, td->urb-><API key>, TRB_LEN(le32_to_cpu(event->transfer_len))); /* Fast path - was this the last TRB in the TD for this URB? */ if (event_trb == td->last_trb) { if (TRB_LEN(le32_to_cpu(event->transfer_len)) != 0) { td->urb->actual_length = td->urb-><API key> - TRB_LEN(le32_to_cpu(event->transfer_len)); if (td->urb-><API key> < td->urb->actual_length) { xhci_warn(xhci, "HC gave bad length " "of %d bytes left\n", TRB_LEN(le32_to_cpu(event->transfer_len))); td->urb->actual_length = 0; if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; } /* Don't overwrite a previously set error code */ if (*status == -EINPROGRESS) { if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; } } else { td->urb->actual_length = td->urb-><API key>; /* Ignore a short packet completion if the * untransferred length was zero. */ if (*status == -EREMOTEIO) *status = 0; } } else { /* Slow path - walk the list, starting from the dequeue * pointer, to get the actual length transferred. */ td->urb->actual_length = 0; for (cur_trb = ep_ring->dequeue, cur_seg = ep_ring->deq_seg; cur_trb != event_trb; next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) { if (!TRB_TYPE_NOOP_LE32(cur_trb->generic.field[3]) && !TRB_TYPE_LINK_LE32(cur_trb->generic.field[3])) td->urb->actual_length += TRB_LEN(le32_to_cpu(cur_trb->generic.field[2])); } /* If the ring didn't stop on a Link or No-op TRB, add * in the actual bytes transferred from the Normal TRB */ if (trb_comp_code != COMP_STOP_INVAL) td->urb->actual_length += TRB_LEN(le32_to_cpu(cur_trb->generic.field[2])) - TRB_LEN(le32_to_cpu(event->transfer_len)); } return finish_td(xhci, td, event_trb, event, ep, status, false); } /* * If this function returns an error condition, it means it got a Transfer * event with a corrupted Slot ID, Endpoint ID, or TRB DMA address. * At this point, the host controller is probably hosed and should be reset. */ static int handle_tx_event(struct xhci_hcd *xhci, struct xhci_transfer_event *event) { struct xhci_virt_device *xdev; struct xhci_virt_ep *ep; struct xhci_ring *ep_ring; unsigned int slot_id; int ep_index; struct xhci_td *td = NULL; dma_addr_t event_dma; struct xhci_segment *event_seg; union xhci_trb *event_trb; struct urb *urb = NULL; int status = -EINPROGRESS; struct urb_priv *urb_priv; struct xhci_ep_ctx *ep_ctx; struct list_head *tmp; u32 trb_comp_code; int ret = 0; int td_num = 0; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags)); xdev = xhci->devs[slot_id]; if (!xdev) { xhci_err(xhci, "ERROR Transfer event pointed to bad slot\n"); xhci_err(xhci, "@%016llx %08x %08x %08x %08x\n", (unsigned long long) <API key>( xhci->event_ring->deq_seg, xhci->event_ring->dequeue), lower_32_bits(le64_to_cpu(event->buffer)), upper_32_bits(le64_to_cpu(event->buffer)), le32_to_cpu(event->transfer_len), le32_to_cpu(event->flags)); xhci_dbg(xhci, "Event ring:\n"); xhci_debug_segment(xhci, xhci->event_ring->deq_seg); return -ENODEV; } /* Endpoint ID is 1 based, our index is zero based */ ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1; ep = &xdev->eps[ep_index]; ep_ring = <API key>(ep, le64_to_cpu(event->buffer)); ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); if (!ep_ring || (le32_to_cpu(ep_ctx->ep_info) & EP_STATE_MASK) == EP_STATE_DISABLED) { xhci_err(xhci, "ERROR Transfer event for disabled endpoint " "or incorrect stream ring\n"); xhci_err(xhci, "@%016llx %08x %08x %08x %08x\n", (unsigned long long) <API key>( xhci->event_ring->deq_seg, xhci->event_ring->dequeue), lower_32_bits(le64_to_cpu(event->buffer)), upper_32_bits(le64_to_cpu(event->buffer)), le32_to_cpu(event->transfer_len), le32_to_cpu(event->flags)); xhci_dbg(xhci, "Event ring:\n"); xhci_debug_segment(xhci, xhci->event_ring->deq_seg); return -ENODEV; } /* Count current td numbers if ep->skip is set */ if (ep->skip) { list_for_each(tmp, &ep_ring->td_list) td_num++; } event_dma = le64_to_cpu(event->buffer); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); /* Look for common error cases */ switch (trb_comp_code) { /* Skip codes that require special handling depending on * transfer type */ case COMP_SUCCESS: case COMP_SHORT_TX: break; case COMP_STOP: xhci_dbg(xhci, "Stopped on Transfer TRB\n"); break; case COMP_STOP_INVAL: xhci_dbg(xhci, "Stopped on No-op or Link TRB\n"); break; case COMP_STALL: xhci_dbg(xhci, "Stalled endpoint\n"); ep->ep_state |= EP_HALTED; status = -EPIPE; break; case COMP_TRB_ERR: xhci_warn(xhci, "WARN: TRB error on endpoint\n"); status = -EILSEQ; break; case COMP_SPLIT_ERR: case COMP_TX_ERR: xhci_dbg(xhci, "Transfer error on endpoint\n"); status = -EPROTO; break; case COMP_BABBLE: xhci_dbg(xhci, "Babble error on endpoint\n"); status = -EOVERFLOW; break; case COMP_DB_ERR: xhci_warn(xhci, "WARN: HC couldn't access mem fast enough\n"); status = -ENOSR; break; case COMP_BW_OVER: xhci_warn(xhci, "WARN: bandwidth overrun event on endpoint\n"); break; case COMP_BUFF_OVER: xhci_warn(xhci, "WARN: buffer overrun event on endpoint\n"); break; case COMP_UNDERRUN: /* * When the Isoch ring is empty, the xHC will generate * a Ring Overrun Event for IN Isoch endpoint or Ring * Underrun Event for OUT Isoch endpoint. */ xhci_dbg(xhci, "underrun event on endpoint\n"); if (!list_empty(&ep_ring->td_list)) xhci_dbg(xhci, "Underrun Event for slot %d ep %d " "still with TDs queued?\n", TRB_TO_SLOT_ID(le32_to_cpu(event->flags)), ep_index); goto cleanup; case COMP_OVERRUN: xhci_dbg(xhci, "overrun event on endpoint\n"); if (!list_empty(&ep_ring->td_list)) xhci_dbg(xhci, "Overrun Event for slot %d ep %d " "still with TDs queued?\n", TRB_TO_SLOT_ID(le32_to_cpu(event->flags)), ep_index); goto cleanup; case COMP_DEV_ERR: xhci_warn(xhci, "WARN: detect an incompatible device"); status = -EPROTO; break; case COMP_MISSED_INT: /* * When encounter missed service error, one or more isoc tds * may be missed by xHC. * Set skip flag of the ep_ring; Complete the missed tds as * short transfer when process the ep_ring next time. */ ep->skip = true; xhci_dbg(xhci, "Miss service interval error, set skip flag\n"); goto cleanup; default: if (<API key>(xhci, trb_comp_code)) { status = 0; break; } xhci_warn(xhci, "ERROR Unknown event condition, HC probably " "busted\n"); goto cleanup; } do { /* This TRB should be in the TD at the head of this ring's * TD list. */ if (list_empty(&ep_ring->td_list)) { xhci_warn(xhci, "WARN Event TRB for slot %d ep %d " "with no TDs queued?\n", TRB_TO_SLOT_ID(le32_to_cpu(event->flags)), ep_index); xhci_dbg(xhci, "Event TRB with TRB type ID %u\n", (le32_to_cpu(event->flags) & TRB_TYPE_BITMASK)>>10); <API key>(xhci, (union xhci_trb *) event); if (ep->skip) { ep->skip = false; xhci_dbg(xhci, "td_list is empty while skip " "flag set. Clear skip flag.\n"); } ret = 0; goto cleanup; } /* We've skipped all the TDs on the ep ring when ep->skip set */ if (ep->skip && td_num == 0) { ep->skip = false; xhci_dbg(xhci, "All tds on the ep_ring skipped. " "Clear skip flag.\n"); ret = 0; goto cleanup; } td = list_entry(ep_ring->td_list.next, struct xhci_td, td_list); if (ep->skip) td_num /* Is this a TRB in the currently executing TD? */ event_seg = trb_in_td(ep_ring->deq_seg, ep_ring->dequeue, td->last_trb, event_dma); /* * Skip the Force Stopped Event. The event_trb(event_dma) of FSE * is not in the current TD pointed by ep_ring->dequeue because * that the hardware dequeue pointer still at the previous TRB * of the current TD. The previous TRB maybe a Link TD or the * last TRB of the previous TD. The command completion handle * will take care the rest. */ if (!event_seg && (trb_comp_code == COMP_STOP || trb_comp_code == COMP_STOP_INVAL)) { ret = 0; goto cleanup; } if (!event_seg) { if (!ep->skip || !<API key>(&td->urb->ep->desc)) { /* Some host controllers give a spurious * successful event after a short transfer. * Ignore it. */ if ((xhci->quirks & <API key>) && ep_ring->last_td_was_short) { ep_ring->last_td_was_short = false; ret = 0; goto cleanup; } /* HC is busted, give up! */ xhci_err(xhci, "ERROR Transfer event TRB DMA ptr not " "part of current TD\n"); return -ESHUTDOWN; } ret = skip_isoc_td(xhci, td, event, ep, &status); goto cleanup; } if (trb_comp_code == COMP_SHORT_TX) ep_ring->last_td_was_short = true; else ep_ring->last_td_was_short = false; if (ep->skip) { xhci_dbg(xhci, "Found td. Clear skip flag.\n"); ep->skip = false; } event_trb = &event_seg->trbs[(event_dma - event_seg->dma) / sizeof(*event_trb)]; /* * No-op TRB should not trigger interrupts. * If event_trb is a no-op TRB, it means the * corresponding TD has been cancelled. Just ignore * the TD. */ if (TRB_TYPE_NOOP_LE32(event_trb->generic.field[3])) { xhci_dbg(xhci, "event_trb is a no-op TRB. Skip it\n"); goto cleanup; } /* Now update the urb's actual_length and give back to * the core */ if (<API key>(&td->urb->ep->desc)) ret = process_ctrl_td(xhci, td, event_trb, event, ep, &status); else if (<API key>(&td->urb->ep->desc)) ret = process_isoc_td(xhci, td, event_trb, event, ep, &status); else ret = <API key>(xhci, td, event_trb, event, ep, &status); cleanup: /* * Do not update event ring dequeue pointer if ep->skip is set. * Will roll back to continue process missed tds. */ if (trb_comp_code == COMP_MISSED_INT || !ep->skip) { inc_deq(xhci, xhci->event_ring); } if (ret) { urb = td->urb; urb_priv = urb->hcpriv; /* Leave the TD around for the reset endpoint function * to use(but only if it's not a control endpoint, * since we already queued the Set TR dequeue pointer * command for stalled control endpoints). */ if (<API key>(&urb->ep->desc) || (trb_comp_code != COMP_STALL && trb_comp_code != COMP_BABBLE)) xhci_urb_free_priv(xhci, urb_priv); <API key>(bus_to_hcd(urb->dev->bus), urb); if ((urb->actual_length != urb-><API key> && (urb->transfer_flags & URB_SHORT_NOT_OK)) || (status != 0 && !<API key>(&urb->ep->desc))) xhci_dbg(xhci, "Giveback URB %p, len = %d, " "expected = %x, status = %d\n", urb, urb->actual_length, urb-><API key>, status); spin_unlock(&xhci->lock); /* EHCI, UHCI, and OHCI always unconditionally set the * urb->status of an isochronous endpoint to 0. */ if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) status = 0; <API key>(bus_to_hcd(urb->dev->bus), urb, status); spin_lock(&xhci->lock); } /* * If ep->skip is set, it means there are missed tds on the * endpoint ring need to take care of. * Process them as short transfer until reach the td pointed by * the event. */ } while (ep->skip && trb_comp_code != COMP_MISSED_INT); return 0; } /* * This function handles all OS-owned events on the event ring. It may drop * xhci->lock between event processing (e.g. to pass up port status changes). * Returns >0 for "possibly more events to process" (caller should call again), * otherwise 0 if done. In future, <0 returns should indicate error code. */ static int xhci_handle_event(struct xhci_hcd *xhci) { union xhci_trb *event; int update_ptrs = 1; int ret; if (!xhci->event_ring || !xhci->event_ring->dequeue) { xhci->error_bitmask |= 1 << 1; return 0; } event = xhci->event_ring->dequeue; /* Does the HC or OS own the TRB? */ if ((le32_to_cpu(event->event_cmd.flags) & TRB_CYCLE) != xhci->event_ring->cycle_state) { xhci->error_bitmask |= 1 << 2; return 0; } /* * Barrier between reading the TRB_CYCLE (valid) flag above and any * speculative reads of the event's flags/data below. */ rmb(); /* FIXME: Handle more event types. */ switch ((le32_to_cpu(event->event_cmd.flags) & TRB_TYPE_BITMASK)) { case TRB_TYPE(TRB_COMPLETION): <API key>(xhci, &event->event_cmd); break; case TRB_TYPE(TRB_PORT_STATUS): handle_port_status(xhci, event); update_ptrs = 0; break; case TRB_TYPE(TRB_TRANSFER): ret = handle_tx_event(xhci, &event->trans_event); if (ret < 0) xhci->error_bitmask |= 1 << 9; else update_ptrs = 0; break; case TRB_TYPE(TRB_DEV_NOTE): <API key>(xhci, event); break; default: if ((le32_to_cpu(event->event_cmd.flags) & TRB_TYPE_BITMASK) >= TRB_TYPE(48)) handle_vendor_event(xhci, event); else xhci->error_bitmask |= 1 << 3; } /* Any of the above functions may drop and re-acquire the lock, so check * to make sure a watchdog timer didn't mark the host as non-responsive. */ if (xhci->xhc_state & XHCI_STATE_DYING) { xhci_dbg(xhci, "xHCI host dying, returning from " "event handler.\n"); return 0; } if (update_ptrs) /* Update SW event ring dequeue pointer */ inc_deq(xhci, xhci->event_ring); /* Are there more items on the event ring? Caller will call us again to * check. */ return 1; } /* * xHCI spec says we can get an interrupt, and if the HC has an error condition, * we might get bad data out of the event ring. Section 4.10.2.7 has a list of * indicators of an event TRB error, but we check the status *first* to be safe. */ irqreturn_t xhci_irq(struct usb_hcd *hcd) { struct xhci_hcd *xhci = hcd_to_xhci(hcd); u32 status; union xhci_trb *trb; u64 temp_64; union xhci_trb *event_ring_deq; dma_addr_t deq; spin_lock(&xhci->lock); trb = xhci->event_ring->dequeue; /* Check if the xHC generated the interrupt, or the irq is shared */ status = xhci_readl(xhci, &xhci->op_regs->status); if (status == 0xffffffff) goto hw_died; if (!(status & STS_EINT)) { spin_unlock(&xhci->lock); return IRQ_NONE; } if (status & STS_FATAL) { xhci_warn(xhci, "WARNING: Host System Error\n"); xhci_halt(xhci); hw_died: spin_unlock(&xhci->lock); return -ESHUTDOWN; } /* * Clear the op reg interrupt status first, * so we can receive interrupts from other MSI-X interrupters. * Write 1 to clear the interrupt status. */ status |= STS_EINT; xhci_writel(xhci, status, &xhci->op_regs->status); /* FIXME when MSI-X is supported and there are multiple vectors */ /* Clear the MSI-X event interrupt status */ if (hcd->irq) { u32 irq_pending; /* Acknowledge the PCI interrupt */ irq_pending = xhci_readl(xhci, &xhci->ir_set->irq_pending); irq_pending |= IMAN_IP; xhci_writel(xhci, irq_pending, &xhci->ir_set->irq_pending); } if (xhci->xhc_state & XHCI_STATE_DYING) { xhci_dbg(xhci, "xHCI dying, ignoring interrupt. " "Shouldn't IRQs be disabled?\n"); /* Clear the event handler busy flag (RW1C); * the event ring should be empty. */ temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue); xhci_write_64(xhci, temp_64 | ERST_EHB, &xhci->ir_set->erst_dequeue); spin_unlock(&xhci->lock); return IRQ_HANDLED; } event_ring_deq = xhci->event_ring->dequeue; /* FIXME this should be a delayed service routine * that clears the EHB. */ while (xhci_handle_event(xhci) > 0) {} temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue); /* If necessary, update the HW's version of the event ring deq ptr. */ if (event_ring_deq != xhci->event_ring->dequeue) { deq = <API key>(xhci->event_ring->deq_seg, xhci->event_ring->dequeue); if (deq == 0) xhci_warn(xhci, "WARN something wrong with SW event " "ring dequeue ptr.\n"); /* Update HC event ring dequeue pointer */ temp_64 &= ERST_PTR_MASK; temp_64 |= ((u64) deq & (u64) ~ERST_PTR_MASK); } /* Clear the event handler busy flag (RW1C); event ring is empty. */ temp_64 |= ERST_EHB; xhci_write_64(xhci, temp_64, &xhci->ir_set->erst_dequeue); spin_unlock(&xhci->lock); return IRQ_HANDLED; } irqreturn_t xhci_msi_irq(int irq, struct usb_hcd *hcd) { return xhci_irq(hcd); } /* * Generic function for queueing a TRB on a ring. * The caller must have checked to make sure there's room on the ring. * * @more_trbs_coming: Will you enqueue more TRBs before calling * prepare_transfer()? */ static void queue_trb(struct xhci_hcd *xhci, struct xhci_ring *ring, bool more_trbs_coming, u32 field1, u32 field2, u32 field3, u32 field4) { struct xhci_generic_trb *trb; trb = &ring->enqueue->generic; trb->field[0] = cpu_to_le32(field1); trb->field[1] = cpu_to_le32(field2); trb->field[2] = cpu_to_le32(field3); trb->field[3] = cpu_to_le32(field4); inc_enq(xhci, ring, more_trbs_coming); } /* * Does various checks on the endpoint ring, and makes it ready to queue num_trbs. * FIXME allocate segments if the ring is full. */ static int prepare_ring(struct xhci_hcd *xhci, struct xhci_ring *ep_ring, u32 ep_state, unsigned int num_trbs, gfp_t mem_flags) { unsigned int num_trbs_needed; /* Make sure the endpoint has been added to xHC schedule */ switch (ep_state) { case EP_STATE_DISABLED: /* * USB core changed config/interfaces without notifying us, * or hardware is reporting the wrong state. */ xhci_warn(xhci, "WARN urb submitted to disabled ep\n"); return -ENOENT; case EP_STATE_ERROR: xhci_warn(xhci, "WARN waiting for error on ep to be cleared\n"); /* FIXME event handling code for error needs to clear it */ /* XXX not sure if this should be -ENOENT or not */ return -EINVAL; case EP_STATE_HALTED: xhci_dbg(xhci, "WARN halted endpoint, queueing URB anyway.\n"); case EP_STATE_STOPPED: case EP_STATE_RUNNING: break; default: xhci_err(xhci, "ERROR unknown endpoint state for ep\n"); /* * FIXME issue Configure Endpoint command to try to get the HC * back into a known state. */ return -EINVAL; } while (1) { if (room_on_ring(xhci, ep_ring, num_trbs)) break; if (ep_ring == xhci->cmd_ring) { xhci_err(xhci, "Do not support expand command ring\n"); return -ENOMEM; } xhci_dbg(xhci, "ERROR no room on ep ring, " "try ring expansion\n"); num_trbs_needed = num_trbs - ep_ring->num_trbs_free; if (xhci_ring_expansion(xhci, ep_ring, num_trbs_needed, mem_flags)) { xhci_err(xhci, "Ring expansion failed\n"); return -ENOMEM; } }; if (enqueue_is_link_trb(ep_ring)) { struct xhci_ring *ring = ep_ring; union xhci_trb *next; next = ring->enqueue; while (last_trb(xhci, ring, ring->enq_seg, next)) { /* If we're not dealing with 0.95 hardware or isoc rings * on AMD 0.96 host, clear the chain bit. */ if (!xhci_link_trb_quirk(xhci) && !(ring->type == TYPE_ISOC && (xhci->quirks & XHCI_AMD_0x96_HOST))) next->link.control &= cpu_to_le32(~TRB_CHAIN); else next->link.control |= cpu_to_le32(TRB_CHAIN); wmb(); next->link.control ^= cpu_to_le32(TRB_CYCLE); /* Toggle the cycle bit after the last ring segment. */ if (<API key>(xhci, ring, ring->enq_seg, next)) { ring->cycle_state = (ring->cycle_state ? 0 : 1); } ring->enq_seg = ring->enq_seg->next; ring->enqueue = ring->enq_seg->trbs; next = ring->enqueue; } } return 0; } static int prepare_transfer(struct xhci_hcd *xhci, struct xhci_virt_device *xdev, unsigned int ep_index, unsigned int stream_id, unsigned int num_trbs, struct urb *urb, unsigned int td_index, gfp_t mem_flags) { int ret; struct urb_priv *urb_priv; struct xhci_td *td; struct xhci_ring *ep_ring; struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); ep_ring = <API key>(xdev, ep_index, stream_id); if (!ep_ring) { xhci_dbg(xhci, "Can't prepare ring for bad stream ID %u\n", stream_id); return -EINVAL; } ret = prepare_ring(xhci, ep_ring, le32_to_cpu(ep_ctx->ep_info) & EP_STATE_MASK, num_trbs, mem_flags); if (ret) return ret; urb_priv = urb->hcpriv; td = urb_priv->td[td_index]; INIT_LIST_HEAD(&td->td_list); INIT_LIST_HEAD(&td->cancelled_td_list); if (td_index == 0) { ret = <API key>(bus_to_hcd(urb->dev->bus), urb); if (unlikely(ret)) return ret; } td->urb = urb; /* Add this TD to the tail of the endpoint ring's TD list */ list_add_tail(&td->td_list, &ep_ring->td_list); td->start_seg = ep_ring->enq_seg; td->first_trb = ep_ring->enqueue; urb_priv->td[td_index] = td; return 0; } static unsigned int <API key>(struct xhci_hcd *xhci, struct urb *urb) { int num_sgs, num_trbs, running_total, temp, i; struct scatterlist *sg; sg = NULL; num_sgs = urb->num_mapped_sgs; temp = urb-><API key>; num_trbs = 0; for_each_sg(urb->sg, sg, num_sgs, i) { unsigned int len = sg_dma_len(sg); /* Scatter gather list entries may cross 64KB boundaries */ running_total = TRB_MAX_BUFF_SIZE - (sg_dma_address(sg) & (TRB_MAX_BUFF_SIZE - 1)); running_total &= TRB_MAX_BUFF_SIZE - 1; if (running_total != 0) num_trbs++; /* How many more 64KB chunks to transfer, how many more TRBs? */ while (running_total < sg_dma_len(sg) && running_total < temp) { num_trbs++; running_total += TRB_MAX_BUFF_SIZE; } len = min_t(int, len, temp); temp -= len; if (temp == 0) break; } return num_trbs; } static void check_trb_math(struct urb *urb, int num_trbs, int running_total) { if (num_trbs != 0) dev_err(&urb->dev->dev, "%s - ep %#x - Miscalculated number of " "TRBs, %d left\n", __func__, urb->ep->desc.bEndpointAddress, num_trbs); if (running_total != urb-><API key>) dev_err(&urb->dev->dev, "%s - ep %#x - Miscalculated tx length, " "queued %#x (%d), asked for %#x (%d)\n", __func__, urb->ep->desc.bEndpointAddress, running_total, running_total, urb-><API key>, urb-><API key>); } static void giveback_first_trb(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index, unsigned int stream_id, int start_cycle, struct xhci_generic_trb *start_trb) { /* * Pass all the TRBs to the hardware at once and make sure this write * isn't reordered. */ wmb(); if (start_cycle) start_trb->field[3] |= cpu_to_le32(start_cycle); else start_trb->field[3] &= cpu_to_le32(~TRB_CYCLE); <API key>(xhci, slot_id, ep_index, stream_id); } /* * xHCI uses normal TRBs for both bulk and interrupt. When the interrupt * endpoint is to be serviced, the xHC will consume (at most) one TD. A TD * (comprised of sg list entries) can take several service intervals to * transmit. */ int xhci_queue_intr_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci, xhci->devs[slot_id]->out_ctx, ep_index); int xhci_interval; int ep_interval; xhci_interval = <API key>(le32_to_cpu(ep_ctx->ep_info)); ep_interval = urb->interval; /* Convert to microframes */ if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) ep_interval *= 8; /* FIXME change this to a warning and a suggestion to use the new API * to set the polling interval (once the API is added). */ if (xhci_interval != ep_interval) { if (printk_ratelimit()) dev_dbg(&urb->dev->dev, "Driver uses different interval" " (%d microframe%s) than xHCI " "(%d microframe%s)\n", ep_interval, ep_interval == 1 ? "" : "s", xhci_interval, xhci_interval == 1 ? "" : "s"); urb->interval = xhci_interval; /* Convert back to frames for LS/FS devices */ if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) urb->interval /= 8; } return xhci_queue_bulk_tx(xhci, mem_flags, urb, slot_id, ep_index); } /* * The TD size is the number of bytes remaining in the TD (including this TRB), * right shifted by 10. * It must fit in bits 21:17, so it can't be bigger than 31. */ static u32 xhci_td_remainder(unsigned int remainder) { u32 max = (1 << (21 - 17 + 1)) - 1; if ((remainder >> 10) >= max) return max << 17; else return (remainder >> 10) << 17; } /* * For xHCI 1.0 host controllers, TD size is the number of packets remaining in * the TD (*not* including this TRB). * * Total TD packet count = total_packet_count = * roundup(TD size in bytes / wMaxPacketSize) * * Packets transferred up to and including this TRB = packets_transferred = * rounddown(total bytes transferred including this TRB / wMaxPacketSize) * * TD size = total_packet_count - packets_transferred * * It must fit in bits 21:17, so it can't be bigger than 31. */ static u32 <API key>(int running_total, int trb_buff_len, unsigned int total_packet_count, struct urb *urb) { int packets_transferred; /* One TRB with a zero-length data packet. */ if (running_total == 0 && trb_buff_len == 0) return 0; /* All the TRB queueing functions don't count the current TRB in * running_total. */ packets_transferred = (running_total + trb_buff_len) / usb_endpoint_maxp(&urb->ep->desc); return xhci_td_remainder(total_packet_count - packets_transferred); } static int queue_bulk_sg_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ring *ep_ring; unsigned int num_trbs; struct urb_priv *urb_priv; struct xhci_td *td; struct scatterlist *sg; int num_sgs; int trb_buff_len, this_sg_len, running_total; unsigned int total_packet_count; bool first_trb; u64 addr; bool more_trbs_coming; struct xhci_generic_trb *start_trb; int start_cycle; ep_ring = <API key>(xhci, urb); if (!ep_ring) return -EINVAL; num_trbs = <API key>(xhci, urb); num_sgs = urb->num_mapped_sgs; total_packet_count = roundup(urb-><API key>, usb_endpoint_maxp(&urb->ep->desc)); trb_buff_len = prepare_transfer(xhci, xhci->devs[slot_id], ep_index, urb->stream_id, num_trbs, urb, 0, mem_flags); if (trb_buff_len < 0) return trb_buff_len; urb_priv = urb->hcpriv; td = urb_priv->td[0]; /* * Don't give the first TRB to the hardware (by toggling the cycle bit) * until we've finished creating all the other TRBs. The ring's cycle * state may change as we enqueue the other TRBs, so save it too. */ start_trb = &ep_ring->enqueue->generic; start_cycle = ep_ring->cycle_state; running_total = 0; /* * How much data is in the first TRB? * * There are three forces at work for TRB buffer pointers and lengths: * 1. We don't want to walk off the end of this sg-list entry buffer. * 2. The transfer length that the driver requested may be smaller than * the amount of memory allocated for this scatter-gather list. * 3. TRBs buffers can't cross 64KB boundaries. */ sg = urb->sg; addr = (u64) sg_dma_address(sg); this_sg_len = sg_dma_len(sg); trb_buff_len = TRB_MAX_BUFF_SIZE - (addr & (TRB_MAX_BUFF_SIZE - 1)); trb_buff_len = min_t(int, trb_buff_len, this_sg_len); if (trb_buff_len > urb-><API key>) trb_buff_len = urb-><API key>; first_trb = true; /* Queue the first TRB, even if it's zero-length */ do { u32 field = 0; u32 length_field = 0; u32 remainder = 0; /* Don't change the cycle bit of the first TRB until later */ if (first_trb) { first_trb = false; if (start_cycle == 0) field |= 0x1; } else field |= ep_ring->cycle_state; /* Chain all the TRBs together; clear the chain bit in the last * TRB to indicate it's the last TRB in the chain. */ if (num_trbs > 1) { field |= TRB_CHAIN; } else { /* FIXME - add check for ZERO_PACKET flag before this */ td->last_trb = ep_ring->enqueue; field |= TRB_IOC; } /* Only set interrupt on short packet for IN endpoints */ if (usb_urb_dir_in(urb)) field |= TRB_ISP; if (TRB_MAX_BUFF_SIZE - (addr & (TRB_MAX_BUFF_SIZE - 1)) < trb_buff_len) { xhci_warn(xhci, "WARN: sg dma xfer crosses 64KB boundaries!\n"); xhci_dbg(xhci, "Next boundary at %#x, end dma = %#x\n", (unsigned int) (addr + TRB_MAX_BUFF_SIZE) & ~(TRB_MAX_BUFF_SIZE - 1), (unsigned int) addr + trb_buff_len); } /* Set the TRB length, TD size, and interrupter fields. */ if (xhci->hci_version < 0x100) { remainder = xhci_td_remainder( urb-><API key> - running_total); } else { remainder = <API key>(running_total, trb_buff_len, total_packet_count, urb); } length_field = TRB_LEN(trb_buff_len) | remainder | TRB_INTR_TARGET(0); if (num_trbs > 1) more_trbs_coming = true; else more_trbs_coming = false; queue_trb(xhci, ep_ring, more_trbs_coming, lower_32_bits(addr), upper_32_bits(addr), length_field, field | TRB_TYPE(TRB_NORMAL)); --num_trbs; running_total += trb_buff_len; /* Calculate length for next transfer -- * Are we done queueing all the TRBs for this sg entry? */ this_sg_len -= trb_buff_len; if (this_sg_len == 0) { --num_sgs; if (num_sgs == 0) break; sg = sg_next(sg); addr = (u64) sg_dma_address(sg); this_sg_len = sg_dma_len(sg); } else { addr += trb_buff_len; } trb_buff_len = TRB_MAX_BUFF_SIZE - (addr & (TRB_MAX_BUFF_SIZE - 1)); trb_buff_len = min_t(int, trb_buff_len, this_sg_len); if (running_total + trb_buff_len > urb-><API key>) trb_buff_len = urb-><API key> - running_total; } while (running_total < urb-><API key>); check_trb_math(urb, num_trbs, running_total); giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id, start_cycle, start_trb); return 0; } /* This is very similar to what ehci-q.c qtd_fill() does */ int xhci_queue_bulk_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ring *ep_ring; struct urb_priv *urb_priv; struct xhci_td *td; int num_trbs; struct xhci_generic_trb *start_trb; bool first_trb; bool more_trbs_coming; int start_cycle; u32 field, length_field; int running_total, trb_buff_len, ret; unsigned int total_packet_count; u64 addr; if (urb->num_sgs) return queue_bulk_sg_tx(xhci, mem_flags, urb, slot_id, ep_index); ep_ring = <API key>(xhci, urb); if (!ep_ring) return -EINVAL; num_trbs = 0; /* How much data is (potentially) left before the 64KB boundary? */ running_total = TRB_MAX_BUFF_SIZE - (urb->transfer_dma & (TRB_MAX_BUFF_SIZE - 1)); running_total &= TRB_MAX_BUFF_SIZE - 1; /* If there's some data on this 64KB chunk, or we have to send a * zero-length transfer, we need at least one TRB */ if (running_total != 0 || urb-><API key> == 0) num_trbs++; /* How many more 64KB chunks to transfer, how many more TRBs? */ while (running_total < urb-><API key>) { num_trbs++; running_total += TRB_MAX_BUFF_SIZE; } /* FIXME: this doesn't deal with URB_ZERO_PACKET - need one more */ ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index, urb->stream_id, num_trbs, urb, 0, mem_flags); if (ret < 0) return ret; urb_priv = urb->hcpriv; td = urb_priv->td[0]; /* * Don't give the first TRB to the hardware (by toggling the cycle bit) * until we've finished creating all the other TRBs. The ring's cycle * state may change as we enqueue the other TRBs, so save it too. */ start_trb = &ep_ring->enqueue->generic; start_cycle = ep_ring->cycle_state; running_total = 0; total_packet_count = roundup(urb-><API key>, usb_endpoint_maxp(&urb->ep->desc)); /* How much data is in the first TRB? */ addr = (u64) urb->transfer_dma; trb_buff_len = TRB_MAX_BUFF_SIZE - (urb->transfer_dma & (TRB_MAX_BUFF_SIZE - 1)); if (trb_buff_len > urb-><API key>) trb_buff_len = urb-><API key>; first_trb = true; /* Queue the first TRB, even if it's zero-length */ do { u32 remainder = 0; field = 0; /* Don't change the cycle bit of the first TRB until later */ if (first_trb) { first_trb = false; if (start_cycle == 0) field |= 0x1; } else field |= ep_ring->cycle_state; /* Chain all the TRBs together; clear the chain bit in the last * TRB to indicate it's the last TRB in the chain. */ if (num_trbs > 1) { field |= TRB_CHAIN; } else { /* FIXME - add check for ZERO_PACKET flag before this */ td->last_trb = ep_ring->enqueue; field |= TRB_IOC; } /* Only set interrupt on short packet for IN endpoints */ if (usb_urb_dir_in(urb)) field |= TRB_ISP; /* Set the TRB length, TD size, and interrupter fields. */ if (xhci->hci_version < 0x100) { remainder = xhci_td_remainder( urb-><API key> - running_total); } else { remainder = <API key>(running_total, trb_buff_len, total_packet_count, urb); } length_field = TRB_LEN(trb_buff_len) | remainder | TRB_INTR_TARGET(0); if (num_trbs > 1) more_trbs_coming = true; else more_trbs_coming = false; queue_trb(xhci, ep_ring, more_trbs_coming, lower_32_bits(addr), upper_32_bits(addr), length_field, field | TRB_TYPE(TRB_NORMAL)); --num_trbs; running_total += trb_buff_len; /* Calculate length for next transfer */ addr += trb_buff_len; trb_buff_len = urb-><API key> - running_total; if (trb_buff_len > TRB_MAX_BUFF_SIZE) trb_buff_len = TRB_MAX_BUFF_SIZE; } while (running_total < urb-><API key>); check_trb_math(urb, num_trbs, running_total); giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id, start_cycle, start_trb); return 0; } /* Caller must have locked xhci->lock */ int xhci_queue_ctrl_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ring *ep_ring; int num_trbs; int ret; struct usb_ctrlrequest *setup; struct xhci_generic_trb *start_trb; int start_cycle; u32 field, length_field; struct urb_priv *urb_priv; struct xhci_td *td; ep_ring = <API key>(xhci, urb); if (!ep_ring) return -EINVAL; /* * Need to copy setup packet into setup TRB, so we can't use the setup * DMA address. */ if (!urb->setup_packet) return -EINVAL; /* 1 TRB for setup, 1 for status */ num_trbs = 2; /* * Don't need to check if we need additional event data and normal TRBs, * since data in control transfers will never get bigger than 16MB * XXX: can we get a buffer that crosses 64KB boundaries? */ if (urb-><API key> > 0) num_trbs++; ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index, urb->stream_id, num_trbs, urb, 0, mem_flags); if (ret < 0) return ret; urb_priv = urb->hcpriv; td = urb_priv->td[0]; /* * Don't give the first TRB to the hardware (by toggling the cycle bit) * until we've finished creating all the other TRBs. The ring's cycle * state may change as we enqueue the other TRBs, so save it too. */ start_trb = &ep_ring->enqueue->generic; start_cycle = ep_ring->cycle_state; /* Queue setup TRB - see section 6.4.1.2.1 */ /* FIXME better way to translate setup_packet into two u32 fields? */ setup = (struct usb_ctrlrequest *) urb->setup_packet; field = 0; field |= TRB_IDT | TRB_TYPE(TRB_SETUP); if (start_cycle == 0) field |= 0x1; /* xHCI 1.0 6.4.1.2.1: Transfer Type field */ if (xhci->hci_version == 0x100) { if (urb-><API key> > 0) { if (setup->bRequestType & USB_DIR_IN) field |= TRB_TX_TYPE(TRB_DATA_IN); else field |= TRB_TX_TYPE(TRB_DATA_OUT); } } queue_trb(xhci, ep_ring, true, setup->bRequestType | setup->bRequest << 8 | le16_to_cpu(setup->wValue) << 16, le16_to_cpu(setup->wIndex) | le16_to_cpu(setup->wLength) << 16, TRB_LEN(8) | TRB_INTR_TARGET(0), /* Immediate data in pointer */ field); /* If there's data, queue data TRBs */ /* Only set interrupt on short packet for IN endpoints */ if (usb_urb_dir_in(urb)) field = TRB_ISP | TRB_TYPE(TRB_DATA); else field = TRB_TYPE(TRB_DATA); length_field = TRB_LEN(urb-><API key>) | xhci_td_remainder(urb-><API key>) | TRB_INTR_TARGET(0); if (urb-><API key> > 0) { if (setup->bRequestType & USB_DIR_IN) field |= TRB_DIR_IN; queue_trb(xhci, ep_ring, true, lower_32_bits(urb->transfer_dma), upper_32_bits(urb->transfer_dma), length_field, field | ep_ring->cycle_state); } /* Save the DMA address of the last TRB in the TD */ td->last_trb = ep_ring->enqueue; /* Queue status TRB - see Table 7 and sections 4.11.2.2 and 6.4.1.2.3 */ /* If the device sent data, the status stage is an OUT transfer */ if (urb-><API key> > 0 && setup->bRequestType & USB_DIR_IN) field = 0; else field = TRB_DIR_IN; queue_trb(xhci, ep_ring, false, 0, 0, TRB_INTR_TARGET(0), /* Event on completion */ field | TRB_IOC | TRB_TYPE(TRB_STATUS) | ep_ring->cycle_state); giveback_first_trb(xhci, slot_id, ep_index, 0, start_cycle, start_trb); return 0; } static int <API key>(struct xhci_hcd *xhci, struct urb *urb, int i) { int num_trbs = 0; u64 addr, td_len; addr = (u64) (urb->transfer_dma + urb->iso_frame_desc[i].offset); td_len = urb->iso_frame_desc[i].length; num_trbs = DIV_ROUND_UP(td_len + (addr & (TRB_MAX_BUFF_SIZE - 1)), TRB_MAX_BUFF_SIZE); if (num_trbs == 0) num_trbs++; return num_trbs; } /* * The transfer burst count field of the isochronous TRB defines the number of * bursts that are required to move all packets in this TD. Only SuperSpeed * devices can burst up to bMaxBurst number of packets per service interval. * This field is zero based, meaning a value of zero in the field means one * burst. Basically, for everything but SuperSpeed devices, this field will be * zero. Only xHCI 1.0 host controllers support this field. */ static unsigned int <API key>(struct xhci_hcd *xhci, struct usb_device *udev, struct urb *urb, unsigned int total_packet_count) { unsigned int max_burst; if (xhci->hci_version < 0x100 || udev->speed != USB_SPEED_SUPER) return 0; max_burst = urb->ep->ss_ep_comp.bMaxBurst; return roundup(total_packet_count, max_burst + 1) - 1; } /* * Returns the number of packets in the last "burst" of packets. This field is * valid for all speeds of devices. USB 2.0 devices can only do one "burst", so * the last burst packet count is equal to the total number of packets in the * TD. SuperSpeed endpoints can have up to 3 bursts. All but the last burst * must contain (bMaxBurst + 1) number of packets, but the last burst can * contain 1 to (bMaxBurst + 1) packets. */ static unsigned int <API key>(struct xhci_hcd *xhci, struct usb_device *udev, struct urb *urb, unsigned int total_packet_count) { unsigned int max_burst; unsigned int residue; if (xhci->hci_version < 0x100) return 0; switch (udev->speed) { case USB_SPEED_SUPER: /* bMaxBurst is zero based: 0 means 1 packet per burst */ max_burst = urb->ep->ss_ep_comp.bMaxBurst; residue = total_packet_count % (max_burst + 1); /* If residue is zero, the last burst contains (max_burst + 1) * number of packets, but the TLBPC field is zero-based. */ if (residue == 0) return max_burst; return residue - 1; default: if (total_packet_count == 0) return 0; return total_packet_count - 1; } } /* This is for isoc transfer */ static int xhci_queue_isoc_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ring *ep_ring; struct urb_priv *urb_priv; struct xhci_td *td; int num_tds, trbs_per_td; struct xhci_generic_trb *start_trb; bool first_trb; int start_cycle; u32 field, length_field; int running_total, trb_buff_len, td_len, td_remain_len, ret; u64 start_addr, addr; int i, j; bool more_trbs_coming; ep_ring = xhci->devs[slot_id]->eps[ep_index].ring; num_tds = urb->number_of_packets; if (num_tds < 1) { xhci_dbg(xhci, "Isoc URB with zero packets?\n"); return -EINVAL; } start_addr = (u64) urb->transfer_dma; start_trb = &ep_ring->enqueue->generic; start_cycle = ep_ring->cycle_state; urb_priv = urb->hcpriv; /* Queue the first TRB, even if it's zero-length */ for (i = 0; i < num_tds; i++) { unsigned int total_packet_count; unsigned int burst_count; unsigned int residue; first_trb = true; running_total = 0; addr = start_addr + urb->iso_frame_desc[i].offset; td_len = urb->iso_frame_desc[i].length; td_remain_len = td_len; total_packet_count = roundup(td_len, usb_endpoint_maxp(&urb->ep->desc)); /* A zero-length transfer still involves at least one packet. */ if (total_packet_count == 0) total_packet_count++; burst_count = <API key>(xhci, urb->dev, urb, total_packet_count); residue = <API key>(xhci, urb->dev, urb, total_packet_count); trbs_per_td = <API key>(xhci, urb, i); ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index, urb->stream_id, trbs_per_td, urb, i, mem_flags); if (ret < 0) { if (i == 0) return ret; goto cleanup; } td = urb_priv->td[i]; for (j = 0; j < trbs_per_td; j++) { u32 remainder = 0; field = TRB_TBC(burst_count) | TRB_TLBPC(residue); if (first_trb) { /* Queue the isoc TRB */ field |= TRB_TYPE(TRB_ISOC); /* Assume URB_ISO_ASAP is set */ field |= TRB_SIA; if (i == 0) { if (start_cycle == 0) field |= 0x1; } else field |= ep_ring->cycle_state; first_trb = false; } else { /* Queue other normal TRBs */ field |= TRB_TYPE(TRB_NORMAL); field |= ep_ring->cycle_state; } /* Only set interrupt on short packet for IN EPs */ if (usb_urb_dir_in(urb)) field |= TRB_ISP; /* Chain all the TRBs together; clear the chain bit in * the last TRB to indicate it's the last TRB in the * chain. */ if (j < trbs_per_td - 1) { field |= TRB_CHAIN; more_trbs_coming = true; } else { td->last_trb = ep_ring->enqueue; field |= TRB_IOC; if (xhci->hci_version == 0x100) { /* Set BEI bit except for the last td */ if (i < num_tds - 1) field |= TRB_BEI; } more_trbs_coming = false; } /* Calculate TRB length */ trb_buff_len = TRB_MAX_BUFF_SIZE - (addr & ((1 << TRB_MAX_BUFF_SHIFT) - 1)); if (trb_buff_len > td_remain_len) trb_buff_len = td_remain_len; /* Set the TRB length, TD size, & interrupter fields. */ if (xhci->hci_version < 0x100) { remainder = xhci_td_remainder( td_len - running_total); } else { remainder = <API key>( running_total, trb_buff_len, total_packet_count, urb); } length_field = TRB_LEN(trb_buff_len) | remainder | TRB_INTR_TARGET(0); queue_trb(xhci, ep_ring, more_trbs_coming, lower_32_bits(addr), upper_32_bits(addr), length_field, field); running_total += trb_buff_len; addr += trb_buff_len; td_remain_len -= trb_buff_len; } /* Check TD length */ if (running_total != td_len) { xhci_err(xhci, "ISOC TD length unmatch\n"); ret = -EINVAL; goto cleanup; } } if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) { if (xhci->quirks & XHCI_AMD_PLL_FIX) <API key>(); } xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs++; giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id, start_cycle, start_trb); return 0; cleanup: /* Clean up a partially enqueued isoc transfer. */ for (i--; i >= 0; i--) list_del_init(&urb_priv->td[i]->td_list); /* Use the first TD as a temporary variable to turn the TDs we've queued * into No-ops with a software-owned cycle bit. That way the hardware * won't accidentally start executing bogus TDs when we partially * overwrite them. td->first_trb and td->start_seg are already set. */ urb_priv->td[0]->last_trb = ep_ring->enqueue; /* Every TRB except the first & last will have its cycle bit flipped. */ td_to_noop(xhci, ep_ring, urb_priv->td[0], true); /* Reset the ring enqueue back to the first TRB and its cycle bit. */ ep_ring->enqueue = urb_priv->td[0]->first_trb; ep_ring->enq_seg = urb_priv->td[0]->start_seg; ep_ring->cycle_state = start_cycle; ep_ring->num_trbs_free = ep_ring->num_trbs_free_temp; <API key>(bus_to_hcd(urb->dev->bus), urb); return ret; } /* * Check transfer ring to guarantee there is enough room for the urb. * Update ISO URB start_frame and interval. * Update interval as xhci_queue_intr_tx does. Just use xhci frame_index to * update the urb->start_frame by now. * Always assume URB_ISO_ASAP set, and NEVER use urb->start_frame as input. */ int <API key>(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_virt_device *xdev; struct xhci_ring *ep_ring; struct xhci_ep_ctx *ep_ctx; int start_frame; int xhci_interval; int ep_interval; int num_tds, num_trbs, i; int ret; xdev = xhci->devs[slot_id]; ep_ring = xdev->eps[ep_index].ring; ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); num_trbs = 0; num_tds = urb->number_of_packets; for (i = 0; i < num_tds; i++) num_trbs += <API key>(xhci, urb, i); /* Check the ring to guarantee there is enough room for the whole urb. * Do not insert any td of the urb to the ring if the check failed. */ ret = prepare_ring(xhci, ep_ring, le32_to_cpu(ep_ctx->ep_info) & EP_STATE_MASK, num_trbs, mem_flags); if (ret) return ret; start_frame = xhci_readl(xhci, &xhci->run_regs->microframe_index); start_frame &= 0x3fff; urb->start_frame = start_frame; if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) urb->start_frame >>= 3; xhci_interval = <API key>(le32_to_cpu(ep_ctx->ep_info)); ep_interval = urb->interval; /* Convert to microframes */ if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) ep_interval *= 8; /* FIXME change this to a warning and a suggestion to use the new API * to set the polling interval (once the API is added). */ if (xhci_interval != ep_interval) { if (printk_ratelimit()) dev_dbg(&urb->dev->dev, "Driver uses different interval" " (%d microframe%s) than xHCI " "(%d microframe%s)\n", ep_interval, ep_interval == 1 ? "" : "s", xhci_interval, xhci_interval == 1 ? "" : "s"); urb->interval = xhci_interval; /* Convert back to frames for LS/FS devices */ if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) urb->interval /= 8; } ep_ring->num_trbs_free_temp = ep_ring->num_trbs_free; return xhci_queue_isoc_tx(xhci, mem_flags, urb, slot_id, ep_index); } /* Generic function for queueing a command TRB on the command ring. * Check to make sure there's room on the command ring for one command TRB. * Also check that there's room reserved for commands that must not fail. * If this is a command that must not fail, meaning <API key> = TRUE, * then only check for the number of reserved spots. * Don't decrement xhci-><API key> after we've queued the TRB * because the command event handler may want to resubmit a failed command. */ static int queue_command(struct xhci_hcd *xhci, u32 field1, u32 field2, u32 field3, u32 field4, bool <API key>) { int reserved_trbs = xhci-><API key>; int ret; if (!<API key>) reserved_trbs++; ret = prepare_ring(xhci, xhci->cmd_ring, EP_STATE_RUNNING, reserved_trbs, GFP_ATOMIC); if (ret < 0) { xhci_err(xhci, "ERR: No room for command on command ring\n"); if (<API key>) xhci_err(xhci, "ERR: Reserved TRB counting for " "unfailable commands failed.\n"); return ret; } queue_trb(xhci, xhci->cmd_ring, false, field1, field2, field3, field4 | xhci->cmd_ring->cycle_state); return 0; } /* Queue a slot enable or disable request on the command ring */ int <API key>(struct xhci_hcd *xhci, u32 trb_type, u32 slot_id) { return queue_command(xhci, 0, 0, 0, TRB_TYPE(trb_type) | SLOT_ID_FOR_TRB(slot_id), false); } /* Queue an address device command TRB */ int <API key>(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr, u32 slot_id) { return queue_command(xhci, lower_32_bits(in_ctx_ptr), upper_32_bits(in_ctx_ptr), 0, TRB_TYPE(TRB_ADDR_DEV) | SLOT_ID_FOR_TRB(slot_id), false); } int <API key>(struct xhci_hcd *xhci, u32 field1, u32 field2, u32 field3, u32 field4) { return queue_command(xhci, field1, field2, field3, field4, false); } /* Queue a reset device command TRB */ int <API key>(struct xhci_hcd *xhci, u32 slot_id) { return queue_command(xhci, 0, 0, 0, TRB_TYPE(TRB_RESET_DEV) | SLOT_ID_FOR_TRB(slot_id), false); } /* Queue a configure endpoint command TRB */ int <API key>(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr, u32 slot_id, bool <API key>) { return queue_command(xhci, lower_32_bits(in_ctx_ptr), upper_32_bits(in_ctx_ptr), 0, TRB_TYPE(TRB_CONFIG_EP) | SLOT_ID_FOR_TRB(slot_id), <API key>); } /* Queue an evaluate context command TRB */ int <API key>(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr, u32 slot_id) { return queue_command(xhci, lower_32_bits(in_ctx_ptr), upper_32_bits(in_ctx_ptr), 0, TRB_TYPE(TRB_EVAL_CONTEXT) | SLOT_ID_FOR_TRB(slot_id), false); } /* * Suspend is set to indicate "Stop Endpoint Command" is being issued to stop * activity on an endpoint that is about to be suspended. */ int <API key>(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index, int suspend) { u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id); u32 trb_ep_index = EP_ID_FOR_TRB(ep_index); u32 type = TRB_TYPE(TRB_STOP_RING); u32 trb_suspend = <API key>(suspend); return queue_command(xhci, 0, 0, 0, trb_slot_id | trb_ep_index | type | trb_suspend, false); } /* Set Transfer Ring Dequeue Pointer command. * This should not be used for endpoints that have streams enabled. */ static int queue_set_tr_deq(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_segment *deq_seg, union xhci_trb *deq_ptr, u32 cycle_state) { dma_addr_t addr; u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id); u32 trb_ep_index = EP_ID_FOR_TRB(ep_index); u32 trb_stream_id = STREAM_ID_FOR_TRB(stream_id); u32 type = TRB_TYPE(TRB_SET_DEQ); struct xhci_virt_ep *ep; addr = <API key>(deq_seg, deq_ptr); if (addr == 0) { xhci_warn(xhci, "WARN Cannot submit Set TR Deq Ptr\n"); xhci_warn(xhci, "WARN deq seg = %p, deq pt = %p\n", deq_seg, deq_ptr); return 0; } ep = &xhci->devs[slot_id]->eps[ep_index]; if ((ep->ep_state & SET_DEQ_PENDING)) { xhci_warn(xhci, "WARN Cannot submit Set TR Deq Ptr\n"); xhci_warn(xhci, "A Set TR Deq Ptr command is pending.\n"); return 0; } ep->queued_deq_seg = deq_seg; ep->queued_deq_ptr = deq_ptr; return queue_command(xhci, lower_32_bits(addr) | cycle_state, upper_32_bits(addr), trb_stream_id, trb_slot_id | trb_ep_index | type, false); } int xhci_queue_reset_ep(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index) { u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id); u32 trb_ep_index = EP_ID_FOR_TRB(ep_index); u32 type = TRB_TYPE(TRB_RESET_EP); return queue_command(xhci, 0, 0, 0, trb_slot_id | trb_ep_index | type, false); }
#include <linux/module.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/time.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/spinlock.h> #include <linux/hrtimer.h> #include <linux/clk.h> #include <mach/hardware.h> #include <mach/iommu_domains.h> #include <mach/iommu.h> #include <linux/iommu.h> #include <linux/io.h> #include <linux/debugfs.h> #include <linux/fb.h> #include <linux/msm_mdp.h> #include <linux/file.h> #include <linux/android_pmem.h> #include <linux/major.h> #include <asm/system.h> #include <asm/mach-types.h> #include <linux/semaphore.h> #include <linux/uaccess.h> #include <linux/mutex.h> #include <linux/msm_kgsl.h> #include "mdp.h" #include "msm_fb.h" #include "mdp4.h" #define VERSION_KEY_MASK 0xFFFFFF00 struct mdp4_overlay_ctrl { struct mdp4_overlay_pipe plist[OVERLAY_PIPE_MAX]; struct mdp4_overlay_pipe *stage[MDP4_MIXER_MAX][<API key>]; struct mdp4_overlay_pipe *baselayer[MDP4_MIXER_MAX]; struct blend_cfg blend[MDP4_MIXER_MAX][<API key>]; uint32 mixer_cfg[MDP4_MIXER_MAX]; uint32 flush[MDP4_MIXER_MAX]; struct iommu_free_list iommu_free[MDP4_MIXER_MAX]; struct iommu_free_list iommu_free_prev[MDP4_MIXER_MAX]; uint32 dmap_cfg[5]; uint32 cs_controller; uint32 panel_3d; uint32 panel_mode; uint32 mixer0_played; uint32 mixer1_played; uint32 mixer2_played; } mdp4_overlay_db = { .cs_controller = CS_CONTROLLER_0, .plist = { { .pipe_type = OVERLAY_TYPE_RGB, .pipe_num = OVERLAY_PIPE_RGB1, .pipe_ndx = 1, }, { .pipe_type = OVERLAY_TYPE_RGB, .pipe_num = OVERLAY_PIPE_RGB2, .pipe_ndx = 2, }, { .pipe_type = OVERLAY_TYPE_VIDEO, .pipe_num = OVERLAY_PIPE_VG1, .pipe_ndx = 3, }, { .pipe_type = OVERLAY_TYPE_VIDEO, .pipe_num = OVERLAY_PIPE_VG2, .pipe_ndx = 4, }, { .pipe_type = OVERLAY_TYPE_BF, .pipe_num = OVERLAY_PIPE_RGB3, .pipe_ndx = 5, .mixer_num = MDP4_MIXER0, }, { .pipe_type = OVERLAY_TYPE_BF, .pipe_num = OVERLAY_PIPE_VG3, .pipe_ndx = 6, .mixer_num = MDP4_MIXER1, }, { .pipe_type = OVERLAY_TYPE_BF, .pipe_num = OVERLAY_PIPE_VG4, .pipe_ndx = 7, .mixer_num = MDP4_MIXER2, }, }, }; static DEFINE_MUTEX(iommu_mutex); static DEFINE_MUTEX(perf_mutex); static struct mdp4_overlay_ctrl *ctrl = &mdp4_overlay_db; struct mdp4_overlay_perf { u32 mdp_clk_rate; u32 use_ov_blt[MDP4_MIXER_MAX]; u64 mdp_ov_ab_bw[MDP4_MIXER_MAX]; u64 mdp_ov_ib_bw[MDP4_MIXER_MAX]; u32 mdp_ab_bw; u32 mdp_ib_bw; }; static struct mdp4_overlay_perf perf_request; static struct mdp4_overlay_perf perf_current; void <API key>(struct msm_fb_data_type *mfd) { if (!hdmi_prim_display && mfd->index == 0) { if (ctrl->panel_mode & <API key>) <API key>(mfd); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) <API key>(mfd); else if (ctrl->panel_mode & MDP4_PANEL_LCDC) <API key>(mfd); } else if (hdmi_prim_display || mfd->index == 1) { <API key>(mfd); } } static struct ion_client *display_iclient; static int <API key>(struct msm_fb_data_type *mfd) { int ret = 0; if (!mfd) { pr_err("%s: mfd is invalid\n", __func__); return -ENODEV; } pr_debug("%s %d mfd->index=%d,mapped=%d\n", __func__, __LINE__, mfd->index, mfd->sec_mapped); if (mfd->sec_mapped) return 0; ret = <API key>(); if (ret) { pr_err("IOMMU clock enabled failed while open"); return ret; } ret = msm_ion_secure_heap(ION_HEAP(ION_CP_MM_HEAP_ID)); if (ret) pr_err("ION heap secure failed heap id %d ret %d\n", ION_CP_MM_HEAP_ID, ret); else mfd->sec_mapped = 1; <API key>(); return ret; } int <API key>(struct msm_fb_data_type *mfd) { int ret = 0; int i, sec_cnt = 0; struct mdp4_overlay_pipe *pipe; if (!mfd) { pr_err("%s: mfd is invalid\n", __func__); return -ENODEV; } if (mfd->sec_mapped == 0) return 0; for (i = 0; i < OVERLAY_PIPE_MAX; i++) { pipe = &ctrl->plist[i]; if ((pipe->mixer_num == mfd->index) && pipe->flags & <API key>) sec_cnt++; } if (sec_cnt) return 0; pr_debug("%s %d mfd->index=%d,mapped=%d\n", __func__, __LINE__, mfd->index, mfd->sec_mapped); ret = <API key>(); if (ret) { pr_err("IOMMU clock enabled failed while close\n"); return ret; } <API key>(ION_HEAP(ION_CP_MM_HEAP_ID)); mfd->sec_mapped = 0; <API key>(); return ret; } /* * <API key>() * <API key>() * <API key>() * above three functiosns need to be called from same thread and * in order so that no mutex are needed. */ void <API key>(int mixer) { int i; struct ion_handle *ihdl; struct iommu_free_list *flist, *pflist; if (mixer >= MDP4_MIXER_MAX) return; mutex_lock(&iommu_mutex); pflist = &ctrl->iommu_free_prev[mixer]; flist = &ctrl->iommu_free[mixer]; pr_debug("%s: mixer=%d fndx=%d %d\n", __func__, mixer, pflist->fndx, flist->fndx); if (pflist->fndx == 0) { goto flist_to_pflist; } for (i = 0; i < IOMMU_FREE_LIST_MAX; i++) { ihdl = pflist->ihdl[i]; if (ihdl == NULL) continue; pr_debug("%s: mixer=%d i=%d ihdl=0x%p\n", __func__, mixer, i, ihdl); ion_unmap_iommu(display_iclient, ihdl, DISPLAY_READ_DOMAIN, GEN_POOL); mdp4_stat.iommu_unmap++; pr_debug("%s: map=%d unmap=%d drop=%d\n", __func__, (int)mdp4_stat.iommu_map, (int)mdp4_stat.iommu_unmap, (int)mdp4_stat.iommu_drop); ion_free(display_iclient, ihdl); } flist_to_pflist: /* move flist to pflist*/ memcpy(pflist, flist, sizeof(*pflist)); memset(flist, 0, sizeof(*flist)); mutex_unlock(&iommu_mutex); } void <API key>(int mixer, struct ion_handle *ihdl) { struct iommu_free_list *flist; flist = &ctrl->iommu_free[mixer]; if (flist->fndx >= IOMMU_FREE_LIST_MAX) { pr_err("%s: Error, mixer=%d iommu fndx=%d\n", __func__, mixer, flist->fndx); mdp4_stat.iommu_drop++; return; } pr_debug("%s: add mixer=%d fndx=%d ihdl=0x%p\n", __func__, mixer, flist->fndx, ihdl); flist->ihdl[flist->fndx++] = ihdl; } void <API key>(int ndx, int all) { struct mdp4_overlay_pipe *pipe; struct <API key> *iom; int plane, mixer; pipe = <API key>(ndx); if (pipe == NULL) return; if (pipe->flags & <API key>) { pipe->flags &= ~<API key>; if (pipe->put0_need) { fput_light(pipe->srcp0_file, pipe->put0_need); pipe->put0_need = 0; } if (pipe->put1_need) { fput_light(pipe->srcp1_file, pipe->put1_need); pipe->put1_need = 0; } if (pipe->put2_need) { fput_light(pipe->srcp2_file, pipe->put2_need); pipe->put2_need = 0; } pr_debug("%s: ndx=%d flags=%x put=%d\n", __func__, pipe->pipe_ndx, pipe->flags, pipe->put0_need); return; } mutex_lock(&iommu_mutex); mixer = pipe->mixer_num; iom = &pipe->iommu; pr_debug("%s: mixer=%d ndx=%d all=%d\n", __func__, mixer, pipe->pipe_ndx, all); for (plane = 0; plane < MDP4_MAX_PLANE; plane++) { if (iom->prev_ihdl[plane]) { <API key>(mixer, iom->prev_ihdl[plane]); iom->prev_ihdl[plane] = NULL; } if (all && iom->ihdl[plane]) { <API key>(mixer, iom->ihdl[plane]); iom->ihdl[plane] = NULL; } } mutex_unlock(&iommu_mutex); } int <API key>(int mem_id, struct mdp4_overlay_pipe *pipe, unsigned int plane, unsigned long *start, unsigned long *len, struct ion_handle **srcp_ihdl) { struct <API key> *iom; if (!display_iclient) return -EINVAL; *srcp_ihdl = ion_import_dma_buf(display_iclient, mem_id); if (IS_ERR_OR_NULL(*srcp_ihdl)) { pr_err("ion_import_dma_buf() failed\n"); return PTR_ERR(*srcp_ihdl); } pr_debug("%s(): ion_hdl %p, ion_buf %d\n", __func__, *srcp_ihdl, ion_share_dma_buf(display_iclient, *srcp_ihdl)); pr_debug("mixer %u, pipe %u, plane %u\n", pipe->mixer_num, pipe->pipe_ndx, plane); if (ion_map_iommu(display_iclient, *srcp_ihdl, DISPLAY_READ_DOMAIN, GEN_POOL, SZ_4K, 0, start, len, 0, 0)) { ion_free(display_iclient, *srcp_ihdl); pr_err("ion_map_iommu() failed\n"); return -EINVAL; } mutex_lock(&iommu_mutex); iom = &pipe->iommu; if (iom->prev_ihdl[plane]) { <API key>(pipe->mixer_num, iom->prev_ihdl[plane]); mdp4_stat.iommu_drop++; pr_err("%s: dropped, ndx=%d plane=%d\n", __func__, pipe->pipe_ndx, plane); } iom->prev_ihdl[plane] = iom->ihdl[plane]; iom->ihdl[plane] = *srcp_ihdl; mdp4_stat.iommu_map++; pr_debug("%s: ndx=%d plane=%d prev=0x%p cur=0x%p start=0x%lx len=%lx\n", __func__, pipe->pipe_ndx, plane, iom->prev_ihdl[plane], iom->ihdl[plane], *start, *len); mutex_unlock(&iommu_mutex); return 0; } static struct <API key> mdp_iommu[MDP4_MIXER_MAX][OVERLAY_PIPE_MAX]; void mdp4_iommu_unmap(struct mdp4_overlay_pipe *pipe) { struct <API key> *iom_pipe_info; unsigned char i, j; if (!display_iclient) return; for (j = 0; j < OVERLAY_PIPE_MAX; j++) { iom_pipe_info = &mdp_iommu[pipe->mixer_num][j]; for (i = 0; i < MDP4_MAX_PLANE; i++) { if (iom_pipe_info->prev_ihdl[i]) { pr_debug("%s(): mixer %u, pipe %u, plane %u, " "prev_ihdl %p\n", __func__, pipe->mixer_num, j + 1, i, iom_pipe_info->prev_ihdl[i]); ion_unmap_iommu(display_iclient, iom_pipe_info->prev_ihdl[i], DISPLAY_READ_DOMAIN, GEN_POOL); ion_free(display_iclient, iom_pipe_info->prev_ihdl[i]); iom_pipe_info->prev_ihdl[i] = NULL; } if (iom_pipe_info->mark_unmap) { if (iom_pipe_info->ihdl[i]) { pr_debug("%s(): MARK, mixer %u, pipe %u, plane %u, " "ihdl %p\n", __func__, pipe->mixer_num, j + 1, i, iom_pipe_info->ihdl[i]); ion_unmap_iommu(display_iclient, iom_pipe_info->ihdl[i], DISPLAY_READ_DOMAIN, GEN_POOL); ion_free(display_iclient, iom_pipe_info->ihdl[i]); iom_pipe_info->ihdl[i] = NULL; } } } iom_pipe_info->mark_unmap = 0; } } #if defined(<API key>) static int panel_rotate_180 = 1; #endif int <API key>(int mixer_num) { if (mixer_num == MDP4_MIXER2) return ctrl->mixer2_played; else if (mixer_num == MDP4_MIXER1) return ctrl->mixer1_played; else return ctrl->mixer0_played; } void <API key>(int mixer_num, uint32 panel_3d) { ctrl->panel_3d = panel_3d; } void <API key>(int mixer_num, uint32 mode) { ctrl->panel_mode |= mode; } void <API key>(int mixer_num, uint32 mode) { ctrl->panel_mode &= ~mode; } uint32 <API key>(void) { return ctrl->panel_mode; } int <API key>(void) { return (mdp_rev >= MDP_REV_42); } void <API key>(struct msm_fb_data_type *mfd, int atv) { uint32 dmae_cfg_reg; if (atv) dmae_cfg_reg = DMA_DEFLKR_EN; else dmae_cfg_reg = 0; if (mfd->fb_imgType == MDP_BGR_565) dmae_cfg_reg |= <API key>; else dmae_cfg_reg |= <API key>; if (mfd->panel_info.bpp == 18) { dmae_cfg_reg |= DMA_DSTC0G_6BITS | /* 666 18BPP */ DMA_DSTC1B_6BITS | DMA_DSTC2R_6BITS; } else if (mfd->panel_info.bpp == 16) { dmae_cfg_reg |= DMA_DSTC0G_6BITS | /* 565 16BPP */ DMA_DSTC1B_5BITS | DMA_DSTC2R_5BITS; } else { dmae_cfg_reg |= DMA_DSTC0G_8BITS | /* 888 16BPP */ DMA_DSTC1B_8BITS | DMA_DSTC2R_8BITS; } mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); /* dma2 config register */ MDP_OUTP(MDP_BASE + 0xb0000, dmae_cfg_reg); if (atv) { MDP_OUTP(MDP_BASE + 0xb0070, 0xeb0010); MDP_OUTP(MDP_BASE + 0xb0074, 0xf00010); MDP_OUTP(MDP_BASE + 0xb0078, 0xf00010); MDP_OUTP(MDP_BASE + 0xb3000, 0x80); MDP_OUTP(MDP_BASE + 0xb3010, 0x1800040); MDP_OUTP(MDP_BASE + 0xb3014, 0x1000080); MDP_OUTP(MDP_BASE + 0xb4004, 0x67686970); } else { mdp_vid_quant_set(); } mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } #ifdef <API key> void unfill_black_screen(void) { return; } #else void unfill_black_screen(void) { uint32 temp_src_format; mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); /* * VG2 Constant Color */ temp_src_format = inpdw(MDP_BASE + 0x30050); MDP_OUTP(MDP_BASE + 0x30050, temp_src_format&(~BIT(22))); /* * <API key> */ MDP_OUTP(MDP_BASE + 0x18000, BIT(3)); mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); return; } #endif #ifdef <API key> void fill_black_screen(void) { return; } #else void fill_black_screen(void) { /*Black color*/ uint32 color = 0x00000000; uint32 temp_src_format; mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); /* * VG2 Constant Color */ MDP_OUTP(MDP_BASE + 0x31008, color); /* * MDP_VG2_SRC_FORMAT */ temp_src_format = inpdw(MDP_BASE + 0x30050); MDP_OUTP(MDP_BASE + 0x30050, temp_src_format | BIT(22)); /* * <API key> */ MDP_OUTP(MDP_BASE + 0x18000, BIT(3)); mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); return; } #endif void <API key>(struct mdp4_overlay_pipe *pipe) { mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); MDP_OUTP(MDP_BASE + 0xb0004, (pipe->src_height << 16 | pipe->src_width)); if (pipe->dma_blt_addr) { uint32 off, bpp; #ifdef BLT_RGB565 bpp = 2; /* overlay ouput is RGB565 */ #else bpp = 3; /* overlay ouput is RGB888 */ #endif off = 0; if (pipe->ov_cnt & 0x01) off = pipe->src_height * pipe->src_width * bpp; MDP_OUTP(MDP_BASE + 0xb0008, pipe->dma_blt_addr + off); /* RGB888, output of overlay blending */ MDP_OUTP(MDP_BASE + 0xb000c, pipe->src_width * bpp); } else { /* dma_e source */ MDP_OUTP(MDP_BASE + 0xb0008, pipe->srcp0_addr); MDP_OUTP(MDP_BASE + 0xb000c, pipe->srcp0_ystride); } /* dma_e dest */ MDP_OUTP(MDP_BASE + 0xb0010, (pipe->dst_y << 16 | pipe->dst_x)); mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } void <API key>(struct msm_fb_data_type *mfd, int lcdc) { uint32 dma2_cfg_reg; uint32 mask, curr; dma2_cfg_reg = DMA_DITHER_EN; #ifdef BLT_RGB565 /* RGB888 is 0 */ dma2_cfg_reg |= <API key>; /* blt only */ #endif if (mfd->fb_imgType == MDP_BGR_565) dma2_cfg_reg |= <API key>; else dma2_cfg_reg |= <API key>; if ((mfd->panel_info.type == MIPI_CMD_PANEL) || (mfd->panel_info.type == MIPI_VIDEO_PANEL)) { dma2_cfg_reg |= DMA_DSTC0G_8BITS | /* 888 24BPP */ DMA_DSTC1B_8BITS | DMA_DSTC2R_8BITS; } else if (mfd->panel_info.bpp == 18) { dma2_cfg_reg |= DMA_DSTC0G_6BITS | /* 666 18BPP */ DMA_DSTC1B_6BITS | DMA_DSTC2R_6BITS; } else if (mfd->panel_info.bpp == 16) { dma2_cfg_reg |= DMA_DSTC0G_6BITS | /* 565 16BPP */ DMA_DSTC1B_5BITS | DMA_DSTC2R_5BITS; } else { dma2_cfg_reg |= DMA_DSTC0G_8BITS | /* 888 24BPP */ DMA_DSTC1B_8BITS | DMA_DSTC2R_8BITS; } mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); #ifndef <API key> if (lcdc) dma2_cfg_reg |= DMA_PACK_ALIGN_MSB; #endif /* dma2 config register */ curr = inpdw(MDP_BASE + 0x90000); mask = 0x0FFFFFFF; dma2_cfg_reg = (dma2_cfg_reg & mask) | (curr & ~mask); MDP_OUTP(MDP_BASE + 0x90000, dma2_cfg_reg); ctrl->dmap_cfg[0] = dma2_cfg_reg; mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } /* * <API key>: called form baselayer only */ void <API key>(struct mdp4_overlay_pipe *pipe) { uint32 off, bpp; if (!in_interrupt()) mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); if (pipe->dma_blt_addr) { #ifdef BLT_RGB565 bpp = 2; /* overlay ouput is RGB565 */ #else bpp = 3; /* overlay ouput is RGB888 */ #endif off = 0; if (pipe->dmap_cnt & 0x01) off = pipe->src_height * pipe->src_width * bpp; ctrl->dmap_cfg[2] = pipe->dma_blt_addr + off; MDP_OUTP(MDP_BASE + 0x90008, pipe->dma_blt_addr + off); /* RGB888, output of overlay blending */ MDP_OUTP(MDP_BASE + 0x9000c, pipe->src_width * bpp); ctrl->dmap_cfg[3] = pipe->src_width * bpp; } else { MDP_OUTP(MDP_BASE + 0x90008, pipe->srcp0_addr); ctrl->dmap_cfg[2] = pipe->srcp0_addr; MDP_OUTP(MDP_BASE + 0x9000c, pipe->srcp0_ystride); ctrl->dmap_cfg[3] = pipe->srcp0_ystride; } /* dma_p source */ MDP_OUTP(MDP_BASE + 0x90004, (pipe->src_height << 16 | pipe->src_width)); ctrl->dmap_cfg[1] = (pipe->src_height << 16 | pipe->src_width); /* dma_p dest */ MDP_OUTP(MDP_BASE + 0x90010, (pipe->dst_y << 16 | pipe->dst_x)); ctrl->dmap_cfg[4] = (pipe->dst_y << 16 | pipe->dst_x); if (!in_interrupt()) mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } static void <API key>(void) { MDP_OUTP(MDP_BASE + 0x90000, ctrl->dmap_cfg[0]); MDP_OUTP(MDP_BASE + 0x90004, ctrl->dmap_cfg[1]); MDP_OUTP(MDP_BASE + 0x90008, ctrl->dmap_cfg[2]); MDP_OUTP(MDP_BASE + 0x9000c, ctrl->dmap_cfg[3]); MDP_OUTP(MDP_BASE + 0x90010, ctrl->dmap_cfg[4]); } #define <API key> 0x20000000 #define <API key> 29 static int mdp4_leading_0(uint32 num) { uint32 bit = 0x80000000; int i; for (i = 0; i < 32; i++) { if (bit & num) return i; bit >>= 1; } return i; } static uint32 <API key>(int f_num, uint32 src, uint32 dst) { uint32 val, s; int n; n = mdp4_leading_0(src); if (n > f_num) n = f_num; s = src << n; /* maximum to reduce lose of resolution */ val = s / dst; if (n < f_num) { n = f_num - n; val <<= n; val |= ((s % dst) << n) / dst; } return val; } static void mdp4_scale_setup(struct mdp4_overlay_pipe *pipe) { pipe->phasex_step = <API key>; pipe->phasey_step = <API key>; if (pipe->dst_h && pipe->src_h != pipe->dst_h) { u32 upscale_max; upscale_max = (mdp_rev >= MDP_REV_41) ? <API key> : <API key>; if (pipe->dst_h > pipe->src_h * upscale_max) return; pipe->op_mode |= MDP4_OP_SCALEY_EN; if (pipe->pipe_type == OVERLAY_TYPE_VIDEO) { if (pipe->flags & <API key> && pipe->alpha_enable && pipe->dst_h > pipe->src_h) pipe->op_mode |= <API key>; else if (pipe->dst_h <= (pipe->src_h / 4)) pipe->op_mode |= <API key>; else pipe->op_mode |= MDP4_OP_SCALEY_FIR; } else { /* RGB pipe */ pipe->op_mode |= <API key> | <API key> | <API key>; } pipe->phasey_step = <API key>(29, pipe->src_h, pipe->dst_h); } if (pipe->dst_w && pipe->src_w != pipe->dst_w) { u32 upscale_max; upscale_max = (mdp_rev >= MDP_REV_41) ? <API key> : <API key>; if (pipe->dst_w > pipe->src_w * upscale_max) return; pipe->op_mode |= MDP4_OP_SCALEX_EN; if (pipe->pipe_type == OVERLAY_TYPE_VIDEO) { if (pipe->flags & <API key> && pipe->alpha_enable && pipe->dst_w > pipe->src_w) pipe->op_mode |= <API key>; else if (pipe->dst_w <= (pipe->src_w / 4)) pipe->op_mode |= <API key>; else pipe->op_mode |= MDP4_OP_SCALEX_FIR; } else { /* RGB pipe */ pipe->op_mode |= <API key> | <API key> | <API key>; } pipe->phasex_step = <API key>(29, pipe->src_w, pipe->dst_w); } } void <API key>(struct mdp4_overlay_pipe *pipe) { char *base; uint32 src_size, src_xy, dst_size, dst_xy; uint32 format; uint32 off; int i; src_size = ((pipe->src_h << 16) | pipe->src_w); src_xy = ((pipe->src_y << 16) | pipe->src_x); dst_size = ((pipe->dst_h << 16) | pipe->dst_w); dst_xy = ((pipe->dst_y << 16) | pipe->dst_x); base = MDP_BASE + MDP4_VIDEO_BASE; off = MDP4_VIDEO_OFF; /* 0x10000 */ mdp_clk_ctrl(1); for(i = 0; i < 4; i++) { /* 4 pipes */ format = inpdw(base + 0x50); format |= <API key>; outpdw(base + 0x0000, src_size);/* MDP_RGB_SRC_SIZE */ outpdw(base + 0x0004, src_xy); /* MDP_RGB_SRC_XY */ outpdw(base + 0x0008, dst_size);/* MDP_RGB_DST_SIZE */ outpdw(base + 0x000c, dst_xy); /* MDP_RGB_DST_XY */ outpdw(base + 0x0050, format);/* MDP_RGB_SRC_FORMAT */ outpdw(base + 0x1008, 0x0);/* Black */ base += off; } /* * keep it at primary * will be picked up at first commit */ ctrl->flush[MDP4_MIXER0] = 0x3c; /* all pipes */ mdp_clk_ctrl(0); } void <API key>(struct mdp4_overlay_pipe *pipe) { char *rgb_base; uint32 src_size, src_xy, dst_size, dst_xy; uint32 format, pattern; uint32 curr, mask; uint32 offset = 0; int pnum; pnum = pipe->pipe_num - OVERLAY_PIPE_RGB1; /* start from 0 */ rgb_base = MDP_BASE + MDP4_RGB_BASE; rgb_base += (MDP4_RGB_OFF * pnum); src_size = ((pipe->src_h << 16) | pipe->src_w); src_xy = ((pipe->src_y << 16) | pipe->src_x); dst_size = ((pipe->dst_h << 16) | pipe->dst_w); dst_xy = ((pipe->dst_y << 16) | pipe->dst_x); if ((pipe->src_x + pipe->src_w) > 0x7FF) { offset += pipe->src_x * pipe->bpp; src_xy &= 0xFFFF0000; } if ((pipe->src_y + pipe->src_h) > 0x7FF) { offset += pipe->src_y * pipe->src_width * pipe->bpp; src_xy &= 0x0000FFFF; } format = mdp4_overlay_format(pipe); pattern = <API key>(pipe); #ifdef MDP4_IGC_LUT_ENABLE pipe->op_mode |= MDP4_OP_IGC_LUT_EN; #endif mdp4_scale_setup(pipe); mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); /* Ensure proper covert matrix loaded when color space swaps */ curr = inpdw(rgb_base + 0x0058); /* Don't touch bits you don't want to configure*/ mask = 0xFFFEFFFF; pipe->op_mode = (pipe->op_mode & mask) | (curr & ~mask); #if defined(<API key>) //2012-11-20 taewonee.kim@lge.com : QCT pre patch for the inverted clone image [START] if((pipe->mfd->panel_info.type != DTV_PANEL)&&(pipe->mfd->panel_info.type != WRITEBACK_PANEL)) //2012-11-20 taewonee.kim@lge.com : QCT pre patch for the inverted clone image [END] { if (panel_rotate_180 && (pipe->pipe_num == OVERLAY_PIPE_RGB1 || pipe->pipe_num == OVERLAY_PIPE_RGB2)) { uint32 op_mode = pipe->op_mode | MDP4_OP_FLIP_UD | MDP4_OP_SCALEY_EN; if (pipe->ext_flag & MDP_FLIP_UD) op_mode &= ~MDP4_OP_FLIP_UD; pipe->op_mode = op_mode; } if ((pipe->op_mode & MDP4_OP_FLIP_UD) && pipe->mfd) dst_xy = (((pipe->mfd->panel_info.yres - pipe->dst_y - pipe->dst_h) << 16) | pipe->dst_x); } if (!pipe->mfd) pr_err("rgb mfd is not set\n"); #endif outpdw(rgb_base + 0x0000, src_size); /* MDP_RGB_SRC_SIZE */ outpdw(rgb_base + 0x0004, src_xy); /* MDP_RGB_SRC_XY */ outpdw(rgb_base + 0x0008, dst_size); /* MDP_RGB_DST_SIZE */ outpdw(rgb_base + 0x000c, dst_xy); /* MDP_RGB_DST_XY */ outpdw(rgb_base + 0x0010, pipe->srcp0_addr + offset); outpdw(rgb_base + 0x0040, pipe->srcp0_ystride); outpdw(rgb_base + 0x0050, format);/* MDP_RGB_SRC_FORMAT */ outpdw(rgb_base + 0x0054, pattern);/* <API key> */ if (format & <API key>) { u32 op_mode = pipe->op_mode; op_mode &= ~(MDP4_OP_FLIP_LR + MDP4_OP_SCALEX_EN); op_mode &= ~(MDP4_OP_FLIP_UD + MDP4_OP_SCALEY_EN); outpdw(rgb_base + 0x0058, op_mode);/* MDP_RGB_OP_MODE */ } else { if (pipe->op_mode & MDP4_OP_FLIP_LR && mdp_rev >= MDP_REV_42) { /* Enable x-scaling bit to enable LR flip */ /* for MDP > 4.2 targets */ pipe->op_mode |= 0x01; } outpdw(rgb_base + 0x0058, pipe->op_mode);/* MDP_RGB_OP_MODE */ } outpdw(rgb_base + 0x005c, pipe->phasex_step); outpdw(rgb_base + 0x0060, pipe->phasey_step); mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); mdp4_stat.pipe[pipe->pipe_num]++; } static void <API key>(struct mdp4_overlay_pipe *pipe, char *vg_base, uint32 *luma_off, uint32 *chroma_off) { uint32 src_xy; *luma_off = 0; *chroma_off = 0; if (pipe->src_x && (pipe->frame_format == <API key>)) { src_xy = (pipe->src_y << 16) | pipe->src_x; src_xy &= 0xffff0000; outpdw(vg_base + 0x0004, src_xy); /* MDP_RGB_SRC_XY */ switch (pipe->src_format) { case MDP_Y_CR_CB_H2V2: case MDP_Y_CR_CB_GH2V2: case MDP_Y_CB_CR_H2V2: *luma_off = pipe->src_x; *chroma_off = pipe->src_x/2; break; case <API key>: case <API key>: case MDP_Y_CBCR_H2V2: case MDP_Y_CRCB_H2V2: case MDP_Y_CRCB_H1V1: case MDP_Y_CBCR_H1V1: case MDP_Y_CRCB_H2V1: case MDP_Y_CBCR_H2V1: case MDP_Y_CRCB_H1V2: case MDP_Y_CBCR_H1V2: *luma_off = pipe->src_x + (pipe->src_y * pipe->srcp0_ystride); *chroma_off = pipe->src_x + (pipe->src_y * pipe->srcp1_ystride); break; case MDP_YCBYCR_H2V1: case MDP_YCRYCB_H2V1: if (pipe->src_x & 0x1) pipe->src_x += 1; *luma_off += pipe->src_x * 2; break; case MDP_ARGB_8888: case MDP_RGBA_8888: case MDP_BGRA_8888: case MDP_RGBX_8888: case MDP_RGB_565: case MDP_BGR_565: case MDP_XRGB_8888: case MDP_RGB_888: case MDP_YCBCR_H1V1: case MDP_YCRCB_H1V1: *luma_off = pipe->src_x * pipe->bpp; break; default: pr_err("%s: fmt %u not supported for adjustment\n", __func__, pipe->src_format); break; } } } void <API key>(struct mdp4_overlay_pipe *pipe) { char *vg_base; uint32 frame_size, src_size, src_xy, dst_size, dst_xy; uint32 format, pattern, luma_offset, chroma_offset; /* 2012-11-29 wonhee.jeong@lge.com this code add to mdp tunning when start DMB in G, GK (apq8064) [S]*/ /* This source code confirmed by QCT*/ uint32 mask, curr, addr; /* 2012-11-29 wonhee.jeong@lge.com this code add to mdp tunning when start DMB in G, GK (apq8064) [E]*/ int pnum, ptype, i; uint32_t block; pnum = pipe->pipe_num - OVERLAY_PIPE_VG1; /* start from 0 */ vg_base = MDP_BASE + MDP4_VIDEO_BASE; vg_base += (MDP4_VIDEO_OFF * pnum); frame_size = ((pipe->src_height << 16) | pipe->src_width); src_size = ((pipe->src_h << 16) | pipe->src_w); src_xy = ((pipe->src_y << 16) | pipe->src_x); dst_size = ((pipe->dst_h << 16) | pipe->dst_w); dst_xy = ((pipe->dst_y << 16) | pipe->dst_x); ptype = <API key>(pipe->src_format); format = mdp4_overlay_format(pipe); pattern = <API key>(pipe); /* CSC Post Processing enabled? */ if (pipe->flags & <API key>) { if (pipe->pp_cfg.config_ops & <API key>) { if (pipe->pp_cfg.csc_cfg.flags & MDP_CSC_FLAG_ENABLE) pipe->op_mode |= MDP4_OP_CSC_EN; if (pipe->pp_cfg.csc_cfg.flags & MDP_CSC_FLAG_YUV_IN) pipe->op_mode |= <API key>; if (pipe->pp_cfg.csc_cfg.flags & <API key>) pipe->op_mode |= <API key>; mdp4_csc_write(&pipe->pp_cfg.csc_cfg, (uint32_t) (vg_base + MDP4_VIDEO_CSC_OFF)); if (pipe->pipe_num == OVERLAY_PIPE_VG1) block = MDP_BLOCK_VG_1; else block = MDP_BLOCK_VG_2; for (i = 0; i < CSC_MAX_BLOCKS; i++) { if (block == csc_cfg_matrix[i].block) { memcpy(&csc_cfg_matrix[i].csc_data, &(pipe->pp_cfg.csc_cfg), sizeof(struct mdp_csc_cfg)); break; } } } if (pipe->pp_cfg.config_ops & <API key>) { <API key>(&pipe->pp_cfg.qseed_cfg[0], (uint32_t) vg_base); <API key>(&pipe->pp_cfg.qseed_cfg[1], (uint32_t) vg_base); } } /* not RGB use VG pipe, pure VG pipe */ if (ptype != OVERLAY_TYPE_RGB) pipe->op_mode |= (MDP4_OP_CSC_EN | <API key>); #ifdef MDP4_IGC_LUT_ENABLE pipe->op_mode |= MDP4_OP_IGC_LUT_EN; #endif mdp4_scale_setup(pipe); luma_offset = 0; chroma_offset = 0; if (ptype == OVERLAY_TYPE_RGB) { if ((pipe->src_y + pipe->src_h) > 0x7FF) { luma_offset = pipe->src_y * pipe->src_width * pipe->bpp; src_xy &= 0x0000FFFF; } if ((pipe->src_x + pipe->src_w) > 0x7FF) { luma_offset += pipe->src_x * pipe->bpp; src_xy &= 0xFFFF0000; } } #if defined(<API key>) //2012-11-20 taewonee.kim@lge.com : QCT pre patch for the inverted clone image [START] if((pipe->mfd->panel_info.type != DTV_PANEL) && (pipe->mfd->panel_info.type != WRITEBACK_PANEL)) //2012-11-20 taewonee.kim@lge.com : QCT pre patch for the inverted clone image [END] { if (panel_rotate_180) { uint32 op_mode = pipe->op_mode | MDP4_OP_FLIP_UD; if (pipe->ext_flag & MDP_FLIP_UD) op_mode &= ~MDP4_OP_FLIP_UD; pipe->op_mode = op_mode; } if ((pipe->op_mode & MDP4_OP_FLIP_UD) && pipe->mfd) { dst_xy = (((pipe->mfd->panel_info.yres - pipe->dst_y - pipe->dst_h) << 16) | pipe->dst_x); outpdw(MDP_BASE + 0xE0044, 0xe0fff); } } if (!pipe->mfd) pr_err("vg mfd is not set\n"); #endif mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); outpdw(vg_base + 0x0000, src_size); /* MDP_RGB_SRC_SIZE */ outpdw(vg_base + 0x0004, src_xy); /* MDP_RGB_SRC_XY */ outpdw(vg_base + 0x0008, dst_size); /* MDP_RGB_DST_SIZE */ outpdw(vg_base + 0x000c, dst_xy); /* MDP_RGB_DST_XY */ if (pipe->frame_format != <API key>) { struct mdp4_overlay_pipe *real_pipe; u32 psize, csize; /* * video tile frame size register is NOT double buffered. * when this register updated, it kicks in immediatly * During transition from smaller resolution to higher * resolution it may have possibility that mdp still fetch * from smaller resolution buffer with new higher resolution * frame size. This will cause iommu page fault. */ real_pipe = <API key>(pipe->pipe_ndx); psize = real_pipe->prev_src_height * real_pipe->prev_src_width; csize = pipe->src_height * pipe->src_width; if (psize && (csize > psize)) { frame_size = (real_pipe->prev_src_height << 16 | real_pipe->prev_src_width); } outpdw(vg_base + 0x0048, frame_size); /* TILE frame size */ real_pipe->prev_src_height = pipe->src_height; real_pipe->prev_src_width = pipe->src_width; } /* * Adjust src X offset to avoid MDP from overfetching pixels * present before the offset. This is required for video * frames coming with unused green pixels along the left margin */ /* not RGB use VG pipe, pure VG pipe */ if (ptype != OVERLAY_TYPE_RGB) { <API key>(pipe, vg_base, &luma_offset, &chroma_offset); } /* 2012-11-29 wonhee.jeong@lge.com this code add to mdp tunning when start DMB in G, GK (apq8064) [S]*/ /* This source code confirmed by QCT*/ /* Ensure proper covert matrix loaded when color space swaps */ curr = inpdw(vg_base + 0x0058); mask = 0x600; if ((curr & mask) != (pipe->op_mode & mask)) { addr = ((uint32_t)vg_base) + 0x4000; if (ptype != OVERLAY_TYPE_RGB) mdp4_csc_write(&(mdp_csc_convert[1]), addr); else mdp4_csc_write(&(mdp_csc_convert[0]), addr); mask = 0xFFFCFFFF; } else { /* Don't touch bits you don't want to configure*/ mask = 0xFFFCF1FF; } pipe->op_mode = (pipe->op_mode & mask) | (curr & ~mask); /* 2012-11-29 wonhee.jeong@lge.com this code add to mdp tunning when start DMB in G, GK (apq8064) [E]*/ /* luma component plane */ outpdw(vg_base + 0x0010, pipe->srcp0_addr + luma_offset); /* chroma component plane or planar color 1 */ outpdw(vg_base + 0x0014, pipe->srcp1_addr + chroma_offset); /* planar color 2 */ outpdw(vg_base + 0x0018, pipe->srcp2_addr + chroma_offset); outpdw(vg_base + 0x0040, pipe->srcp1_ystride << 16 | pipe->srcp0_ystride); outpdw(vg_base + 0x0044, pipe->srcp3_ystride << 16 | pipe->srcp2_ystride); outpdw(vg_base + 0x0050, format); /* MDP_RGB_SRC_FORMAT */ outpdw(vg_base + 0x0054, pattern); /* <API key> */ if (format & <API key>) { u32 op_mode = pipe->op_mode; op_mode &= ~(MDP4_OP_FLIP_LR + MDP4_OP_SCALEX_EN); op_mode &= ~(MDP4_OP_FLIP_UD + MDP4_OP_SCALEY_EN); outpdw(vg_base + 0x0058, op_mode);/* MDP_RGB_OP_MODE */ } else outpdw(vg_base + 0x0058, pipe->op_mode);/* MDP_RGB_OP_MODE */ outpdw(vg_base + 0x005c, pipe->phasex_step); outpdw(vg_base + 0x0060, pipe->phasey_step); if (pipe->op_mode & MDP4_OP_DITHER_EN) { outpdw(vg_base + 0x0068, pipe->r_bit << 4 | pipe->b_bit << 2 | pipe->g_bit); } if (mdp_rev > MDP_REV_41) { /* mdp chip select controller */ mask = 0; if (pipe->pipe_num == OVERLAY_PIPE_VG1) mask = 0x020; /* bit 5 */ else if (pipe->pipe_num == OVERLAY_PIPE_VG2) mask = 0x02000; /* bit 13 */ if (mask) { if (pipe->op_mode & <API key>) ctrl->cs_controller &= ~mask; else ctrl->cs_controller |= mask; /* NOT double buffered */ outpdw(MDP_BASE + 0x00c0, ctrl->cs_controller); } } mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); mdp4_stat.pipe[pipe->pipe_num]++; } int <API key>(uint32 format) { switch (format) { case MDP_RGB_565: case MDP_RGB_888: case MDP_BGR_565: case MDP_XRGB_8888: case MDP_ARGB_8888: case MDP_RGBA_8888: case MDP_BGRA_8888: case MDP_RGBX_8888: return OVERLAY_TYPE_RGB; case MDP_YCBYCR_H2V1: case MDP_YCRYCB_H2V1: case MDP_Y_CRCB_H2V1: case MDP_Y_CBCR_H2V1: case MDP_Y_CRCB_H1V2: case MDP_Y_CBCR_H1V2: case MDP_Y_CRCB_H2V2: case MDP_Y_CBCR_H2V2: case <API key>: case <API key>: case MDP_Y_CR_CB_H2V2: case MDP_Y_CR_CB_GH2V2: case MDP_Y_CB_CR_H2V2: case MDP_Y_CRCB_H1V1: case MDP_Y_CBCR_H1V1: case MDP_YCRCB_H1V1: case MDP_YCBCR_H1V1: return OVERLAY_TYPE_VIDEO; case MDP_RGB_BORDERFILL: return OVERLAY_TYPE_BF; default: mdp4_stat.err_format++; return -ERANGE; } } #define C3_ALPHA 3 /* alpha */ #define C2_R_Cr 2 /* R/Cr */ #define C1_B_Cb 1 /* B/Cb */ #define C0_G_Y 0 /* G/luma */ #define YUV_444_MAX_WIDTH 1280 /* Max width for YUV 444*/ int <API key>(struct mdp4_overlay_pipe *pipe) { switch (pipe->src_format) { case MDP_RGB_565: pipe->frame_format = <API key>; pipe->fetch_plane = <API key>; pipe->a_bit = 0; pipe->r_bit = 1; /* R, 5 bits */ pipe->b_bit = 1; /* B, 5 bits */ pipe->g_bit = 2; /* G, 6 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 2; pipe->element2 = C2_R_Cr; pipe->element1 = C0_G_Y; pipe->element0 = C1_B_Cb; pipe->bpp = 2; /* 2 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_RGB_888: pipe->frame_format = <API key>; pipe->fetch_plane = <API key>; pipe->a_bit = 0; pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 2; pipe->element2 = C1_B_Cb; pipe->element1 = C0_G_Y; pipe->element0 = C2_R_Cr; pipe->bpp = 3; /* 3 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_BGR_565: pipe->frame_format = <API key>; pipe->fetch_plane = <API key>; pipe->a_bit = 0; pipe->r_bit = 1; /* R, 5 bits */ pipe->b_bit = 1; /* B, 5 bits */ pipe->g_bit = 2; /* G, 6 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 2; pipe->element2 = C1_B_Cb; pipe->element1 = C0_G_Y; pipe->element0 = C2_R_Cr; pipe->bpp = 2; /* 2 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_XRGB_8888: pipe->frame_format = <API key>; pipe->fetch_plane = <API key>; pipe->a_bit = 3; /* alpha, 4 bits */ pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 3; pipe->element3 = C1_B_Cb; pipe->element2 = C0_G_Y; pipe->element1 = C2_R_Cr; pipe->element0 = C3_ALPHA; /* alpha */ pipe->bpp = 4; /* 4 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_ARGB_8888: pipe->frame_format = <API key>; pipe->fetch_plane = <API key>; pipe->a_bit = 3; /* alpha, 4 bits */ pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 1; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 3; pipe->element3 = C1_B_Cb; pipe->element2 = C0_G_Y; pipe->element1 = C2_R_Cr; pipe->element0 = C3_ALPHA; /* alpha */ pipe->bpp = 4; /* 4 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_RGBA_8888: pipe->frame_format = <API key>; pipe->fetch_plane = <API key>; pipe->a_bit = 3; /* alpha, 4 bits */ pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 1; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 3; pipe->element3 = C3_ALPHA; /* alpha */ pipe->element2 = C1_B_Cb; pipe->element1 = C0_G_Y; pipe->element0 = C2_R_Cr; pipe->bpp = 4; /* 4 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_RGBX_8888: pipe->frame_format = <API key>; pipe->fetch_plane = <API key>; pipe->a_bit = 3; pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 3; pipe->element3 = C3_ALPHA; /* alpha */ pipe->element2 = C1_B_Cb; pipe->element1 = C0_G_Y; pipe->element0 = C2_R_Cr; pipe->bpp = 4; /* 4 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_BGRA_8888: pipe->frame_format = <API key>; pipe->fetch_plane = <API key>; pipe->a_bit = 3; /* alpha, 4 bits */ pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 1; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 3; pipe->element3 = C3_ALPHA; /* alpha */ pipe->element2 = C2_R_Cr; pipe->element1 = C0_G_Y; pipe->element0 = C1_B_Cb; pipe->bpp = 4; /* 4 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_YCBYCR_H2V1: case MDP_YCRYCB_H2V1: pipe->frame_format = <API key>; pipe->fetch_plane = <API key>; pipe->a_bit = 0; /* alpha, 4 bits */ pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 3; if (pipe->src_format == MDP_YCRYCB_H2V1) { pipe->element3 = C0_G_Y; pipe->element2 = C2_R_Cr; pipe->element1 = C0_G_Y; pipe->element0 = C1_B_Cb; } else if (pipe->src_format == MDP_YCBYCR_H2V1) { pipe->element3 = C0_G_Y; pipe->element2 = C1_B_Cb; pipe->element1 = C0_G_Y; pipe->element0 = C2_R_Cr; } pipe->bpp = 2; /* 2 bpp */ pipe->chroma_sample = MDP4_CHROMA_H2V1; break; case MDP_Y_CRCB_H2V1: case MDP_Y_CBCR_H2V1: case MDP_Y_CRCB_H1V2: case MDP_Y_CBCR_H1V2: case MDP_Y_CRCB_H2V2: case MDP_Y_CBCR_H2V2: case MDP_Y_CRCB_H1V1: case MDP_Y_CBCR_H1V1: pipe->frame_format = <API key>; pipe->fetch_plane = <API key>; pipe->a_bit = 0; pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 1; if (pipe->src_format == MDP_Y_CRCB_H2V1) { pipe->element1 = C1_B_Cb; pipe->element0 = C2_R_Cr; pipe->chroma_sample = MDP4_CHROMA_H2V1; } else if (pipe->src_format == MDP_Y_CRCB_H1V1) { pipe->element1 = C1_B_Cb; pipe->element0 = C2_R_Cr; if (pipe->src_width > YUV_444_MAX_WIDTH) pipe->chroma_sample = MDP4_CHROMA_H1V2; else pipe->chroma_sample = MDP4_CHROMA_RGB; } else if (pipe->src_format == MDP_Y_CBCR_H2V1) { pipe->element1 = C2_R_Cr; pipe->element0 = C1_B_Cb; pipe->chroma_sample = MDP4_CHROMA_H2V1; } else if (pipe->src_format == MDP_Y_CBCR_H1V1) { pipe->element1 = C2_R_Cr; pipe->element0 = C1_B_Cb; if (pipe->src_width > YUV_444_MAX_WIDTH) pipe->chroma_sample = MDP4_CHROMA_H1V2; else pipe->chroma_sample = MDP4_CHROMA_RGB; } else if (pipe->src_format == MDP_Y_CRCB_H1V2) { pipe->element1 = C1_B_Cb; pipe->element0 = C2_R_Cr; pipe->chroma_sample = MDP4_CHROMA_H1V2; } else if (pipe->src_format == MDP_Y_CBCR_H1V2) { pipe->element1 = C2_R_Cr; pipe->element0 = C1_B_Cb; pipe->chroma_sample = MDP4_CHROMA_H1V2; } else if (pipe->src_format == MDP_Y_CRCB_H2V2) { pipe->element1 = C1_B_Cb; pipe->element0 = C2_R_Cr; pipe->chroma_sample = MDP4_CHROMA_420; } else if (pipe->src_format == MDP_Y_CBCR_H2V2) { pipe->element1 = C2_R_Cr; pipe->element0 = C1_B_Cb; pipe->chroma_sample = MDP4_CHROMA_420; } pipe->bpp = 2; /* 2 bpp */ break; case <API key>: case <API key>: pipe->frame_format = <API key>; pipe->fetch_plane = <API key>; pipe->a_bit = 0; pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 1; if (pipe->src_format == <API key>) { pipe->element1 = C1_B_Cb; pipe->element0 = C2_R_Cr; pipe->chroma_sample = MDP4_CHROMA_420; } else if (pipe->src_format == <API key>) { pipe->element1 = C2_R_Cr; pipe->element0 = C1_B_Cb; pipe->chroma_sample = MDP4_CHROMA_420; } pipe->bpp = 2; /* 2 bpp */ break; case MDP_Y_CR_CB_H2V2: case MDP_Y_CR_CB_GH2V2: case MDP_Y_CB_CR_H2V2: pipe->frame_format = <API key>; pipe->fetch_plane = <API key>; pipe->a_bit = 0; pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->chroma_sample = MDP4_CHROMA_420; pipe->bpp = 2; /* 2 bpp */ break; case MDP_YCBCR_H1V1: case MDP_YCRCB_H1V1: pipe->frame_format = <API key>; pipe->fetch_plane = <API key>; pipe->a_bit = 0; pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 2; pipe->element0 = C0_G_Y; if (pipe->src_format == MDP_YCRCB_H1V1) { pipe->element1 = C2_R_Cr; pipe->element2 = C1_B_Cb; } else { pipe->element1 = C1_B_Cb; pipe->element2 = C2_R_Cr; } pipe->bpp = 3; /* 3 bpp */ case MDP_RGB_BORDERFILL: pipe->alpha_enable = 0; pipe->alpha = 0; break; default: /* not likely */ mdp4_stat.err_format++; return -ERANGE; } return 0; } /* * color_key_convert: output with 12 bits color key */ static uint32 color_key_convert(int start, int num, uint32 color) { uint32 data; data = (color >> start) & ((1 << num) - 1); /* convert to 8 bits */ if (num == 5) data = ((data << 3) | (data >> 2)); else if (num == 6) data = ((data << 2) | (data >> 4)); /* convert 8 bits to 12 bits */ data = (data << 4) | (data >> 4); return data; } void transp_color_key(int format, uint32 transp, uint32 *c0, uint32 *c1, uint32 *c2) { int b_start, g_start, r_start; int b_num, g_num, r_num; switch (format) { case MDP_RGB_565: b_start = 0; g_start = 5; r_start = 11; r_num = 5; g_num = 6; b_num = 5; break; case MDP_RGB_888: case MDP_XRGB_8888: case MDP_ARGB_8888: case MDP_BGRA_8888: b_start = 0; g_start = 8; r_start = 16; r_num = 8; g_num = 8; b_num = 8; break; case MDP_RGBA_8888: case MDP_RGBX_8888: b_start = 16; g_start = 8; r_start = 0; r_num = 8; g_num = 8; b_num = 8; break; case MDP_BGR_565: b_start = 11; g_start = 5; r_start = 0; r_num = 5; g_num = 6; b_num = 5; break; case MDP_Y_CB_CR_H2V2: case MDP_Y_CBCR_H2V2: case MDP_Y_CBCR_H2V1: case MDP_YCBCR_H1V1: b_start = 8; g_start = 16; r_start = 0; r_num = 8; g_num = 8; b_num = 8; break; case MDP_Y_CR_CB_H2V2: case MDP_Y_CR_CB_GH2V2: case MDP_Y_CRCB_H2V2: case MDP_Y_CRCB_H2V1: case MDP_Y_CRCB_H1V2: case MDP_Y_CBCR_H1V2: case MDP_Y_CRCB_H1V1: case MDP_Y_CBCR_H1V1: case MDP_YCRCB_H1V1: b_start = 0; g_start = 16; r_start = 8; r_num = 8; g_num = 8; b_num = 8; break; default: b_start = 0; g_start = 8; r_start = 16; r_num = 8; g_num = 8; b_num = 8; break; } *c0 = color_key_convert(g_start, g_num, transp); *c1 = color_key_convert(b_start, b_num, transp); *c2 = color_key_convert(r_start, r_num, transp); } uint32 mdp4_overlay_format(struct mdp4_overlay_pipe *pipe) { uint32 format; format = 0; if (pipe->solid_fill) format |= <API key>; if (pipe->unpack_align_msb) format |= <API key>; if (pipe->unpack_tight) format |= <API key>; if (pipe->alpha_enable) format |= <API key>; if (pipe->flags & <API key>) format |= <API key>; format |= (pipe->unpack_count << 13); format |= ((pipe->bpp - 1) << 9); format |= (pipe->a_bit << 6); format |= (pipe->r_bit << 4); format |= (pipe->b_bit << 2); format |= pipe->g_bit; format |= (pipe->frame_format << 29); /* video/graphic */ format |= (pipe->fetch_plane << 19); format |= (pipe->chroma_site << 28); format |= (pipe->chroma_sample << 26); return format; } uint32 <API key>(struct mdp4_overlay_pipe *pipe) { return (pipe->element3 << 24) | (pipe->element2 << 16) | (pipe->element1 << 8) | pipe->element0; } /* * <API key>: only be called from base layer */ void <API key>(struct mdp4_overlay_pipe *pipe) { uint32 data, intf; char *overlay_base; uint32 curr; intf = 0; if (pipe->mixer_num == MDP4_MIXER2) overlay_base = MDP_BASE + <API key>; else if (pipe->mixer_num == MDP4_MIXER1) { overlay_base = MDP_BASE + <API key>;/* 0x18000 */ intf = inpdw(MDP_BASE + 0x0038); /* MDP_DISP_INTF_SEL */ intf >>= 4; intf &= 0x03; } else overlay_base = MDP_BASE + <API key>;/* 0x10000 */ if (!in_interrupt()) mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); /* * BLT support both primary and external external */ if (pipe->ov_blt_addr) { int off, bpp; #ifdef BLT_RGB565 bpp = 2; /* overlay ouput is RGB565 */ #else bpp = 3; /* overlay ouput is RGB888 */ #endif data = pipe->src_height; data <<= 16; data |= pipe->src_width; outpdw(overlay_base + 0x0008, data); /* ROI, height + width */ if (pipe->mixer_num == MDP4_MIXER0 || pipe->mixer_num == MDP4_MIXER1) { off = 0; if (pipe->ov_cnt & 0x01) off = pipe->src_height * pipe->src_width * bpp; outpdw(overlay_base + 0x000c, pipe->ov_blt_addr + off); /* overlay ouput is RGB888 */ outpdw(overlay_base + 0x0010, pipe->src_width * bpp); outpdw(overlay_base + 0x001c, pipe->ov_blt_addr + off); /* MDDI - BLT + on demand */ outpdw(overlay_base + 0x0004, 0x08); curr = inpdw(overlay_base + 0x0014); curr &= 0x4; #ifdef BLT_RGB565 outpdw(overlay_base + 0x0014, curr | 0x1); /* RGB565 */ #else outpdw(overlay_base + 0x0014, curr | 0x0); /* RGB888 */ #endif } else if (pipe->mixer_num == MDP4_MIXER2) { if (ctrl->panel_mode & <API key>) { off = 0; bpp = 1; if (pipe->ov_cnt & 0x01) off = pipe->src_height * pipe->src_width * bpp; outpdw(overlay_base + 0x000c, pipe->ov_blt_addr + off); /* overlay ouput is RGB888 */ outpdw(overlay_base + 0x0010, ((pipe->src_width << 16) | pipe->src_width)); outpdw(overlay_base + 0x001c, pipe->ov_blt_addr + off); off = pipe->src_height * pipe->src_width; /* align chroma to 2k address */ off = (off + 2047) & ~2047; /* UV plane adress */ outpdw(overlay_base + 0x0020, pipe->ov_blt_addr + off); /* MDDI - BLT + on demand */ outpdw(overlay_base + 0x0004, 0x08); /* pseudo planar + writeback */ curr = inpdw(overlay_base + 0x0014); curr &= 0x4; outpdw(overlay_base + 0x0014, curr | 0x012); /* rgb->yuv */ outpdw(overlay_base + 0x0200, 0x05); } } } else { data = pipe->src_height; data <<= 16; data |= pipe->src_width; outpdw(overlay_base + 0x0008, data); /* ROI, height + width */ outpdw(overlay_base + 0x000c, pipe->srcp0_addr); outpdw(overlay_base + 0x0010, pipe->srcp0_ystride); outpdw(overlay_base + 0x0004, 0x01); /* directout */ } if (pipe->mixer_num == MDP4_MIXER1) { if (intf == TV_INTF) { curr = inpdw(overlay_base + 0x0014); curr &= 0x4; outpdw(overlay_base + 0x0014, 0x02); /* yuv422 */ /* overlay1 CSC config */ outpdw(overlay_base + 0x0200, 0x05); /* rgb->yuv */ } } #ifdef MDP4_IGC_LUT_ENABLE curr = inpdw(overlay_base + 0x0014); curr &= ~0x4; outpdw(overlay_base + 0x0014, curr | 0x4); /* GC_LUT_EN, 888 */ #endif if (!in_interrupt()) mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } int <API key>(struct mdp4_overlay_pipe *pipe) { uint32 data, mask; int mixer; mixer = pipe->mixer_num; data = ctrl->mixer_cfg[mixer]; mask = 0x0f; mask <<= (4 * pipe->pipe_num); data &= mask; return data; } int mdp4_mixer_info(int mixer_num, struct mdp_mixer_info *info) { int ndx, cnt; struct mdp4_overlay_pipe *pipe; if (mixer_num > MDP4_MIXER_MAX) return -ENODEV; cnt = 0; ndx = <API key>; for ( ; ndx < <API key>; ndx++) { pipe = &ctrl->plist[ndx]; if (pipe == NULL) continue; if (!pipe->pipe_used) continue; info->z_order = pipe->mixer_stage - MDP4_MIXER_STAGE0; /* z_order == -1, means base layer */ info->ptype = pipe->pipe_type; info->pnum = pipe->pipe_num; info->pndx = pipe->pipe_ndx; info->mixer_num = pipe->mixer_num; info++; cnt++; } return cnt; } void mdp4_mixer_reset(int mixer) { uint32 data, data1, mask; int i, ndx, min, max, bit; mdp_clk_ctrl(1); /* <API key>, shard by both mixer 0 and 1 */ data = inpdw(MDP_BASE + 0x10100); data1 = data; if (mixer == 0) { min = 1; max = 8; bit = 0x03; /* mixer0, dmap */ } else { min = 9; max = 0xf; bit = 0x0C; /* mixer1, dmae */ } mask = 0x0f; for (i = 0 ; i < 8 ; i++) { ndx = data & mask; ndx >>= (i * 4); if (ndx >= min && ndx <= max) data1 &= ~mask; /* unstage pipe from mixer */ mask <<= 4; } pr_debug("%s: => MIXER_RESET, data1=%x data=%x bit=%x\n", __func__, data1, data, bit); /* unstage pipes of mixer to be reset */ outpdw(MDP_BASE + 0x10100, data1); /* <API key> */ outpdw(MDP_BASE + 0x18000, 0); mdp4_sw_reset(bit); /* reset mixer */ /* 0 => mixer0, dmap */ /* restore origianl stage */ outpdw(MDP_BASE + 0x10100, data); /* <API key> */ outpdw(MDP_BASE + 0x18000, 0); mdp4_vg_csc_restore(); <API key>(); mdp_clk_ctrl(0); } void <API key>(int mixer) { struct mdp4_overlay_pipe *pipe; int i, num; u32 data, stage; int off; unsigned long flags; data = 0; for (i = <API key>; i < <API key>; i++) { pipe = ctrl->stage[mixer][i]; if (pipe == NULL) continue; pr_debug("%s: mixer=%d ndx=%d stage=%d\n", __func__, mixer, pipe->pipe_ndx, i); stage = pipe->mixer_stage; if (mixer >= MDP4_MIXER1) stage += 8; stage <<= (4 * pipe->pipe_num); data |= stage; } /* * stage_commit may be called from overlay_unset * for command panel, mdp clocks may be off at this time. * so mdp clock enabled is necessary */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); mdp_clk_ctrl(1); if (data) <API key>(mixer); off = 0; if (data != ctrl->mixer_cfg[mixer]) { ctrl->mixer_cfg[mixer] = data; if (mixer >= MDP4_MIXER2) { /* <API key> */ off = 0x100f0; } else { /* mixer 0 or 1 */ num = mixer + 1; num &= 0x01; data |= ctrl->mixer_cfg[num]; off = 0x10100; } pr_debug("%s: mixer=%d data=%x flush=%x pid=%d\n", __func__, mixer, data, ctrl->flush[mixer], current->pid); } local_irq_save(flags); if (off) outpdw(MDP_BASE + off, data); if (ctrl->flush[mixer]) { outpdw(MDP_BASE + 0x18000, ctrl->flush[mixer]); ctrl->flush[mixer] = 0; } local_irq_restore(flags); mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); mdp_clk_ctrl(0); } void mdp4_mixer_stage_up(struct mdp4_overlay_pipe *pipe, int commit) { struct mdp4_overlay_pipe *pp; int i, mixer; mixer = pipe->mixer_num; for (i = <API key>; i < <API key>; i++) { pp = ctrl->stage[mixer][i]; if (pp && pp->pipe_ndx == pipe->pipe_ndx) { ctrl->stage[mixer][i] = NULL; break; } } ctrl->stage[mixer][pipe->mixer_stage] = pipe; /* keep it */ if (commit) <API key>(mixer); } void <API key>(struct mdp4_overlay_pipe *pipe, int commit) { struct mdp4_overlay_pipe *pp; int i, mixer; mixer = pipe->mixer_num; for (i = <API key>; i < <API key>; i++) { pp = ctrl->stage[mixer][i]; if (pp && pp->pipe_ndx == pipe->pipe_ndx) ctrl->stage[mixer][i] = NULL; /* clear it */ } if (commit) <API key>(mixer); } /* * mixer0: rgb3: border color at register 0x15004, 0x15008 * mixer1: vg3: border color at register 0x1D004, 0x1D008 * mixer2: xxx: border color at register 0x8D004, 0x8D008 */ void <API key>(struct mdp4_overlay_pipe *pipe) { struct mdp4_overlay_pipe *bspipe; int ptype, pnum, pndx, mixer; int format, alpha_enable, alpha; struct <API key> iom; if (pipe->pipe_type != OVERLAY_TYPE_BF) return; mixer = pipe->mixer_num; if (ctrl->baselayer[mixer]) return; bspipe = ctrl->stage[mixer][<API key>]; if (bspipe == NULL) { pr_err("%s: no base layer at mixer=%d\n", __func__, mixer); return; } /* * bspipe is clone here * get real pipe */ bspipe = <API key>(bspipe->pipe_ndx); if (bspipe == NULL) { pr_err("%s: <API key> returned null pipe ndx\n", __func__); return; } /* save original base layer */ ctrl->baselayer[mixer] = bspipe; iom = pipe->iommu; pipe->alpha = 0; /* make sure bf pipe has alpha 0 */ ptype = pipe->pipe_type; pnum = pipe->pipe_num; pndx = pipe->pipe_ndx; format = pipe->src_format; alpha_enable = pipe->alpha_enable; alpha = pipe->alpha; *pipe = *bspipe; /* keep base layer configuration */ pipe->pipe_type = ptype; pipe->pipe_num = pnum; pipe->pipe_ndx = pndx; pipe->src_format = format; pipe->alpha_enable = alpha_enable; pipe->alpha = alpha; pipe->iommu = iom; /* free original base layer pipe to be sued as normal pipe */ bspipe->pipe_used = 0; if (ctrl->panel_mode & <API key>) <API key>(0, pipe); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) <API key>(0, pipe); else if (ctrl->panel_mode & MDP4_PANEL_LCDC) mdp4_lcdc_base_swap(0, pipe); else if (ctrl->panel_mode & MDP4_PANEL_DTV) mdp4_dtv_base_swap(0, pipe); <API key>(bspipe, 1); /* borderfill pipe as base layer */ mdp4_mixer_stage_up(pipe, 0); } void <API key>(struct mdp4_overlay_pipe *pipe) { struct mdp4_overlay_pipe *bspipe; int ptype, pnum, pndx, mixer; int format, alpha_enable, alpha; struct <API key> iom; if (pipe->pipe_type != OVERLAY_TYPE_BF) return; mixer = pipe->mixer_num; /* retrieve original base layer */ bspipe = ctrl->baselayer[mixer]; if (bspipe == NULL) { pr_err("%s: no base layer at mixer=%d\n", __func__, mixer); return; } iom = bspipe->iommu; ptype = bspipe->pipe_type; pnum = bspipe->pipe_num; pndx = bspipe->pipe_ndx; format = bspipe->src_format; alpha_enable = bspipe->alpha_enable; alpha = bspipe->alpha; *bspipe = *pipe; /* restore base layer configuration */ bspipe->pipe_type = ptype; bspipe->pipe_num = pnum; bspipe->pipe_ndx = pndx; bspipe->src_format = format; bspipe->alpha_enable = alpha_enable; bspipe->alpha = alpha; bspipe->iommu = iom; bspipe->pipe_used++; /* mark base layer pipe used */ ctrl->baselayer[mixer] = NULL; /* free borderfill pipe */ pipe->pipe_used = 0; if (ctrl->panel_mode & <API key>) <API key>(0, bspipe); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) <API key>(0, bspipe); else if (ctrl->panel_mode & MDP4_PANEL_LCDC) mdp4_lcdc_base_swap(0, bspipe); else if (ctrl->panel_mode & MDP4_PANEL_DTV) mdp4_dtv_base_swap(0, bspipe); /* free borderfill pipe */ <API key>(pipe, 1); <API key>(pipe, 0); /* commit will happen for bspipe up */ <API key>(pipe, 0); /* stage up base layer */ <API key>(bspipe, 1); /* restore original base layer */ mdp4_mixer_stage_up(bspipe, 1); } static struct mdp4_overlay_pipe *<API key>(int mixer, struct mdp4_overlay_pipe *sp) { struct mdp4_overlay_pipe *pp; struct mdp4_overlay_pipe *kp; int i; kp = ctrl->stage[mixer][<API key>]; for (i = <API key>; i < <API key>; i++) { pp = ctrl->stage[mixer][i]; if (pp == NULL) continue; if (pp == sp) break; if ((pp->dst_x <= sp->dst_x) && ((pp->dst_x + pp->dst_w) >= (sp->dst_x + sp->dst_w))) { if ((pp->dst_y <= sp->dst_y) && ((pp->dst_y + pp->dst_h) >= (sp->dst_y + sp->dst_h))) { kp = pp; } } } return kp; } static void <API key>(struct blend_cfg *blend) { struct mdp4_overlay_pipe *pipe; char *base; u32 op_mode, format; int pnum, ptype; pipe = blend->solidfill_pipe; if (pipe == NULL) return; if (pipe->pipe_type == OVERLAY_TYPE_BF) return; ptype = <API key>(pipe->src_format); if (ptype == OVERLAY_TYPE_RGB) { pnum = pipe->pipe_num - OVERLAY_PIPE_RGB1; base = MDP_BASE + MDP4_RGB_BASE; base += MDP4_RGB_OFF * pnum; } else { pnum = pipe->pipe_num - OVERLAY_PIPE_VG1; base = MDP_BASE + MDP4_VIDEO_BASE; base += MDP4_VIDEO_OFF * pnum; } format = inpdw(base + 0x50); if (blend->solidfill) { format |= <API key>; /* * If solid fill is enabled, flip and scale * have to be disabled. otherwise, h/w * underruns. */ op_mode = inpdw(base + 0x0058); op_mode &= ~(MDP4_OP_FLIP_LR + MDP4_OP_SCALEX_EN); op_mode &= ~(MDP4_OP_FLIP_UD + MDP4_OP_SCALEY_EN); outpdw(base + 0x0058, op_mode); outpdw(base + 0x1008, 0); /* black */ /* * Set src size and dst size same to avoid underruns */ outpdw(base + 0x0000, inpdw(base + 0x0008)); } else { u32 src_size = ((pipe->src_h << 16) | pipe->src_w); outpdw(base + 0x0000, src_size); format &= ~<API key>; blend->solidfill_pipe = NULL; } outpdw(base + 0x50, format); <API key>(pipe, 0); } void <API key>(int mixer) { int i, off; unsigned char *overlay_base; struct blend_cfg *blend; if (mixer == MDP4_MIXER2) overlay_base = MDP_BASE + <API key>; else if (mixer == MDP4_MIXER1) overlay_base = MDP_BASE + <API key>; else overlay_base = MDP_BASE + <API key>; blend = &ctrl->blend[mixer][<API key>]; blend++; /* stage0 */ for (i = MDP4_MIXER_STAGE0; i < <API key>; i++) { off = 20 * i; off = 0x20 * (i - MDP4_MIXER_STAGE0); if (i == MDP4_MIXER_STAGE3) off -= 4; outpdw(overlay_base + off + 0x104, blend->op); blend++; } } static void <API key>(struct mdp4_overlay_pipe *s_pipe, struct mdp4_overlay_pipe *d_pipe, int alpha_drop, struct blend_cfg *blend) { int d_alpha, s_alpha; u32 op; d_alpha = d_pipe->alpha_enable; s_alpha = s_pipe->alpha_enable; /* base on fg's alpha */ blend->fg_alpha = s_pipe->alpha; blend->bg_alpha = 0x0ff - s_pipe->alpha; blend->op = <API key> | <API key>; blend->co3_sel = 1; /* use fg alpha */ op = s_pipe->blend_op; if (op == BLEND_OP_OPAQUE) { blend->bg_alpha = 0; blend->fg_alpha = 0xff; } else if ((op == <API key>) && (!alpha_drop) && s_alpha) { blend->op = <API key> | <API key> | <API key>; if (blend->fg_alpha != 0xff) { blend->bg_alpha = blend->fg_alpha; blend->op |= <API key>; } } else if (!alpha_drop && s_alpha) { blend->op = <API key> | <API key> | <API key>; if (blend->fg_alpha != 0xff) { blend->bg_alpha = blend->fg_alpha; blend->op |= <API key> | <API key>; } } if (!s_alpha && d_alpha) blend->co3_sel = 0; pr_debug("%s: op %d bg alpha %d, fg alpha %d blend: %x\n", __func__, op, blend->bg_alpha, blend->fg_alpha, blend->op); } static void <API key>(struct mdp4_overlay_pipe *s_pipe, struct mdp4_overlay_pipe *d_pipe, int alpha_drop, struct blend_cfg *blend) { int ptype, d_alpha, s_alpha; d_alpha = d_pipe->alpha_enable; s_alpha = s_pipe->alpha_enable; /* base on fg's alpha */ blend->bg_alpha = 0x0ff - s_pipe->alpha; blend->fg_alpha = s_pipe->alpha; blend->co3_sel = 1; /* use fg alpha */ if (s_pipe->is_fg) { if (s_pipe->alpha == 0xff) { blend->solidfill = 1; blend->solidfill_pipe = d_pipe; } } else if (s_alpha) { if (!alpha_drop) { blend->op = <API key>; if (!(s_pipe->flags & <API key>)) blend->op |= <API key>; } else blend->op = <API key>; blend->op |= <API key>; } else if (d_alpha) { ptype = <API key>(s_pipe->src_format); if (ptype == OVERLAY_TYPE_VIDEO && (!(s_pipe->flags & <API key>))) { blend->op = (<API key> | <API key>); if (!(s_pipe->flags & <API key>)) blend->op |= <API key>; blend->co3_sel = 0; /* use bg alpha */ } else { /* s_pipe is rgb without alpha */ blend->op = (<API key> | <API key>); blend->bg_alpha = 0; } } } /* * D(i+1) = Ks * S + Kd * D(i) */ void <API key>(int mixer) { struct mdp4_overlay_pipe *d_pipe; struct mdp4_overlay_pipe *s_pipe; struct blend_cfg *blend; int i, off, alpha_drop; unsigned char *overlay_base; uint32 c0, c1, c2; d_pipe = ctrl->stage[mixer][<API key>]; if (d_pipe == NULL) { pr_err("%s: Error: no bg_pipe at mixer=%d\n", __func__, mixer); return; } blend = &ctrl->blend[mixer][MDP4_MIXER_STAGE0]; for (i = MDP4_MIXER_STAGE0; i < <API key>; i++) { blend->solidfill = 0; blend->op = (<API key> | <API key>); s_pipe = ctrl->stage[mixer][i]; if (s_pipe == NULL) { blend++; d_pipe = NULL; continue; } alpha_drop = 0; /* per stage */ /* alpha channel is lost on VG pipe when using QSEED or M/N */ if (s_pipe->pipe_type == OVERLAY_TYPE_VIDEO && s_pipe->alpha_enable && ((s_pipe->op_mode & MDP4_OP_SCALEY_EN) || (s_pipe->op_mode & MDP4_OP_SCALEX_EN)) && !(s_pipe->op_mode & (<API key> | <API key>))) alpha_drop = 1; d_pipe = <API key>(mixer, s_pipe); pr_debug("%s: stage=%d: bg: ndx=%d da=%d dalpha=%x " "fg: ndx=%d sa=%d salpha=%x is_fg=%d alpha_drop=%d\n", __func__, i-2, d_pipe->pipe_ndx, d_pipe->alpha_enable, d_pipe->alpha, s_pipe->pipe_ndx, s_pipe->alpha_enable, s_pipe->alpha, s_pipe->is_fg, alpha_drop); if ((s_pipe->blend_op == <API key>) || (s_pipe->blend_op >= BLEND_OP_MAX)) <API key>(s_pipe, d_pipe, alpha_drop, blend); else <API key>(s_pipe, d_pipe, alpha_drop, blend); if (s_pipe->transp != MDP_TRANSP_NOP) { if (s_pipe->is_fg) { transp_color_key(s_pipe->src_format, s_pipe->transp, &c0, &c1, &c2); /* Fg blocked */ blend->op |= <API key>; /* lower limit */ blend->transp_low0 = (c1 << 16 | c0); blend->transp_low1 = c2; /* upper limit */ blend->transp_high0 = (c1 << 16 | c0); blend->transp_high1 = c2; } else { transp_color_key(d_pipe->src_format, s_pipe->transp, &c0, &c1, &c2); /* Fg blocked */ blend->op |= <API key>; blend--; /* one stage back */ /* lower limit */ blend->transp_low0 = (c1 << 16 | c0); blend->transp_low1 = c2; /* upper limit */ blend->transp_high0 = (c1 << 16 | c0); blend->transp_high1 = c2; blend++; /* back to original stage */ } } blend++; } /* mixer numer, /dev/fb0, /dev/fb1, /dev/fb2 */ if (mixer == MDP4_MIXER2) overlay_base = MDP_BASE + <API key>;/* 0x88000 */ else if (mixer == MDP4_MIXER1) overlay_base = MDP_BASE + <API key>;/* 0x18000 */ else overlay_base = MDP_BASE + <API key>;/* 0x10000 */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); blend = &ctrl->blend[mixer][<API key>]; /* lower limit */ outpdw(overlay_base + 0x180, blend->transp_low0); outpdw(overlay_base + 0x184, blend->transp_low1); /* upper limit */ outpdw(overlay_base + 0x188, blend->transp_high0); outpdw(overlay_base + 0x18c, blend->transp_high1); blend++; /* stage0 */ for (i = MDP4_MIXER_STAGE0; i < <API key>; i++) { off = 20 * i; off = 0x20 * (i - MDP4_MIXER_STAGE0); if (i == MDP4_MIXER_STAGE3) off -= 4; if (blend->solidfill_pipe) <API key>(blend); outpdw(overlay_base + off + 0x108, blend->fg_alpha); outpdw(overlay_base + off + 0x10c, blend->bg_alpha); if (mdp_rev >= MDP_REV_42) outpdw(overlay_base + off + 0x104, blend->op); outpdw(overlay_base + (off << 5) + 0x1004, blend->co3_sel); outpdw(overlay_base + off + 0x110, blend->transp_low0);/* low */ outpdw(overlay_base + off + 0x114, blend->transp_low1);/* low */ /* upper limit */ outpdw(overlay_base + off + 0x118, blend->transp_high0); outpdw(overlay_base + off + 0x11c, blend->transp_high1); blend++; } mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } void <API key>(struct mdp4_overlay_pipe *pipe, int all) { int mixer; uint32 *reg; mixer = pipe->mixer_num; reg = &ctrl->flush[mixer]; *reg |= (1 << (2 + pipe->pipe_num)); if (all) { if (mixer == MDP4_MIXER0) *reg |= 0x01; else *reg |= 0x02; } } void <API key>(int m0, int m1) { u32 data; data = ctrl->flush[m0] | ctrl->flush[m1]; ctrl->flush[m0] = data; } void <API key>(struct mdp4_overlay_pipe *pipe) { int mixer; mixer = pipe->mixer_num; ctrl->flush[mixer] = 0; } struct mdp4_overlay_pipe *<API key>(int mixer, int stage) { return ctrl->stage[mixer][stage]; } struct mdp4_overlay_pipe *<API key>(int ndx) { struct mdp4_overlay_pipe *pipe; if (ndx <= 0 || ndx > OVERLAY_PIPE_MAX) return NULL; pipe = &ctrl->plist[ndx - 1]; /* ndx start from 1 */ if (pipe->pipe_used == 0) return NULL; return pipe; } struct mdp4_overlay_pipe *<API key>(int ptype, int mixer) { int i; struct mdp4_overlay_pipe *pipe; if (ptype == OVERLAY_TYPE_BF) { if (!<API key>()) return NULL; } for (i = 0; i < OVERLAY_PIPE_MAX; i++) { pipe = &ctrl->plist[i]; if (pipe->pipe_type == ptype || (ptype == OVERLAY_TYPE_RGB && pipe->pipe_type == OVERLAY_TYPE_VIDEO)) { if ((ptype == OVERLAY_TYPE_BF && mixer != pipe->mixer_num) || (ptype != OVERLAY_TYPE_BF && pipe->pipe_used != 0)) { continue; } else if (ptype == OVERLAY_TYPE_BF) { //borderfill pipe <API key>(pipe); } init_completion(&pipe->comp); init_completion(&pipe->dmas_comp); pr_debug("%s: pipe=%x ndx=%d num=%d\n", __func__, (int)pipe, pipe->pipe_ndx, pipe->pipe_num); return pipe; } } pr_err("%s: ptype=%d FAILED\n", __func__, ptype); return NULL; } void <API key>(struct mdp4_overlay_pipe *pipe, int all) { uint32 ptype, num, ndx, mixer; struct <API key> iom; struct mdp4_overlay_pipe *orgpipe; pr_debug("%s: pipe=%x ndx=%d\n", __func__, (int)pipe, pipe->pipe_ndx); ptype = pipe->pipe_type; num = pipe->pipe_num; ndx = pipe->pipe_ndx; mixer = pipe->mixer_num; /* No need for borderfill pipe */ if (pipe->pipe_type != OVERLAY_TYPE_BF) <API key>(pipe->pipe_ndx, all); iom = pipe->iommu; memset(pipe, 0, sizeof(*pipe)); pipe->pipe_type = ptype; pipe->pipe_num = num; pipe->pipe_ndx = ndx; pipe->mixer_num = mixer; pipe->iommu = iom; /*Clear real pipe attributes as well */ orgpipe = <API key>(pipe->pipe_ndx); if (orgpipe != NULL) orgpipe->pipe_used = 0; } static int <API key>(struct mdp_overlay *req, int mixer, struct mdp4_overlay_pipe **ppipe, struct msm_fb_data_type *mfd) { struct mdp4_overlay_pipe *pipe; int ret, ptype; u32 upscale_max; upscale_max = (mdp_rev >= MDP_REV_41) ? <API key> : <API key>; if (mfd == NULL) { pr_err("%s: mfd == NULL, -ENODEV\n", __func__); return -ENODEV; } if (mixer >= MDP4_MIXER_MAX) { pr_err("%s: mixer out of range!\n", __func__); mdp4_stat.err_mixer++; return -ERANGE; } if (req->z_order < 0 || req->z_order > 3) { pr_err("%s: z_order=%d out of range!\n", __func__, req->z_order); mdp4_stat.err_zorder++; return -ERANGE; } if (req->src_rect.h > 0xFFF || req->src_rect.h < 2) { pr_err("%s: src_h is out of range: 0X%x!\n", __func__, req->src_rect.h); mdp4_stat.err_size++; return -EINVAL; } if (req->src_rect.w > 0xFFF || req->src_rect.w < 2) { pr_err("%s: src_w is out of range: 0X%x!\n", __func__, req->src_rect.w); mdp4_stat.err_size++; return -EINVAL; } if (req->src_rect.x > 0xFFF) { pr_err("%s: src_x is out of range: 0X%x!\n", __func__, req->src_rect.x); mdp4_stat.err_size++; return -EINVAL; } if (req->src_rect.y > 0xFFF) { pr_err("%s: src_y is out of range: 0X%x!\n", __func__, req->src_rect.y); mdp4_stat.err_size++; return -EINVAL; } if (req->dst_rect.h > 0xFFF || req->dst_rect.h < 2) { pr_err("%s: dst_h is out of range: 0X%x!\n", __func__, req->dst_rect.h); mdp4_stat.err_size++; return -EINVAL; } if (req->dst_rect.w > 0xFFF || req->dst_rect.w < 2) { pr_err("%s: dst_w is out of range: 0X%x!\n", __func__, req->dst_rect.w); mdp4_stat.err_size++; return -EINVAL; } if (req->dst_rect.x > 0xFFF) { pr_err("%s: dst_x is out of range: 0X%x!\n", __func__, req->dst_rect.x); mdp4_stat.err_size++; return -EINVAL; } if (req->dst_rect.y > 0xFFF) { pr_err("%s: dst_y is out of range: 0X%x!\n", __func__, req->dst_rect.y); mdp4_stat.err_size++; return -EINVAL; } if (req->src_rect.h == 0 || req->src_rect.w == 0) { pr_err("%s: src img of zero size!\n", __func__); mdp4_stat.err_size++; return -EINVAL; } if (req->dst_rect.h > (req->src_rect.h * upscale_max)) { mdp4_stat.err_scale++; pr_err("%s: scale up, too much (h)!\n", __func__); return -ERANGE; } if (req->src_rect.h > (req->dst_rect.h * 8)) { /* too little */ mdp4_stat.err_scale++; pr_err("%s: scale down, too little (h)!\n", __func__); return -ERANGE; } if (req->dst_rect.w > (req->src_rect.w * upscale_max)) { mdp4_stat.err_scale++; pr_err("%s: scale up, too much (w)!\n", __func__); return -ERANGE; } if (req->src_rect.w > (req->dst_rect.w * 8)) { /* too little */ mdp4_stat.err_scale++; pr_err("%s: scale down, too little (w)!\n", __func__); return -ERANGE; } if (mdp_hw_revision == MDP4_REVISION_V1) { /* non integer down saceling ratio smaller than 1/4 * is not supportted */ if (req->src_rect.h > (req->dst_rect.h * 4)) { if (req->src_rect.h % req->dst_rect.h) { mdp4_stat.err_scale++; pr_err("%s: need integer (h)!\n", __func__); return -ERANGE; } } if (req->src_rect.w > (req->dst_rect.w * 4)) { if (req->src_rect.w % req->dst_rect.w) { mdp4_stat.err_scale++; pr_err("%s: need integer (w)!\n", __func__); return -ERANGE; } } } if (((req->src_rect.x + req->src_rect.w) > req->src.width) || ((req->src_rect.y + req->src_rect.h) > req->src.height)) { mdp4_stat.err_size++; pr_err("%s invalid src rectangle\n", __func__); return -ERANGE; } if (ctrl->panel_3d != <API key>) { int xres; int yres; xres = mfd->panel_info.xres; yres = mfd->panel_info.yres; if (((req->dst_rect.x + req->dst_rect.w) > xres) || ((req->dst_rect.y + req->dst_rect.h) > yres)) { mdp4_stat.err_size++; pr_err("%s invalid dst rectangle (%dx%d) vs (%dx%d)\n", __func__,(req->dst_rect.x + req->dst_rect.w),(req->dst_rect.y + req->dst_rect.h),xres,yres); return -ERANGE; } } ptype = <API key>(req->src.format); if (ptype < 0) { pr_err("%s: <API key>!\n", __func__); return ptype; } if (req->flags & MDP_OV_PIPE_SHARE) ptype = OVERLAY_TYPE_VIDEO; /* VG pipe supports both RGB+YUV */ if (req->id == MSMFB_NEW_REQUEST) /* new request */ pipe = <API key>(ptype, mixer); else pipe = <API key>(req->id); if (pipe == NULL) { pr_err("%s: pipe == NULL!\n", __func__); return -ENOMEM; } #if defined(<API key>) pipe->mfd = mfd; #endif if (!display_iclient && !IS_ERR_OR_NULL(mfd->iclient)) { display_iclient = mfd->iclient; pr_debug("%s(): display_iclient %p\n", __func__, display_iclient); } pipe->src_format = req->src.format; ret = <API key>(pipe); if (ret < 0) { pr_err("%s: <API key>!\n", __func__); return ret; } /* * base layer == 1, reserved for frame buffer * zorder 0 == stage 0 == 2 * zorder 1 == stage 1 == 3 * zorder 2 == stage 2 == 4 */ if (req->id == MSMFB_NEW_REQUEST) { /* new request */ if (<API key>(pipe)) { pr_err("%s: ndx=%d still staged\n", __func__, pipe->pipe_ndx); return -EPERM; } pipe->pipe_used++; pipe->mixer_num = mixer; pr_debug("%s: zorder=%d pipe ndx=%d num=%d\n", __func__, req->z_order, pipe->pipe_ndx, pipe->pipe_num); } pipe->mixer_stage = req->z_order + MDP4_MIXER_STAGE0; pipe->src_width = req->src.width & 0x1fff; /* source img width */ pipe->src_height = req->src.height & 0x1fff; /* source img height */ pipe->src_h = req->src_rect.h & 0x07ff; pipe->src_w = req->src_rect.w & 0x07ff; pipe->src_y = req->src_rect.y & 0x07ff; pipe->src_x = req->src_rect.x & 0x07ff; pipe->dst_h = req->dst_rect.h & 0x07ff; pipe->dst_w = req->dst_rect.w & 0x07ff; pipe->dst_y = req->dst_rect.y & 0x07ff; pipe->dst_x = req->dst_rect.x & 0x07ff; pipe->op_mode = 0; #if defined(<API key>) pipe->ext_flag = req->flags; #endif if (req->flags & MDP_FLIP_LR) pipe->op_mode |= MDP4_OP_FLIP_LR; if (req->flags & MDP_FLIP_UD) pipe->op_mode |= MDP4_OP_FLIP_UD; if (req->flags & MDP_DITHER) pipe->op_mode |= MDP4_OP_DITHER_EN; if (req->flags & MDP_DEINTERLACE) pipe->op_mode |= MDP4_OP_DEINT_EN; if (req->flags & MDP_DEINTERLACE_ODD) pipe->op_mode |= <API key>; pipe->is_fg = req->is_fg;/* control alpha and color key */ pipe->alpha = req->alpha & 0x0ff; pipe->blend_op = req->blend_op; pipe->transp = req->transp_mask; pipe->flags = req->flags; *ppipe = pipe; return 0; } static int <API key>(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { u32 pclk; u32 xscale, yscale; u32 hsync = 0; u32 shift = 16; u64 rst; int ptype; int ret = -EINVAL; if (!pipe) { pr_err("%s: pipe is null!\n", __func__); return ret; } if (!mfd) { pr_err("%s: mfd is null!\n", __func__); return ret; } pr_debug("%s: pipe sets: panel res(x,y)=(%d,%d)\n", __func__, mfd->panel_info.xres, mfd->panel_info.yres); pr_debug("%s: src(w,h)(%d,%d),src(x,y)(%d,%d)\n", __func__, pipe->src_w, pipe->src_h, pipe->src_x, pipe->src_y); pr_debug("%s: dst(w,h)(%d,%d),dst(x,y)(%d,%d)\n", __func__, pipe->dst_w, pipe->dst_h, pipe->dst_x, pipe->dst_y); pclk = (mfd->panel_info.type == MIPI_VIDEO_PANEL || mfd->panel_info.type == MIPI_CMD_PANEL) ? mfd->panel_info.mipi.dsi_pclk_rate : mfd->panel_info.clk_rate; if (mfd->panel_info.type == LVDS_PANEL && mfd->panel_info.lvds.channel_mode == <API key>) pclk = pclk << 1; if (!pclk) { pipe->req_clk = mdp_max_clk; pr_err("%s panel pixel clk is zero!\n", __func__); return ret; } pr_debug("%s: mdp panel pixel clk is %d.\n", __func__, pclk); if (!pipe->dst_h) { pr_err("%s: pipe dst_h is zero!\n", __func__); pipe->req_clk = mdp_max_clk; return ret; } if (!pipe->src_h) { pr_err("%s: pipe src_h is zero!\n", __func__); pipe->req_clk = mdp_max_clk; return ret; } if (!pipe->dst_w) { pr_err("%s: pipe dst_w is zero!\n", __func__); pipe->req_clk = mdp_max_clk; return ret; } if (!pipe->dst_h) { pr_err("%s: pipe dst_h is zero!\n", __func__); pipe->req_clk = mdp_max_clk; return ret; } if (pipe->mixer_num == MDP4_MIXER0) { if (pipe->blt_forced) return 0; ptype = <API key>(pipe->src_format); if (ptype == OVERLAY_TYPE_VIDEO) { if ((pipe->src_h >= 720) && (pipe->src_w >= 1080)) { pipe->req_clk = (u32) mdp_max_clk + 100; pipe->blt_forced++; return 0; } else if ((pipe->src_h >= 1080) && (pipe->src_w >= 720)) { pipe->req_clk = (u32) mdp_max_clk + 100; pipe->blt_forced++; return 0; } } } /* * For the scaling cases, make more margin by removing porch * values and adding extra 20%. */ if ((pipe->src_h != pipe->dst_h) || (pipe->src_w != pipe->dst_w)) { hsync = mfd->panel_info.xres; hsync *= 100; hsync /= 120; pr_debug("%s: panel hsync is %d. with scaling\n", __func__, hsync); } else { hsync = mfd->panel_info.lcdc.h_back_porch + mfd->panel_info.lcdc.h_front_porch + mfd->panel_info.lcdc.h_pulse_width + mfd->panel_info.xres; pr_debug("%s: panel hsync is %d.\n", __func__, hsync); } if (!hsync) { pipe->req_clk = mdp_max_clk; pr_err("%s: panel hsync is zero!\n", __func__); return 0; } xscale = mfd->panel_info.xres; xscale += pipe->src_w; if (xscale < pipe->dst_w) { pipe->req_clk = mdp_max_clk; pr_err("%s: xres+src_w cannot be less than dst_w!\n", __func__); return ret; } xscale -= pipe->dst_w; xscale <<= shift; xscale /= hsync; pr_debug("%s: the right %d shifted xscale is %d.\n", __func__, shift, xscale); if (pipe->src_h > pipe->dst_h) { yscale = pipe->src_h; yscale <<= shift; yscale /= pipe->dst_h; } else { /* upscale */ yscale = pipe->dst_h; yscale <<= shift; yscale /= pipe->src_h; } yscale *= pipe->src_w; yscale /= hsync; pr_debug("%s: the right %d shifted yscale is %d.\n", __func__, shift, yscale); rst = pclk; if (yscale > xscale) rst *= yscale; else rst *= xscale; rst >>= shift; /* * There is one special case for the panels that have low * v_back_porch (<=4), mdp clk should be fast enough to buffer * 4 lines input during back porch time if scaling is * required(FIR). */ if ((mfd->panel_info.lcdc.v_back_porch <= 4) && (pipe->src_h != pipe->dst_h) && (mfd->panel_info.lcdc.v_back_porch)) { u32 clk = 0; clk = 4 * (pclk >> shift) / mfd->panel_info.lcdc.v_back_porch; clk <<= shift; pr_debug("%s: mdp clk rate %d based on low vbp %d\n", __func__, clk, mfd->panel_info.lcdc.v_back_porch); rst = (rst > clk) ? rst : clk; } /* * If the calculated mdp clk is less than panel pixel clk, * most likely due to upscaling, mdp clk rate will be set to * greater than pclk. Now the driver uses 1.15 as the * factor. Ideally this factor is passed from board file. */ if (rst < pclk) { rst = ((pclk >> shift) * 23 / 20) << shift; pr_debug("%s calculated mdp clk is less than pclk.\n", __func__); } /* * Interlaced videos require the max mdp clk but cannot * be explained by mdp clk equation. */ if (pipe->flags & MDP_DEINTERLACE) { rst = (rst > mdp_max_clk) ? rst : mdp_max_clk; pr_info("%s deinterlace requires max mdp clk.\n", __func__); } pipe->req_clk = (u32) rst; pr_debug("%s: required mdp clk %d mixer %d pipe ndx %d\n", __func__, pipe->req_clk, pipe->mixer_num, pipe->pipe_ndx); return 0; } static int <API key>(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { u32 fps; int ret = -EINVAL; u32 quota; u32 shift = 16; if (!pipe) { pr_err("%s: pipe is null!\n", __func__); return ret; } if (!mfd) { pr_err("%s: mfd is null!\n", __func__); return ret; } fps = <API key>(mfd); quota = pipe->src_w * pipe->src_h * fps * pipe->bpp; quota >>= shift; pipe->bw_ab_quota = quota * mdp_bw_ab_factor / 100; pipe->bw_ib_quota = quota * mdp_bw_ib_factor / 100; pr_debug("%s max_bw=%llu ab_factor=%d ib_factor=%d\n", __func__, mdp_max_bw, mdp_bw_ab_factor, mdp_bw_ib_factor); /* down scaling factor for ib */ if ((!pipe->dst_h) && (!pipe->src_h) && (pipe->src_h > pipe->dst_h)) { u64 ib = quota; ib *= pipe->src_h; ib /= pipe->dst_h; pipe->bw_ib_quota = max(ib, pipe->bw_ib_quota); pr_debug("%s: src_h=%d dst_h=%d mdp ib %llu, ib_quota=%llu\n", __func__, pipe->src_h, pipe->dst_h, ib<<shift, pipe->bw_ib_quota<<shift); } pipe->bw_ab_quota <<= shift; pipe->bw_ib_quota <<= shift; pr_debug("%s: pipe ndx=%d src(h,w)(%d, %d) fps=%d bpp=%d\n", __func__, pipe->pipe_ndx, pipe->src_h, pipe->src_w, fps, pipe->bpp); pr_debug("%s: ab_quota=%llu ib_quota=%llu\n", __func__, pipe->bw_ab_quota, pipe->bw_ib_quota); return 0; } int <API key>(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { struct mdp4_overlay_perf *perf_req = &perf_request; u32 fps; int bpp; int ret = -EINVAL; u32 quota; u32 shift = 16; if (!pipe) { pr_err("%s: pipe is null!\n", __func__); return ret; } if (!mfd) { pr_err("%s: mfd is null!\n", __func__); return ret; } mutex_lock(&perf_mutex); bpp = BLT_BPP; fps = <API key>(mfd); /* read and write bw*/ quota = pipe->dst_w * pipe->dst_h * fps * bpp * 2; quota >>= shift; perf_req->mdp_ov_ab_bw[pipe->mixer_num] = quota * mdp_bw_ab_factor / 100; perf_req->mdp_ov_ib_bw[pipe->mixer_num] = quota * mdp_bw_ib_factor / 100; perf_req->mdp_ov_ab_bw[pipe->mixer_num] <<= shift; perf_req->mdp_ov_ib_bw[pipe->mixer_num] <<= shift; pr_debug("%s: pipe ndx=%d dst(h,w)(%d, %d) fps=%d bpp=%d\n", __func__, pipe->pipe_ndx, pipe->dst_h, pipe->dst_w, fps, bpp); pr_debug("%s: overlay=%d ab_bw=%llu ib_bw=%llu\n", __func__, pipe->mixer_num, perf_req->mdp_ov_ab_bw[pipe->mixer_num], perf_req->mdp_ov_ib_bw[pipe->mixer_num]); mutex_unlock(&perf_mutex); return 0; } int <API key>(struct msm_fb_data_type *mfd) { u32 worst_mdp_clk = 0; int i; struct mdp4_overlay_perf *perf_req = &perf_request; struct mdp4_overlay_pipe *pipe; u32 cnt = 0; int ret = -EINVAL; u64 ab_quota_total = 0, ib_quota_total = 0; if (!mfd) { pr_err("%s: mfd is null!\n", __func__); return ret; } mutex_lock(&perf_mutex); pipe = ctrl->plist; for (i = 0; i < MDP4_MIXER_MAX; i++) perf_req->use_ov_blt[i] = 0; for (i = 0; i < OVERLAY_PIPE_MAX; i++, pipe++) { if (!pipe) { mutex_unlock(&perf_mutex); return ret; } if (!pipe->pipe_used) continue; cnt++; if (worst_mdp_clk < pipe->req_clk) worst_mdp_clk = pipe->req_clk; if (pipe->req_clk > mdp_max_clk) perf_req->use_ov_blt[pipe->mixer_num] = 1; if (pipe->mixer_num == MDP4_MIXER2) perf_req->use_ov_blt[MDP4_MIXER2] = 1; if (pipe->pipe_type != OVERLAY_TYPE_BF) { ab_quota_total += pipe->bw_ab_quota; ib_quota_total += pipe->bw_ib_quota; } if (mfd->mdp_rev == MDP_REV_41) { /* * writeback (blt) mode to provide work around * for dsi cmd mode interface hardware bug. */ if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) { if (pipe->dst_x != 0) perf_req->use_ov_blt[MDP4_MIXER0] = 1; } if ((mfd->panel_info.xres > 1280) && (mfd->panel_info.type != DTV_PANEL)) { perf_req->use_ov_blt[MDP4_MIXER0] = 1; } } } perf_req->mdp_clk_rate = min(worst_mdp_clk, mdp_max_clk); perf_req->mdp_clk_rate = mdp_clk_round_rate(perf_req->mdp_clk_rate); for (i = 0; i < MDP4_MIXER_MAX; i++) { if (perf_req->use_ov_blt[i]) { ab_quota_total += perf_req->mdp_ov_ab_bw[i]; ib_quota_total += perf_req->mdp_ov_ib_bw[i]; } } perf_req->mdp_ab_bw = roundup(ab_quota_total, <API key>); perf_req->mdp_ib_bw = roundup(ib_quota_total, <API key>); pr_debug("%s %d: ab_quota_total=(%llu, %d) ib_quota_total=(%llu, %d)\n", __func__, __LINE__, ab_quota_total, perf_req->mdp_ab_bw, ib_quota_total, perf_req->mdp_ib_bw); if (ab_quota_total > mdp_max_bw) pr_warn("%s: req ab bw=%llu is larger than max bw=%llu", __func__, ab_quota_total, mdp_max_bw); if (ib_quota_total > mdp_max_bw) pr_warn("%s: req ib bw=%llu is larger than max bw=%llu", __func__, ib_quota_total, mdp_max_bw); pr_debug("%s %d: pid %d cnt %d clk %d ov0_blt %d, ov1_blt %d\n", __func__, __LINE__, current->pid, cnt, perf_req->mdp_clk_rate, perf_req->use_ov_blt[0], perf_req->use_ov_blt[1]); mutex_unlock(&perf_mutex); return 0; } int <API key>(struct mdp4_overlay_pipe *pipe, struct msm_fb_data_type *mfd) { int ret = 0; if (<API key>(mfd, pipe)) { pr_err("%s unable to calc mdp pipe clk rate ret=%d\n", __func__, ret); ret = -EINVAL; } if (<API key>(mfd, pipe)) { pr_err("%s unable to calc mdp pipe bandwidth ret=%d\n", __func__, ret); ret = -EINVAL; } return ret; } void <API key>(struct msm_fb_data_type *mfd, int flag) { struct mdp4_overlay_perf *perf_req = &perf_request; struct mdp4_overlay_perf *perf_cur = &perf_current; pr_debug("%s %d: req mdp clk %d, cur mdp clk %d flag %d\n", __func__, __LINE__, perf_req->mdp_clk_rate, perf_cur->mdp_clk_rate, flag); mutex_lock(&perf_mutex); if (!mdp4_extn_disp) perf_cur->use_ov_blt[1] = 0; if (flag) { if (perf_req->mdp_clk_rate > perf_cur->mdp_clk_rate) { mdp_set_core_clk(perf_req->mdp_clk_rate); pr_info("%s mdp clk is changed [%d] from %d to %d\n", __func__, flag, perf_cur->mdp_clk_rate, perf_req->mdp_clk_rate); perf_cur->mdp_clk_rate = perf_req->mdp_clk_rate; } if ((perf_req->mdp_ab_bw > perf_cur->mdp_ab_bw) || (perf_req->mdp_ib_bw > perf_cur->mdp_ib_bw)) { <API key> (perf_req->mdp_ab_bw, perf_req->mdp_ib_bw); pr_debug("%s mdp ab_bw is changed [%d] from %d to %d\n", __func__, flag, perf_cur->mdp_ab_bw, perf_req->mdp_ab_bw); pr_debug("%s mdp ib_bw is changed [%d] from %d to %d\n", __func__, flag, perf_cur->mdp_ib_bw, perf_req->mdp_ib_bw); perf_cur->mdp_ab_bw = perf_req->mdp_ab_bw; perf_cur->mdp_ib_bw = perf_req->mdp_ib_bw; } if ((mfd->panel_info.pdest == DISPLAY_1 && perf_req->use_ov_blt[0] && !perf_cur->use_ov_blt[0]) || dbg_force_ov0_blt) { if (mfd->panel_info.type == LCDC_PANEL || mfd->panel_info.type == LVDS_PANEL) <API key>(mfd); else if (mfd->panel_info.type == MIPI_VIDEO_PANEL) <API key>(mfd); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) <API key>(mfd); pr_debug("%s mixer0 start blt [%d] from %d to %d.\n", __func__, flag, perf_cur->use_ov_blt[0], perf_req->use_ov_blt[0]); perf_cur->use_ov_blt[0] = perf_req->use_ov_blt[0]; } if ((mfd->panel_info.pdest == DISPLAY_2 && perf_req->use_ov_blt[1] && !perf_cur->use_ov_blt[1]) || dbg_force_ov1_blt) { <API key>(mfd); pr_debug("%s mixer1 start blt [%d] from %d to %d.\n", __func__, flag, perf_cur->use_ov_blt[1], perf_req->use_ov_blt[1]); perf_cur->use_ov_blt[1] = perf_req->use_ov_blt[1]; } } else { if (perf_req->mdp_clk_rate < perf_cur->mdp_clk_rate) { pr_info("%s mdp clk is changed [%d] from %d to %d\n", __func__, flag, perf_cur->mdp_clk_rate, perf_req->mdp_clk_rate); mdp_set_core_clk(perf_req->mdp_clk_rate); perf_cur->mdp_clk_rate = perf_req->mdp_clk_rate; } if (perf_req->mdp_ab_bw < perf_cur->mdp_ab_bw || perf_req->mdp_ib_bw < perf_cur->mdp_ib_bw) { <API key> (perf_req->mdp_ab_bw, perf_req->mdp_ib_bw); pr_debug("%s mdp ab bw is changed [%d] from %d to %d\n", __func__, flag, perf_cur->mdp_ab_bw, perf_req->mdp_ab_bw); pr_debug("%s mdp ib bw is changed [%d] from %d to %d\n", __func__, flag, perf_cur->mdp_ib_bw, perf_req->mdp_ib_bw); perf_cur->mdp_ab_bw = perf_req->mdp_ab_bw; perf_cur->mdp_ib_bw = perf_req->mdp_ib_bw; } if ((mfd->panel_info.pdest == DISPLAY_1 && !perf_req->use_ov_blt[0] && perf_cur->use_ov_blt[0]) || dbg_force_ov0_blt) { if (mfd->panel_info.type == LCDC_PANEL || mfd->panel_info.type == LVDS_PANEL) <API key>(mfd); else if (mfd->panel_info.type == MIPI_VIDEO_PANEL) <API key>(mfd); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) <API key>(mfd); pr_debug("%s mixer0 stop blt [%d] from %d to %d.\n", __func__, flag, perf_cur->use_ov_blt[0], perf_req->use_ov_blt[0]); perf_cur->use_ov_blt[0] = perf_req->use_ov_blt[0]; } if ((mfd->panel_info.pdest == DISPLAY_2 && !perf_req->use_ov_blt[1] && perf_cur->use_ov_blt[1]) || dbg_force_ov1_blt) { <API key>(mfd); pr_debug("%s mixer1 stop blt [%d] from %d to %d.\n", __func__, flag, perf_cur->use_ov_blt[1], perf_req->use_ov_blt[1]); perf_cur->use_ov_blt[1] = perf_req->use_ov_blt[1]; } } mutex_unlock(&perf_mutex); return; } static int get_img(struct msmfb_data *img, struct fb_info *info, struct mdp4_overlay_pipe *pipe, unsigned int plane, unsigned long *start, unsigned long *len, struct file **srcp_file, int *p_need, struct ion_handle **srcp_ihdl) { struct file *file; int put_needed, ret = 0, fb_num; #ifdef CONFIG_ANDROID_PMEM unsigned long vstart; #endif *p_need = 0; if (img->flags & MDP_BLIT_SRC_GEM) { *srcp_file = NULL; return kgsl_gem_obj_addr(img->memory_id, (int) img->priv, start, len); } if (img->flags & <API key>) { file = fget_light(img->memory_id, &put_needed); if (file == NULL) return -EINVAL; pipe->flags |= <API key>; if (MAJOR(file->f_dentry->d_inode->i_rdev) == FB_MAJOR) { fb_num = MINOR(file->f_dentry->d_inode->i_rdev); if (get_fb_phys_info(start, len, fb_num, <API key>)) { ret = -1; } else { *srcp_file = file; *p_need = put_needed; } } else ret = -1; if (ret) fput_light(file, put_needed); return ret; } #ifdef <API key> return <API key>(img->memory_id, pipe, plane, start, len, srcp_ihdl); #endif #ifdef CONFIG_ANDROID_PMEM if (!get_pmem_file(img->memory_id, start, &vstart, len, srcp_file)) return 0; else return -EINVAL; #endif } #ifdef <API key> int <API key>(struct fb_info *info, struct msmfb_overlay_3d *req) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; int ret = -EPERM; if (<API key>(&mfd->dma->ov_mutex)) return -EINTR; if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) { <API key>(mfd, req); ret = 0; } else if (ctrl->panel_mode & <API key>) { <API key>(mfd, req); ret = 0; } mutex_unlock(&mfd->dma->ov_mutex); return ret; } #else int <API key>(struct fb_info *info, struct msmfb_overlay_3d *req) { /* do nothing */ return -EPERM; } #endif int mdp4_overlay_blt(struct fb_info *info, struct msmfb_overlay_blt *req) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; if (mfd == NULL) return -ENODEV; if (<API key>(&mfd->dma->ov_mutex)) return -EINTR; if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) <API key>(mfd, req); else if (ctrl->panel_mode & <API key>) <API key>(mfd, req); else if (ctrl->panel_mode & MDP4_PANEL_LCDC) <API key>(mfd, req); else if (ctrl->panel_mode & MDP4_PANEL_MDDI) <API key>(mfd, req); mutex_unlock(&mfd->dma->ov_mutex); return 0; } int mdp4_overlay_get(struct fb_info *info, struct mdp_overlay *req) { struct mdp4_overlay_pipe *pipe; pipe = <API key>(req->id); if (pipe == NULL) return -ENODEV; *req = pipe->req_data; if (<API key>()) req->flags |= <API key>; return 0; } int mdp4_overlay_set(struct fb_info *info, struct mdp_overlay *req) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; int ret, mixer; struct mdp4_overlay_pipe *pipe; if (mfd == NULL) { pr_err("%s: mfd == NULL, -ENODEV\n", __func__); return -ENODEV; } if (info->node != 0 || mfd->cont_splash_done) /* primary */ if (!mfd->panel_power_on) /* suspended */ return -EPERM; if (req->src.format == MDP_FB_FORMAT) req->src.format = mfd->fb_imgType; if (<API key>(&mfd->dma->ov_mutex)) { pr_err("%s: <API key>, -EINTR\n", __func__); return -EINTR; } mixer = mfd->panel_info.pdest; /* DISPLAY_1 or DISPLAY_2 */ ret = <API key>(req, mixer, &pipe, mfd); if (ret < 0) { mutex_unlock(&mfd->dma->ov_mutex); pr_err("%s: <API key>, ret=%d\n", __func__, ret); return ret; } #if (CONFIG_MACH_LGE) <API key>(mfd, pipe); if(pipe->mixer_num == MDP4_MIXER0 && pipe->req_clk > mdp_max_clk && OVERLAY_TYPE_RGB == <API key>(pipe->src_format)) { pr_err("%s UI blt case, can't compose with MDP directly.\n", __func__); if(req->id == MSMFB_NEW_REQUEST) { <API key>(pipe,0); } mutex_unlock(&mfd->dma->ov_mutex); return -EINVAL; } #endif if (pipe->flags & <API key>) { <API key>(mfd); } /* return id back to user */ req->id = pipe->pipe_ndx; /* pipe_ndx start from 1 */ pipe->req_data = *req; /* keep original req */ if (!IS_ERR_OR_NULL(mfd->iclient)) { pr_debug("pipe->flags 0x%x\n", pipe->flags); if (pipe->flags & <API key>) { mfd->mem_hid &= ~BIT(ION_IOMMU_HEAP_ID); mfd->mem_hid |= ION_SECURE; } else { mfd->mem_hid |= BIT(ION_IOMMU_HEAP_ID); mfd->mem_hid &= ~ION_SECURE; } } mdp4_stat.overlay_set[pipe->mixer_num]++; if (pipe->flags & <API key>) { if (pipe->pipe_num <= OVERLAY_PIPE_VG2) memcpy(&pipe->pp_cfg, &req->overlay_pp_cfg, sizeof(struct <API key>)); else pr_debug("%s: RGB Pipes don't support CSC/QSEED\n", __func__); } <API key>(pipe, mfd); #if (CONFIG_MACH_LGE) #if defined(<API key>) || defined(<API key>) if(pipe->mixer_num == MDP4_MIXER0 && OVERLAY_TYPE_VIDEO == <API key>(pipe->src_format)) { pr_debug("%s video blt mode off, req_clk is max now.\n", __func__); pipe->req_clk = mdp_max_clk; } #else if(pipe->mixer_num == MDP4_MIXER0 && pipe->req_clk > mdp_max_clk && OVERLAY_TYPE_VIDEO == <API key>(pipe->src_format)) { pr_debug("%s video blt mode off, req_clk is max now.\n", __func__); pipe->req_clk = mdp_max_clk; } #endif #endif mutex_unlock(&mfd->dma->ov_mutex); return 0; } int <API key>(int mixer) { struct mdp4_overlay_pipe *pipe; int i, cnt = 0; /* free pipe besides base layer pipe */ for (i = MDP4_MIXER_STAGE3; i > <API key>; i pipe = ctrl->stage[mixer][i]; if (pipe == NULL) continue; pipe->flags &= ~MDP_OV_PLAY_NOWAIT; <API key>(pipe, 1); <API key>(pipe, 1); <API key>(pipe, 1); cnt++; } return cnt; } int mdp4_overlay_unset(struct fb_info *info, int ndx) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; struct mdp4_overlay_pipe *pipe; if (mfd == NULL) return -ENODEV; if (<API key>(&mfd->dma->ov_mutex)) return -EINTR; pipe = <API key>(ndx); if (pipe == NULL) { mutex_unlock(&mfd->dma->ov_mutex); return -ENODEV; } if (pipe->pipe_type == OVERLAY_TYPE_BF) { <API key>(pipe); mutex_unlock(&mfd->dma->ov_mutex); return 0; } if (pipe->mixer_num == MDP4_MIXER2) ctrl->mixer2_played = 0; else if (pipe->mixer_num == MDP4_MIXER1) ctrl->mixer1_played = 0; else { /* mixer 0 */ ctrl->mixer0_played = 0; if (ctrl->panel_mode & MDP4_PANEL_MDDI) { if (mfd->panel_power_on) <API key>(mfd); } } <API key>(pipe, 1); <API key>(pipe, 0); if (pipe->blt_forced) { if (pipe->flags & <API key>) { pipe->blt_forced = 0; pipe->req_clk = 0; <API key>(mfd); } } if (pipe->mixer_num == MDP4_MIXER0) { if (ctrl->panel_mode & MDP4_PANEL_MDDI) { if (mfd->panel_power_on) <API key>(); } } else { /* mixer1, DTV, ATV */ if (ctrl->panel_mode & MDP4_PANEL_DTV) <API key>(mfd, pipe); } mdp4_stat.overlay_unset[pipe->mixer_num]++; <API key>(pipe, 0); mutex_unlock(&mfd->dma->ov_mutex); return 0; } int <API key>(struct fb_info *info) { if (!hdmi_prim_display && info->node == 0) { if (ctrl->panel_mode & <API key>) <API key>(0); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) <API key>(0); else if (ctrl->panel_mode & MDP4_PANEL_LCDC) <API key>(0); } else if (hdmi_prim_display || info->node == 1) { mdp4_dtv_wait4vsync(0); } return 0; } int <API key>(struct fb_info *info, int enable) { int cmd; if (enable) cmd = 1; else cmd = 0; if (!hdmi_prim_display && info->node == 0) { if (ctrl->panel_mode & <API key>) <API key>(info, cmd); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) <API key>(info, cmd); else if (ctrl->panel_mode & MDP4_PANEL_LCDC) <API key>(info, cmd); } else if (hdmi_prim_display || info->node == 1) mdp4_dtv_vsync_ctrl(info, cmd); return 0; } struct tile_desc { uint32 width; /* tile's width */ uint32 height; /* tile's height */ uint32 row_tile_w; /* tiles per row's width */ uint32 row_tile_h; /* tiles per row's height */ }; void tile_samsung(struct tile_desc *tp) { /* * each row of samsung tile consists of two tiles in height * and two tiles in width which means width should align to * 64 x 2 bytes and height should align to 32 x 2 bytes. * video decoder generate two tiles in width and one tile * in height which ends up height align to 32 X 1 bytes. */ tp->width = 64; /* 64 bytes */ tp->row_tile_w = 2; /* 2 tiles per row's width */ tp->height = 32; /* 32 bytes */ tp->row_tile_h = 1; /* 1 tiles per row's height */ } uint32 tile_mem_size(struct mdp4_overlay_pipe *pipe, struct tile_desc *tp) { uint32 tile_w, tile_h; uint32 row_num_w, row_num_h; tile_w = tp->width * tp->row_tile_w; tile_h = tp->height * tp->row_tile_h; row_num_w = (pipe->src_width + tile_w - 1) / tile_w; row_num_h = (pipe->src_height + tile_h - 1) / tile_h; return ((row_num_w * row_num_h * tile_w * tile_h) + 8191) & ~8191; } int <API key>(struct fb_info *info, struct msmfb_overlay_data *req) { return 0; } /* * <API key>: called from dma_done isr * No mutex/sleep allowed */ void <API key>(int mixer) { /* * non double buffer register update here * perf level, new clock rate should be done here */ } /* * <API key>: called from tasklet context * No mutex/sleep allowed */ void <API key>(struct mdp4_overlay_pipe *pipe) { if (pipe->pipe_type == OVERLAY_TYPE_VIDEO) <API key>(pipe); /* video/graphic pipe */ else <API key>(pipe); /* rgb pipe */ pr_debug("%s: pipe=%x ndx=%d num=%d used=%d\n", __func__, (int) pipe, pipe->pipe_ndx, pipe->pipe_num, pipe->pipe_used); <API key>(pipe, 1); mdp4_mixer_stage_up(pipe, 0); } int mdp4_overlay_play(struct fb_info *info, struct msmfb_overlay_data *req) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; struct msmfb_data *img; struct mdp4_overlay_pipe *pipe; ulong start, addr; ulong len = 0; struct ion_handle *srcp0_ihdl = NULL; struct ion_handle *srcp1_ihdl = NULL, *srcp2_ihdl = NULL; uint32_t overlay_version = 0; int ret = 0; if (mfd == NULL) return -ENODEV; pipe = <API key>(req->id); if (pipe == NULL) { mdp4_stat.err_play++; return -ENODEV; } if (pipe->pipe_type == OVERLAY_TYPE_BF) { <API key>(pipe); <API key>(pipe->mixer_num); return 0; } mutex_lock(&mfd->dma->ov_mutex); img = &req->data; get_img(img, info, pipe, 0, &start, &len, &pipe->srcp0_file, &pipe->put0_need, &srcp0_ihdl); if (len == 0) { pr_err("%s: pmem Error\n", __func__); ret = -1; goto end; } addr = start + img->offset; pipe->srcp0_addr = addr; pipe->srcp0_ystride = pipe->src_width * pipe->bpp; pr_debug("%s: mixer=%d ndx=%x addr=%x flags=%x pid=%d\n", __func__, pipe->mixer_num, pipe->pipe_ndx, (int)addr, pipe->flags, current->pid); if ((req->version_key & VERSION_KEY_MASK) == 0xF9E8D700) overlay_version = (req->version_key & ~VERSION_KEY_MASK); if (pipe->fetch_plane == <API key>) { if (overlay_version > 0) { img = &req->plane1_data; get_img(img, info, pipe, 1, &start, &len, &pipe->srcp1_file, &pipe->put1_need, &srcp1_ihdl); if (len == 0) { pr_err("%s: Error to get plane1\n", __func__); ret = -EINVAL; goto end; } pipe->srcp1_addr = start + img->offset; } else if (pipe->frame_format == <API key>) { struct tile_desc tile; tile_samsung(&tile); pipe->srcp1_addr = addr + tile_mem_size(pipe, &tile); } else { pipe->srcp1_addr = addr + (pipe->src_width * pipe->src_height); } pipe->srcp0_ystride = pipe->src_width; if ((pipe->src_format == MDP_Y_CRCB_H1V1) || (pipe->src_format == MDP_Y_CBCR_H1V1) || (pipe->src_format == MDP_Y_CRCB_H1V2) || (pipe->src_format == MDP_Y_CBCR_H1V2)) { if (pipe->src_width > YUV_444_MAX_WIDTH) pipe->srcp1_ystride = pipe->src_width << 2; else pipe->srcp1_ystride = pipe->src_width << 1; } else pipe->srcp1_ystride = pipe->src_width; } else if (pipe->fetch_plane == <API key>) { if (overlay_version > 0) { img = &req->plane1_data; get_img(img, info, pipe, 1, &start, &len, &pipe->srcp1_file, &pipe->put1_need, &srcp1_ihdl); if (len == 0) { pr_err("%s: Error to get plane1\n", __func__); ret = -EINVAL; goto end; } pipe->srcp1_addr = start + img->offset; img = &req->plane2_data; get_img(img, info, pipe, 2, &start, &len, &pipe->srcp2_file, &pipe->put2_need, &srcp2_ihdl); if (len == 0) { pr_err("%s: Error to get plane2\n", __func__); ret = -EINVAL; goto end; } pipe->srcp2_addr = start + img->offset; } else { if (pipe->src_format == MDP_Y_CR_CB_GH2V2) { addr += (ALIGN(pipe->src_width, 16) * pipe->src_height); pipe->srcp1_addr = addr; addr += ((ALIGN((pipe->src_width / 2), 16)) * (pipe->src_height / 2)); pipe->srcp2_addr = addr; } else { addr += (pipe->src_width * pipe->src_height); pipe->srcp1_addr = addr; addr += ((pipe->src_width / 2) * (pipe->src_height / 2)); pipe->srcp2_addr = addr; } } /* mdp planar format expects Cb in srcp1 and Cr in p2 */ if ((pipe->src_format == MDP_Y_CR_CB_H2V2) || (pipe->src_format == MDP_Y_CR_CB_GH2V2)) swap(pipe->srcp1_addr, pipe->srcp2_addr); if (pipe->src_format == MDP_Y_CR_CB_GH2V2) { pipe->srcp0_ystride = ALIGN(pipe->src_width, 16); pipe->srcp1_ystride = ALIGN(pipe->src_width / 2, 16); pipe->srcp2_ystride = ALIGN(pipe->src_width / 2, 16); } else { pipe->srcp0_ystride = pipe->src_width; pipe->srcp1_ystride = pipe->src_width / 2; pipe->srcp2_ystride = pipe->src_width / 2; } } <API key>(mfd); #if defined(<API key>) pipe->mfd = mfd; #endif if (pipe->mixer_num == MDP4_MIXER0) { if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) { /* cndx = 0 */ <API key>(0, pipe); } else if (ctrl->panel_mode & <API key>) { /* cndx = 0 */ <API key>(0, pipe); } else if (ctrl->panel_mode & MDP4_PANEL_LCDC) { /* cndx = 0 */ <API key>(0, pipe); } } else if (pipe->mixer_num == MDP4_MIXER1) { if (ctrl->panel_mode & MDP4_PANEL_DTV) mdp4_dtv_pipe_queue(0, pipe);/* cndx = 0 */ } else if (pipe->mixer_num == MDP4_MIXER2) { ctrl->mixer2_played++; if (ctrl->panel_mode & <API key>) mdp4_wfd_pipe_queue(0, pipe);/* cndx = 0 */ } if (!(pipe->flags & MDP_OV_PLAY_NOWAIT)) mdp4_iommu_unmap(pipe); mdp4_stat.overlay_play[pipe->mixer_num]++; end: mutex_unlock(&mfd->dma->ov_mutex); return ret; } int mdp4_overlay_commit(struct fb_info *info) { int ret = 0, release_busy = true; struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; int mixer; if (mfd == NULL) { ret = -ENODEV; goto <API key>; } if (!mfd->panel_power_on) { ret = -EINVAL; goto <API key>; } mixer = mfd->panel_info.pdest; /* DISPLAY_1 or DISPLAY_2 */ if (mixer >= MDP4_MIXER_MAX) return -EPERM; mutex_lock(&mfd->dma->ov_mutex); <API key>(mfd); switch (mfd->panel.type) { case MIPI_CMD_PANEL: <API key>(0, 1, &release_busy); break; case MIPI_VIDEO_PANEL: <API key>(0, 1); break; case LCDC_PANEL: <API key>(0, 1); break; case DTV_PANEL: <API key>(0, 1); break; case WRITEBACK_PANEL: <API key>(mfd, 0, 1); break; default: pr_err("Panel Not Supported for Commit"); ret = -EINVAL; break; } <API key>(mfd); <API key>(mfd); if (release_busy) mutex_unlock(&mfd->dma->ov_mutex); <API key>: if (release_busy) msm_fb_release_busy(mfd); return ret; } void <API key>(struct fb_info *info) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; <API key>(mfd, 0); } struct msm_iommu_ctx { char *name; int domain; }; static struct msm_iommu_ctx msm_iommu_ctx_names[] = { /* Display read*/ { .name = "mdp_port0_cb0", .domain = DISPLAY_READ_DOMAIN, }, /* Display read*/ { .name = "mdp_port0_cb1", .domain = DISPLAY_READ_DOMAIN, }, /* Display write */ { .name = "mdp_port1_cb0", .domain = DISPLAY_READ_DOMAIN, }, /* Display write */ { .name = "mdp_port1_cb1", .domain = DISPLAY_READ_DOMAIN, }, }; static struct msm_iommu_ctx <API key>[] = { /* Display read*/ { .name = "mdp_port0_cb0", .domain = DISPLAY_READ_DOMAIN, }, /* Display read*/ { .name = "mdp_port0_cb1", .domain = <API key>, }, /* Display write */ { .name = "mdp_port1_cb0", .domain = DISPLAY_READ_DOMAIN, }, /* Display write */ { .name = "mdp_port1_cb1", .domain = <API key>, }, }; void mdp4_iommu_attach(void) { static int done; struct msm_iommu_ctx *ctx_names; struct iommu_domain *domain; int i, arr_size; if (!done) { if (<API key>) { ctx_names = <API key>; arr_size = ARRAY_SIZE(<API key>); } else { ctx_names = msm_iommu_ctx_names; arr_size = ARRAY_SIZE(msm_iommu_ctx_names); } for (i = 0; i < arr_size; i++) { int domain_idx; struct device *ctx = msm_iommu_get_ctx( ctx_names[i].name); if (!ctx) continue; domain_idx = ctx_names[i].domain; domain = <API key>(domain_idx); if (!domain) continue; if (iommu_attach_device(domain, ctx)) { WARN(1, "%s: could not attach domain %d to context %s." " iommu programming will not occur.\n", __func__, domain_idx, ctx_names[i].name); continue; } } done = 1; } } int <API key>(struct fb_info *info, struct mdp_overlay *req, struct mdp4_overlay_pipe **ppipe) { struct mdp4_overlay_pipe *pipe; int err; struct msm_fb_data_type *mfb = info->par; req->z_order = 0; req->id = MSMFB_NEW_REQUEST; req->is_fg = false; req->alpha = 0xff; err = <API key>(req, MDP4_MIXER0, &pipe, mfb); if (err < 0) { pr_err("%s:Could not allocate MDP overlay pipe\n", __func__); return err; } <API key>(pipe->mixer_num); *ppipe = pipe; return 0; } void <API key>(struct mdp4_overlay_pipe *pipe) { <API key>(pipe, 1); <API key>(pipe, 1); <API key>(pipe, 1); } int <API key>(struct fb_info *info, struct mdp4_overlay_pipe *pipe, unsigned long srcp0_addr, unsigned long srcp1_addr, unsigned long srcp2_addr) { struct msm_fb_data_type *mfd = info->par; int err; if (<API key>(&mfd->dma->ov_mutex)) return -EINTR; switch (pipe->src_format) { case MDP_Y_CR_CB_H2V2: /* YUV420 */ pipe->srcp0_addr = srcp0_addr; pipe->srcp0_ystride = pipe->src_width; /* * For YUV420, the luma plane is 1 byte per pixel times * num of pixels in the image Also, the planes are * switched in MDP, srcp2 is actually first chroma plane */ pipe->srcp2_addr = srcp1_addr ? srcp1_addr : pipe->srcp0_addr + (pipe->src_width * pipe->src_height); pipe->srcp2_ystride = pipe->src_width/2; /* * The chroma planes are half the size of the luma * planes */ pipe->srcp1_addr = srcp2_addr ? srcp2_addr : pipe->srcp2_addr + (pipe->src_width * pipe->src_height / 4); pipe->srcp1_ystride = pipe->src_width/2; break; case MDP_Y_CRCB_H2V2: /* NV12 */ pipe->srcp0_addr = srcp0_addr; pipe->srcp0_ystride = pipe->src_width; pipe->srcp1_addr = srcp1_addr ? srcp1_addr : pipe->srcp0_addr + (pipe->src_width * pipe->src_height); pipe->srcp1_ystride = pipe->src_width; break; default: pr_err("%s: format (%u) is not supported\n", __func__, pipe->src_format); err = -EINVAL; goto done; } pr_debug("%s: pipe ndx=%d stage=%d format=%x\n", __func__, pipe->pipe_ndx, pipe->mixer_stage, pipe->src_format); if (pipe->pipe_type == OVERLAY_TYPE_VIDEO) <API key>(pipe); else <API key>(pipe); if (ctrl->panel_mode & MDP4_PANEL_LCDC) <API key>(pipe, 1); mdp4_mixer_stage_up(pipe, 0); /* mixer stage commit commits this */ <API key>(pipe->mixer_num); #ifdef V4L2_VSYNC /* * TODO: incorporate v4l2 into vsycn driven mechanism */ if (ctrl->panel_mode & MDP4_PANEL_LCDC) { <API key>(mfd, pipe); } else { #ifdef <API key> if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) { <API key>(mfd); <API key>(mfd, pipe); } #else if (ctrl->panel_mode & MDP4_PANEL_MDDI) { <API key>(mfd); <API key>(mfd, pipe); } #endif } #endif done: mutex_unlock(&mfd->dma->ov_mutex); return err; } int mdp4_overlay_reset() { memset(&perf_request, 0, sizeof(perf_request)); memset(&perf_current, 0, sizeof(perf_current)); return 0; }
<?php /** * Collector event * * @author Sergey Kambalin <greyexpert@gmail.com> * @package ow_system_plugins.base.bol * @since 1.0 */ class <API key> extends OW_Event { public function __construct( $name, $params = array() ) { parent::__construct($name, $params); $this->data = array(); } public function add( $item ) { $this->data[] = $item; } public function setData( $data ) { throw new LogicException("Can't set data in collector event `" . $this->getName() . "`!"); } }
package org.mo.game.editor.face.apl.logic.report; import org.mo.jfa.common.page.FAbstractFormPage; public class FWebReportPage extends FAbstractFormPage{ private static final long serialVersionUID = 1L; private String _tempName; public String getTempName(){ return _tempName; } public void setTempName(String tempName){ _tempName = tempName; } }
import xml.etree.ElementTree as ET import requests from flask import Flask import batalha import pokemon import ataque class Cliente: def __init__(self, execute = False, ip = '127.0.0.1', port = 5000, npc = False): self.ip = ip self.port = port self.npc = npc if (execute): self.iniciaBatalha() def writeXML(self, pkmn): #Escreve um XML a partir de um pokemon root = ET.Element('battle_state') ET.SubElement(root, "pokemon") poke = root.find('pokemon') ET.SubElement(poke, "name") poke.find('name').text = pkmn.getNome() ET.SubElement(poke, "level") poke.find('level').text = str(pkmn.getLvl()) ET.SubElement(poke, "attributes") poke_att = poke.find('attributes') ET.SubElement(poke_att, "health") poke_att.find('health').text = str(pkmn.getHp()) ET.SubElement(poke_att, "attack") poke_att.find('attack').text = str(pkmn.getAtk()) ET.SubElement(poke_att, "defense") poke_att.find('defense').text = str(pkmn.getDefe()) ET.SubElement(poke_att, "speed") poke_att.find('speed').text = str(pkmn.getSpd()) ET.SubElement(poke_att, "special") poke_att.find('special').text = str(pkmn.getSpc()) ET.SubElement(poke, "type") ET.SubElement(poke, "type") tipos = poke.findall('type') tipos[0].text = str(pkmn.getTyp1()) tipos[1].text = str(pkmn.getTyp2()) for i in range(0, 4): atk = pkmn.getAtks(i) if (atk is not None): ET.SubElement(poke, "attacks") poke_atk = poke.findall('attacks') ET.SubElement(poke_atk[-1], "id") poke_atk[-1].find('id').text = str(i + 1) ET.SubElement(poke_atk[-1], "name") poke_atk[-1].find('name').text = atk.getNome() ET.SubElement(poke_atk[-1], "type") poke_atk[-1].find('type').text = str(atk.getTyp()) ET.SubElement(poke_atk[-1], "power") poke_atk[-1].find('power').text = str(atk.getPwr()) ET.SubElement(poke_atk[-1], "accuracy") poke_atk[-1].find('accuracy').text = str(atk.getAcu()) ET.SubElement(poke_atk[-1], "power_points") poke_atk[-1].find('power_points').text = str(atk.getPpAtual()) s = ET.tostring(root) return s def iniciaBatalha(self): pkmn = pokemon.Pokemon() xml = self.writeXML(pkmn) try: self.battle_state = requests.post('http://{}:{}/battle/'.format(self.ip, self.port), data = xml).text except requests.exceptions.ConnectionError: print("Não foi possível conectar ao servidor.") return None pkmn2 = pokemon.lePokemonXML(1, self.battle_state) self.batalha = batalha.Batalha([pkmn, pkmn2]) if (self.npc): self.batalha.pkmn[0].npc = True print("Eu sou um NPC") self.batalha.turno = 0 self.batalha.display.showPokemon(self.batalha.pkmn[0]) self.batalha.display.showPokemon(self.batalha.pkmn[1]) return self.atualizaBatalha() def atualizaBatalha(self): self.batalha.AlternaTurno() root = ET.fromstring(self.battle_state) for i in range(0,2): pkmnXML = root[i] atksXML = root[i].findall('attacks') pkmn = self.batalha.pkmn[i] pkmn.setHpAtual(int(pkmnXML.find('attributes').find('health').text)) self.batalha.showStatus() if (not self.batalha.isOver()): self.batalha.AlternaTurno() if (self.batalha.pkmn[self.batalha.turno].npc): id = self.batalha.<API key>() else: id = self.batalha.EscolheAtaque() self.batalha.pkmn[0].getAtks(id).decreasePp() if (id == 4): self.battle_state = requests.post('http://{}:{}/battle/attack/{}'.format(self.ip, self.port, 0)).text else: self.battle_state = requests.post('http://{}:{}/battle/attack/{}'.format(self.ip, self.port, id + 1)).text self.simulaAtaque(id) self.atualizaBatalha() else: self.batalha.showResults() return 'FIM' def sendShutdownSignal(self): requests.post('http://{}:{}/shutdown'.format(self.ip, self.port)) def simulaAtaque(self, idCliente): disp = self.batalha.display root = ET.fromstring(self.battle_state) pkmnCXML = root[0] pkmnC = self.batalha.pkmn[0] pkmnSXML = root[1] pkmnS = self.batalha.pkmn[1] atksXML = pkmnSXML.findall('attacks') idServidor = self.descobreAtaqueUsado(atksXML, pkmnS) if (int(pkmnSXML.find('attributes').find('health').text) > 0): if (idCliente != 4): if (idServidor != 4): dmg = pkmnS.getHpAtual() - int(pkmnSXML.find('attributes').find('health').text) if (dmg == 0): disp.miss(pkmnC, pkmnS, pkmnC.getAtks(idCliente)) else: disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idCliente), dmg) dmg = pkmnC.getHpAtual() - int(pkmnCXML.find('attributes').find('health').text) if (dmg == 0): disp.miss(pkmnS, pkmnC, pkmnS.getAtks(idServidor)) else: disp.hit(pkmnS, pkmnC, pkmnS.getAtks(idServidor), dmg) else: dmgStruggle = pkmnC.getHpAtual() - int(pkmnCXML.find('attributes').find('health').text) dmg = pkmnS.getHpAtual() - int(pkmnSXML.find('attributes').find('health').text) + round(dmgStruggle / 2, 0) if (dmg == 0): disp.miss(pkmnC, pkmnS, pkmnC.getAtks(idCliente)) else: disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idCliente), dmg) disp.hit(pkmnS, pkmnC, pkmnS.getAtks(idServidor), dmgStruggle) disp.hitSelf(pkmnS, round(dmgStruggle / 2, 0)) else: if (idServidor != 4): dmgStruggle = pkmnS.getHpAtual() - int(pkmnSXML.find('attributes').find('health').text) disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idCliente), dmgStruggle) disp.hitSelf(pkmnC, round(dmgStruggle / 2, 0)) dmg = pkmnC.getHpAtual() - int(pkmnCXML.find('attributes').find('health').text) + round(dmgStruggle / 2, 0) if (dmg == 0): disp.miss(pkmnS, pkmnC, pkmnS.getAtks(idServidor)) else: disp.hit(pkmnS, pkmnC, pkmnS.getAtks(idServidor), dmg) else: print('Ambos usam e se machucam com Struggle!') else: if (idCliente != 4): dmg = pkmnS.getHpAtual() - int(pkmnSXML.find('attributes').find('health').text) if (dmg == 0): disp.miss(pkmnC, pkmnS, pkmnC.getAtks(idCliente)) else: disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idCliente), dmg) else: dmgStruggle = pkmnC.getHpAtual() - int(pkmnCXML.find('attributes').find('health').text) disp.hit(pkmnC, pkmnS, pkmnC.getAtks(idServidor), dmgStruggle * 2) disp.hitSelf(pkmnC, round(dmgStruggle, 0)) def descobreAtaqueUsado(self, atksXML, pkmn): for i in range(0, len(atksXML)): id = int(atksXML[i].find('id').text) - 1 ppXML = int(atksXML[i].find('power_points').text) pp = pkmn.getAtks(id).getPpAtual() if (pp != ppXML): pkmn.getAtks(id).decreasePp() return id return id
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; using System.Threading; using System.Net; using System.Collections; using System.Web; using System.Xml; using System.Reflection; using Microsoft.Win32; using System.Globalization; using Microsoft.FlightSimulator.SimConnect; using System.Runtime.InteropServices; namespace <API key> { public partial class Form1 : Form { #region Global Variables bool bErrorOnLoad = false; Form2 frmAdd = new Form2(); String szAppPath = ""; //String szCommonPath = ""; String szUserAppPath = ""; String szFilePathPub = ""; String szFilePathData = ""; String szServerPath = ""; IPAddress[] ipalLocal1 = null; IPAddress[] ipalLocal2 = null; System.Object lockIPAddressList = new System.Object(); string /* szPathGE , */ szPathFSX; const string szRegKeyRun = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"; //const int <API key> = 64; //WebRequest <API key>; //WebResponse <API key>; //private byte[] <API key> = new byte[<API key>]; //String <API key> = ""; XmlTextReader xmlrSeetingsFile; XmlTextWriter xmlwSeetingsFile; XmlDocument xmldSettings; <API key> gconffixCurrent = new <API key>(); <API key> gconfchCurrent; System.Object lockChConf = new System.Object(); bool bClose = false; bool bConnected = false; //bool bServerUp = false; bool bRestartRequired = false; const int WM_USER_SIMCONNECT = 0x0402; SimConnect simconnect = null; Icon icActive, icDisabled, icReceive; Image imgAtcLabel; HttpListener listener; System.Object lockListenerControl = new System.Object(); uint uiUserAircraftID = 0; bool bUserAircraftIDSet = false; System.Object lockUserAircraftID = new System.Object(); <API key> suadCurrent; System.Object lockKmlUserAircraft = new System.Object(); String <API key> = ""; System.Object lockKmlUserPath = new System.Object(); PathPosition ppPos1, ppPos2; String szKmlUserPrediction = ""; List<PathPositionStored> <API key>; System.Object <API key> = new System.Object(); System.Object <API key> = new System.Object(); DataRequestReturn drrAIPlanes; System.Object lockDrrAiPlanes = new System.Object(); DataRequestReturn drrAIHelicopters; System.Object <API key> = new System.Object(); DataRequestReturn drrAIBoats; System.Object lockDrrAiBoats = new System.Object(); DataRequestReturn drrAIGround; System.Object lockDrrAiGround = new System.Object(); List<ObjectImage> listIconsGE; List<ObjectImage> listImgUnitsAir, listImgUnitsWater, listImgUnitsGround; //List<FlightPlan> listFlightPlans; //System.Object lockFlightPlanList = new System.Object(); byte[] imgNoImage; #endregion #region Structs & Enums enum DEFINITIONS { <API key>, }; enum DATA_REQUESTS { <API key>, REQUEST_USER_PATH, <API key>, <API key>, REQUEST_AI_PLANE, REQUEST_AI_BOAT, REQUEST_AI_GROUND }; enum KML_FILES { <API key>, REQUEST_USER_PATH, <API key>, <API key>, REQUEST_AI_PLANE, REQUEST_AI_BOAT, REQUEST_AI_GROUND, <API key> }; enum KML_ACCESS_MODES { MODE_SERVER, MODE_FILE_LOCAL, <API key> }; enum KML_IMAGE_TYPES { AIRCRAFT, WATER, GROUND }; enum KML_ICON_TYPES { <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, AI_AIRCRAFT, AI_HELICOPTER, AI_BOAT, AI_GROUND_UNIT, PLAN_VOR, PLAN_NDB, PLAN_USER, PLAN_PORT, PLAN_INTER, ATC_LABEL, UNKNOWN }; [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] struct <API key> { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public String szTitle; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public String szATCType; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public String szATCModel; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public String szATCID; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] public String szATCAirline; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public String szATCFlightNumber; public double dLatitude; public double dLongitude; public double dAltitude; public double dSpeed; public double dVSpeed; //public double dSpeedX; //public double dSpeedY; //public double dSpeedZ; public double dTime; }; struct DataRequestReturn { public List<<API key>> listFirst; public List<<API key>> listSecond; public uint uiLastEntryNumber; public uint uiCurrentDataSet; public bool bClearOnNextRun; }; struct <API key> { public uint uiObjectID; public <API key> bmsoObject; public String szCoursePrediction; public PathPositionStored[] ppsPredictionPoints; } struct PathPosition { public bool bInitialized; public double dLat; public double dLong; public double dAlt; public double dTime; } struct PathPositionStored { public double dLat; public double dLong; public double dAlt; public double dTime; } struct ObjectImage { public String szTitle; public String szPath; public byte[] bData; }; class <API key> { public bool bLoadKMLFile; //public bool bCheckForUpdates; public long iServerPort; public uint uiServerAccessLevel; public String szUserdefinedPath; public bool bQueryUserAircraft; public long iTimerUserAircraft; public bool bQueryUserPath; public long iTimerUserPath; public bool bUserPathPrediction; public long <API key>; public double[] dPredictionTimes; public bool bQueryAIObjects; public bool bQueryAIAircrafts; public long iTimerAIAircrafts; public long iRangeAIAircrafts; public bool bPredictAIAircrafts; public bool <API key>; public bool bQueryAIHelicopters; public long iTimerAIHelicopters; public long iRangeAIHelicopters; public bool <API key>; public bool <API key>; public bool bQueryAIBoats; public long iTimerAIBoats; public long iRangeAIBoats; public bool bPredictAIBoats; public bool <API key>; public bool bQueryAIGroundUnits; public long iTimerAIGroundUnits; public long iRangeAIGroundUnits; public bool <API key>; public bool <API key>; public long <API key>; public long iUpdateGEUserPath; public long <API key>; public long <API key>; public long <API key>; public long iUpdateGEAIBoats; public long <API key>; public bool <API key>; public String <API key>; public String szFsxConnectionHost; public String szFsxConnectionPort; public bool bExitOnFsxExit; private Object lock_utUnits = new Object(); private UnitType priv_utUnits; public UnitType utUnits { get { lock (lock_utUnits) { return priv_utUnits; } } set { lock (lock_utUnits) { priv_utUnits = value; } } } //public bool bLoadFlightPlans; }; struct <API key> { public bool bEnabled; public bool bShowBalloons; }; struct <API key> { public double dTime; public override String ToString() { if (dTime < 60) return "ETA " + dTime + " sec"; else if (dTime < 3600) return "ETA " + Math.Round(dTime / 60.0, 1) + " min"; else return "ETA " + Math.Round(dTime / 3600.0, 2) + " hrs"; } } enum UnitType { METERS, FEET }; //struct <API key> // public String szName; // public int iID; // public override String ToString() // return szName.ToString(); //struct FlightPlan // public int uiID; // public String szName; // public XmlDocument xmldPlan; #endregion #region Form Functions public Form1() { //As this method doesn't start any other threads we don't need to lock anything here (especially not the config file xml document) InitializeComponent(); Text = AssemblyTitle; thrConnect = new Thread(new ThreadStart(<API key>)); text = Text; // Set data for the about page this.labelProductName.Text = AssemblyProduct; this.labelVersion.Text = String.Format("Version {0}", AssemblyVersion); this.labelCopyright.Text = AssemblyCopyright; this.labelCompanyName.Text = AssemblyCompany; // Set file path #if DEBUG szAppPath = Application.StartupPath + "\\..\\.."; szUserAppPath = szAppPath + "\\AppData\\" + AssemblyVersion; #else szAppPath = Application.StartupPath; szUserAppPath = Application.UserAppDataPath; #endif szFilePathPub = szAppPath + "\\pub"; szFilePathData = szAppPath + "\\data"; // Check if config file for current user exists if (!File.Exists(szUserAppPath + "\\settings.cfg")) { if (!Directory.Exists(szUserAppPath)) Directory.CreateDirectory(szUserAppPath); File.Copy(szAppPath + "\\data\\settings.default", szUserAppPath + "\\settings.cfg"); File.SetAttributes(szUserAppPath + "\\settings.cfg", FileAttributes.Normal); } // Load config file into memory xmlrSeetingsFile = new XmlTextReader(szUserAppPath + "\\settings.cfg"); xmldSettings = new XmlDocument(); xmldSettings.PreserveWhitespace = true; xmldSettings.Load(xmlrSeetingsFile); xmlrSeetingsFile.Close(); xmlrSeetingsFile = null; // Make sure we have a config file for the right version // (future version should contain better checks and update from old config files to new version) String szConfigVersion = ""; bool bUpdate = false; try { szConfigVersion = xmldSettings["fsxget"]["settings"].Attributes["version"].Value; } catch { bUpdate = true; } if (bUpdate || !szConfigVersion.Equals(ProductVersion.ToLower())) { try { File.SetAttributes(szUserAppPath + "\\settings.cfg", FileAttributes.Normal); File.Delete(szUserAppPath + "\\settings.cfg"); File.Copy(szAppPath + "\\data\\settings.default", szUserAppPath + "\\settings.cfg"); File.SetAttributes(szUserAppPath + "\\settings.cfg", FileAttributes.Normal); xmlrSeetingsFile = new XmlTextReader(szUserAppPath + "\\settings.cfg"); xmldSettings = new XmlDocument(); xmldSettings.PreserveWhitespace = true; xmldSettings.Load(xmlrSeetingsFile); xmlrSeetingsFile.Close(); xmlrSeetingsFile = null; xmldSettings["fsxget"]["settings"].Attributes["version"].Value = ProductVersion; } catch { MessageBox.Show("The config file for this program cannot be updated. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); bErrorOnLoad = true; return; } } // Mirror values we need from config file in memory to variables try { <API key>(); } catch { MessageBox.Show("The config file for this program contains errors. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); bErrorOnLoad = true; return; } // Write SimConnect configuration file try { File.Delete(szAppPath + "\\SimConnect.cfg"); } catch { } if (!gconffixCurrent.<API key>) { try { StreamWriter swSimConnectCfg = File.CreateText(szAppPath + "\\SimConnect.cfg"); swSimConnectCfg.WriteLine("; FSXGET SimConnect client configuration"); swSimConnectCfg.WriteLine(); swSimConnectCfg.WriteLine("[SimConnect]"); swSimConnectCfg.WriteLine("Protocol=" + gconffixCurrent.<API key>); swSimConnectCfg.WriteLine("Address=" + gconffixCurrent.szFsxConnectionHost); swSimConnectCfg.WriteLine("Port=" + gconffixCurrent.szFsxConnectionPort); swSimConnectCfg.WriteLine(); swSimConnectCfg.Flush(); swSimConnectCfg.Close(); swSimConnectCfg.Dispose(); } catch { MessageBox.Show("The SimConnect client configuration file could not be written. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); bErrorOnLoad = true; return; } } // Update the notification icon context menu lock (lockChConf) { <API key>.Checked = gconfchCurrent.bEnabled; <API key>.Checked = gconfchCurrent.bShowBalloons; } // Set timer intervals timerFSXConnect.Interval = 1500; <API key>.Interval = (int)gconffixCurrent.iTimerUserAircraft; timerQueryUserPath.Interval = (int)gconffixCurrent.iTimerUserPath; timerUserPrediction.Interval = (int)gconffixCurrent.<API key>; <API key>.Interval = (int)gconffixCurrent.iTimerAIAircrafts; <API key>.Interval = (int)gconffixCurrent.iTimerAIHelicopters; timerQueryAIBoats.Interval = (int)gconffixCurrent.iTimerAIBoats; <API key>.Interval = (int)gconffixCurrent.iTimerAIGroundUnits; <API key>.Interval = 10000; // Set server settings szServerPath = "http://+:" + gconffixCurrent.iServerPort.ToString(); listener = new HttpListener(); listener.Prefixes.Add(szServerPath + "/"); // Lookup (in the config file) and load program icons, google earth pins and object images try { // notification icons for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["program"]["icons"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.NodeType == XmlNodeType.Whitespace) continue; if (xmlnTemp.Attributes["Name"].Value == "Taskbar - Enabled") icActive = new Icon(szFilePathData + xmlnTemp.Attributes["Img"].Value); else if (xmlnTemp.Attributes["Name"].Value == "Taskbar - Disabled") icDisabled = new Icon(szFilePathData + xmlnTemp.Attributes["Img"].Value); else if (xmlnTemp.Attributes["Name"].Value == "Taskbar - Connected") icReceive = new Icon(szFilePathData + xmlnTemp.Attributes["Img"].Value); } notifyIconMain.Icon = icDisabled; notifyIconMain.Text = this.Text; notifyIconMain.Visible = true; // google earth icons listIconsGE = new List<ObjectImage>(xmldSettings["fsxget"]["gfx"]["ge"]["icons"].ChildNodes.Count); for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["ge"]["icons"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.NodeType == XmlNodeType.Whitespace) continue; ObjectImage imgTemp = new ObjectImage(); imgTemp.szTitle = xmlnTemp.Attributes["Name"].Value; imgTemp.bData = File.ReadAllBytes(szFilePathPub + xmlnTemp.Attributes["Img"].Value); listIconsGE.Add(imgTemp); } // no-image image imgNoImage = File.ReadAllBytes(szFilePathPub + xmldSettings["fsxget"]["gfx"]["scenery"]["noimage"].Attributes["Img"].Value); // ATC label base image imgAtcLabel = Image.FromFile(szFilePathData + xmldSettings["fsxget"]["gfx"]["ge"]["atclabel"].Attributes["Img"].Value); // object images listImgUnitsAir = new List<ObjectImage>(xmldSettings["fsxget"]["gfx"]["scenery"]["air"].ChildNodes.Count); for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["scenery"]["air"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.NodeType == XmlNodeType.Whitespace) continue; ObjectImage imgTemp = new ObjectImage(); imgTemp.szTitle = xmlnTemp.Attributes["Name"].Value; imgTemp.szPath = xmlnTemp.Attributes["Img"].Value; imgTemp.bData = File.ReadAllBytes(szFilePathPub + xmlnTemp.Attributes["Img"].Value); listImgUnitsAir.Add(imgTemp); } listImgUnitsWater = new List<ObjectImage>(xmldSettings["fsxget"]["gfx"]["scenery"]["water"].ChildNodes.Count); for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["scenery"]["water"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.NodeType == XmlNodeType.Whitespace) continue; ObjectImage imgTemp = new ObjectImage(); imgTemp.szTitle = xmlnTemp.Attributes["Name"].Value; imgTemp.szPath = xmlnTemp.Attributes["Img"].Value; imgTemp.bData = File.ReadAllBytes(szFilePathPub + xmlnTemp.Attributes["Img"].Value); listImgUnitsWater.Add(imgTemp); } listImgUnitsGround = new List<ObjectImage>(xmldSettings["fsxget"]["gfx"]["scenery"]["ground"].ChildNodes.Count); for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["scenery"]["ground"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.NodeType == XmlNodeType.Whitespace) continue; ObjectImage imgTemp = new ObjectImage(); imgTemp.szTitle = xmlnTemp.Attributes["Name"].Value; imgTemp.szPath = xmlnTemp.Attributes["Img"].Value; imgTemp.bData = File.ReadAllBytes(szFilePathPub + xmlnTemp.Attributes["Img"].Value); listImgUnitsWater.Add(imgTemp); } } catch { MessageBox.Show("Could not load all graphics files probably due to errors in the config file. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); bErrorOnLoad = true; return; } // Initialize some variables clearDrrStructure(ref drrAIPlanes); clearDrrStructure(ref drrAIHelicopters); clearDrrStructure(ref drrAIBoats); clearDrrStructure(ref drrAIGround); clearPPStructure(ref ppPos1); clearPPStructure(ref ppPos2); //listFlightPlans = new List<FlightPlan>(); <API key> = new List<PathPositionStored>(gconffixCurrent.dPredictionTimes.GetLength(0)); // Test drive the following function which loads data from the config file, as it will be used regularly later on try { ConfigMirrorToForm(); } catch { MessageBox.Show("The config file for this program contains errors. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); bErrorOnLoad = true; return; } // Load FSX and Google Earth path from registry const string szRegKeyFSX = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft Games\\flight simulator\\10.0"; //const string szRegKeyGE = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Google\\Google Earth Plus"; //const string szRegKeyGE2 = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Google\\Google Earth Pro"; //szPathGE = (string)Registry.GetValue(szRegKeyGE, "InstallDir", ""); //if (szPathGE == "") // szPathGE = (string)Registry.GetValue(szRegKeyGE2, "InstallDir", ""); szPathFSX = (string)Registry.GetValue(szRegKeyFSX, "SetupPath", ""); //if (szPathGE != "") // szPathGE += "\\googleearth.exe"; // if (File.Exists(szPathGE)) // <API key>.Enabled = true; // else // <API key>.Enabled = false; //else // <API key>.Enabled = false; <API key>.Enabled = true; if (szPathFSX != "") { szPathFSX += "fsx.exe"; if (File.Exists(szPathFSX)) <API key>.Enabled = true; else <API key>.Enabled = false; } else <API key>.Enabled = false; // Write Google Earth startup KML file String szTempKMLFile = ""; String szTempKMLFileStatic = ""; if (<API key>("localhost", ref szTempKMLFile) && <API key>("localhost", ref szTempKMLFileStatic)) { try { if (!Directory.Exists(szUserAppPath + "\\pub")) Directory.CreateDirectory(szUserAppPath + "\\pub"); File.WriteAllText(szUserAppPath + "\\pub\\fsxgetd.kml", szTempKMLFile); File.WriteAllText(szUserAppPath + "\\pub\\fsxgets.kml", szTempKMLFileStatic); } catch { MessageBox.Show("Could not write KML file for google earth. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); bErrorOnLoad = true; return; } } else { MessageBox.Show("Could not write KML file for google earth. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); bErrorOnLoad = true; return; } // Init some never-changing form fields textBoxLocalPubPath.Text = szFilePathPub; // Load flight plans //if (gconffixCurrent.bLoadFlightPlans) // LoadFlightPlans(); // Online Update Check //if (gconffixCurrent.bCheckForUpdates) // <API key>(); } private void Form1_Load(object sender, EventArgs e) { if (bErrorOnLoad) return; } private void Form1_Shown(object sender, EventArgs e) { if (bErrorOnLoad) { bClose = true; Close(); } else { Hide(); lock (lockListenerControl) { listener.Start(); listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener); //bServerUp = true; } globalConnect(); } } private void Form1_FormClosing(object sender, <API key> e) { if (!bClose) { e.Cancel = true; safeHideMainDialog(); } } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { if (bErrorOnLoad) return; notifyIconMain.ContextMenuStrip = null; // Save xml document in memory to config file on disc xmlwSeetingsFile = new XmlTextWriter(szUserAppPath + "\\settings.cfg", null); xmldSettings.PreserveWhitespace = true; xmldSettings.Save(xmlwSeetingsFile); xmlwSeetingsFile.Flush(); xmlwSeetingsFile.Close(); xmldSettings = null; // Disconnect with FSX lock (lockChConf) { gconfchCurrent.bEnabled = false; } globalDisconnect(); // Stop server lock (lockListenerControl) { //bServerUp = false; listener.Stop(); listener.Abort(); <API key>.Stop(); } // Delete temporary KML file if (File.Exists(szFilePathPub + "\\fsxget.kml")) { try { File.Delete(szFilePathPub + "\\fsxget.kml"); } catch { } } if (File.Exists(szAppPath + "\\SimConnect.cfg")) { try { File.Delete(szAppPath + "\\SimConnect.cfg"); } catch { } } } protected override void DefWndProc(ref Message m) { if (m.Msg == WM_USER_SIMCONNECT) { if (simconnect != null) { try { simconnect.ReceiveMessage(); } catch { #if DEBUG safeShowBalloonTip(3, "Error", "Error receiving data from FSX!", ToolTipIcon.Error); #endif } } } else base.DefWndProc(ref m); } #endregion #region FSX Connection Object lock_ConnectThread = new Object(); String text; public void <API key>() { while (simconnect == null) { try { simconnect = new SimConnect(text, IntPtr.Zero, WM_USER_SIMCONNECT, null, 0); } catch { } if (simconnect == null) Thread.Sleep(2000); } } private bool openConnection() { if (thrConnect.ThreadState == ThreadState.Unstarted) { thrConnect.Start(); return false; } else if (thrConnect.ThreadState == ThreadState.Stopped) { if (simconnect != null) { try { simconnect.Dispose(); simconnect = null; simconnect = new SimConnect(Text, this.Handle, WM_USER_SIMCONNECT, null, 0); } catch { return false; } if (initDataRequest()) return true; else { simconnect = null; return false; } } else { thrConnect = new Thread(new ThreadStart(<API key>)); thrConnect.Start(); return false; } } else return false; } private void closeConnection() { if (simconnect != null) { simconnect.Dispose(); simconnect = null; } } private bool initDataRequest() { try { // listen to connect and quit msgs simconnect.OnRecvOpen += new SimConnect.<API key>(<API key>); simconnect.OnRecvQuit += new SimConnect.<API key>(<API key>); // listen to exceptions simconnect.OnRecvException += new SimConnect.<API key>(<API key>); // define a data structure simconnect.AddToDataDefinition(DEFINITIONS.<API key>, "Title", null, SIMCONNECT_DATATYPE.STRING256, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.<API key>, "ATC Type", null, SIMCONNECT_DATATYPE.STRING32, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.<API key>, "ATC Model", null, SIMCONNECT_DATATYPE.STRING32, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.<API key>, "ATC ID", null, SIMCONNECT_DATATYPE.STRING32, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.<API key>, "ATC Airline", null, SIMCONNECT_DATATYPE.STRING64, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.<API key>, "ATC Flight Number", null, SIMCONNECT_DATATYPE.STRING32, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.<API key>, "Plane Latitude", "degrees", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.<API key>, "Plane Longitude", "degrees", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.<API key>, "Plane Altitude", "meters", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.<API key>, "Ground Velocity", "knots", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.<API key>, "Velocity World Y", "meter per second", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED); //simconnect.AddToDataDefinition(DEFINITIONS.<API key>, "Velocity World X", "meter per second", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED); //simconnect.AddToDataDefinition(DEFINITIONS.<API key>, "Velocity World Y", "meter per second", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED); //simconnect.AddToDataDefinition(DEFINITIONS.<API key>, "Velocity World Z", "meter per second", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED); simconnect.AddToDataDefinition(DEFINITIONS.<API key>, "Absolute Time", "seconds", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED); // IMPORTANT: register it with the simconnect managed wrapper marshaller // if you skip this step, you will only receive a uint in the .dwData field. simconnect.<API key><<API key>>(DEFINITIONS.<API key>); // catch a simobject data request simconnect.<API key> += new SimConnect.<API key>(<API key>); return true; } catch (COMException ex) { safeShowBalloonTip(3000, Text, "FSX Exception!\n\n" + ex.Message, ToolTipIcon.Error); return false; } } void <API key>(SimConnect sender, <API key> data) { lock (lockUserAircraftID) { bUserAircraftIDSet = false; } if (gconffixCurrent.bQueryUserAircraft) <API key>.Start(); if (gconffixCurrent.bQueryUserPath) timerQueryUserPath.Start(); if (gconffixCurrent.bUserPathPrediction) timerUserPrediction.Start(); if (gconffixCurrent.bQueryAIObjects) { if (gconffixCurrent.bQueryAIAircrafts) <API key>.Start(); if (gconffixCurrent.bQueryAIHelicopters) <API key>.Start(); if (gconffixCurrent.bQueryAIBoats) timerQueryAIBoats.Start(); if (gconffixCurrent.bQueryAIGroundUnits) <API key>.Start(); } <API key>(null, null); <API key>.Start(); } void <API key>(SimConnect sender, SIMCONNECT_RECV data) { globalDisconnect(); if (gconffixCurrent.bExitOnFsxExit && isFsxStartActivated()) { bClose = true; Close(); } } void <API key>(SimConnect sender, <API key> data) { safeShowBalloonTip(3000, Text, "FSX Exception!", ToolTipIcon.Error); } void <API key>(SimConnect sender, <API key> data) { if (data.dwentrynumber == 0 && data.dwoutof == 0) return; <API key> drroTemp; drroTemp.bmsoObject = (<API key>)data.dwData[0]; drroTemp.uiObjectID = data.dwObjectID; drroTemp.szCoursePrediction = ""; drroTemp.ppsPredictionPoints = null; switch ((DATA_REQUESTS)data.dwRequestID) { case DATA_REQUESTS.<API key>: case DATA_REQUESTS.REQUEST_USER_PATH: case DATA_REQUESTS.<API key>: lock (lockUserAircraftID) { bUserAircraftIDSet = true; uiUserAircraftID = drroTemp.uiObjectID; } switch ((DATA_REQUESTS)data.dwRequestID) { case DATA_REQUESTS.<API key>: lock (lockKmlUserAircraft) { suadCurrent = drroTemp.bmsoObject; } break; case DATA_REQUESTS.REQUEST_USER_PATH: lock (lockKmlUserPath) { <API key> += drroTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + drroTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + drroTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "\n"; } break; case DATA_REQUESTS.<API key>: lock (<API key>) { if (!ppPos1.bInitialized) { ppPos1.dLong = drroTemp.bmsoObject.dLongitude; ppPos1.dLat = drroTemp.bmsoObject.dLatitude; ppPos1.dAlt = drroTemp.bmsoObject.dAltitude; ppPos1.dTime = drroTemp.bmsoObject.dTime; ppPos1.bInitialized = true; return; } else { if (!ppPos2.bInitialized) { ppPos2.dLong = drroTemp.bmsoObject.dLongitude; ppPos2.dLat = drroTemp.bmsoObject.dLatitude; ppPos2.dAlt = drroTemp.bmsoObject.dAltitude; ppPos2.dTime = drroTemp.bmsoObject.dTime; ppPos2.bInitialized = true; } else { ppPos1 = ppPos2; ppPos2.dLong = drroTemp.bmsoObject.dLongitude; ppPos2.dLat = drroTemp.bmsoObject.dLatitude; ppPos2.dAlt = drroTemp.bmsoObject.dAltitude; ppPos2.dTime = drroTemp.bmsoObject.dTime; //ppPos2.bInitialized = true; } } if (ppPos1.dTime != ppPos2.dTime && ppPos1.bInitialized && ppPos2.bInitialized) { lock (<API key>) { szKmlUserPrediction = drroTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + drroTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + drroTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "\n"; <API key>.Clear(); for (uint n = 0; n < gconffixCurrent.dPredictionTimes.GetLength(0); n++) { double dLongNew = 0.0, dLatNew = 0.0, dAltNew = 0.0; calcPositionByTime(ref ppPos1, ref ppPos2, gconffixCurrent.dPredictionTimes[n], ref dLatNew, ref dLongNew, ref dAltNew); PathPositionStored ppsTemp; ppsTemp.dLat = dLatNew; ppsTemp.dLong = dLongNew; ppsTemp.dAlt = dAltNew; ppsTemp.dTime = gconffixCurrent.dPredictionTimes[n]; <API key>.Add(ppsTemp); szKmlUserPrediction += dLongNew.ToString().Replace(",", ".") + "," + dLatNew.ToString().Replace(",", ".") + "," + dAltNew.ToString().Replace(",", ".") + "\n"; } } } } break; } break; case DATA_REQUESTS.REQUEST_AI_PLANE: case DATA_REQUESTS.<API key>: case DATA_REQUESTS.REQUEST_AI_BOAT: case DATA_REQUESTS.REQUEST_AI_GROUND: lock (lockUserAircraftID) { if (bUserAircraftIDSet && (drroTemp.uiObjectID == uiUserAircraftID)) return; } switch ((DATA_REQUESTS)data.dwRequestID) { case DATA_REQUESTS.REQUEST_AI_PLANE: <API key>(data.dwentrynumber, data.dwoutof, ref drrAIPlanes, ref lockDrrAiPlanes, ref drroTemp, gconffixCurrent.bPredictAIAircrafts, gconffixCurrent.<API key>); break; case DATA_REQUESTS.<API key>: <API key>(data.dwentrynumber, data.dwoutof, ref drrAIHelicopters, ref <API key>, ref drroTemp, gconffixCurrent.<API key>, gconffixCurrent.<API key>); break; case DATA_REQUESTS.REQUEST_AI_BOAT: <API key>(data.dwentrynumber, data.dwoutof, ref drrAIBoats, ref lockDrrAiBoats, ref drroTemp, gconffixCurrent.bPredictAIBoats, gconffixCurrent.<API key>); break; case DATA_REQUESTS.REQUEST_AI_GROUND: <API key>(data.dwentrynumber, data.dwoutof, ref drrAIGround, ref lockDrrAiGround, ref drroTemp, gconffixCurrent.<API key>, gconffixCurrent.<API key>); break; } break; default: #if DEBUG safeShowBalloonTip(3000, Text, "Received unknown data from FSX!", ToolTipIcon.Warning); #endif break; } } Thread thrConnect; private void globalConnect() { lock (lockChConf) { if (!gconfchCurrent.bEnabled) return; } notifyIconMain.Icon = icActive; notifyIconMain.Text = Text + "(Waiting for connection...)"; if (bConnected) return; lock (lockKmlUserAircraft) { <API key> = ""; uiUserAircraftID = 0; } if (!timerFSXConnect.Enabled) timerFSXConnect.Start(); } private void globalDisconnect() { if (bConnected) { bConnected = false; // Stop all query timers <API key>.Stop(); timerQueryUserPath.Stop(); timerUserPrediction.Stop(); <API key>.Stop(); <API key>.Stop(); timerQueryAIBoats.Stop(); <API key>.Stop(); closeConnection(); lock (lockChConf) { if (gconfchCurrent.bEnabled) safeShowBalloonTip(1000, Text, "Disconnected from FSX!", ToolTipIcon.Info); } } lock (lockChConf) { if (gconfchCurrent.bEnabled) { if (!timerFSXConnect.Enabled) { timerFSXConnect.Start(); notifyIconMain.Icon = icActive; notifyIconMain.Text = Text + "(Waiting for connection...)"; } } else { if (timerFSXConnect.Enabled) { timerFSXConnect.Stop(); thrConnect.Abort(); if (thrConnect.ThreadState != ThreadState.Unstarted) thrConnect.Join(); closeConnection(); } notifyIconMain.Icon = icDisabled; notifyIconMain.Text = Text + "(Disabled)"; } } } #endregion #region Helper Functions #region Old Version //void <API key>(uint entryNumber, uint entriesCount, ref DataRequestReturn <API key>, ref object relatedLock, ref <API key> receivedData, ref String processedData) // lock (relatedLock) // if (entryNumber <= <API key>.uiLastEntryNumber) // if (<API key>.uiCurrentDataSet == 1) // <API key>.szData2 = ""; // <API key>.uiCurrentDataSet = 2; // else // <API key>.szData1 = ""; // <API key>.uiCurrentDataSet = 1; // <API key>.uiLastEntryNumber = entryNumber; // if (<API key>.uiCurrentDataSet == 1) // <API key>.szData1 += processedData; // else // <API key>.szData2 += processedData; // if (entryNumber == entriesCount) // if (<API key>.uiCurrentDataSet == 1) // <API key>.szData2 = ""; // <API key>.uiCurrentDataSet = 2; // else // <API key>.szData1 = ""; // <API key>.uiCurrentDataSet = 1; // <API key>.uiLastEntryNumber = 0; #endregion void <API key>(uint entryNumber, uint entriesCount, ref DataRequestReturn <API key>, ref object relatedLock, ref <API key> receivedData, bool bCoursePrediction, bool bPredictionPoints) { lock (relatedLock) { // In case last data request return aborted unnormally and we're dealing with a new result, switch lists if (entryNumber <= <API key>.uiLastEntryNumber) { if (<API key>.uiCurrentDataSet == 1) <API key>.uiCurrentDataSet = 2; else <API key>.uiCurrentDataSet = 1; } List<<API key>> listCurrent = <API key>.uiCurrentDataSet == 1 ? <API key>.listFirst : <API key>.listSecond; List<<API key>> listOld = <API key>.uiCurrentDataSet == 1 ? <API key>.listSecond : <API key>.listFirst; // In case we have switched lists, clear new list and resize if necessary if (<API key>.bClearOnNextRun) { <API key>.bClearOnNextRun = false; listCurrent.Clear(); if (listCurrent.Capacity < entriesCount) listCurrent.Capacity = (int)((double)entriesCount * 1.1); } // Calculate course prediction if (bCoursePrediction) { foreach (<API key> drroTemp in listOld) { if (drroTemp.uiObjectID == receivedData.uiObjectID) { if (drroTemp.bmsoObject.dTime != receivedData.bmsoObject.dTime) { if (bPredictionPoints) receivedData.ppsPredictionPoints = new PathPositionStored[gconffixCurrent.dPredictionTimes.GetLength(0)]; receivedData.szCoursePrediction = receivedData.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + receivedData.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + receivedData.bmsoObject.dAltitude.ToString().Replace(",", ".") + "\n"; for (uint n = 0; n < gconffixCurrent.dPredictionTimes.GetLength(0); n++) { PathPosition ppOld, ppCurrent; double dLongNew = 0.0, dLatNew = 0.0, dAltNew = 0.0; ppOld.bInitialized = true; ppOld.dLat = drroTemp.bmsoObject.dLatitude; ppOld.dLong = drroTemp.bmsoObject.dLongitude; ppOld.dAlt = drroTemp.bmsoObject.dAltitude; ppOld.dTime = drroTemp.bmsoObject.dTime; ppCurrent.bInitialized = true; ppCurrent.dLat = receivedData.bmsoObject.dLatitude; ppCurrent.dLong = receivedData.bmsoObject.dLongitude; ppCurrent.dAlt = receivedData.bmsoObject.dAltitude; ppCurrent.dTime = receivedData.bmsoObject.dTime; calcPositionByTime(ref ppOld, ref ppCurrent, gconffixCurrent.dPredictionTimes[n], ref dLatNew, ref dLongNew, ref dAltNew); receivedData.szCoursePrediction += dLongNew.ToString().Replace(",", ".") + "," + dLatNew.ToString().Replace(",", ".") + "," + dAltNew.ToString().Replace(",", ".") + "\n"; if (bPredictionPoints) { PathPositionStored ppsTemp; ppsTemp.dLat = dLatNew; ppsTemp.dLong = dLongNew; ppsTemp.dAlt = dAltNew; ppsTemp.dTime = gconffixCurrent.dPredictionTimes[n]; receivedData.ppsPredictionPoints[n] = ppsTemp; } } } else { receivedData.szCoursePrediction = drroTemp.szCoursePrediction; receivedData.ppsPredictionPoints = drroTemp.ppsPredictionPoints; } break; } } } // Set current entry number <API key>.uiLastEntryNumber = entryNumber; // Insert new data into the list if (<API key>.uiCurrentDataSet == 1) <API key>.listFirst.Add(receivedData); else <API key>.listSecond.Add(receivedData); // If this is the last entry from the current return, switch lists, so that http server can work with the just completed list if (entryNumber == entriesCount) { if (<API key>.uiCurrentDataSet == 1) <API key>.uiCurrentDataSet = 2; else <API key>.uiCurrentDataSet = 1; <API key>.uiLastEntryNumber = 0; <API key>.bClearOnNextRun = true; } } } private List<<API key>> GetCurrentList(ref DataRequestReturn drrnCurrent) { if (drrnCurrent.uiCurrentDataSet == 1) return drrnCurrent.listSecond; else return drrnCurrent.listFirst; } private void safeShowBalloonTip(int timeout, String tipTitle, String tipText, ToolTipIcon tipIcon) { lock (lockChConf) { if (!gconfchCurrent.bShowBalloons) return; } notifyIconMain.ShowBalloonTip(timeout, tipTitle, tipText, tipIcon); } private void safeShowMainDialog(int iTab) { notifyIconMain.ContextMenuStrip = null; ConfigMirrorToForm(); // Check startup options if (<API key>()) radioButton8.Checked = true; else if (isFsxStartActivated() && szPathFSX != "") radioButton9.Checked = true; else radioButton10.Checked = true; if (szPathFSX == "") radioButton9.Enabled = false; bRestartRequired = false; tabControl1.SelectedIndex = iTab; Show(); } private void safeHideMainDialog() { notifyIconMain.ContextMenuStrip = <API key>; Hide(); } private void clearDrrStructure(ref DataRequestReturn drrToClear) { if (drrToClear.listFirst == null) drrToClear.listFirst = new List<<API key>>(); if (drrToClear.listSecond == null) drrToClear.listSecond = new List<<API key>>(); drrToClear.listFirst.Clear(); drrToClear.listSecond.Clear(); drrToClear.uiLastEntryNumber = 0; drrToClear.uiCurrentDataSet = 1; drrToClear.bClearOnNextRun = true; } private void clearPPStructure(ref PathPosition ppToClear) { ppToClear.bInitialized = false; ppToClear.dAlt = ppToClear.dLong = ppToClear.dAlt = 0.0; } private bool IsLocalHostIP(IPAddress ipaRequest) { lock (lockIPAddressList) { if (ipalLocal1 != null) { foreach (IPAddress ipaTemp in ipalLocal1) { if (ipaTemp.Equals(ipaRequest)) return true; } } if (ipalLocal2 != null) { foreach (IPAddress ipaTemp in ipalLocal2) { if (ipaTemp.Equals(ipaRequest)) return true; } } } return false; } private bool <API key>(String szIPAddress, ref String szResult) { try { string szTempKMLFile = File.ReadAllText(szFilePathData + "\\fsxget.template"); szTempKMLFile = szTempKMLFile.Replace("%FSXU%", gconffixCurrent.bQueryUserAircraft ? File.ReadAllText(szFilePathData + "\\fsxget-fsxu.part") : ""); szTempKMLFile = szTempKMLFile.Replace("%FSXP%", gconffixCurrent.bQueryUserPath ? File.ReadAllText(szFilePathData + "\\fsxget-fsxp.part") : ""); szTempKMLFile = szTempKMLFile.Replace("%FSXPRE%", gconffixCurrent.bUserPathPrediction ? File.ReadAllText(szFilePathData + "\\fsxget-fsxpre.part") : ""); szTempKMLFile = szTempKMLFile.Replace("%FSXAIP%", gconffixCurrent.bQueryAIAircrafts ? File.ReadAllText(szFilePathData + "\\fsxget-fsxaip.part") : ""); szTempKMLFile = szTempKMLFile.Replace("%FSXAIH%", gconffixCurrent.bQueryAIHelicopters ? File.ReadAllText(szFilePathData + "\\fsxget-fsxaih.part") : ""); szTempKMLFile = szTempKMLFile.Replace("%FSXAIB%", gconffixCurrent.bQueryAIBoats ? File.ReadAllText(szFilePathData + "\\fsxget-fsxaib.part") : ""); szTempKMLFile = szTempKMLFile.Replace("%FSXAIG%", gconffixCurrent.bQueryAIGroundUnits ? File.ReadAllText(szFilePathData + "\\fsxget-fsxaig.part") : ""); //szTempKMLFile = szTempKMLFile.Replace("%FSXFLIGHTPLAN%", gconffixCurrent.bLoadFlightPlans ? File.ReadAllText(szFilePathData + "\\<API key>.part") : ""); szTempKMLFile = szTempKMLFile.Replace("%PATH%", "http://" + szIPAddress + ":" + gconffixCurrent.iServerPort.ToString()); szResult = szTempKMLFile; return true; } catch { return false; } } private bool <API key>(String szIPAddress, ref String szResult) { try { string szTempKMLFile = File.ReadAllText(szFilePathData + "\\fsxgets.template"); //szTempKMLFile = szTempKMLFile.Replace("%FSXU%", ""); //szTempKMLFile = szTempKMLFile.Replace("%FSXP%", ""); //szTempKMLFile = szTempKMLFile.Replace("%FSXPRE%", ""); //szTempKMLFile = szTempKMLFile.Replace("%FSXAIP%", ""); //szTempKMLFile = szTempKMLFile.Replace("%FSXAIH%", ""); //szTempKMLFile = szTempKMLFile.Replace("%FSXAIB%", ""); //szTempKMLFile = szTempKMLFile.Replace("%FSXAIG%", ""); //szTempKMLFile = szTempKMLFile.Replace("%FSXFLIGHTPLAN%", gconffixCurrent.bLoadFlightPlans ? File.ReadAllText(szFilePathData + "\\<API key>.part") : ""); szResult = szTempKMLFile; return true; } catch { return false; } } private void <API key>() { <API key>(null, null); <API key>(null, null); <API key>(null, null); <API key>(null, null); <API key>(null, null); <API key>(null, null); } private void UpdateButtonStates() { if (<API key>.SelectedItems.Count == 1) button2.Enabled = true; else button2.Enabled = false; } private double ConvertDegToDouble(String szDeg) { String szTemp = szDeg; szTemp = szTemp.Replace("N", "+"); szTemp = szTemp.Replace("S", "-"); szTemp = szTemp.Replace("E", "+"); szTemp = szTemp.Replace("W", "-"); szTemp = szTemp.Replace(" ", ""); szTemp = szTemp.Replace("\"", ""); szTemp = szTemp.Replace("'", "/"); szTemp = szTemp.Replace("°", "/"); char[] szSeperator = { '/' }; String[] szParts = szTemp.Split(szSeperator); if (szParts.GetLength(0) != 3) { throw new System.Exception("Wrong coordinate format!"); } double d1 = System.Double.Parse(szParts[0], System.Globalization.NumberFormatInfo.InvariantInfo); int iSign = Math.Sign(d1); d1 = Math.Abs(d1); double d2 = System.Double.Parse(szParts[1], System.Globalization.NumberFormatInfo.InvariantInfo); double d3 = System.Double.Parse(szParts[2], System.Globalization.NumberFormatInfo.InvariantInfo); return iSign * (d1 + (d2 * 60.0 + d3) / 3600.0); } private bool <API key>() { string szRun = (string)Registry.GetValue(szRegKeyRun, AssemblyTitle, ""); return (szRun.ToLower() == Application.ExecutablePath.ToLower()); } private bool AutoStartActivate() { try { Registry.SetValue(szRegKeyRun, AssemblyTitle, Application.ExecutablePath); } catch { return false; } return true; } private bool AutoStartDeactivate() { try { RegistryKey regkTemp = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true); regkTemp.DeleteValue(AssemblyTitle); } catch { return false; } return true; } private bool isFsxStartActivated() { String szAppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Microsoft\\FSX"; if (File.Exists(szAppDataFolder + "\\EXE.xml")) { XmlTextReader xmlrFsxFile = new XmlTextReader(szAppDataFolder + "\\EXE.xml"); XmlDocument xmldSettings = new XmlDocument(); try { xmldSettings.Load(xmlrFsxFile); } catch { xmlrFsxFile.Close(); xmlrFsxFile = null; return false; } xmlrFsxFile.Close(); xmlrFsxFile = null; try { for (XmlNode xmlnTemp = xmldSettings["SimBase.Document"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.Name.ToLower() == "launch.addon") { try { if (Path.GetFullPath(xmlnTemp["Path"].InnerText).ToLower() == (Path.GetFullPath(szAppPath) + "\\starter.exe").ToLower()) return true; } catch { } } } return false; } catch { return false; } } else return false; } private bool FsxStartActivate() { String szAppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Microsoft\\FSX"; if (File.Exists(szAppDataFolder + "\\EXE.xml")) { bool bLoadError = false; XmlTextReader xmlrFsxFile = new XmlTextReader(szAppDataFolder + "\\EXE.xml"); XmlDocument xmldSettings = new XmlDocument(); try { xmldSettings.Load(xmlrFsxFile); } catch { bLoadError = true; } xmlrFsxFile.Close(); xmlrFsxFile = null; // TODO: One could improve this function not just replacing the document if ["SimBase.Document"] doesn't exist, // but just find and use the document's root element whatever it may be called. This would increase compatibility // with future FS version. (Same should be done for other functions dealing with this document) if (bLoadError || xmldSettings["SimBase.Document"] == null) { try { File.Delete(szAppDataFolder + "\\EXE.xml"); return FsxStartActivate(); } catch { return false; } } else { if (xmldSettings["SimBase.Document"]["Disabled"] == null) { XmlNode nodeTemp = xmldSettings.CreateElement("Disabled"); nodeTemp.InnerText = "False"; xmldSettings["SimBase.Document"].AppendChild(nodeTemp); } else if (xmldSettings["SimBase.Document"]["Disabled"].InnerText.ToLower() == "true") xmldSettings["SimBase.Document"]["Disabled"].InnerText = "False"; xmlrFsxFile = new XmlTextReader(szAppPath + "\\data\\EXE.xml"); XmlDocument xmldTemplate = new XmlDocument(); xmldTemplate.Load(xmlrFsxFile); xmlrFsxFile.Close(); xmlrFsxFile = null; XmlNode nodeFsxget = xmldTemplate["SimBase.Document"]["Launch.Addon"]; XmlNode nodeTemp2 = xmldSettings.CreateElement(nodeFsxget.Name); nodeTemp2.InnerXml = nodeFsxget.InnerXml.Replace("%PATH%", Path.GetFullPath(szAppPath) + "\\starter.exe"); xmldSettings["SimBase.Document"].AppendChild(nodeTemp2); try { File.Delete(szAppDataFolder + "\\EXE.xml"); xmldSettings.Save(szAppDataFolder + "\\EXE.xml"); return true; } catch { return false; } } } else { try { StreamWriter swFsxFile = File.CreateText(szAppDataFolder + "\\EXE.xml"); StreamReader srFsxFileTemplate = File.OpenText(szAppPath + "\\data\\EXE.xml"); swFsxFile.Write(srFsxFileTemplate.ReadToEnd().Replace("%PATH%", Path.GetFullPath(szAppPath) + "\\starter.exe")); swFsxFile.Flush(); swFsxFile.Close(); swFsxFile.Dispose(); srFsxFileTemplate.Close(); srFsxFileTemplate.Dispose(); return true; } catch { return false; } } } private bool FsxStartDeactivate() { String szAppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Microsoft\\FSX"; if (File.Exists(szAppDataFolder + "\\EXE.xml")) { XmlTextReader xmlrFsxFile = new XmlTextReader(szAppDataFolder + "\\EXE.xml"); XmlDocument xmldSettings = new XmlDocument(); xmldSettings.Load(xmlrFsxFile); xmlrFsxFile.Close(); xmlrFsxFile = null; try { bool bChanges = false; for (XmlNode xmlnTemp = xmldSettings["SimBase.Document"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.Name.ToLower() == "launch.addon") { if (xmlnTemp["Path"] != null) { if (Path.GetFullPath(xmlnTemp["Path"].InnerText).ToLower() == (Path.GetFullPath(szAppPath) + "\\starter.exe").ToLower()) { xmldSettings["SimBase.Document"].RemoveChild(xmlnTemp); bChanges = true; } } } } if (bChanges) { try { File.Delete(szAppDataFolder + "\\EXE.xml"); xmldSettings.Save(szAppDataFolder + "\\EXE.xml"); } catch { return false; } } return true; } catch { return true; } } else return true; } private double getValueInUnit(double dValueInMeters, UnitType Unit) { switch (Unit) { case UnitType.METERS: return dValueInMeters; case UnitType.FEET: return dValueInMeters * 3.2808399; default: throw new Exception("Unknown unit type"); } } private double <API key>(double dValueInMeters) { return getValueInUnit(dValueInMeters, gconffixCurrent.utUnits); } private String <API key>() { switch (gconffixCurrent.utUnits) { case UnitType.METERS: return "m"; case UnitType.FEET: return "ft"; default: return " } } private String getCurrentUnitName() { switch (gconffixCurrent.utUnits) { case UnitType.METERS: return "Meters"; case UnitType.FEET: return "Feet"; default: return "Unknown Unit"; } } private void RestartApp() { Program.bRestart = true; bClose = true; Close(); } protected static byte[] BitmapToPngBytes(Bitmap bmp) { byte[] bufferPng = null; if (bmp != null) { byte[] buffer = new byte[1024 + bmp.Height * bmp.Width * 4]; MemoryStream s = new MemoryStream(buffer); bmp.Save(s, System.Drawing.Imaging.ImageFormat.Png); int nSize = (int)s.Position; s.Close(); bufferPng = new byte[nSize]; for (int i = 0; i < nSize; i++) bufferPng[i] = buffer[i]; } return bufferPng; } #endregion #region Calucaltion private void calcPositionByTime(ref PathPosition ppOld, ref PathPosition ppNew, double dSeconds, ref double dResultLat, ref double dResultLong, ref double dResultAlt) { double dTimeElapsed = ppNew.dTime - ppOld.dTime; double dScale = dSeconds / dTimeElapsed; dResultLat = ppNew.dLat + dScale * (ppNew.dLat - ppOld.dLat); dResultLong = ppNew.dLong + dScale * (ppNew.dLong - ppOld.dLong); dResultAlt = ppNew.dAlt + dScale * (ppNew.dAlt - ppOld.dAlt); } #region Old Calculation //private void calcPositionByTime(double dLong, double dLat, double dAlt, double dSpeedX, double dSpeedY, double dSpeedZ, double dSeconds, ref double dResultLat, ref double dResultLong, ref double dResultAlt) // const double dRadEarth = 6371000.8; // dResultLat = dLat + dSpeedZ * dSeconds / 1852.0; // dResultAlt = dAlt + dSpeedY * dSeconds; // double dLatMiddle = dLat + (dSpeedZ * dSeconds / 1852.0 / 2.0); // dResultLong = dLong + (dSpeedX * dSeconds / (2.0 * Math.PI * dRadEarth / 360.0 * Math.Cos(dLatMiddle * Math.PI / 180.0))); // //double dNewPosX = dSpeedX * dSeconds; // //double dNewPosY = dSpeedY * dSeconds; // //double dNewPosZ = dSpeedZ * dSeconds; // //double dCosAngle = (dNewPosY * 1.0 + dNewPosZ * 0.0) / (Math.Sqrt(Math.Pow(dNewPosY, 2.0) + Math.Pow(dNewPosZ, 2.0)) * Math.Sqrt(Math.Pow(0.0, 2.0) + Math.Pow(1.0, 2.0))); // //dResultLat = dLat + Math.Acos(dCosAngle / 180.0 * Math.PI); // //// East-West-Position // //dCosAngle = (dNewPosX * 1.0 + dNewPosY * 0.0) / (Math.Sqrt(Math.Pow(dNewPosX, 2.0) + Math.Pow(dNewPosY, 2.0)) * Math.Sqrt(Math.Pow(1.0, 2.0) + Math.Pow(0.0, 2.0))); // //dResultLong = dLong + Math.Acos(dCosAngle / 180.0 * Math.PI); // //// Altitude // //dResultAlt = dAlt + Math.Sqrt(Math.Pow(dNewPosX, 2.0) + Math.Pow(dNewPosY, 2.0) + Math.Pow(dNewPosZ, 2.0)); // //const double dRadEarth = 6371000.8; // ////x' = cos(theta)*x - sin(theta)*y // ////y' = sin(theta)*x + cos(theta)*y // //// Calculate <API key> // //double dTempX = dAlt + dRadEarth; // //double dTempY = 0.0; // //double dPosY = Math.Cos(dLat) * dTempX - Math.Sin(dLat) * dTempY; // //double dPosZ = Math.Sin(dLat) * dTempX - Math.Cos(dLat) * dTempY; // //// Calculate East-West-Position // //dTempX = dAlt + dRadEarth; // //dTempY = 0; // //double dPosX = Math.Cos(dLong) * dTempX - Math.Sin(dLong) * dTempY; // ////dPosZ = Math.Sin(dLat) * dTempX - Math.Cos(dLat) * dTempY; // //// Normalize // //double dLength = Math.Sqrt(Math.Pow(dPosX, 2.0) + Math.Pow(dPosY, 2.0) + Math.Pow(dPosZ, 2.0)); // //dPosX = dPosX / dLength * (dAlt + dRadEarth); // //dPosY = dPosY / dLength * (dAlt + dRadEarth); // //dPosZ = dPosZ / dLength * (dAlt + dRadEarth); // //double dTest = Math.Sqrt(Math.Pow(dPosX, 2.0) + Math.Pow(dPosY, 2.0) + Math.Pow(dPosZ, 2.0)) - dRadEarth; // //// Calculate position after given time // //double dNewPosX = dPosX + dSpeedX * dSeconds; // //double dNewPosY = dPosY + dSpeedY * dSeconds; // //double dNewPosZ = dPosZ + dSpeedZ * dSeconds; // //// Now again translate into <API key> // //// <API key> // //double dCosAngle = (dNewPosY * dPosY + dNewPosZ * dPosZ) / (Math.Sqrt(Math.Pow(dNewPosY, 2.0) + Math.Pow(dNewPosZ, 2.0)) * Math.Sqrt(Math.Pow(dPosY, 2.0) + Math.Pow(dPosZ, 2.0))); // //dResultLat = dLat + Math.Acos(dCosAngle / 180.0 * Math.PI); // //// East-West-Position // //dCosAngle = (dNewPosX * dPosX + dNewPosY * dPosY) / (Math.Sqrt(Math.Pow(dNewPosX, 2.0) + Math.Pow(dNewPosY, 2.0)) * Math.Sqrt(Math.Pow(dPosX, 2.0) + Math.Pow(dPosY, 2.0))); // //dResultLong = dLong + Math.Acos(dCosAngle / 180.0 * Math.PI); // //// Altitude // //dResultAlt = Math.Sqrt(Math.Pow(dNewPosX, 2.0) + Math.Pow(dNewPosY, 2.0) + Math.Pow(dNewPosZ, 2.0)) - dRadEarth; #endregion #endregion #region Server public void ListenerCallback(IAsyncResult result) { lock (lockListenerControl) { HttpListener listener = (HttpListener)result.AsyncState; if (!listener.IsListening) return; HttpListenerContext context = listener.EndGetContext(result); HttpListenerRequest request = context.Request; <API key> response = context.Response; // This code using the objects IsLocal property doesn't work for some reason ... //if (gconffixCurrent.uiServerAccessLevel == 0 && !request.IsLocal) // response.Abort(); // return; // ... so I'm using my own code. if (gconffixCurrent.uiServerAccessLevel == 0 && !IsLocalHostIP(request.RemoteEndPoint.Address)) { response.Abort(); return; } byte[] buffer = System.Text.Encoding.UTF8.GetBytes(""); String szHeader = ""; bool bContentSet = false; if (request.Url.PathAndQuery.ToLower().StartsWith("/gfx/scenery/air/")) { String szTemp = request.Url.PathAndQuery.Substring(17); if (szTemp.Length >= 4) { // Cut the .png suffix from the url szTemp = szTemp.Substring(0, szTemp.Length - 4); foreach (ObjectImage aimgCurrent in listImgUnitsAir) { String szTemp2 = HttpUtility.UrlDecode(szTemp); if (aimgCurrent.szTitle.ToLower() == HttpUtility.UrlDecode(szTemp).ToLower()) { buffer = aimgCurrent.bData; szHeader = "image/png"; bContentSet = true; break; } } if (!bContentSet) { buffer = imgNoImage; szHeader = "image/png"; bContentSet = true; } } } else if (request.Url.PathAndQuery.ToLower().StartsWith("/gfx/scenery/water/")) { String szTemp = request.Url.PathAndQuery.Substring(19); if (szTemp.Length >= 4) { // Cut the .png suffix from the url szTemp = szTemp.Substring(0, szTemp.Length - 4); foreach (ObjectImage aimgCurrent in listImgUnitsWater) { String szTemp2 = HttpUtility.UrlDecode(szTemp); if (aimgCurrent.szTitle.ToLower() == HttpUtility.UrlDecode(szTemp).ToLower()) { buffer = aimgCurrent.bData; szHeader = "image/png"; bContentSet = true; break; } } if (!bContentSet) { buffer = imgNoImage; szHeader = "image/png"; bContentSet = true; } } } else if (request.Url.PathAndQuery.ToLower().StartsWith("/gfx/scenery/ground/")) { String szTemp = request.Url.PathAndQuery.Substring(20); if (szTemp.Length >= 4) { // Cut the .png suffix from the url szTemp = szTemp.Substring(0, szTemp.Length - 4); foreach (ObjectImage aimgCurrent in listImgUnitsGround) { String szTemp2 = HttpUtility.UrlDecode(szTemp); if (aimgCurrent.szTitle.ToLower() == HttpUtility.UrlDecode(szTemp).ToLower()) { buffer = aimgCurrent.bData; szHeader = "image/png"; bContentSet = true; break; } } if (!bContentSet) { buffer = imgNoImage; szHeader = "image/png"; bContentSet = true; } } } else if (request.Url.PathAndQuery.ToLower().StartsWith("/gfx/ge/icons/")) { String szTemp = request.Url.PathAndQuery.Substring(14); if (szTemp.Length >= 4) { // Cut the .png suffix from the url szTemp = szTemp.Substring(0, szTemp.Length - 4); buffer = null; foreach (ObjectImage oimgTemp in listIconsGE) { if (oimgTemp.szTitle.ToLower() == szTemp.ToLower()) { szHeader = "image/png"; buffer = oimgTemp.bData; bContentSet = true; break; } } if (!bContentSet) { buffer = imgNoImage; szHeader = "image/png"; bContentSet = true; } } } else if (request.Url.PathAndQuery.ToLower() == "/fsxu.kml") { bContentSet = true; szHeader = "application/vnd.google-earth.kml+xml"; buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.<API key>, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.<API key>, request.UserHostName)); } else if (request.Url.PathAndQuery.ToLower() == "/fsxp.kml") { bContentSet = true; szHeader = "application/vnd.google-earth.kml+xml"; buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_USER_PATH, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEUserPath, request.UserHostName)); } else if (request.Url.PathAndQuery.ToLower() == "/fsxpre.kml") { bContentSet = true; szHeader = "application/vnd.google-earth.kml+xml"; buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.<API key>, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.<API key>, request.UserHostName)); } else if (request.Url.PathAndQuery.ToLower() == "/fsxaip.kml") { bContentSet = true; szHeader = "application/vnd.google-earth.kml+xml"; buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_AI_PLANE, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.<API key>, request.UserHostName)); } else if (request.Url.PathAndQuery.ToLower() == "/fsxaih.kml") { bContentSet = true; szHeader = "application/vnd.google-earth.kml+xml"; buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.<API key>, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.<API key>, request.UserHostName)); } else if (request.Url.PathAndQuery.ToLower() == "/fsxaib.kml") { bContentSet = true; szHeader = "application/vnd.google-earth.kml+xml"; buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_AI_BOAT, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEAIBoats, request.UserHostName)); } else if (request.Url.PathAndQuery.ToLower() == "/fsxaig.kml") { bContentSet = true; szHeader = "application/vnd.google-earth.kml+xml"; buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_AI_GROUND, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.<API key>, request.UserHostName)); } else if (request.Url.PathAndQuery.ToLower() == "/fsxflightplans.kml") { bContentSet = true; szHeader = "application/vnd.google-earth.kml+xml"; buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.<API key>, KML_ACCESS_MODES.MODE_SERVER, false, 0, request.UserHostName)); } else if (request.Url.AbsolutePath.ToLower() == "/gfx/ge/label.png") { bContentSet = true; szHeader = "image/png"; buffer = KmlGenAtcLabel(request.QueryString["code"], request.QueryString["fl"], request.QueryString["aircraft"], request.QueryString["speed"], request.QueryString["vspeed"]); } else bContentSet = false; if (bContentSet) { response.AddHeader("Content-type", szHeader); response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); } else { response.StatusCode = 404; response.Close(); } listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener); } } private String KmlGenFile(KML_FILES kmlfWanted, KML_ACCESS_MODES AccessMode, bool bExpires, uint uiSeconds, String szSever) { String szTemp = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><kml xmlns=\"http://earth.google.com/kml/2.1\">" + KmlGetExpireString(bExpires, uiSeconds) + "<Document>"; switch (kmlfWanted) { case KML_FILES.<API key>: szTemp += KmlGenUserPosition(AccessMode, szSever); break; case KML_FILES.REQUEST_USER_PATH: szTemp += KmlGenUserPath(AccessMode, szSever); break; case KML_FILES.<API key>: szTemp += <API key>(AccessMode, szSever); break; case KML_FILES.REQUEST_AI_PLANE: szTemp += KmlGenAIAircraft(AccessMode, szSever); break; case KML_FILES.<API key>: szTemp += KmlGenAIHelicopter(AccessMode, szSever); break; case KML_FILES.REQUEST_AI_BOAT: szTemp += KmlGenAIBoat(AccessMode, szSever); break; case KML_FILES.REQUEST_AI_GROUND: szTemp += KmlGenAIGroundUnit(AccessMode, szSever); break; //case KML_FILES.<API key>: // szTemp += KmlGenFlightPlans(AccessMode, szSever); // break; default: break; } szTemp += "</Document></kml>"; return szTemp; } private String KmlGetExpireString(bool bExpires, uint uiSeconds) { if (!bExpires) return ""; DateTime date = DateTime.Now; date = date.AddSeconds(uiSeconds); date = date.ToUniversalTime(); return "<NetworkLinkControl><expires>" + date.ToString("yyyy") + "-" + date.ToString("MM") + "-" + date.ToString("dd") + "T" + date.ToString("HH") + ":" + date.ToString("mm") + ":" + date.ToString("ss") + "Z" + "</expires></NetworkLinkControl>"; } private String KmlGetImageLink(KML_ACCESS_MODES AccessMode, KML_IMAGE_TYPES ImageType, String szTitle, String szServer) { if (AccessMode == KML_ACCESS_MODES.MODE_SERVER) { String szPrefix = ""; switch (ImageType) { case KML_IMAGE_TYPES.AIRCRAFT: szPrefix = "/gfx/scenery/air/"; break; case KML_IMAGE_TYPES.WATER: szPrefix = "/gfx/scenery/water/"; break; case KML_IMAGE_TYPES.GROUND: szPrefix = "/gfx/scenery/ground/"; break; } return "http://" + szServer + szPrefix + szTitle + ".png"; } else { List<ObjectImage> listTemp; switch (ImageType) { case KML_IMAGE_TYPES.AIRCRAFT: listTemp = listImgUnitsAir; break; case KML_IMAGE_TYPES.WATER: listTemp = listImgUnitsWater; break; case KML_IMAGE_TYPES.GROUND: listTemp = listImgUnitsGround; break; default: return ""; } foreach (ObjectImage oimgTemp in listTemp) { if (oimgTemp.szTitle.ToLower() == szTitle.ToLower()) { if (AccessMode == KML_ACCESS_MODES.MODE_FILE_LOCAL) return szFilePathPub + oimgTemp.szPath; else if (AccessMode == KML_ACCESS_MODES.<API key>) return gconffixCurrent.szUserdefinedPath + oimgTemp.szPath; } } return ""; } } private String KmlGetIconLink(KML_ACCESS_MODES AccessMode, KML_ICON_TYPES IconType, String szServer) { String szIcon = ""; switch (IconType) { case KML_ICON_TYPES.<API key>: szIcon = "fsxu"; break; case KML_ICON_TYPES.<API key>: szIcon = "fsxpm"; break; case KML_ICON_TYPES.AI_AIRCRAFT: szIcon = "fsxaip"; break; case KML_ICON_TYPES.AI_HELICOPTER: szIcon = "fsxaih"; break; case KML_ICON_TYPES.AI_BOAT: szIcon = "fsxaib"; break; case KML_ICON_TYPES.AI_GROUND_UNIT: szIcon = "fsxaig"; break; case KML_ICON_TYPES.<API key>: szIcon = "fsxaippp"; break; case KML_ICON_TYPES.<API key>: szIcon = "fsxaihpp"; break; case KML_ICON_TYPES.<API key>: szIcon = "fsxaibpp"; break; case KML_ICON_TYPES.<API key>: szIcon = "fsxaigpp"; break; case KML_ICON_TYPES.PLAN_INTER: szIcon = "plan-inter"; break; case KML_ICON_TYPES.PLAN_NDB: szIcon = "plan-ndb"; break; case KML_ICON_TYPES.PLAN_PORT: szIcon = "plan-port"; break; case KML_ICON_TYPES.PLAN_USER: szIcon = "plan-user"; break; case KML_ICON_TYPES.PLAN_VOR: szIcon = "plan-vor"; break; case KML_ICON_TYPES.ATC_LABEL: return "http://" + szServer + "/gfx/ge/label.png"; } if (AccessMode == KML_ACCESS_MODES.MODE_SERVER) { return "http://" + szServer + "/gfx/ge/icons/" + szIcon + ".png"; } else { foreach (ObjectImage oimgTemp in listIconsGE) { if (oimgTemp.szTitle.ToLower() == szIcon.ToLower()) { if (AccessMode == KML_ACCESS_MODES.MODE_FILE_LOCAL) return szFilePathPub + oimgTemp.szPath; else if (AccessMode == KML_ACCESS_MODES.<API key>) return gconffixCurrent.szUserdefinedPath + oimgTemp.szPath; } } return ""; } } private String KmlGenETAPoints(ref PathPositionStored[] ppsCurrent, bool bGenerate, KML_ACCESS_MODES AccessMode, KML_ICON_TYPES Icon, String szServer) { if (ppsCurrent == null) return ""; if (bGenerate) { String szTemp = "<Folder><name>ETA Points</name>"; for (uint n = 0; n < ppsCurrent.GetLength(0); n++) szTemp += "<Placemark>" + "<name>ETA " + ((ppsCurrent[n].dTime < 60.0) ? (((int)ppsCurrent[n].dTime).ToString() + " sec") : (ppsCurrent[n].dTime / 60.0 + " min")) + "</name><visibility>1</visibility><open>0</open>" + "<description><![CDATA[Esitmated Position]]></description>" + "<Style>" + "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, Icon, szServer) + "</href></Icon><scale>0.2</scale></IconStyle>" + "<LabelStyle><scale>0.4</scale></LabelStyle>" + "</Style>" + "<Point><altitudeMode>absolute</altitudeMode><coordinates>" + ppsCurrent[n].dLong.ToString().Replace(",", ".") + "," + ppsCurrent[n].dLat.ToString().Replace(",", ".") + "," + ppsCurrent[n].dAlt.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>"; return szTemp + "</Folder>"; } else return ""; } private String KmlGenUserPosition(KML_ACCESS_MODES AccessMode, String szServer) { lock (lockKmlUserAircraft) { return "<Placemark>" + "<name>User Aircraft Position</name><visibility>1</visibility><open>0</open>" + "<description><![CDATA[Microsoft Flight Simulator X - User Aircraft<br>&nbsp;<br>" + "<b>Title:</b> " + suadCurrent.szTitle + "<br>&nbsp;<br>" + "<b>Type:</b> " + suadCurrent.szATCType + "<br>" + "<b>Model:</b> " + suadCurrent.szATCModel + "<br>&nbsp;<br>" + "<b>Identification:</b> " + suadCurrent.szATCID + "<br>&nbsp;<br>" + "<b>Flight Number:</b> " + suadCurrent.szATCFlightNumber + "<br>" + "<b>Airline:</b> " + suadCurrent.szATCAirline + "<br>&nbsp;<br>" + "<b>Altitude:</b> " + ((int)<API key>(suadCurrent.dAltitude)).ToString().Replace(",", ".") + " " + <API key>() + "<br>&nbsp;<br>" + "<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.AIRCRAFT, suadCurrent.szTitle, szServer) + "\"></center>]]></description>" + "<Snippet>" + suadCurrent.szATCType + " " + suadCurrent.szATCModel + " (" + suadCurrent.szTitle + "), " + suadCurrent.szATCID + "\nAltitude: " + ((int)<API key>(suadCurrent.dAltitude)).ToString().Replace(",", ".") + " " + <API key>() + "</Snippet>" + "<Style>" + "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.<API key>, szServer) + "</href></Icon><scale>0.8</scale></IconStyle>" + "<LabelStyle><scale>1.0</scale></LabelStyle>" + "</Style>" + "<Point><altitudeMode>absolute</altitudeMode><coordinates>" + suadCurrent.dLongitude.ToString().Replace(",", ".") + "," + suadCurrent.dLatitude.ToString().Replace(",", ".") + "," + suadCurrent.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>"; } } private String KmlGenUserPath(KML_ACCESS_MODES AccessMode, String szServer) { lock (lockKmlUserPath) { return "<Placemark><name>User Aircraft Path</name><description>Path of the user aircraft since tracking started.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9fffffff</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + <API key> + "</coordinates></LineString></Placemark>"; } } private String <API key>(KML_ACCESS_MODES AccessMode, String szServer) { String szTemp = ""; lock (<API key>) { szTemp = "<Placemark><name>User Aircraft Path Prediction</name><description>Path prediction of the user aircraft.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9f00ffff</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + szKmlUserPrediction + "</coordinates></LineString></Placemark>" + "<Folder><name>ETA Points</name>"; foreach (PathPositionStored ppsTemp in <API key>) { szTemp += "<Placemark>" + "<name>ETA " + ((ppsTemp.dTime < 60.0) ? (((int)ppsTemp.dTime).ToString() + " sec") : (ppsTemp.dTime / 60.0 + " min")) + "</name><visibility>1</visibility><open>0</open>" + "<description><![CDATA[Esitmated Position]]></description>" + "<Style>" + "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.<API key>, szServer) + "</href></Icon><scale>0.2</scale></IconStyle>" + "<LabelStyle><scale>0.4</scale></LabelStyle>" + "</Style>" + "<Point><altitudeMode>absolute</altitudeMode><coordinates>" + ppsTemp.dLong.ToString().Replace(",", ".") + "," + ppsTemp.dLat.ToString().Replace(",", ".") + "," + ppsTemp.dAlt.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>"; } } return szTemp + "</Folder>"; } private String KmlGenAIAircraft(KML_ACCESS_MODES AccessMode, String szServer) { String szTemp = "<Folder><name>Aircraft Positions</name>"; lock (lockDrrAiPlanes) { List<<API key>> listTemp = GetCurrentList(ref drrAIPlanes); foreach (<API key> bmsoTemp in listTemp) { //szTemp += "<Placemark>" + // "<name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><visibility>1</visibility><open>0</open>" + // "<description><![CDATA[Microsoft Flight Simulator X - AI Plane<br>&nbsp;<br>" + // "<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br>&nbsp;<br>" + // "<b>Type:</b> " + bmsoTemp.bmsoObject.szATCType + "<br>" + // "<b>Model:</b> " + bmsoTemp.bmsoObject.szATCModel + "<br>&nbsp;<br>" + // "<b>Identification:</b> " + bmsoTemp.bmsoObject.szATCID + "<br>&nbsp;<br>" + // "<b>Flight Number:</b> " + bmsoTemp.bmsoObject.szATCFlightNumber + "<br>" + // "<b>Airline:</b> " + bmsoTemp.bmsoObject.szATCAirline + "<br>&nbsp;<br>" + // "<b>Altitude:</b> " + ((int)<API key>(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + <API key>() + "<br>&nbsp;<br>" + // "<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.AIRCRAFT, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" + // "<Snippet>" + bmsoTemp.bmsoObject.szTitle + "\nAltitude: " + ((int)<API key>(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + <API key>() + "</Snippet>" + // "<Style>" + // "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.AI_AIRCRAFT, szServer) + "</href></Icon><scale>0.6</scale></IconStyle>" + // "<LabelStyle><scale>0.6</scale></LabelStyle>" + // "</Style>" + // "<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>"; int FL = (int)Math.Round(getValueInUnit(bmsoTemp.bmsoObject.dAltitude, UnitType.FEET) / 100.0, 0); int FLRound = FL - (FL % 10); szTemp += "<Placemark>" + "<name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><visibility>1</visibility><open>0</open>" + "<description><![CDATA[Microsoft Flight Simulator X - AI Plane<br>&nbsp;<br>" + "<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br>&nbsp;<br>" + "<b>Type:</b> " + bmsoTemp.bmsoObject.szATCType + "<br>" + "<b>Model:</b> " + bmsoTemp.bmsoObject.szATCModel + "<br>&nbsp;<br>" + "<b>Identification:</b> " + bmsoTemp.bmsoObject.szATCID + "<br>&nbsp;<br>" + "<b>Flight Number:</b> " + bmsoTemp.bmsoObject.szATCFlightNumber + "<br>" + "<b>Airline:</b> " + bmsoTemp.bmsoObject.szATCAirline + "<br>&nbsp;<br>" + "<b>Altitude:</b> " + ((int)<API key>(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + <API key>() + "<br>&nbsp;<br>" + "<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.AIRCRAFT, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" + "<Snippet>" + bmsoTemp.bmsoObject.szTitle + "\nAltitude: " + ((int)<API key>(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + <API key>() + "</Snippet>" + "<Style>" + "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.ATC_LABEL, szServer) + "?code=" + bmsoTemp.bmsoObject.szATCID + "&amp;fl=FL" + FLRound.ToString() + "&amp;speed=" + Math.Round(bmsoTemp.bmsoObject.dSpeed, 0).ToString() + " kn&amp;vspeed=" + (bmsoTemp.bmsoObject.dVSpeed > 0.0 ? "%2F%5C" : (bmsoTemp.bmsoObject.dVSpeed == 0.0 ? "-" : "%5C%2F")) + "&amp;aircraft=" + bmsoTemp.bmsoObject.szATCModel + "</href></Icon><scale>2.5</scale> <hotSpot x=\"30\" y=\"50\" xunits=\"pixels\" yunits=\"pixels\"/></IconStyle>" + "<LabelStyle><scale>0.6</scale></LabelStyle>" + "</Style>" + "<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>"; } szTemp += "</Folder>"; if (gconffixCurrent.bPredictAIAircrafts) { szTemp += "<Folder><name>Aircraft Courses</name>"; foreach (<API key> bmsoTemp in listTemp) { if (bmsoTemp.szCoursePrediction == "") continue; szTemp += "<Placemark><name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><description>Course prediction of the aircraft.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9fd20091</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.szCoursePrediction + "</coordinates></LineString></Placemark>"; PathPositionStored[] ppsTemp = bmsoTemp.ppsPredictionPoints; szTemp += KmlGenETAPoints(ref ppsTemp, gconffixCurrent.<API key>, AccessMode, KML_ICON_TYPES.<API key>, szServer); } szTemp += "</Folder>"; } } return szTemp; } private String KmlGenAIHelicopter(KML_ACCESS_MODES AccessMode, String szServer) { String szTemp = "<Folder><name>Helicopter Positions</name>"; lock (<API key>) { List<<API key>> listTemp = GetCurrentList(ref drrAIHelicopters); foreach (<API key> bmsoTemp in listTemp) { szTemp += "<Placemark>" + "<name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><visibility>1</visibility><open>0</open>" + "<description><![CDATA[Microsoft Flight Simulator X - AI Helicopter<br>&nbsp;<br>" + "<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br>&nbsp;<br>" + "<b>Type:</b> " + bmsoTemp.bmsoObject.szATCType + "<br>" + "<b>Model:</b> " + bmsoTemp.bmsoObject.szATCModel + "<br>&nbsp;<br>" + "<b>Identification:</b> " + bmsoTemp.bmsoObject.szATCID + "<br>&nbsp;<br>" + "<b>Flight Number:</b> " + bmsoTemp.bmsoObject.szATCFlightNumber + "<br>" + "<b>Airline:</b> " + bmsoTemp.bmsoObject.szATCAirline + "<br>&nbsp;<br>" + "<b>Altitude:</b> " + ((int)<API key>(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + <API key>() + "<br>&nbsp;<br>" + "<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.AIRCRAFT, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" + "<Snippet>" + bmsoTemp.bmsoObject.szTitle + "\nAltitude: " + ((int)<API key>(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + <API key>() + "</Snippet>" + "<Style>" + "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.AI_HELICOPTER, szServer) + "</href></Icon><scale>0.6</scale></IconStyle>" + "<LabelStyle><scale>0.6</scale></LabelStyle>" + "</Style>" + "<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>"; } szTemp += "</Folder>"; if (gconffixCurrent.<API key>) { szTemp += "<Folder><name>Helicopter Courses</name>"; foreach (<API key> bmsoTemp in listTemp) { if (bmsoTemp.szCoursePrediction == "") continue; szTemp += "<Placemark><name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><description>Course prediction of the helicopter.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9fd20091</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.szCoursePrediction + "</coordinates></LineString></Placemark>"; PathPositionStored[] ppsTemp = bmsoTemp.ppsPredictionPoints; szTemp += KmlGenETAPoints(ref ppsTemp, gconffixCurrent.<API key>, AccessMode, KML_ICON_TYPES.<API key>, szServer); } szTemp += "</Folder>"; } } return szTemp; } private String KmlGenAIBoat(KML_ACCESS_MODES AccessMode, String szServer) { String szTemp = "<Folder><name>Boat Positions</name>"; lock (lockDrrAiBoats) { List<<API key>> listTemp = GetCurrentList(ref drrAIBoats); foreach (<API key> bmsoTemp in listTemp) { szTemp += "<Placemark>" + "<name>" + bmsoTemp.bmsoObject.szTitle + "</name><visibility>1</visibility><open>0</open>" + "<description><![CDATA[Microsoft Flight Simulator X - AI Boat<br>&nbsp;<br>" + "<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br>&nbsp;<br>" + "<b>Altitude:</b> " + ((int)<API key>(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + <API key>() + "<br>&nbsp;<br>" + "<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.WATER, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" + "<Snippet>Altitude: " + ((int)<API key>(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + <API key>() + "</Snippet>" + "<Style>" + "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.AI_BOAT, szServer) + "</href></Icon><scale>0.6</scale></IconStyle>" + "<LabelStyle><scale>0.6</scale></LabelStyle>" + "</Style>" + "<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>"; } szTemp += "</Folder>"; if (gconffixCurrent.bPredictAIBoats) { szTemp += "<Folder><name>Boat Courses</name>"; foreach (<API key> bmsoTemp in listTemp) { if (bmsoTemp.szCoursePrediction == "") continue; szTemp += "<Placemark><name>" + bmsoTemp.bmsoObject.szTitle + "</name><description>Course prediction of the boat.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9f00b545</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.szCoursePrediction + "</coordinates></LineString></Placemark>"; PathPositionStored[] ppsTemp = bmsoTemp.ppsPredictionPoints; szTemp += KmlGenETAPoints(ref ppsTemp, gconffixCurrent.<API key>, AccessMode, KML_ICON_TYPES.<API key>, szServer); } szTemp += "</Folder>"; } } return szTemp; } private String KmlGenAIGroundUnit(KML_ACCESS_MODES AccessMode, String szServer) { String szTemp = "<Folder><name>Ground Vehicle Positions</name>"; lock (lockDrrAiGround) { List<<API key>> listTemp = GetCurrentList(ref drrAIGround); foreach (<API key> bmsoTemp in listTemp) { szTemp += "<Placemark>" + "<name>" + bmsoTemp.bmsoObject.szTitle + "</name><visibility>1</visibility><open>0</open>" + "<description><![CDATA[Microsoft Flight Simulator X - AI Vehicle<br>&nbsp;<br>" + "<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br>&nbsp;<br>" + "<b>Altitude:</b> " + ((int)<API key>(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + <API key>() + "<br>&nbsp;<br>" + "<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.GROUND, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" + "<Snippet>Altitude: " + ((int)<API key>(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + <API key>() + "</Snippet>" + "<Style>" + "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.AI_GROUND_UNIT, szServer) + "</href></Icon><scale>0.6</scale></IconStyle>" + "<LabelStyle><scale>0.6</scale></LabelStyle>" + "</Style>" + "<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>"; } szTemp += "</Folder>"; if (gconffixCurrent.<API key>) { szTemp += "<Folder><name>Ground Vehicle Courses</name>"; foreach (<API key> bmsoTemp in listTemp) { if (bmsoTemp.szCoursePrediction == "") continue; szTemp += "<Placemark><name>" + bmsoTemp.bmsoObject.szTitle + "</name><description>Course prediction of the ground vehicle.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9f00b545</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.szCoursePrediction + "</coordinates></LineString></Placemark>"; PathPositionStored[] ppsTemp = bmsoTemp.ppsPredictionPoints; szTemp += KmlGenETAPoints(ref ppsTemp, gconffixCurrent.<API key>, AccessMode, KML_ICON_TYPES.<API key>, szServer); } szTemp += "</Folder>"; } } return szTemp; } private byte[] KmlGenAtcLabel(String CallSign, String FL, String Aircraft, String Speed, String VerticalSpeed) { Bitmap bmp = new Bitmap(imgAtcLabel); Graphics g = Graphics.FromImage(bmp); Pen pen = new Pen(Color.FromArgb(81, 255, 147)); Brush brush = new SolidBrush(Color.FromArgb(81, 255, 147)); Font font = new Font("Courier New", 10, FontStyle.Bold); Font font_small = new Font("Courier New", 6, FontStyle.Bold); float fX = 72; float fY = 13; g.DrawString(CallSign, font, brush, new PointF(fX, fY)); fY += g.MeasureString(CallSign, font).Height; g.DrawString(FL + " " + VerticalSpeed, font, brush, new PointF(fX, fY)); fY += g.MeasureString(FL + " " + VerticalSpeed, font).Height; g.DrawString(Aircraft, font, brush, new PointF(fX, fY)); return BitmapToPngBytes(bmp); } //private String KmlGenFlightPlans(KML_ACCESS_MODES AccessMode, String szServer) // String szTemp = ""; // lock (lockFlightPlanList) // foreach (FlightPlan fpTemp in listFlightPlans) // XmlDocument xmldTemp = fpTemp.xmldPlan; // String szTempInner = ""; // String szTempWaypoints = ""; // String szPath = ""; // try // for (XmlNode xmlnTemp = xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) // if (xmlnTemp.Name.ToLower() != "atcwaypoint") // continue; // KML_ICON_TYPES iconType; // String szType = xmlnTemp["ATCWaypointType"].InnerText.ToLower(); // if (szType == "intersection") // iconType = KML_ICON_TYPES.PLAN_INTER; // else if (szType == "ndb") // iconType = KML_ICON_TYPES.PLAN_NDB; // else if (szType == "vor") // iconType = KML_ICON_TYPES.PLAN_VOR; // else if (szType == "user") // iconType = KML_ICON_TYPES.PLAN_USER; // else if (szType == "airport") // iconType = KML_ICON_TYPES.PLAN_PORT; // else // iconType = KML_ICON_TYPES.UNKNOWN; // char[] szSeperator = { ',' }; // String[] szCoordinates = xmlnTemp["WorldPosition"].InnerText.Split(szSeperator); // if (szCoordinates.GetLength(0) != 3) // throw new System.Exception("Invalid position value"); // String szAirway = "", szICAOIdent = "", szICAORegion = ""; // if (xmlnTemp["ATCAirway"] != null) // szAirway = xmlnTemp["ATCAirway"].InnerText; // if (xmlnTemp["ICAO"] != null) // if (xmlnTemp["ICAO"]["ICAOIdent"] != null) // szICAOIdent = xmlnTemp["ICAO"]["ICAOIdent"].InnerText; // if (xmlnTemp["ICAO"]["ICAORegion"] != null) // szICAORegion = xmlnTemp["ICAO"]["ICAORegion"].InnerText; // double dCurrentLong = ConvertDegToDouble(szCoordinates[1]); // double dCurrentLat = ConvertDegToDouble(szCoordinates[0]); // double dCurrentAlt = System.Double.Parse(szCoordinates[2]); // szTempWaypoints += "<Placemark>" + // "<name>" + xmlnTemp["ATCWaypointType"].InnerText + " (" + xmlnTemp.Attributes["id"].Value + ")</name><visibility>1</visibility><open>0</open>" + // "<description><![CDATA[Flight Plane Element<br>&nbsp;<br>" + // "<b>Waypoint Type:</b> " + xmlnTemp["ATCWaypointType"].InnerText + "<br>&nbsp;<br>" + // (szAirway != "" ? "<b>ATC Airway:</b> " + szAirway + "<br>&nbsp;<br>" : "") + // (szICAOIdent != "" ? "<b>ICAO Identification:</b> " + szICAOIdent + "<br>" : "") + // (szICAORegion != "" ? "<b>ICAO Region:</b> " + szICAORegion : "") + // "]]></description>" + // "<Snippet>Waypoint Type: " + xmlnTemp["ATCWaypointType"].InnerText + (szAirway != "" ? "\nAirway: " + szAirway : "") + "</Snippet>" + // "<Style>" + // "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, iconType, szServer) + "</href></Icon><scale>1.0</scale></IconStyle>" + // "<LabelStyle><scale>0.6</scale></LabelStyle>" + // "</Style>" + // "<Point><altitudeMode>clampToGround</altitudeMode><coordinates>" + dCurrentLong.ToString().Replace(",", ".") + "," + dCurrentLat.ToString().Replace(",", ".") + "," + dCurrentAlt.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>"; // szPath += dCurrentLong.ToString().Replace(",", ".") + "," + dCurrentLat.ToString().Replace(",", ".") + "," + dCurrentAlt.ToString().Replace(",", ".") + "\n"; // szTempInner = "<Folder><open>0</open>" + // "<name>" + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["Title"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["Title"].InnerText : "n/a") + "</name>" + // "<description><![CDATA[" + // "Type: " + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["FPType"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["FPType"].InnerText : "n/a") + " (" + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["RouteType"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["RouteType"].InnerText : "n/a") + ")<br>" + // "Flight from " + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["DepartureName"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["DepartureName"].InnerText : "n/a") + " to " + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["DestinationName"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["DestinationName"].InnerText : "n/a") + ".<br>&nbsp;<br>" + // "Altitude: " + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["CruisingAlt"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["CruisingAlt"].InnerText : "n/a") + // "]]></description>" + // "<Placemark><name>Path</name><Style><LineStyle><color>9f1ab6ff</color><width>2</width></LineStyle></Style><LineString><tessellate>1</tessellate><altitudeMode>clampToGround</altitudeMode><coordinates>" + szPath + "</coordinates></LineString></Placemark>" + // "<Folder><open>0</open><name>Waypoints</name>" + szTempWaypoints + "</Folder>" + // "</Folder>"; // catch // szTemp += "<Folder><name>Invalid Flight Plan</name><snippet>Error loading flight plan.</snippet></Folder>"; // continue; // szTemp += szTempInner; // return szTemp; #endregion #region Update Check // private void <API key>() // try // <API key> = ""; // <API key>.BeginGetResponse(new AsyncCallback(RespCallback), <API key>); // catch //#if DEBUG // notifyIconMain.ShowBalloonTip(5, Text, "Couldn't check for program update online!", ToolTipIcon.Warning); //#endif // private void RespCallback(IAsyncResult asynchronousResult) // try // WebRequest myWebRequest = (WebRequest)asynchronousResult.AsyncState; // <API key> = myWebRequest.EndGetResponse(asynchronousResult); // Stream responseStream = <API key>.GetResponseStream(); // responseStream.BeginRead(<API key>, 0, <API key>, new AsyncCallback(ReadCallBack), responseStream); // catch //#if DEBUG // notifyIconMain.ShowBalloonTip(5, Text, "Couldn't check for program update online!", ToolTipIcon.Warning); //#endif // private void ReadCallBack(IAsyncResult asyncResult) // try // Stream responseStream = (Stream)asyncResult.AsyncState; // int iRead = responseStream.EndRead(asyncResult); // if (iRead > 0) // <API key> += Encoding.ASCII.GetString(<API key>, 0, iRead); // responseStream.BeginRead(<API key>, 0, <API key>, new AsyncCallback(ReadCallBack), responseStream); // else // responseStream.Close(); // <API key>.Close(); // char[] szSeperator = { '.' }; // String[] szVersionLocal = Application.ProductVersion.Split(szSeperator); // String[] szVersionOnline = <API key>.Split(szSeperator); // for (int i = 0; i < Math.Min(szVersionLocal.GetLength(0), szVersionOnline.GetLength(0)); i++) // if (Int64.Parse(szVersionOnline[i]) > Int64.Parse(szVersionLocal[i])) // break; // else if (Int64.Parse(szVersionOnline[i]) < Int64.Parse(szVersionLocal[i])) // break; // catch //#if DEBUG // notifyIconMain.ShowBalloonTip(5, Text, "Couldn't check for program update online!", ToolTipIcon.Warning); //#endif #endregion #region Timers private void <API key>(object sender, EventArgs e) { if (openConnection()) { timerFSXConnect.Stop(); bConnected = true; notifyIconMain.Icon = icReceive; notifyIconMain.Text = Text + "(Waiting for connection...)"; safeShowBalloonTip(1000, Text, "Connected to FSX!", ToolTipIcon.Info); } } private void <API key>(object sender, EventArgs e) { IPHostEntry ipheLocalhost1 = Dns.GetHostEntry(Dns.GetHostName()); IPHostEntry ipheLocalhost2 = Dns.GetHostEntry("localhost"); lock (lockIPAddressList) { ipalLocal1 = ipheLocalhost1.AddressList; ipalLocal2 = ipheLocalhost2.AddressList; } } private void <API key>(object sender, EventArgs e) { simconnect.<API key>(DATA_REQUESTS.<API key>, DEFINITIONS.<API key>, 0, <API key>.USER); } private void <API key>(object sender, EventArgs e) { simconnect.<API key>(DATA_REQUESTS.REQUEST_USER_PATH, DEFINITIONS.<API key>, 0, <API key>.USER); } private void <API key>(object sender, EventArgs e) { simconnect.<API key>(DATA_REQUESTS.<API key>, DEFINITIONS.<API key>, 0, <API key>.USER); } private void <API key>(object sender, EventArgs e) { simconnect.<API key>(DATA_REQUESTS.REQUEST_AI_PLANE, DEFINITIONS.<API key>, (uint)gconffixCurrent.iRangeAIAircrafts, <API key>.AIRCRAFT); } private void <API key>(object sender, EventArgs e) { simconnect.<API key>(DATA_REQUESTS.<API key>, DEFINITIONS.<API key>, (uint)gconffixCurrent.iRangeAIHelicopters, <API key>.HELICOPTER); } private void <API key>(object sender, EventArgs e) { simconnect.<API key>(DATA_REQUESTS.REQUEST_AI_BOAT, DEFINITIONS.<API key>, (uint)gconffixCurrent.iRangeAIBoats, <API key>.BOAT); } private void <API key>(object sender, EventArgs e) { simconnect.<API key>(DATA_REQUESTS.REQUEST_AI_GROUND, DEFINITIONS.<API key>, (uint)gconffixCurrent.iRangeAIGroundUnits, <API key>.GROUND); } #endregion #region Config File Read & Write private void <API key>() { gconffixCurrent.bExitOnFsxExit = (xmldSettings["fsxget"]["settings"]["options"]["general"]["application-startup"].Attributes["Exit"].Value.ToLower() == "true"); lock (lockChConf) { gconfchCurrent.bEnabled = (xmldSettings["fsxget"]["settings"]["options"]["general"]["enable-on-startup"].Attributes["Enabled"].Value == "1"); gconfchCurrent.bShowBalloons = (xmldSettings["fsxget"]["settings"]["options"]["general"]["show-balloon-tips"].Attributes["Enabled"].Value == "1"); } gconffixCurrent.bLoadKMLFile = (xmldSettings["fsxget"]["settings"]["options"]["general"]["load-kml-file"].Attributes["Enabled"].Value == "1"); //gconffixCurrent.bCheckForUpdates = (xmldSettings["fsxget"]["settings"]["options"]["general"]["update-check"].Attributes["Enabled"].Value == "1"); gconffixCurrent.iTimerUserAircraft = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Interval"].Value); gconffixCurrent.bQueryUserAircraft = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Enabled"].Value == "1"); gconffixCurrent.iTimerUserPath = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Interval"].Value); gconffixCurrent.bQueryUserPath = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Enabled"].Value == "1"); gconffixCurrent.<API key> = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["<API key>"].Attributes["Interval"].Value); gconffixCurrent.bUserPathPrediction = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["<API key>"].Attributes["Enabled"].Value == "1"); int iCount = 0; for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["<API key>"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.Name == "prediction-point") iCount++; } gconffixCurrent.dPredictionTimes = new double[iCount]; iCount = 0; for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["<API key>"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.Name == "prediction-point") { gconffixCurrent.dPredictionTimes[iCount] = System.Int64.Parse(xmlnTemp.Attributes["Time"].Value); iCount++; } } gconffixCurrent.iTimerAIAircrafts = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Interval"].Value); gconffixCurrent.iRangeAIAircrafts = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Range"].Value); gconffixCurrent.bQueryAIAircrafts = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Enabled"].Value == "1"); gconffixCurrent.bPredictAIAircrafts = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Prediction"].Value == "1"); gconffixCurrent.<API key> = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["PredictionPoints"].Value == "1"); gconffixCurrent.iTimerAIHelicopters = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Interval"].Value); gconffixCurrent.iRangeAIHelicopters = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Range"].Value); gconffixCurrent.bQueryAIHelicopters = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Enabled"].Value == "1"); gconffixCurrent.<API key> = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Prediction"].Value == "1"); gconffixCurrent.<API key> = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["PredictionPoints"].Value == "1"); gconffixCurrent.iTimerAIBoats = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Interval"].Value); gconffixCurrent.iRangeAIBoats = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Range"].Value); gconffixCurrent.bQueryAIBoats = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Enabled"].Value == "1"); gconffixCurrent.bPredictAIBoats = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Prediction"].Value == "1"); gconffixCurrent.<API key> = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["PredictionPoints"].Value == "1"); gconffixCurrent.iTimerAIGroundUnits = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Interval"].Value); gconffixCurrent.iRangeAIGroundUnits = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Range"].Value); gconffixCurrent.bQueryAIGroundUnits = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Enabled"].Value == "1"); gconffixCurrent.<API key> = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Prediction"].Value == "1"); gconffixCurrent.<API key> = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["PredictionPoints"].Value == "1"); gconffixCurrent.bQueryAIObjects = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"].Attributes["Enabled"].Value == "1"); gconffixCurrent.<API key> = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-aircraft"].Attributes["Interval"].Value); gconffixCurrent.iUpdateGEUserPath = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path"].Attributes["Interval"].Value); gconffixCurrent.<API key> = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["<API key>"].Attributes["Interval"].Value); gconffixCurrent.<API key> = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-aircrafts"].Attributes["Interval"].Value); gconffixCurrent.<API key> = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-helicopters"].Attributes["Interval"].Value); gconffixCurrent.iUpdateGEAIBoats = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-boats"].Attributes["Interval"].Value); gconffixCurrent.<API key> = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-ground-units"].Attributes["Interval"].Value); gconffixCurrent.iServerPort = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["port"].Attributes["Value"].Value); gconffixCurrent.uiServerAccessLevel = (uint)System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["access-level"].Attributes["Value"].Value); gconffixCurrent.<API key> = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Local"].Value.ToLower() == "true"); gconffixCurrent.szFsxConnectionHost = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Host"].Value; gconffixCurrent.szFsxConnectionPort = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Port"].Value; gconffixCurrent.<API key> = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Protocol"].Value; //gconffixCurrent.bLoadFlightPlans = (xmldSettings["fsxget"]["settings"]["options"]["flightplans"].Attributes["Enabled"].Value == "1"); gconffixCurrent.utUnits = (UnitType)System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["units"].InnerText); gconffixCurrent.szUserdefinedPath = ""; } private void ConfigMirrorToForm() { checkBox1.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["application-startup"].Attributes["Exit"].Value.ToLower() == "true"); <API key>.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["enable-on-startup"].Attributes["Enabled"].Value == "1"); <API key>.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["show-balloon-tips"].Attributes["Enabled"].Value == "1"); checkBoxLoadKMLFile.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["load-kml-file"].Attributes["Enabled"].Value == "1"); //checkBoxUpdateCheck.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["update-check"].Attributes["Enabled"].Value == "1"); <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Interval"].Value); <API key>.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Enabled"].Value == "1"); <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Interval"].Value); checkQueryUserPath.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Enabled"].Value == "1"); <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["<API key>"].Attributes["Interval"].Value); <API key>.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["<API key>"].Attributes["Enabled"].Value == "1"); <API key>.Items.Clear(); for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["<API key>"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) { if (xmlnTemp.Name == "prediction-point") { <API key> lbptiTemp = new <API key>(); lbptiTemp.dTime = System.Int64.Parse(xmlnTemp.Attributes["Time"].Value); bool bInserted = false; for (int n = 0; n < <API key>.Items.Count; n++) { if (((<API key>)<API key>.Items[n]).dTime > lbptiTemp.dTime) { <API key>.Items.Insert(n, lbptiTemp); bInserted = true; break; } } if (!bInserted) <API key>.Items.Add(lbptiTemp); } } <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Interval"].Value); <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Range"].Value); <API key>.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["PredictionPoints"].Value == "1"); <API key>.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Prediction"].Value == "1"); <API key>(null, null); <API key>.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Enabled"].Value == "1"); <API key>(null, null); <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Interval"].Value); <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Range"].Value); <API key>.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["PredictionPoints"].Value == "1"); <API key>.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Prediction"].Value == "1"); <API key>(null, null); <API key>.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Enabled"].Value == "1"); <API key>(null, null); <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Interval"].Value); <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Range"].Value); <API key>.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["PredictionPoints"].Value == "1"); <API key>.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Prediction"].Value == "1"); <API key>(null, null); <API key>.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Enabled"].Value == "1"); <API key>(null, null); <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Interval"].Value); <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Range"].Value); <API key>.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["PredictionPoints"].Value == "1"); <API key>.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Prediction"].Value == "1"); <API key>(null, null); <API key>.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Enabled"].Value == "1"); <API key>(null, null); <API key>.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"].Attributes["Enabled"].Value == "1"); <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-aircraft"].Attributes["Interval"].Value); <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path"].Attributes["Interval"].Value); <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["<API key>"].Attributes["Interval"].Value); <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-aircrafts"].Attributes["Interval"].Value); <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-helicopters"].Attributes["Interval"].Value); <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-boats"].Attributes["Interval"].Value); <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-ground-units"].Attributes["Interval"].Value); <API key>.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["port"].Attributes["Value"].Value); if (System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["access-level"].Attributes["Value"].Value) == 1) <API key>.Checked = true; else <API key>.Checked = true; //<API key>.Checked = (xmldSettings["fsxget"]["settings"]["options"]["flightplans"].Attributes["Enabled"].Value == "1"); //listViewFlightPlans.Items.Clear(); //int iCount = 0; //for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["flightplans"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) // ListViewItem lviTemp = listViewFlightPlans.Items.Insert(iCount, xmlnTemp.Attributes["Name"].Value); // lviTemp.Checked = (xmlnTemp.Attributes["Show"].Value == "1" ? true : false); // lviTemp.SubItems.Add(xmlnTemp.Attributes["File"].Value); // iCount++; radioButton7.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Local"].Value.ToLower() == "true"); radioButton6.Checked = !radioButton7.Checked; textBox1.Text = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Host"].Value; textBox3.Text = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Port"].Value; comboBox1.SelectedIndex = comboBox1.FindString(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Protocol"].Value); comboBox2.SelectedIndex = int.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["units"].InnerText); <API key>(); UpdateButtonStates(); } private void <API key>() { xmldSettings["fsxget"]["settings"]["options"]["general"]["application-startup"].Attributes["Exit"].Value = checkBox1.Checked ? "True" : "False"; xmldSettings["fsxget"]["settings"]["options"]["general"]["enable-on-startup"].Attributes["Enabled"].Value = <API key>.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["general"]["show-balloon-tips"].Attributes["Enabled"].Value = <API key>.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["general"]["load-kml-file"].Attributes["Enabled"].Value = checkBoxLoadKMLFile.Checked ? "1" : "0"; //xmldSettings["fsxget"]["settings"]["options"]["general"]["update-check"].Attributes["Enabled"].Value = checkBoxUpdateCheck.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Interval"].Value = <API key>.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Enabled"].Value = <API key>.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Interval"].Value = <API key>.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Enabled"].Value = checkQueryUserPath.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["<API key>"].Attributes["Interval"].Value = <API key>.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["<API key>"].Attributes["Enabled"].Value = <API key>.Checked ? "1" : "0"; XmlNode xmlnTempLoop = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["<API key>"].FirstChild; while (xmlnTempLoop != null) { XmlNode xmlnDelete = xmlnTempLoop; xmlnTempLoop = xmlnTempLoop.NextSibling; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["<API key>"].RemoveChild(xmlnDelete); } for (int n = 0; n < <API key>.Items.Count; n++) { XmlNode xmlnTemp = xmldSettings.CreateElement("prediction-point"); XmlAttribute xmlaTemp = xmldSettings.CreateAttribute("Time"); xmlaTemp.Value = ((<API key>)<API key>.Items[n]).dTime.ToString(); xmlnTemp.Attributes.Append(xmlaTemp); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["<API key>"].AppendChild(xmlnTemp); } xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Interval"].Value = <API key>.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Range"].Value = <API key>.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Enabled"].Value = <API key>.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Prediction"].Value = <API key>.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["PredictionPoints"].Value = <API key>.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Interval"].Value = <API key>.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Range"].Value = <API key>.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Enabled"].Value = <API key>.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Prediction"].Value = <API key>.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["PredictionPoints"].Value = <API key>.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Interval"].Value = <API key>.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Range"].Value = <API key>.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Enabled"].Value = <API key>.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Prediction"].Value = <API key>.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["PredictionPoints"].Value = <API key>.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Interval"].Value = <API key>.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Range"].Value = <API key>.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Enabled"].Value = <API key>.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["Prediction"].Value = <API key>.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["<API key>"].Attributes["PredictionPoints"].Value = <API key>.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"].Attributes["Enabled"].Value = <API key>.Checked ? "1" : "0"; xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-aircraft"].Attributes["Interval"].Value = <API key>.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path"].Attributes["Interval"].Value = <API key>.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["<API key>"].Attributes["Interval"].Value = <API key>.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-aircrafts"].Attributes["Interval"].Value = <API key>.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-helicopters"].Attributes["Interval"].Value = <API key>.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-boats"].Attributes["Interval"].Value = <API key>.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-ground-units"].Attributes["Interval"].Value = <API key>.Value.ToString(); xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["port"].Attributes["Value"].Value = <API key>.Value.ToString(); if (<API key>.Checked) xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["access-level"].Attributes["Value"].Value = "1"; else xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["access-level"].Attributes["Value"].Value = "0"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Local"].Value = radioButton7.Checked ? "True" : "False"; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Protocol"].Value = comboBox1.SelectedItem.ToString(); xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Host"].Value = textBox1.Text; xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Port"].Value = textBox3.Text; xmldSettings["fsxget"]["settings"]["options"]["ge"]["units"].InnerXml = comboBox2.SelectedIndex.ToString(); //xmldSettings["fsxget"]["settings"]["options"]["flightplans"].Attributes["Enabled"].Value = <API key>.Checked ? "1" : "0"; } //private void LoadFlightPlans() // bool bError = false; // FlightPlan fpTemp; // XmlDocument xmldTemp = new XmlDocument(); // try // int iCount = 0; // fpTemp.szName = ""; // fpTemp.uiID = 0; // fpTemp.xmldPlan = null; // for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["flightplans"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling) // try // if (xmlnTemp.Attributes["Show"].Value == "0") // continue; // XmlReader xmlrTemp = new XmlTextReader(xmlnTemp.Attributes["File"].Value); // fpTemp.uiID = iCount; // fpTemp.xmldPlan = new XmlDocument(); // fpTemp.xmldPlan.Load(xmlrTemp); // xmlrTemp.Close(); // xmlrTemp = null; // catch // bError = true; // continue; // lock (lockFlightPlanList) // listFlightPlans.Add(fpTemp); // iCount++; // catch // MessageBox.Show("Could not read flight plan list from settings file! No flight plans will be loaded.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); // if (bError) // MessageBox.Show("There were errors loading some of the flight plans! These flight plans will not be shown.\n\nThis problem might be due to incorrect or no longer existing flight plan files.\nPlease remove them from the flight plan list in the options dialog.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); #endregion #region Assembly Attribute Accessors public string AssemblyTitle { get { // Get all Title attributes on this assembly object[] attributes = Assembly.<API key>().GetCustomAttributes(typeof(<API key>), false); // If there is at least one Title attribute if (attributes.Length > 0) { // Select the first one <API key> titleAttribute = (<API key>)attributes[0]; // If it is not an empty string, return it if (titleAttribute.Title != "") return titleAttribute.Title; } // If there was no Title attribute, or if the Title attribute was the empty string, return the .exe name return System.IO.Path.<API key>(Assembly.<API key>().CodeBase); } } public string AssemblyVersion { get { return Assembly.<API key>().GetName().Version.ToString(); } } public string AssemblyDescription { get { // Get all Description attributes on this assembly object[] attributes = Assembly.<API key>().GetCustomAttributes(typeof(<API key>), false); // If there aren't any Description attributes, return an empty string if (attributes.Length == 0) return ""; // If there is a Description attribute, return its value return ((<API key>)attributes[0]).Description; } } public string AssemblyProduct { get { // Get all Product attributes on this assembly object[] attributes = Assembly.<API key>().GetCustomAttributes(typeof(<API key>), false); // If there aren't any Product attributes, return an empty string if (attributes.Length == 0) return ""; // If there is a Product attribute, return its value return ((<API key>)attributes[0]).Product; } } public string AssemblyCopyright { get { object[] attributes = Assembly.<API key>().GetCustomAttributes(typeof(<API key>), false); if (attributes.Length == 0) return ""; return ((<API key>)attributes[0]).Copyright; } } public string AssemblyCompany { get { // Get all Company attributes on this assembly object[] attributes = Assembly.<API key>().GetCustomAttributes(typeof(<API key>), false); // If there aren't any Company attributes, return an empty string if (attributes.Length == 0) return ""; // If there is a Company attribute, return its value return ((<API key>)attributes[0]).Company; } } #endregion #region User Interface Handlers private void <API key>(object sender, EventArgs e) { bClose = true; Close(); } private void <API key>(object sender, EventArgs e) { safeShowMainDialog(0); } private void <API key>(object sender, EventArgs e) { bool bTemp = <API key>.Checked; lock (lockChConf) { if (bTemp != gconfchCurrent.bEnabled) { gconfchCurrent.bEnabled = bTemp; if (gconfchCurrent.bEnabled) globalConnect(); else globalDisconnect(); } } } private void <API key>(object sender, EventArgs e) { lock (lockChConf) { gconfchCurrent.bShowBalloons = <API key>.Checked; } // This call is safe as the existence of this key has been checked by calling configMirrorToForm at startup. xmldSettings["fsxget"]["settings"]["options"]["general"]["show-balloon-tips"].Attributes["Enabled"].Value = <API key>.Checked ? "1" : "0"; } private void <API key>(object sender, EventArgs e) { safeShowMainDialog(5); } private void <API key>(object sender, EventArgs e) { lock (lockKmlUserPath) { <API key> = ""; } lock (<API key>) { szKmlUserPrediction = ""; <API key>.Clear(); } lock (<API key>) { clearPPStructure(ref ppPos1); clearPPStructure(ref ppPos2); } } private void <API key>(object sender, EventArgs e) { try { System.Diagnostics.Process.Start(szPathFSX); } catch { MessageBox.Show("An error occured while trying to start Microsoft Flight Simulator X.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void <API key>(object sender, EventArgs e) { try { lock (lockListenerControl) { if (gconffixCurrent.bLoadKMLFile && bConnected) System.Diagnostics.Process.Start(szUserAppPath + "\\pub\\fsxgetd.kml"); else System.Diagnostics.Process.Start(szUserAppPath + "\\pub\\fsxgets.kml"); } } catch { MessageBox.Show("An error occured while trying to start Google Earth.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void <API key>(object sender, MouseEventArgs e) { if (notifyIconMain.ContextMenuStrip == null) this.Activate(); } private void <API key>(object sender, <API key> e) { try { linkLabel1.LinkVisited = true; System.Diagnostics.Process.Start("http: } catch { MessageBox.Show("Unable to open http: } } private void <API key>(object sender, EventArgs e) { <API key>.Enabled = <API key>.Enabled = <API key>.Enabled = <API key>.Enabled = <API key>.Checked; bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { <API key>(null, null); bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { <API key>.Enabled = <API key>.Enabled = <API key>.Enabled = (<API key>.Enabled & <API key>.Checked); } private void <API key>(object sender, EventArgs e) { <API key>(null, null); bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { <API key>.Enabled = <API key>.Enabled = <API key>.Enabled = (<API key>.Enabled & <API key>.Checked); } private void <API key>(object sender, EventArgs e) { <API key>(null, null); bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { <API key>.Enabled = <API key>.Enabled = <API key>.Enabled = (<API key>.Enabled & <API key>.Checked); } private void <API key>(object sender, EventArgs e) { <API key>(null, null); bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { <API key>.Enabled = <API key>.Enabled = <API key>.Enabled = (<API key>.Enabled & <API key>.Checked); } private void <API key>(object sender, EventArgs e) { <API key>.Enabled = <API key>.Checked; bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { <API key>.Enabled = checkQueryUserPath.Checked; bRestartRequired = true; } private void buttonOK_Click(object sender, EventArgs e) { // Set startup options if necessary if (radioButton8.Checked) { if (!<API key>()) if (!AutoStartActivate()) MessageBox.Show("Couldn't change autorun value in registry!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); if (isFsxStartActivated()) if (!FsxStartDeactivate()) MessageBox.Show("Couldn't change FSX startup options!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (radioButton9.Checked) { if (!isFsxStartActivated()) if (!FsxStartActivate()) MessageBox.Show("Couldn't change FSX startup options!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); if (<API key>()) if (!AutoStartDeactivate()) MessageBox.Show("Couldn't change autorun value in registry!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { if (isFsxStartActivated()) if (!FsxStartDeactivate()) MessageBox.Show("Couldn't change FSX startup options!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); if (<API key>()) if (!AutoStartDeactivate()) MessageBox.Show("Couldn't change autorun value in registry!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning); } //string szRun = (string)Registry.GetValue(szRegKeyRun, AssemblyTitle, ""); <API key>(); <API key>.Checked = <API key>.Checked; notifyIconMain.ContextMenuStrip = <API key>; gconffixCurrent.utUnits = (UnitType)comboBox2.SelectedIndex; if (bRestartRequired) if (MessageBox.Show("Some of the changes you made require a restart. Do you want to restart " + Text + " now for those changes to take effect.", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) RestartApp(); Hide(); } private void buttonCancel_Click(object sender, EventArgs e) { safeHideMainDialog(); } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { gconffixCurrent.bLoadKMLFile = checkBoxLoadKMLFile.Checked; } private void <API key>(object sender, EventArgs e) { <API key>.Enabled = <API key>.Checked; bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { <API key>.Enabled = (checkBoxSaveLog.Checked); } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { <API key>(null, null); bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { <API key>.Enabled = (<API key>.Enabled & <API key>.Checked); } private void <API key>(object sender, EventArgs e) { <API key>(null, null); bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { <API key>.Enabled = (<API key>.Enabled & <API key>.Checked); } private void <API key>(object sender, EventArgs e) { <API key>(null, null); bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { <API key>.Enabled = (<API key>.Enabled & <API key>.Checked); } private void <API key>(object sender, EventArgs e) { <API key>(null, null); bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { <API key>.Enabled = (<API key>.Enabled & <API key>.Checked); } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { String szTemp = sender.ToString(); if (szTemp.Length < 7) return; szTemp = szTemp.Substring(7); String szKMLFile = ""; if (<API key>(szTemp, ref szKMLFile)) { safeShowMainDialog(0); if (<API key>.ShowDialog() == DialogResult.OK) { try { File.WriteAllText(<API key>.FileName, szKMLFile); } catch { MessageBox.Show("Could not save KML file!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } } safeHideMainDialog(); } } private void <API key>(object sender, CancelEventArgs e) { <API key>.DropDown.Items.Clear(); lock (lockIPAddressList) { bool bAddressFound = false; if (ipalLocal1 != null) { foreach (IPAddress ipaTemp in ipalLocal1) { bAddressFound = true; <API key>.DropDown.Items.Add("For IP " + ipaTemp.ToString(), null, <API key>); } } if (ipalLocal2 != null) { foreach (IPAddress ipaTemp in ipalLocal2) { bAddressFound = true; <API key>.DropDown.Items.Add("For IP " + ipaTemp.ToString(), null, <API key>); } } if (!bAddressFound) <API key>.Enabled = false; else <API key>.Enabled = true; } } private void button3_Click(object sender, EventArgs e) { if (MessageBox.Show("Are you sure you want to remove the selected items?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { //foreach (ListViewItem lviTemp in listViewFlightPlans.SelectedItems) // listViewFlightPlans.Items.Remove(lviTemp); } } private void <API key>(object sender, EventArgs e) { comboBox1.Enabled = textBox1.Enabled = textBox3.Enabled = !radioButton7.Checked; bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { comboBox1.Enabled = textBox1.Enabled = textBox3.Enabled = radioButton6.Checked; bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { bRestartRequired = true; } private void <API key>(object sender, EventArgs e) { if (radioButton10.Checked) radioButton8.Checked = radioButton9.Checked = checkBox1.Enabled = false; } private void <API key>(object sender, EventArgs e) { checkBox1.Enabled = radioButton9.Checked; } private void <API key>(object sender, EventArgs e) { if (radioButton10.Checked) radioButton8.Checked = radioButton9.Checked = checkBox1.Enabled = false; } private void <API key>(object sender, EventArgs e) { } private void <API key>(object sender, EventArgs e) { gconffixCurrent.bExitOnFsxExit = checkBox1.Checked; } private void <API key>(object sender, EventArgs e) { } private void <API key>(object sender, EventArgs e) { UpdateButtonStates(); } private void button2_Click(object sender, EventArgs e) { if (<API key>.SelectedItems.Count == 1) { int iIndex = <API key>.SelectedIndex; <API key>.Items.RemoveAt(iIndex); if (<API key>.SelectedItems.Count == 0) { if (<API key>.Items.Count > iIndex) <API key>.SelectedIndex = iIndex; else if (<API key>.Items.Count > 0) <API key>.SelectedIndex = <API key>.Items.Count - 1; } bRestartRequired = true; } } private void button1_Click(object sender, EventArgs e) { int iSeconds; if (frmAdd.ShowDialog(out iSeconds) == DialogResult.Cancel) return; <API key> lbptiTemp = new <API key>(); lbptiTemp.dTime = iSeconds; bool bInserted = false; for (int n = 0; n < <API key>.Items.Count; n++) { if (((<API key>)<API key>.Items[n]).dTime > lbptiTemp.dTime) { <API key>.Items.Insert(n, lbptiTemp); bInserted = true; break; } } if (!bInserted) <API key>.Items.Add(lbptiTemp); bRestartRequired = true; } #endregion } }
#ifndef <API key> #define <API key> #include "base/basictypes.h" #include "base/compiler_specific.h" #include "chrome/browser/extensions/<API key>.h" class <API key> : public ExtensionInstallUI { public: <API key>(); virtual ~<API key>(); virtual void OnInstallSuccess(const extensions::Extension* extension, SkBitmap* icon) OVERRIDE; virtual void OnInstallFailure( const extensions::CrxInstallerError& error) OVERRIDE; private: <API key>(<API key>); }; #endif
#include <linux/module.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/completion.h> #include <linux/devfreq.h> #include <linux/device.h> #include <linux/delay.h> #include <linux/pagemap.h> #include <linux/err.h> #include <linux/leds.h> #include <linux/scatterlist.h> #include <linux/log2.h> #include <linux/regulator/consumer.h> #include <linux/pm_runtime.h> #include <linux/pm_wakeup.h> #include <linux/suspend.h> #include <linux/fault-inject.h> #include <linux/random.h> #include <linux/slab.h> #include <linux/of.h> #include <linux/pm.h> #include <linux/jiffies.h> #include <trace/events/mmc.h> #include <linux/mmc/card.h> #include <linux/mmc/host.h> #include <linux/mmc/mmc.h> #include <linux/mmc/sd.h> #include <linux/mmc/slot-gpio.h> #include "core.h" #include "bus.h" #include "host.h" #include "sdio_bus.h" #include "mmc_ops.h" #include "sd_ops.h" #include "sdio_ops.h" /* If the device is not responding */ #define MMC_CORE_TIMEOUT_MS (10 * 60 * 1000) /* 10 minute timeout */ /* * Background operations can take a long time, depending on the housekeeping * operations the card has to perform. */ #define <API key> (30 * 1000) /* max time to wait in ms */ static struct workqueue_struct *workqueue; static const unsigned freqs[] = { 400000, 300000, 200000, 100000 }; /* * Enabling software CRCs on the data blocks can be a significant (30%) * performance cost, and for other reasons may not always be desired. * So we allow it it to be disabled. */ bool use_spi_crc = 1; module_param(use_spi_crc, bool, 0); /* * Internal function. Schedule delayed work in the MMC work queue. */ static int <API key>(struct delayed_work *work, unsigned long delay) { return queue_delayed_work(workqueue, work, delay); } /* * Internal function. Flush all scheduled work from the MMC work queue. */ static void <API key>(void) { flush_workqueue(workqueue); } #ifdef <API key> /* * Internal function. Inject random data errors. * If mmc_data is NULL no errors are injected. */ static void <API key>(struct mmc_host *host, struct mmc_request *mrq) { struct mmc_command *cmd = mrq->cmd; struct mmc_data *data = mrq->data; static const int data_errors[] = { -ETIMEDOUT, -EILSEQ, -EIO, }; if (!data) return; if (cmd->error || data->error || !should_fail(&host->fail_mmc_request, data->blksz * data->blocks)) return; data->error = data_errors[prandom_u32() % ARRAY_SIZE(data_errors)]; data->bytes_xfered = (prandom_u32() % (data->bytes_xfered >> 9)) << 9; data->fault_injected = true; } #else /* <API key> */ static inline void <API key>(struct mmc_host *host, struct mmc_request *mrq) { } #endif /* <API key> */ static bool mmc_is_data_request(struct mmc_request *mmc_request) { switch (mmc_request->cmd->opcode) { case <API key>: case <API key>: case MMC_WRITE_BLOCK: case <API key>: return true; default: return false; } } static void <API key>(struct mmc_host *host, bool lock_needed) { struct <API key> *clk_scaling = &host->clk_scaling; if (!clk_scaling->enable) return; if (lock_needed) spin_lock_bh(&clk_scaling->lock); clk_scaling->start_busy = ktime_get(); clk_scaling->is_busy_started = true; if (lock_needed) spin_unlock_bh(&clk_scaling->lock); } static void <API key>(struct mmc_host *host, bool lock_needed) { struct <API key> *clk_scaling = &host->clk_scaling; if (!clk_scaling->enable) return; if (lock_needed) spin_lock_bh(&clk_scaling->lock); if (!clk_scaling->is_busy_started) { WARN_ON(1); goto out; } clk_scaling->total_busy_time_us += ktime_to_us(ktime_sub(ktime_get(), clk_scaling->start_busy)); pr_debug("%s: accumulated busy time is %lu usec\n", mmc_hostname(host), clk_scaling->total_busy_time_us); clk_scaling->is_busy_started = false; out: if (lock_needed) spin_unlock_bh(&clk_scaling->lock); } /** * <API key>() - start busy timer for data requests * @host: pointer to mmc host structure * @lock_needed: flag indication if locking is needed * * This function starts the busy timer in case it was not already started. */ void <API key>(struct mmc_host *host, bool lock_needed) { if (!host->clk_scaling.enable) return; if (lock_needed) spin_lock_bh(&host->clk_scaling.lock); if (!host->clk_scaling.is_busy_started && !test_bit(<API key>, &host->cmdq_ctx.curr_state)) { host->clk_scaling.start_busy = ktime_get(); host->clk_scaling.is_busy_started = true; } if (lock_needed) spin_unlock_bh(&host->clk_scaling.lock); } EXPORT_SYMBOL(<API key>); /** * <API key>() - stop busy timer for last data requests * @host: pointer to mmc host structure * @lock_needed: flag indication if locking is needed * * This function stops the busy timer in case it is the last data request. * In case the current request is not the last one, the busy time till * now will be accumulated and the counter will be restarted. */ void <API key>(struct mmc_host *host, bool lock_needed, bool is_cmdq_dcmd) { if (!host->clk_scaling.enable) return; if (lock_needed) spin_lock_bh(&host->clk_scaling.lock); /* * For CQ mode: In completion of DCMD request, start busy time in * case of pending data requests */ if (is_cmdq_dcmd) { if (host->cmdq_ctx.data_active_reqs) { host->clk_scaling.is_busy_started = true; host->clk_scaling.start_busy = ktime_get(); } goto out; } host->clk_scaling.total_busy_time_us += ktime_to_us(ktime_sub(ktime_get(), host->clk_scaling.start_busy)); if (host->cmdq_ctx.data_active_reqs) { host->clk_scaling.is_busy_started = true; host->clk_scaling.start_busy = ktime_get(); } else { host->clk_scaling.is_busy_started = false; } out: if (lock_needed) spin_unlock_bh(&host->clk_scaling.lock); } EXPORT_SYMBOL(<API key>); /** * mmc_can_scale_clk() - Check clock scaling capability * @host: pointer to mmc host structure */ bool mmc_can_scale_clk(struct mmc_host *host) { if (!host) { pr_err("bad host parameter\n"); WARN_ON(1); return false; } return host->caps2 & MMC_CAP2_CLK_SCALE; } EXPORT_SYMBOL(mmc_can_scale_clk); static int <API key>(struct device *dev, struct devfreq_dev_status *status) { struct mmc_host *host = container_of(dev, struct mmc_host, class_dev); struct <API key> *clk_scaling; if (!host) { pr_err("bad host parameter\n"); WARN_ON(1); return -EINVAL; } clk_scaling = &host->clk_scaling; if (!clk_scaling->enable) return 0; spin_lock_bh(&clk_scaling->lock); /* accumulate the busy time of ongoing work */ memset(status, 0, sizeof(*status)); if (clk_scaling->is_busy_started) { if (mmc_card_cmdq(host->card)) { /* the "busy-timer" will be restarted in case there * are pending data requests */ <API key>(host, false, false); } else { <API key>(host, false); <API key>(host, false); } } status->busy_time = clk_scaling->total_busy_time_us; status->total_time = ktime_to_us(ktime_sub(ktime_get(), clk_scaling-><API key>)); clk_scaling->total_busy_time_us = 0; status->current_frequency = clk_scaling->curr_freq; clk_scaling-><API key> = ktime_get(); pr_debug("%s: status: load = %lu%% - total_time=%lu busy_time = %lu, clk=%lu\n", mmc_hostname(host), (status->busy_time*100)/status->total_time, status->total_time, status->busy_time, status->current_frequency); spin_unlock_bh(&clk_scaling->lock); return 0; } static bool <API key>(struct mmc_host *host) { struct mmc_card *card = host->card; u32 status; if (!card || (mmc_card_mmc(card) && (card->part_curr == <API key> || <API key>(card)))) return false; if (mmc_send_status(card, &status)) { pr_err("%s: Get card status fail\n", mmc_hostname(card->host)); return false; } return R1_CURRENT_STATE(status) == R1_STATE_TRAN; } int <API key>(struct mmc_host *host) { int err = 0; err = <API key>(host->cmdq_ctx.queue_empty_wq, (!host->cmdq_ctx.active_reqs)); if (host->cmdq_ctx.active_reqs) { pr_err("%s: %s: unexpected active requests (%lu)\n", mmc_hostname(host), __func__, host->cmdq_ctx.active_reqs); return -EPERM; } err = mmc_cmdq_halt(host, true); if (err) { pr_err("%s: %s: mmc_cmdq_halt failed (%d)\n", mmc_hostname(host), __func__, err); goto out; } out: return err; } EXPORT_SYMBOL(<API key>); int mmc_clk_update_freq(struct mmc_host *host, unsigned long freq, enum mmc_load state) { int err = 0; bool cmdq_mode; if (!host) { pr_err("bad host parameter\n"); WARN_ON(1); return -EINVAL; } mmc_host_clk_hold(host); cmdq_mode = mmc_card_cmdq(host->card); /* make sure the card supports the frequency we want */ if (unlikely(freq > host->card->clk_scaling_highest)) { freq = host->card->clk_scaling_highest; pr_warn("%s: %s: frequency was overridden to %lu\n", mmc_hostname(host), __func__, host->card->clk_scaling_highest); } if (unlikely(freq < host->card->clk_scaling_lowest)) { freq = host->card->clk_scaling_lowest; pr_warn("%s: %s: frequency was overridden to %lu\n", mmc_hostname(host), __func__, host->card->clk_scaling_lowest); } if (freq == host->clk_scaling.curr_freq) goto out; if (host->ops->notify_load) { err = host->ops->notify_load(host, state); if (err) { pr_err("%s: %s: fail on notify_load\n", mmc_hostname(host), __func__); goto out; } } if (cmdq_mode) { err = <API key>(host); if (err) { pr_err("%s: %s: failed halting queue (%d)\n", mmc_hostname(host), __func__, err); goto halt_failed; } } if (!<API key>(host)) { pr_debug("%s: invalid state for clock scaling - skipping", mmc_hostname(host)); goto invalid_state; } err = host->bus_ops->change_bus_speed(host, &freq); if (!err) host->clk_scaling.curr_freq = freq; else pr_err("%s: %s: failed (%d) at freq=%lu\n", mmc_hostname(host), __func__, err, freq); invalid_state: if (cmdq_mode) { if (mmc_cmdq_halt(host, false)) pr_err("%s: %s: cmdq unhalt failed\n", mmc_hostname(host), __func__); } halt_failed: if (err) { /* restore previous state */ if (host->ops->notify_load) if (host->ops->notify_load(host, host->clk_scaling.state)) pr_err("%s: %s: fail on notify_load restore\n", mmc_hostname(host), __func__); } out: <API key>(host); return err; } EXPORT_SYMBOL(mmc_clk_update_freq); static int <API key>(struct device *dev, unsigned long *freq, u32 devfreq_flags) { struct mmc_host *host = container_of(dev, struct mmc_host, class_dev); struct <API key> *clk_scaling; int err = 0; int abort; if (!(host && freq)) { pr_err("%s: unexpected host/freq parameter\n", __func__); err = -EINVAL; goto out; } clk_scaling = &host->clk_scaling; if (!clk_scaling->enable) goto out; pr_debug("%s: target freq = %lu (%s)\n", mmc_hostname(host), *freq, current->comm); if ((clk_scaling->curr_freq == *freq) || clk_scaling-><API key>) goto out; /* No need to scale the clocks if they are gated */ if (!host->ios.clock) goto out; spin_lock_bh(&clk_scaling->lock); if (clk_scaling-><API key>) { pr_debug("%s: clocks scaling is already in-progress by mmc thread\n", mmc_hostname(host)); spin_unlock_bh(&clk_scaling->lock); goto out; } clk_scaling->need_freq_change = true; clk_scaling->target_freq = *freq; clk_scaling->state = *freq < clk_scaling->curr_freq ? MMC_LOAD_LOW : MMC_LOAD_HIGH; spin_unlock_bh(&clk_scaling->lock); abort = __mmc_claim_host(host, &clk_scaling->devfreq_abort); if (abort) goto out; /* * In case we were able to claim host there is no need to * defer the frequency change. It will be done now */ clk_scaling->need_freq_change = false; mmc_host_clk_hold(host); err = mmc_clk_update_freq(host, *freq, clk_scaling->state); if (err && err != -EAGAIN) pr_err("%s: clock scale to %lu failed with error %d\n", mmc_hostname(host), *freq, err); else pr_debug("%s: clock change to %lu finished successfully (%s)\n", mmc_hostname(host), *freq, current->comm); <API key>(host); mmc_release_host(host); out: return err; } /** * <API key>() - scale clocks from data path (mmc thread context) * @host: pointer to mmc host structure * * This function does clock scaling in case "need_freq_change" flag was set * by the clock scaling logic. */ void <API key>(struct mmc_host *host) { unsigned long target_freq; int err; if (!host->clk_scaling.enable) return; spin_lock_bh(&host->clk_scaling.lock); if (host->clk_scaling.<API key> || !(host->clk_scaling.need_freq_change)) { spin_unlock_bh(&host->clk_scaling.lock); return; } atomic_inc(&host->clk_scaling.devfreq_abort); target_freq = host->clk_scaling.target_freq; host->clk_scaling.<API key> = true; host->clk_scaling.need_freq_change = false; spin_unlock_bh(&host->clk_scaling.lock); pr_debug("%s: doing deferred frequency change (%lu) (%s)\n", mmc_hostname(host), target_freq, current->comm); err = mmc_clk_update_freq(host, target_freq, host->clk_scaling.state); if (err && err != -EAGAIN) pr_err("%s: failed on deferred scale clocks (%d)\n", mmc_hostname(host), err); else pr_debug("%s: clocks were successfully scaled to %lu (%s)\n", mmc_hostname(host), target_freq, current->comm); host->clk_scaling.<API key> = false; atomic_dec(&host->clk_scaling.devfreq_abort); } EXPORT_SYMBOL(<API key>); static int <API key>(struct mmc_host *host) { int i; struct <API key> *clk_scaling = &host->clk_scaling; pr_debug("%s: supported: lowest=%lu, highest=%lu\n", mmc_hostname(host), host->card->clk_scaling_lowest, host->card->clk_scaling_highest); if (!clk_scaling->freq_table) { pr_debug("%s: no frequency table defined - setting default\n", mmc_hostname(host)); clk_scaling->freq_table = kzalloc( 2*sizeof(*(clk_scaling->freq_table)), GFP_KERNEL); if (!clk_scaling->freq_table) return -ENOMEM; clk_scaling->freq_table[0] = host->card->clk_scaling_lowest; clk_scaling->freq_table[1] = host->card->clk_scaling_highest; clk_scaling->freq_table_sz = 2; goto out; } if (host->card->clk_scaling_lowest > clk_scaling->freq_table[0]) pr_debug("%s: frequency table undershot possible freq\n", mmc_hostname(host)); if (strcmp(mmc_hostname(host), "mmc1") == 0) { clk_scaling->freq_table[0] = host->card->clk_scaling_highest; } else { for (i = 0; i < clk_scaling->freq_table_sz; i++) { if (clk_scaling->freq_table[i] < host->card->clk_scaling_highest) { continue; } else { break; } } clk_scaling->freq_table[i] = host->card->clk_scaling_highest; clk_scaling->freq_table_sz = i + 1; } out: clk_scaling->devfreq_profile.freq_table = clk_scaling->freq_table; clk_scaling->devfreq_profile.max_state = clk_scaling->freq_table_sz; for (i = 0; i < clk_scaling->freq_table_sz; i++) pr_debug("%s: freq[%d] = %u\n", mmc_hostname(host), i, clk_scaling->freq_table[i]); return 0; } /** * <API key>() - Initialize clock scaling * @host: pointer to mmc host structure * * Initialize clock scaling for supported hosts. It is assumed that the caller * ensure clock is running at maximum possible frequency before calling this * function. Shall use struct <API key> to configure * governor. */ int <API key>(struct mmc_host *host) { int err; if (!host || !host->card) { pr_err("%s: unexpected host/card parameters\n", __func__); return -EINVAL; } if (!mmc_can_scale_clk(host) || !host->bus_ops->change_bus_speed) { pr_debug("%s: clock scaling is not supported\n", mmc_hostname(host)); return 0; } pr_debug("registering %s dev (%p) to devfreq", mmc_hostname(host), mmc_classdev(host)); if (host->clk_scaling.devfreq) { pr_err("%s: dev is already registered for dev %p\n", mmc_hostname(host), mmc_dev(host)); return -EPERM; } spin_lock_init(&host->clk_scaling.lock); atomic_set(&host->clk_scaling.devfreq_abort, 0); host->clk_scaling.curr_freq = host->ios.clock; host->clk_scaling.<API key> = false; host->clk_scaling.need_freq_change = false; host->clk_scaling.is_busy_started = false; host->clk_scaling.devfreq_profile.polling_ms = host->clk_scaling.polling_delay_ms; host->clk_scaling.devfreq_profile.get_dev_status = <API key>; host->clk_scaling.devfreq_profile.target = <API key>; host->clk_scaling.devfreq_profile.initial_freq = host->ios.clock; host->clk_scaling.ondemand_gov_data.simple_scaling = true; host->clk_scaling.ondemand_gov_data.upthreshold = host->clk_scaling.upthreshold; host->clk_scaling.ondemand_gov_data.downdifferential = host->clk_scaling.upthreshold - host->clk_scaling.downthreshold; err = <API key>(host); if (err) { pr_err("%s: fail to create devfreq frequency table\n", mmc_hostname(host)); return err; } pr_debug("%s: adding devfreq with: upthreshold=%u downthreshold=%u polling=%u\n", mmc_hostname(host), host->clk_scaling.ondemand_gov_data.upthreshold, host->clk_scaling.ondemand_gov_data.downdifferential, host->clk_scaling.devfreq_profile.polling_ms); host->clk_scaling.devfreq = devfreq_add_device( mmc_classdev(host), &host->clk_scaling.devfreq_profile, "simple_ondemand", &host->clk_scaling.ondemand_gov_data); if (!host->clk_scaling.devfreq) { pr_err("%s: unable to register with devfreq\n", mmc_hostname(host)); return -EPERM; } pr_debug("%s: clk scaling is enabled for device %s (%p) with devfreq %p (clock = %uHz)\n", mmc_hostname(host), dev_name(mmc_classdev(host)), mmc_classdev(host), host->clk_scaling.devfreq, host->ios.clock); host->clk_scaling.enable = true; return err; } EXPORT_SYMBOL(<API key>); /** * <API key>() - suspend clock scaling * @host: pointer to mmc host structure * * This API will suspend devfreq feature for the specific host. * The statistics collected by mmc will be cleared. * This function is intended to be called by the pm callbacks * (e.g. runtime_suspend, suspend) of the mmc device */ int <API key>(struct mmc_host *host) { int err; if (!host) { WARN(1, "bad host parameter\n"); return -EINVAL; } if (!mmc_can_scale_clk(host) || !host->clk_scaling.enable) return 0; if (!host->clk_scaling.devfreq) { pr_err("%s: %s: no devfreq is assosiated with this device\n", mmc_hostname(host), __func__); return -EPERM; } atomic_inc(&host->clk_scaling.devfreq_abort); wake_up(&host->wq); err = <API key>(host->clk_scaling.devfreq); if (err) { pr_err("%s: %s: failed to suspend devfreq\n", mmc_hostname(host), __func__); return err; } host->clk_scaling.enable = false; host->clk_scaling.total_busy_time_us = 0; pr_debug("%s: devfreq suspended\n", mmc_hostname(host)); return 0; } EXPORT_SYMBOL(<API key>); /** * <API key>() - resume clock scaling * @host: pointer to mmc host structure * * This API will resume devfreq feature for the specific host. * This API is intended to be called by the pm callbacks * (e.g. runtime_suspend, suspend) of the mmc device */ int <API key>(struct mmc_host *host) { int err = 0; u32 max_clk_idx = 0; u32 devfreq_max_clk = 0; u32 devfreq_min_clk = 0; if (!host) { WARN(1, "bad host parameter\n"); return -EINVAL; } if (!mmc_can_scale_clk(host)) return 0; if (!host->clk_scaling.devfreq) { pr_err("%s: %s: no devfreq is assosiated with this device\n", mmc_hostname(host), __func__); return -EPERM; } atomic_set(&host->clk_scaling.devfreq_abort, 0); max_clk_idx = host->clk_scaling.freq_table_sz - 1; devfreq_max_clk = host->clk_scaling.freq_table[max_clk_idx]; devfreq_min_clk = host->clk_scaling.freq_table[0]; host->clk_scaling.curr_freq = devfreq_max_clk; if (host->ios.clock < host->card->clk_scaling_highest) host->clk_scaling.curr_freq = devfreq_min_clk; host->clk_scaling.<API key> = false; host->clk_scaling.need_freq_change = false; err = <API key>(host->clk_scaling.devfreq); if (err) { pr_err("%s: %s: failed to resume devfreq (%d)\n", mmc_hostname(host), __func__, err); } else { host->clk_scaling.enable = true; pr_debug("%s: devfreq resumed\n", mmc_hostname(host)); } return err; } EXPORT_SYMBOL(<API key>); /** * <API key>() - Disable clock scaling * @host: pointer to mmc host structure * * Disable clock scaling permanently. */ int <API key>(struct mmc_host *host) { int err; if (!host) { pr_err("%s: bad host parameter\n", __func__); WARN_ON(1); return -EINVAL; } if (!mmc_can_scale_clk(host)) return 0; if (!host->clk_scaling.devfreq) { pr_err("%s: %s: no devfreq is assosiated with this device\n", mmc_hostname(host), __func__); return -EPERM; } err = <API key>(host); if (err) { pr_err("%s: %s: fail to suspend clock scaling (%d)\n", mmc_hostname(host), __func__, err); return err; } err = <API key>(host->clk_scaling.devfreq); if (err) { pr_err("%s: remove devfreq failed (%d)\n", mmc_hostname(host), err); return err; } host->clk_scaling.devfreq = NULL; atomic_set(&host->clk_scaling.devfreq_abort, 1); pr_debug("%s: devfreq was removed\n", mmc_hostname(host)); return 0; } EXPORT_SYMBOL(<API key>); /** * mmc_request_done - finish processing an MMC request * @host: MMC host which completed request * @mrq: MMC request which request * * MMC drivers should call this function when they have completed * their processing of a request. */ void mmc_request_done(struct mmc_host *host, struct mmc_request *mrq) { struct mmc_command *cmd = mrq->cmd; int err = cmd->error; #ifdef <API key> ktime_t diff; #endif if (host->clk_scaling.is_busy_started) <API key>(host, true); if (err && cmd->retries && mmc_host_is_spi(host)) { if (cmd->resp[0] & <API key>) cmd->retries = 0; } if (err && cmd->retries && !mmc_card_removed(host->card)) { /* * Request starter must handle retries - see * <API key>(). */ if (mrq->done) mrq->done(mrq); } else { <API key>(host, mrq); led_trigger_event(host->led, LED_OFF); pr_debug("%s: req done (CMD%u): %d: %08x %08x %08x %08x\n", mmc_hostname(host), cmd->opcode, err, cmd->resp[0], cmd->resp[1], cmd->resp[2], cmd->resp[3]); if (mrq->data) { #ifdef <API key> if (host->perf_enable) { diff = ktime_sub(ktime_get(), host->perf.start); if (mrq->data->flags == MMC_DATA_READ) { host->perf.rbytes_drv += mrq->data->bytes_xfered; host->perf.rtime_drv = ktime_add(host->perf.rtime_drv, diff); } else { host->perf.wbytes_drv += mrq->data->bytes_xfered; host->perf.wtime_drv = ktime_add(host->perf.wtime_drv, diff); } } #endif pr_debug("%s: %d bytes transferred: %d\n", mmc_hostname(host), mrq->data->bytes_xfered, mrq->data->error); <API key>(cmd->opcode, cmd->arg, mrq->data); } if (mrq->stop) { pr_debug("%s: (CMD%u): %d: %08x %08x %08x %08x\n", mmc_hostname(host), mrq->stop->opcode, mrq->stop->error, mrq->stop->resp[0], mrq->stop->resp[1], mrq->stop->resp[2], mrq->stop->resp[3]); } if (mrq->done) mrq->done(mrq); <API key>(host); } } EXPORT_SYMBOL(mmc_request_done); static void mmc_start_request(struct mmc_host *host, struct mmc_request *mrq) { #ifdef CONFIG_MMC_DEBUG unsigned int i, sz; struct scatterlist *sg; #endif if (mrq->sbc) { pr_debug("<%s: starting CMD%u arg %08x flags %08x>\n", mmc_hostname(host), mrq->sbc->opcode, mrq->sbc->arg, mrq->sbc->flags); } pr_debug("%s: starting CMD%u arg %08x flags %08x\n", mmc_hostname(host), mrq->cmd->opcode, mrq->cmd->arg, mrq->cmd->flags); if (mrq->data) { pr_debug("%s: blksz %d blocks %d flags %08x " "tsac %d ms nsac %d\n", mmc_hostname(host), mrq->data->blksz, mrq->data->blocks, mrq->data->flags, mrq->data->timeout_ns / 1000000, mrq->data->timeout_clks); } if (mrq->stop) { pr_debug("%s: CMD%u arg %08x flags %08x\n", mmc_hostname(host), mrq->stop->opcode, mrq->stop->arg, mrq->stop->flags); } WARN_ON(!host->claimed); mrq->cmd->error = 0; mrq->cmd->mrq = mrq; if (mrq->data) { BUG_ON(mrq->data->blksz > host->max_blk_size); BUG_ON(mrq->data->blocks > host->max_blk_count); BUG_ON(mrq->data->blocks * mrq->data->blksz > host->max_req_size); #ifdef CONFIG_MMC_DEBUG sz = 0; for_each_sg(mrq->data->sg, sg, mrq->data->sg_len, i) sz += sg->length; BUG_ON(sz != mrq->data->blocks * mrq->data->blksz); #endif mrq->cmd->data = mrq->data; mrq->data->error = 0; mrq->data->mrq = mrq; if (mrq->stop) { mrq->data->stop = mrq->stop; mrq->stop->error = 0; mrq->stop->mrq = mrq; } #ifdef <API key> if (host->perf_enable) host->perf.start = ktime_get(); #endif } mmc_host_clk_hold(host); led_trigger_event(host->led, LED_FULL); if (mmc_is_data_request(mrq)) { <API key>(host); <API key>(host, true); } host->ops->request(host, mrq); } static void <API key>(struct mmc_host *host, struct mmc_request *mrq) { if (mrq->data) { pr_debug("%s: blksz %d blocks %d flags %08x tsac %lu ms nsac %d\n", mmc_hostname(host), mrq->data->blksz, mrq->data->blocks, mrq->data->flags, mrq->data->timeout_ns / NSEC_PER_MSEC, mrq->data->timeout_clks); BUG_ON(mrq->data->blksz > host->max_blk_size); BUG_ON(mrq->data->blocks > host->max_blk_count); BUG_ON(mrq->data->blocks * mrq->data->blksz > host->max_req_size); mrq->data->error = 0; mrq->data->mrq = mrq; } if (mrq->cmd) { mrq->cmd->error = 0; mrq->cmd->mrq = mrq; } mmc_host_clk_hold(host); if (likely(host->cmdq_ops->request)) host->cmdq_ops->request(host, mrq); else pr_err("%s: %s: issue request failed\n", mmc_hostname(host), __func__); } /** * <API key> - initialize bkops statistics * @card: MMC card to start BKOPS * * Initialize and enable the bkops statistics */ void <API key>(struct mmc_card *card) { int i; struct mmc_bkops_stats *stats; if (!card) return; stats = &card->bkops.stats; spin_lock(&stats->lock); stats->manual_start = 0; stats->hpi = 0; stats->auto_start = 0; stats->auto_stop = 0; for (i = 0 ; i < <API key> ; i++) stats->level[i] = 0; stats->enabled = true; spin_unlock(&stats->lock); } EXPORT_SYMBOL(<API key>); static void <API key>(struct mmc_bkops_stats *stats) { spin_lock_irq(&stats->lock); if (stats->enabled) stats->hpi++; spin_unlock_irq(&stats->lock); } static void <API key>(struct mmc_bkops_stats *stats) { spin_lock_irq(&stats->lock); if (stats->enabled) stats->manual_start++; spin_unlock_irq(&stats->lock); } static void <API key>(struct mmc_bkops_stats *stats) { spin_lock_irq(&stats->lock); if (stats->enabled) stats->auto_start++; spin_unlock_irq(&stats->lock); } static void <API key>(struct mmc_bkops_stats *stats) { spin_lock_irq(&stats->lock); if (stats->enabled) stats->auto_stop++; spin_unlock_irq(&stats->lock); } static void <API key>(struct mmc_bkops_stats *stats, unsigned level) { BUG_ON(level >= <API key>); spin_lock_irq(&stats->lock); if (stats->enabled) stats->level[level]++; spin_unlock_irq(&stats->lock); } /** * mmc_set_auto_bkops - set auto BKOPS for supported cards * @card: MMC card to start BKOPS * @enable: enable/disable flag * * Configure the card to run automatic BKOPS. * * Should be called when host is claimed. */ int mmc_set_auto_bkops(struct mmc_card *card, bool enable) { int ret = 0; u8 bkops_en; BUG_ON(!card); enable = !!enable; if (unlikely(!<API key>(card))) { pr_err("%s: %s: card doesn't support auto bkops\n", mmc_hostname(card->host), __func__); return -EPERM; } if (enable) { if (<API key>(card)) goto out; bkops_en = card->ext_csd.bkops_en | <API key>; } else { if (!<API key>(card)) goto out; bkops_en = card->ext_csd.bkops_en & ~<API key>; } ret = mmc_switch(card, <API key>, EXT_CSD_BKOPS_EN, bkops_en, 0); if (ret) { pr_err("%s: %s: error in setting auto bkops to %d (%d)\n", mmc_hostname(card->host), __func__, enable, ret); } else { if (enable) { <API key>(card); <API key>(&card->bkops.stats); } else { <API key>(card); <API key>(&card->bkops.stats); } card->ext_csd.bkops_en = bkops_en; pr_debug("%s: %s: bkops state %x\n", mmc_hostname(card->host), __func__, bkops_en); } out: return ret; } EXPORT_SYMBOL(mmc_set_auto_bkops); /** * mmc_check_bkops - check BKOPS for supported cards * @card: MMC card to check BKOPS * * Read the BKOPS status in order to determine whether the * card requires bkops to be started. */ void mmc_check_bkops(struct mmc_card *card) { int err; BUG_ON(!card); if (<API key>(card)) return; err = <API key>(card); if (err) { pr_err("%s: Failed to read bkops status: %d\n", mmc_hostname(card->host), err); return; } card->bkops.needs_check = false; <API key>(&card->bkops.stats, card->ext_csd.raw_bkops_status); card->bkops.needs_bkops = card->ext_csd.raw_bkops_status > 0; } EXPORT_SYMBOL(mmc_check_bkops); /** * <API key> - start BKOPS for supported cards * @card: MMC card to start BKOPS * * Send START_BKOPS to the card. * The function should be called with claimed host. */ void <API key>(struct mmc_card *card) { int err; BUG_ON(!card); if (unlikely(!<API key>(card))) return; if (<API key>(card)) return; err = __mmc_switch(card, <API key>, EXT_CSD_BKOPS_START, 1, 0, false, true, false); if (err) { pr_err("%s: Error %d starting manual bkops\n", mmc_hostname(card->host), err); } else { <API key>(card); <API key>(&card->bkops.stats); card->bkops.needs_bkops = false; } } EXPORT_SYMBOL(<API key>); /* * mmc_wait_data_done() - done callback for data request * @mrq: done data request * * Wakes up mmc context, passed as a callback to host controller driver */ static void mmc_wait_data_done(struct mmc_request *mrq) { unsigned long flags; struct mmc_context_info *context_info = &mrq->host->context_info; spin_lock_irqsave(&context_info->lock, flags); context_info->is_done_rcv = true; <API key>(&context_info->wait); <API key>(&context_info->lock, flags); } static void mmc_wait_done(struct mmc_request *mrq) { complete(&mrq->completion); } /* *<API key>() - starts data request * @host: MMC host to start the request * @mrq: data request to start * * Sets the done callback to be called when request is completed by the card. * Starts data mmc request execution */ static int <API key>(struct mmc_host *host, struct mmc_request *mrq) { mrq->done = mmc_wait_data_done; mrq->host = host; if (mmc_card_removed(host->card)) { mrq->cmd->error = -ENOMEDIUM; mmc_wait_data_done(mrq); return -ENOMEDIUM; } mmc_start_request(host, mrq); return 0; } static int __mmc_start_req(struct mmc_host *host, struct mmc_request *mrq) { init_completion(&mrq->completion); mrq->done = mmc_wait_done; if (mmc_card_removed(host->card)) { mrq->cmd->error = -ENOMEDIUM; complete(&mrq->completion); return -ENOMEDIUM; } mmc_start_request(host, mrq); return 0; } /* * <API key>() - wait for request completed * @host: MMC host to prepare the command. * @mrq: MMC request to wait for * * Blocks MMC context till host controller will ack end of data request * execution or new request notification arrives from the block layer. * Handles command retries. * * Returns enum mmc_blk_status after checking errors. */ static int <API key>(struct mmc_host *host, struct mmc_request *mrq, struct mmc_async_req *next_req) { struct mmc_command *cmd; struct mmc_context_info *context_info = &host->context_info; int err; bool is_done_rcv = false; unsigned long flags; while (1) { <API key>(context_info->wait, (context_info->is_done_rcv || context_info->is_new_req)); spin_lock_irqsave(&context_info->lock, flags); is_done_rcv = context_info->is_done_rcv; context_info->is_waiting_last_req = false; <API key>(&context_info->lock, flags); if (is_done_rcv) { context_info->is_done_rcv = false; context_info->is_new_req = false; cmd = mrq->cmd; if (!cmd->error || !cmd->retries || mmc_card_removed(host->card)) { err = host->areq->err_check(host->card, host->areq); break; /* return err */ } else { pr_info("%s: req failed (CMD%u): %d, retrying...\n", mmc_hostname(host), cmd->opcode, cmd->error); cmd->retries cmd->error = 0; host->ops->request(host, mrq); continue; /* wait for done/new event again */ } } else if (context_info->is_new_req) { context_info->is_new_req = false; if (!next_req) { err = MMC_BLK_NEW_REQUEST; break; /* return err */ } } } return err; } static void <API key>(struct mmc_host *host, struct mmc_request *mrq) { struct mmc_command *cmd; while (1) { <API key>(&mrq->completion); cmd = mrq->cmd; /* * If host has timed out waiting for the sanitize/bkops * to complete, card might be still in programming state * so let's try to bring the card out of programming * state. */ if ((cmd->bkops_busy || cmd->sanitize_busy) && cmd->error == -ETIMEDOUT) { if (!mmc_interrupt_hpi(host->card)) { pr_warn("%s: %s: Interrupted sanitize/bkops\n", mmc_hostname(host), __func__); cmd->error = 0; break; } else { pr_err("%s: %s: Failed to interrupt sanitize\n", mmc_hostname(host), __func__); } } if (!cmd->error || !cmd->retries || mmc_card_removed(host->card)) break; pr_debug("%s: req failed (CMD%u): %d, retrying...\n", mmc_hostname(host), cmd->opcode, cmd->error); cmd->retries cmd->error = 0; host->ops->request(host, mrq); } } /** * mmc_pre_req - Prepare for a new request * @host: MMC host to prepare command * @mrq: MMC request to prepare for * @is_first_req: true if there is no previous started request * that may run in parellel to this call, otherwise false * * mmc_pre_req() is called in prior to mmc_start_req() to let * host prepare for the new request. Preparation of a request may be * performed while another request is running on the host. */ static void mmc_pre_req(struct mmc_host *host, struct mmc_request *mrq, bool is_first_req) { if (host->ops->pre_req) { mmc_host_clk_hold(host); host->ops->pre_req(host, mrq, is_first_req); <API key>(host); } } /** * mmc_post_req - Post process a completed request * @host: MMC host to post process command * @mrq: MMC request to post process for * @err: Error, if non zero, clean up any resources made in pre_req * * Let the host post process a completed request. Post processing of * a request may be performed while another reuqest is running. */ static void mmc_post_req(struct mmc_host *host, struct mmc_request *mrq, int err) { if (host->ops->post_req) { mmc_host_clk_hold(host); host->ops->post_req(host, mrq, err); <API key>(host); } } /** * <API key> - discard the task[s] in the device * @host: host instance * @tasks: mask of tasks to be knocked off * 0: remove all queued tasks */ int <API key>(struct mmc_host *host, u32 tasks) { return mmc_discard_queue(host, tasks); } EXPORT_SYMBOL(<API key>); /** * mmc_cmdq_post_req - post process of a completed request * @host: host instance * @tag: the request tag. * @err: non-zero is error, success otherwise */ void mmc_cmdq_post_req(struct mmc_host *host, int tag, int err) { if (likely(host->cmdq_ops->post_req)) host->cmdq_ops->post_req(host, tag, err); } EXPORT_SYMBOL(mmc_cmdq_post_req); /** * mmc_cmdq_halt - halt/un-halt the command queue engine * @host: host instance * @halt: true - halt, un-halt otherwise * * Host halts the command queue engine. It should complete * the ongoing transfer and release the bus. * All legacy commands can be sent upon successful * completion of this function. * Returns 0 on success, negative otherwise */ int mmc_cmdq_halt(struct mmc_host *host, bool halt) { int err = 0; if ((halt && mmc_host_halt(host)) || (!halt && !mmc_host_halt(host))) { pr_debug("%s: %s: CQE is already %s\n", mmc_hostname(host), __func__, halt ? "halted" : "un-halted"); return 0; } mmc_host_clk_hold(host); if (host->cmdq_ops->halt) { err = host->cmdq_ops->halt(host, halt); if (!err && host->ops->notify_halt) host->ops->notify_halt(host, halt); if (!err && halt) mmc_host_set_halt(host); else if (!err && !halt) { mmc_host_clr_halt(host); wake_up(&host->cmdq_ctx.wait); } } else { err = -ENOSYS; } <API key>(host); return err; } EXPORT_SYMBOL(mmc_cmdq_halt); int mmc_cmdq_start_req(struct mmc_host *host, struct mmc_cmdq_req *cmdq_req) { struct mmc_request *mrq = &cmdq_req->mrq; mrq->host = host; if (mmc_card_removed(host->card)) { mrq->cmd->error = -ENOMEDIUM; return -ENOMEDIUM; } <API key>(host, mrq); return 0; } EXPORT_SYMBOL(mmc_cmdq_start_req); static void <API key>(struct mmc_request *mrq) { <API key>(mrq->host); complete(&mrq->completion); } int <API key>(struct mmc_host *host, struct mmc_cmdq_req *cmdq_req) { struct mmc_request *mrq = &cmdq_req->mrq; struct mmc_command *cmd = mrq->cmd; int err = 0; init_completion(&mrq->completion); mrq->done = <API key>; err = mmc_cmdq_start_req(host, cmdq_req); if (err) return err; <API key>(&mrq->completion); if (cmd->error) { pr_err("%s: DCMD %d failed with err %d\n", mmc_hostname(host), cmd->opcode, cmd->error); err = cmd->error; mmc_host_clk_hold(host); host->cmdq_ops->dumpstate(host); <API key>(host); } return err; } EXPORT_SYMBOL(<API key>); int <API key>(struct mmc_command *cmd) { return <API key>(cmd, <API key>, EXT_CSD_FLUSH_CACHE, 1, 0, true, true); } EXPORT_SYMBOL(<API key>); /** * mmc_start_req - start a non-blocking request * @host: MMC host to start command * @areq: async request to start * @error: out parameter returns 0 for success, otherwise non zero * * Start a new MMC custom command request for a host. * If there is on ongoing async request wait for completion * of that request and start the new one and return. * Does not wait for the new request to complete. * * Returns the completed request, NULL in case of none completed. * Wait for the an ongoing request (previoulsy started) to complete and * return the completed request. If there is no ongoing request, NULL * is returned without waiting. NULL is not an error condition. */ struct mmc_async_req *mmc_start_req(struct mmc_host *host, struct mmc_async_req *areq, int *error) { int err = 0; int start_err = 0; struct mmc_async_req *data = host->areq; /* Prepare a new request */ if (areq) mmc_pre_req(host, areq->mrq, !host->areq); if (host->areq) { err = <API key>(host, host->areq->mrq, areq); if (err == MMC_BLK_NEW_REQUEST) { if (error) *error = err; /* * The previous request was not completed, * nothing to return */ return NULL; } /* * Check BKOPS urgency for each R1 response */ if (host->card && mmc_card_mmc(host->card) && ((mmc_resp_type(host->areq->mrq->cmd) == MMC_RSP_R1) || (mmc_resp_type(host->areq->mrq->cmd) == MMC_RSP_R1B)) && (host->areq->mrq->cmd->resp[0] & R1_EXCEPTION_EVENT)) mmc_check_bkops(host->card); } if (!err && areq) { <API key>(areq->mrq->cmd->opcode, areq->mrq->cmd->arg, areq->mrq->data); start_err = <API key>(host, areq->mrq); } if (host->areq) mmc_post_req(host, host->areq->mrq, 0); if (err && areq) mmc_post_req(host, areq->mrq, -EINVAL); if (err) host->areq = NULL; else host->areq = areq; if (error) *error = err; return data; } EXPORT_SYMBOL(mmc_start_req); /** * mmc_wait_for_req - start a request and wait for completion * @host: MMC host to start command * @mrq: MMC request to start * * Start a new MMC custom command request for a host, and wait * for the command to complete. Does not attempt to parse the * response. */ void mmc_wait_for_req(struct mmc_host *host, struct mmc_request *mrq) { __mmc_start_req(host, mrq); <API key>(host, mrq); } EXPORT_SYMBOL(mmc_wait_for_req); /** * mmc_interrupt_hpi - Issue for High priority Interrupt * @card: the MMC card associated with the HPI transfer * * Issued High Priority Interrupt, and check for card status * until out-of prg-state. */ int mmc_interrupt_hpi(struct mmc_card *card) { int err; u32 status; unsigned long prg_wait; BUG_ON(!card); if (!card->ext_csd.hpi_en) { pr_info("%s: HPI enable bit unset\n", mmc_hostname(card->host)); return 1; } mmc_claim_host(card->host); err = mmc_send_status(card, &status); if (err) { pr_err("%s: Get card status fail\n", mmc_hostname(card->host)); goto out; } switch (R1_CURRENT_STATE(status)) { case R1_STATE_IDLE: case R1_STATE_READY: case R1_STATE_STBY: case R1_STATE_TRAN: /* * In idle and transfer states, HPI is not needed and the caller * can issue the next intended command immediately */ goto out; case R1_STATE_PRG: break; default: pr_debug("%s: HPI cannot be sent. Card state=%d\n", mmc_hostname(card->host), R1_CURRENT_STATE(status)); err = -EINVAL; goto out; } err = mmc_send_hpi_cmd(card, &status); prg_wait = jiffies + msecs_to_jiffies(card->ext_csd.out_of_int_time); do { err = mmc_send_status(card, &status); if (!err && R1_CURRENT_STATE(status) == R1_STATE_TRAN) break; if (time_after(jiffies, prg_wait)) { err = mmc_send_status(card, &status); if (!err && R1_CURRENT_STATE(status) != R1_STATE_TRAN) err = -ETIMEDOUT; else break; } } while (!err); out: mmc_release_host(card->host); return err; } EXPORT_SYMBOL(mmc_interrupt_hpi); /** * mmc_wait_for_cmd - start a command and wait for completion * @host: MMC host to start command * @cmd: MMC command to start * @retries: maximum number of retries * * Start a new MMC command for a host, and wait for the command * to complete. Return any error that occurred while the command * was executing. Do not attempt to parse the response. */ int mmc_wait_for_cmd(struct mmc_host *host, struct mmc_command *cmd, int retries) { struct mmc_request mrq = {NULL}; WARN_ON(!host->claimed); memset(cmd->resp, 0, sizeof(cmd->resp)); cmd->retries = retries; mrq.cmd = cmd; cmd->data = NULL; mmc_wait_for_req(host, &mrq); return cmd->error; } EXPORT_SYMBOL(mmc_wait_for_cmd); /** * mmc_stop_bkops - stop ongoing BKOPS * @card: MMC card to check BKOPS * * Send HPI command to stop ongoing background operations to * allow rapid servicing of foreground operations, e.g. read/ * writes. Wait until the card comes out of the programming state * to avoid errors in servicing read/write requests. */ int mmc_stop_bkops(struct mmc_card *card) { int err = 0; BUG_ON(!card); if (unlikely(!<API key>(card))) goto out; if (!<API key>(card)) goto out; err = mmc_interrupt_hpi(card); /* * If err is EINVAL, we can't issue an HPI. * It should complete the BKOPS. */ if (!err || (err == -EINVAL)) { <API key>(card); <API key>(&card->bkops.stats); err = 0; } out: return err; } EXPORT_SYMBOL(mmc_stop_bkops); int <API key>(struct mmc_card *card) { int err; u8 *ext_csd; /* * In future work, we should consider storing the entire ext_csd. */ ext_csd = kmalloc(512, GFP_KERNEL); if (!ext_csd) { pr_err("%s: could not allocate buffer to receive the ext_csd.\n", mmc_hostname(card->host)); return -ENOMEM; } mmc_claim_host(card->host); err = mmc_send_ext_csd(card, ext_csd); mmc_release_host(card->host); if (err) goto out; card->ext_csd.raw_bkops_status = ext_csd[<API key>] & <API key>; card->ext_csd.<API key> = ext_csd[<API key>] & (<API key> | <API key> | <API key> | <API key>); out: kfree(ext_csd); return err; } EXPORT_SYMBOL(<API key>); /** * <API key> - set the timeout for a data command * @data: data phase for command * @card: the MMC card associated with the data transfer * * Computes the data timeout parameters according to the * correct algorithm given the card type. */ void <API key>(struct mmc_data *data, const struct mmc_card *card) { unsigned int mult; if (!card) { WARN_ON(1); return; } /* * SDIO cards only define an upper 1 s limit on access. */ if (mmc_card_sdio(card)) { data->timeout_ns = 1000000000; data->timeout_clks = 0; return; } /* * SD cards use a 100 multiplier rather than 10 */ mult = mmc_card_sd(card) ? 100 : 10; /* * Scale up the multiplier (and therefore the timeout) by * the r2w factor for writes. */ if (data->flags & MMC_DATA_WRITE) mult <<= card->csd.r2w_factor; data->timeout_ns = card->csd.tacc_ns * mult; data->timeout_clks = card->csd.tacc_clks * mult; /* * SD cards also have an upper limit on the timeout. */ if (mmc_card_sd(card)) { unsigned int timeout_us, limit_us; timeout_us = data->timeout_ns / 1000; if (mmc_host_clk_rate(card->host)) timeout_us += data->timeout_clks * 1000 / (mmc_host_clk_rate(card->host) / 1000); if (data->flags & MMC_DATA_WRITE) /* * The MMC spec "It is strongly recommended * for hosts to implement more than 500ms * timeout value even if the card indicates * the 250ms maximum busy length." Even the * previous value of 300ms is known to be * insufficient for some cards. */ limit_us = 3000000; else limit_us = 100000; /* * SDHC cards always use these fixed values. */ if (timeout_us > limit_us || mmc_card_blockaddr(card)) { data->timeout_ns = limit_us * 1000; data->timeout_clks = 0; } /* assign limit value if invalid */ if (timeout_us == 0) data->timeout_ns = limit_us * 1000; } /* * Some cards require longer data read timeout than indicated in CSD. * Address this by setting the read timeout to a "reasonably high" * value. For the cards tested, 600ms has proven enough. If necessary, * this value can be increased if other problematic cards require this. */ if (<API key>(card) && data->flags & MMC_DATA_READ) { data->timeout_ns = 600000000; data->timeout_clks = 0; } /* * Some cards need very high timeouts if driven in SPI mode. * The worst observed timeout was 900ms after writing a * continuous stream of data until the internal logic * overflowed. */ if (mmc_host_is_spi(card->host)) { if (data->flags & MMC_DATA_WRITE) { if (data->timeout_ns < 1000000000) data->timeout_ns = 1000000000; } else { if (data->timeout_ns < 100000000) data->timeout_ns = 100000000; /* 100ms */ } } /* Increase the timeout values for some bad INAND MCP devices */ if (card->quirks & <API key>) { data->timeout_ns = 4000000000u; data->timeout_clks = 0; } } EXPORT_SYMBOL(<API key>); /** * mmc_align_data_size - pads a transfer size to a more optimal value * @card: the MMC card associated with the data transfer * @sz: original transfer size * * Pads the original data size with a number of extra bytes in * order to avoid controller bugs and/or performance hits * (e.g. some controllers revert to PIO for certain sizes). * * Returns the improved size, which might be unmodified. * * Note that this function is only relevant when issuing a * single scatter gather entry. */ unsigned int mmc_align_data_size(struct mmc_card *card, unsigned int sz) { /* * FIXME: We don't have a system for the controller to tell * the core about its problems yet, so for now we just 32-bit * align the size. */ sz = ((sz + 3) / 4) * 4; return sz; } EXPORT_SYMBOL(mmc_align_data_size); /** * __mmc_claim_host - exclusively claim a host * @host: mmc host to claim * @abort: whether or not the operation should be aborted * * Claim a host for a set of operations. If @abort is non null and * dereference a non-zero value then this will return prematurely with * that non-zero value without acquiring the lock. Returns zero * with the lock held otherwise. */ int __mmc_claim_host(struct mmc_host *host, atomic_t *abort) { DECLARE_WAITQUEUE(wait, current); unsigned long flags; int stop; might_sleep(); add_wait_queue(&host->wq, &wait); spin_lock_irqsave(&host->lock, flags); while (1) { set_current_state(<API key>); stop = abort ? atomic_read(abort) : 0; if (stop || !host->claimed || host->claimer == current) break; <API key>(&host->lock, flags); schedule(); spin_lock_irqsave(&host->lock, flags); } set_current_state(TASK_RUNNING); if (!stop) { host->claimed = 1; host->claimer = current; host->claim_cnt += 1; } else wake_up(&host->wq); <API key>(&host->lock, flags); remove_wait_queue(&host->wq, &wait); if (host->ops->enable && !stop && host->claim_cnt == 1) host->ops->enable(host); return stop; } EXPORT_SYMBOL(__mmc_claim_host); /** * mmc_release_host - release a host * @host: mmc host to release * * Release a MMC host, allowing others to claim the host * for their operations. */ void mmc_release_host(struct mmc_host *host) { unsigned long flags; WARN_ON(!host->claimed); if (host->ops->disable && host->claim_cnt == 1) host->ops->disable(host); spin_lock_irqsave(&host->lock, flags); if (--host->claim_cnt) { /* Release for nested claim */ <API key>(&host->lock, flags); } else { host->claimed = 0; host->claimer = NULL; <API key>(&host->lock, flags); wake_up(&host->wq); } } EXPORT_SYMBOL(mmc_release_host); /* * This is a helper function, which fetches a runtime pm reference for the * card device and also claims the host. */ void mmc_get_card(struct mmc_card *card) { pm_runtime_get_sync(&card->dev); mmc_claim_host(card->host); } EXPORT_SYMBOL(mmc_get_card); /* * This is a helper function, which releases the host and drops the runtime * pm reference for the card device. */ void mmc_put_card(struct mmc_card *card) { mmc_release_host(card->host); <API key>(&card->dev); <API key>(&card->dev); } EXPORT_SYMBOL(mmc_put_card); /* * Internal function that does the actual ios call to the host driver, * optionally printing some debug output. */ void mmc_set_ios(struct mmc_host *host) { struct mmc_ios *ios = &host->ios; pr_debug("%s: clock %uHz busmode %u powermode %u cs %u Vdd %u " "width %u timing %u\n", mmc_hostname(host), ios->clock, ios->bus_mode, ios->power_mode, ios->chip_select, ios->vdd, ios->bus_width, ios->timing); if (ios->clock > 0) mmc_set_ungated(host); host->ops->set_ios(host, ios); if (ios->old_rate != ios->clock) { if (likely(ios->clk_ts)) { char trace_info[80]; snprintf(trace_info, 80, "%s: freq_KHz %d --> %d | t = %d", mmc_hostname(host), ios->old_rate / 1000, ios->clock / 1000, jiffies_to_msecs( (long)jiffies - (long)ios->clk_ts)); trace_mmc_clk(trace_info); } ios->old_rate = ios->clock; ios->clk_ts = jiffies; } } EXPORT_SYMBOL(mmc_set_ios); /* * Control chip select pin on a host. */ void mmc_set_chip_select(struct mmc_host *host, int mode) { mmc_host_clk_hold(host); host->ios.chip_select = mode; mmc_set_ios(host); <API key>(host); } /* * Sets the host clock to the highest possible frequency that * is below "hz". */ static void __mmc_set_clock(struct mmc_host *host, unsigned int hz) { WARN_ON(hz && hz < host->f_min); if (hz > host->f_max) hz = host->f_max; host->ios.clock = hz; mmc_set_ios(host); } void mmc_set_clock(struct mmc_host *host, unsigned int hz) { mmc_host_clk_hold(host); __mmc_set_clock(host, hz); <API key>(host); } #ifdef CONFIG_MMC_CLKGATE /* * This gates the clock by setting it to 0 Hz. */ void mmc_gate_clock(struct mmc_host *host) { unsigned long flags; WARN_ON(!host->ios.clock); spin_lock_irqsave(&host->clk_lock, flags); host->clk_old = host->ios.clock; host->ios.clock = 0; host->clk_gated = true; <API key>(&host->clk_lock, flags); mmc_set_ios(host); } /* * This restores the clock from gating by using the cached * clock value. */ void mmc_ungate_clock(struct mmc_host *host) { /* * We should previously have gated the clock, so the clock shall * be 0 here! The clock may however be 0 during initialization, * when some request operations are performed before setting * the frequency. When ungate is requested in that situation * we just ignore the call. */ if (host->clk_old) { WARN_ON(host->ios.clock); /* This call will also set host->clk_gated to false */ __mmc_set_clock(host, host->clk_old); } } void mmc_set_ungated(struct mmc_host *host) { unsigned long flags; /* * We've been given a new frequency while the clock is gated, * so make sure we regard this as ungating it. */ spin_lock_irqsave(&host->clk_lock, flags); host->clk_gated = false; <API key>(&host->clk_lock, flags); } #else void mmc_set_ungated(struct mmc_host *host) { } #endif int mmc_execute_tuning(struct mmc_card *card) { struct mmc_host *host = card->host; u32 opcode; int err; if (!host->ops->execute_tuning) return 0; if (mmc_card_mmc(card)) opcode = <API key>; else opcode = <API key>; mmc_host_clk_hold(host); err = host->ops->execute_tuning(host, opcode); <API key>(host); if (err) pr_err("%s: tuning execution failed\n", mmc_hostname(host)); return err; } /* * Change the bus mode (open drain/push-pull) of a host. */ void mmc_set_bus_mode(struct mmc_host *host, unsigned int mode) { mmc_host_clk_hold(host); host->ios.bus_mode = mode; mmc_set_ios(host); <API key>(host); } /* * Change data bus width of a host. */ void mmc_set_bus_width(struct mmc_host *host, unsigned int width) { mmc_host_clk_hold(host); host->ios.bus_width = width; mmc_set_ios(host); <API key>(host); } /** * <API key> - Convert a voltage to the OCR bit number * @vdd: voltage (mV) * @low_bits: prefer low bits in boundary cases * * This function returns the OCR bit number according to the provided @vdd * value. If conversion is not possible a negative errno value returned. * * Depending on the @low_bits flag the function prefers low or high OCR bits * on boundary voltages. For example, * with @low_bits = true, 3300 mV translates to ilog2(MMC_VDD_32_33); * with @low_bits = false, 3300 mV translates to ilog2(MMC_VDD_33_34); * * Any value in the [1951:1999] range translates to the ilog2(MMC_VDD_20_21). */ static int <API key>(int vdd, bool low_bits) { const int max_bit = ilog2(MMC_VDD_35_36); int bit; if (vdd < 1650 || vdd > 3600) return -EINVAL; if (vdd >= 1650 && vdd <= 1950) return ilog2(MMC_VDD_165_195); if (low_bits) vdd -= 1; /* Base 2000 mV, step 100 mV, bit's base 8. */ bit = (vdd - 2000) / 100 + 8; if (bit > max_bit) return max_bit; return bit; } /** * <API key> - Convert a voltage range to the OCR mask * @vdd_min: minimum voltage value (mV) * @vdd_max: maximum voltage value (mV) * * This function returns the OCR mask bits according to the provided @vdd_min * and @vdd_max values. If conversion is not possible the function returns 0. * * Notes wrt boundary cases: * This function sets the OCR bits for all boundary voltages, for example * [3300:3400] range is translated to MMC_VDD_32_33 | MMC_VDD_33_34 | * MMC_VDD_34_35 mask. */ u32 <API key>(int vdd_min, int vdd_max) { u32 mask = 0; if (vdd_max < vdd_min) return 0; /* Prefer high bits for the boundary vdd_max values. */ vdd_max = <API key>(vdd_max, false); if (vdd_max < 0) return 0; /* Prefer low bits for the boundary vdd_min values. */ vdd_min = <API key>(vdd_min, true); if (vdd_min < 0) return 0; /* Fill the mask, from max bit to min bit. */ while (vdd_max >= vdd_min) mask |= 1 << vdd_max return mask; } EXPORT_SYMBOL(<API key>); #ifdef CONFIG_OF /** * <API key> - return mask of supported voltages * @np: The device node need to be parsed. * @mask: mask of voltages available for MMC/SD/SDIO * * 1. Return zero on success. * 2. Return negative errno: voltage-range is invalid. */ int <API key>(struct device_node *np, u32 *mask) { const u32 *voltage_ranges; int num_ranges, i; voltage_ranges = of_get_property(np, "voltage-ranges", &num_ranges); num_ranges = num_ranges / sizeof(*voltage_ranges) / 2; if (!voltage_ranges || !num_ranges) { pr_info("%s: voltage-ranges unspecified\n", np->full_name); return -EINVAL; } for (i = 0; i < num_ranges; i++) { const int j = i * 2; u32 ocr_mask; ocr_mask = <API key>( be32_to_cpu(voltage_ranges[j]), be32_to_cpu(voltage_ranges[j + 1])); if (!ocr_mask) { pr_err("%s: voltage-range #%d is invalid\n", np->full_name, i); return -EINVAL; } *mask |= ocr_mask; } return 0; } EXPORT_SYMBOL(<API key>); #endif /* CONFIG_OF */ #ifdef CONFIG_REGULATOR /** * <API key> - return mask of supported voltages * @supply: regulator to use * * This returns either a negative errno, or a mask of voltages that * can be provided to MMC/SD/SDIO devices using the specified voltage * regulator. This would normally be called before registering the * MMC host adapter. */ int <API key>(struct regulator *supply) { int result = 0; int count; int i; int vdd_uV; int vdd_mV; count = <API key>(supply); if (count < 0) return count; for (i = 0; i < count; i++) { vdd_uV = <API key>(supply, i); if (vdd_uV <= 0) continue; vdd_mV = vdd_uV / 1000; result |= <API key>(vdd_mV, vdd_mV); } if (!result) { vdd_uV = <API key>(supply); if (vdd_uV <= 0) return vdd_uV; vdd_mV = vdd_uV / 1000; result = <API key>(vdd_mV, vdd_mV); } return result; } EXPORT_SYMBOL_GPL(<API key>); /** * <API key> - set regulator to match host->ios voltage * @mmc: the host to regulate * @supply: regulator to use * @vdd_bit: zero for power off, else a bit number (host->ios.vdd) * * Returns zero on success, else negative errno. * * MMC host drivers may use this to enable or disable a regulator using * a particular supply voltage. This would normally be called from the * set_ios() method. */ int <API key>(struct mmc_host *mmc, struct regulator *supply, unsigned short vdd_bit) { int result = 0; int min_uV, max_uV; if (vdd_bit) { int tmp; /* * REVISIT <API key>() may have set some * bits this regulator doesn't quite support ... don't * be too picky, most cards and regulators are OK with * a 0.1V range goof (it's a small error percentage). */ tmp = vdd_bit - ilog2(MMC_VDD_165_195); if (tmp == 0) { min_uV = 1650 * 1000; max_uV = 1950 * 1000; } else { min_uV = 1900 * 1000 + tmp * 100 * 1000; max_uV = min_uV + 100 * 1000; } result = <API key>(supply, min_uV, max_uV); if (result == 0 && !mmc->regulator_enabled) { result = regulator_enable(supply); if (!result) mmc->regulator_enabled = true; } } else if (mmc->regulator_enabled) { result = regulator_disable(supply); if (result == 0) mmc->regulator_enabled = false; } if (result) dev_err(mmc_dev(mmc), "could not set regulator OCR (%d)\n", result); return result; } EXPORT_SYMBOL_GPL(<API key>); #endif /* CONFIG_REGULATOR */ int <API key>(struct mmc_host *mmc) { struct device *dev = mmc_dev(mmc); int ret; mmc->supply.vmmc = <API key>(dev, "vmmc"); mmc->supply.vqmmc = <API key>(dev, "vqmmc"); if (IS_ERR(mmc->supply.vmmc)) { if (PTR_ERR(mmc->supply.vmmc) == -EPROBE_DEFER) return -EPROBE_DEFER; dev_info(dev, "No vmmc regulator found\n"); } else { ret = <API key>(mmc->supply.vmmc); if (ret > 0) mmc->ocr_avail = ret; else dev_warn(dev, "Failed getting OCR mask: %d\n", ret); } if (IS_ERR(mmc->supply.vqmmc)) { if (PTR_ERR(mmc->supply.vqmmc) == -EPROBE_DEFER) return -EPROBE_DEFER; dev_info(dev, "No vqmmc regulator found\n"); } return 0; } EXPORT_SYMBOL_GPL(<API key>); /* * Mask off any voltages we don't support and select * the lowest voltage */ u32 mmc_select_voltage(struct mmc_host *host, u32 ocr) { int bit; /* * Sanity check the voltages that the card claims to * support. */ if (ocr & 0x7F) { dev_warn(mmc_dev(host), "card claims to support voltages below defined range\n"); ocr &= ~0x7F; } ocr &= host->ocr_avail; if (!ocr) { dev_warn(mmc_dev(host), "no support for card's volts\n"); return 0; } if (host->caps2 & <API key>) { bit = ffs(ocr) - 1; ocr &= 3 << bit; mmc_power_cycle(host, ocr); } else { bit = fls(ocr) - 1; ocr &= 3 << bit; if (bit != host->ios.vdd) dev_warn(mmc_dev(host), "exceeding card's volts\n"); } return ocr; } int <API key>(struct mmc_host *host, int signal_voltage) { int err = 0; int old_signal_voltage = host->ios.signal_voltage; host->ios.signal_voltage = signal_voltage; if (host->ops-><API key>) { mmc_host_clk_hold(host); err = host->ops-><API key>(host, &host->ios); <API key>(host); } if (err) host->ios.signal_voltage = old_signal_voltage; return err; } int <API key>(struct mmc_host *host, int signal_voltage, u32 ocr) { struct mmc_command cmd = {0}; int err = 0; u32 clock; BUG_ON(!host); /* * Send CMD11 only if the request is to switch the card to * 1.8V signalling. */ if (signal_voltage == <API key>) return <API key>(host, signal_voltage); /* * If we cannot switch voltages, return failure so the caller * can continue without UHS mode */ if (!host->ops-><API key>) return -EPERM; if (!host->ops->card_busy) pr_warn("%s: cannot verify signal voltage switch\n", mmc_hostname(host)); cmd.opcode = SD_SWITCH_VOLTAGE; cmd.arg = 0; cmd.flags = MMC_RSP_R1 | MMC_CMD_AC; /* * Hold the clock reference so clock doesn't get auto gated during this * voltage switch sequence. */ mmc_host_clk_hold(host); err = mmc_wait_for_cmd(host, &cmd, 0); if (err) goto exit; if (!mmc_host_is_spi(host) && (cmd.resp[0] & R1_ERROR)) { err = -EIO; goto exit; } /* * The card should drive cmd and dat[0:3] low immediately * after the response of cmd11, but wait 1 ms to be sure */ mmc_delay(1); if (host->ops->card_busy && !host->ops->card_busy(host)) { err = -EAGAIN; goto power_cycle; } /* * During a signal voltage level switch, the clock must be gated * for 5 ms according to the SD spec */ host->card_clock_off = true; clock = host->ios.clock; host->ios.clock = 0; mmc_set_ios(host); if (<API key>(host, signal_voltage)) { /* * Voltages may not have been switched, but we've already * sent CMD11, so a power cycle is required anyway */ err = -EAGAIN; host->ios.clock = clock; mmc_set_ios(host); host->card_clock_off = false; goto power_cycle; } /* Keep clock gated for at least 5 ms */ mmc_delay(5); host->ios.clock = clock; mmc_set_ios(host); host->card_clock_off = false; /* Wait for at least 1 ms according to spec */ mmc_delay(1); /* * Failure to switch is indicated by the card holding * dat[0:3] low */ if (host->ops->card_busy && host->ops->card_busy(host)) err = -EAGAIN; power_cycle: if (err) { pr_debug("%s: Signal voltage switch failed, " "power cycling card\n", mmc_hostname(host)); mmc_power_cycle(host, ocr); } exit: <API key>(host); return err; } /* * Select timing parameters for host. */ void mmc_set_timing(struct mmc_host *host, unsigned int timing) { mmc_host_clk_hold(host); host->ios.timing = timing; mmc_set_ios(host); <API key>(host); } /* * Select appropriate driver type for host. */ void mmc_set_driver_type(struct mmc_host *host, unsigned int drv_type) { mmc_host_clk_hold(host); host->ios.drv_type = drv_type; mmc_set_ios(host); <API key>(host); } /* * Apply power to the MMC stack. This is a two-stage process. * First, we enable power to the card without the clock running. * We then wait a bit for the power to stabilise. Finally, * enable the bus drivers and clock to the card. * * We must _NOT_ enable the clock prior to power stablising. * * If a host does all the power sequencing itself, ignore the * initial MMC_POWER_UP stage. */ void mmc_power_up(struct mmc_host *host, u32 ocr) { if (host->ios.power_mode == MMC_POWER_ON) return; mmc_host_clk_hold(host); host->ios.vdd = fls(ocr) - 1; if (mmc_host_is_spi(host)) host->ios.chip_select = MMC_CS_HIGH; else { host->ios.chip_select = MMC_CS_DONTCARE; host->ios.bus_mode = <API key>; } host->ios.power_mode = MMC_POWER_UP; host->ios.bus_width = MMC_BUS_WIDTH_1; host->ios.timing = MMC_TIMING_LEGACY; mmc_set_ios(host); /* Try to set signal voltage to 3.3V but fall back to 1.8v or 1.2v */ if (<API key>(host, <API key>) == 0) dev_dbg(mmc_dev(host), "Initial signal voltage of 3.3v\n"); else if (<API key>(host, <API key>) == 0) dev_dbg(mmc_dev(host), "Initial signal voltage of 1.8v\n"); else if (<API key>(host, <API key>) == 0) dev_dbg(mmc_dev(host), "Initial signal voltage of 1.2v\n"); /* * This delay should be sufficient to allow the power supply * to reach the minimum voltage. */ mmc_delay(10); host->ios.clock = host->f_init; host->ios.power_mode = MMC_POWER_ON; mmc_set_ios(host); /* * This delay must be at least 74 clock sizes, or 1 ms, or the * time required to reach a stable voltage. */ mmc_delay(10); <API key>(host); } void mmc_power_off(struct mmc_host *host) { if (host->ios.power_mode == MMC_POWER_OFF) return; mmc_host_clk_hold(host); host->ios.clock = 0; host->ios.vdd = 0; if (!mmc_host_is_spi(host)) { host->ios.bus_mode = <API key>; host->ios.chip_select = MMC_CS_DONTCARE; } host->ios.power_mode = MMC_POWER_OFF; host->ios.bus_width = MMC_BUS_WIDTH_1; host->ios.timing = MMC_TIMING_LEGACY; mmc_set_ios(host); /* * Some configurations, such as the 802.11 SDIO card in the OLPC * XO-1.5, require a short delay after poweroff before the card * can be successfully turned on again. */ mmc_delay(1); <API key>(host); } void mmc_power_cycle(struct mmc_host *host, u32 ocr) { mmc_power_off(host); /* Wait at least 1 ms according to SD spec */ mmc_delay(1); mmc_power_up(host, ocr); } /* * Cleanup when the last reference to the bus operator is dropped. */ static void __mmc_release_bus(struct mmc_host *host) { BUG_ON(!host); BUG_ON(host->bus_refs); BUG_ON(!host->bus_dead); host->bus_ops = NULL; } /* * Increase reference count of bus operator */ static inline void mmc_bus_get(struct mmc_host *host) { unsigned long flags; spin_lock_irqsave(&host->lock, flags); host->bus_refs++; <API key>(&host->lock, flags); } /* * Decrease reference count of bus operator and free it if * it is the last reference. */ static inline void mmc_bus_put(struct mmc_host *host) { unsigned long flags; spin_lock_irqsave(&host->lock, flags); host->bus_refs if ((host->bus_refs == 0) && host->bus_ops) __mmc_release_bus(host); <API key>(&host->lock, flags); } /* * Assign a mmc bus handler to a host. Only one bus handler may control a * host at any given time. */ void mmc_attach_bus(struct mmc_host *host, const struct mmc_bus_ops *ops) { unsigned long flags; BUG_ON(!host); BUG_ON(!ops); WARN_ON(!host->claimed); spin_lock_irqsave(&host->lock, flags); BUG_ON(host->bus_ops); BUG_ON(host->bus_refs); host->bus_ops = ops; host->bus_refs = 1; host->bus_dead = 0; <API key>(&host->lock, flags); } /* * Remove the current bus handler from a host. */ void mmc_detach_bus(struct mmc_host *host) { unsigned long flags; BUG_ON(!host); WARN_ON(!host->claimed); WARN_ON(!host->bus_ops); spin_lock_irqsave(&host->lock, flags); host->bus_dead = 1; <API key>(&host->lock, flags); mmc_bus_put(host); } static void _mmc_detect_change(struct mmc_host *host, unsigned long delay, bool cd_irq) { #ifdef CONFIG_MMC_DEBUG unsigned long flags; spin_lock_irqsave(&host->lock, flags); WARN_ON(host->removed); <API key>(&host->lock, flags); #endif /* * If the device is configured as wakeup, we prevent a new sleep for * 5 s to give provision for user space to consume the event. */ if (cd_irq && !(host->caps & MMC_CAP_NEEDS_POLL) && device_can_wakeup(mmc_dev(host))) pm_wakeup_event(mmc_dev(host), 5000); host->detect_change = 1; <API key>(&host->detect, delay); } /** * mmc_detect_change - process change of state on a MMC socket * @host: host which changed state. * @delay: optional delay to wait before detection (jiffies) * * MMC drivers should call this when they detect a card has been * inserted or removed. The MMC layer will confirm that any * present card is still functional, and initialize any newly * inserted. */ void mmc_detect_change(struct mmc_host *host, unsigned long delay) { _mmc_detect_change(host, delay, true); } EXPORT_SYMBOL(mmc_detect_change); void mmc_init_erase(struct mmc_card *card) { unsigned int sz; if (is_power_of_2(card->erase_size)) card->erase_shift = ffs(card->erase_size) - 1; else card->erase_shift = 0; /* * It is possible to erase an arbitrarily large area of an SD or MMC * card. That is not desirable because it can take a long time * (minutes) potentially delaying more important I/O, and also the * timeout calculations become increasingly hugely over-estimated. * Consequently, 'pref_erase' is defined as a guide to limit erases * to that size and alignment. * * For SD cards that define Allocation Unit size, limit erases to one * Allocation Unit at a time. For MMC cards that define High Capacity * Erase Size, whether it is switched on or not, limit to that size. * Otherwise just have a stab at a good value. For modern cards it * will end up being 4MiB. Note that if the value is too small, it * can end up taking longer to erase. */ if (mmc_card_sd(card) && card->ssr.au) { card->pref_erase = card->ssr.au; card->erase_shift = ffs(card->ssr.au) - 1; } else if (card->ext_csd.hc_erase_size) { card->pref_erase = card->ext_csd.hc_erase_size; } else if (card->erase_size) { sz = (card->csd.capacity << (card->csd.read_blkbits - 9)) >> 11; if (sz < 128) card->pref_erase = 512 * 1024 / 512; else if (sz < 512) card->pref_erase = 1024 * 1024 / 512; else if (sz < 1024) card->pref_erase = 2 * 1024 * 1024 / 512; else card->pref_erase = 4 * 1024 * 1024 / 512; if (card->pref_erase < card->erase_size) card->pref_erase = card->erase_size; else { sz = card->pref_erase % card->erase_size; if (sz) card->pref_erase += card->erase_size - sz; } } else card->pref_erase = 0; } static unsigned int <API key>(struct mmc_card *card, unsigned int arg, unsigned int qty) { unsigned int erase_timeout; if (arg == MMC_DISCARD_ARG || (arg == MMC_TRIM_ARG && card->ext_csd.rev >= 6)) { erase_timeout = card->ext_csd.trim_timeout; } else if (card->ext_csd.erase_group_def & 1) { /* High Capacity Erase Group Size uses HC timeouts */ if (arg == MMC_TRIM_ARG) erase_timeout = card->ext_csd.trim_timeout; else erase_timeout = card->ext_csd.hc_erase_timeout; } else { /* CSD Erase Group Size uses write timeout */ unsigned int mult = (10 << card->csd.r2w_factor); unsigned int timeout_clks = card->csd.tacc_clks * mult; unsigned int timeout_us; /* Avoid overflow: e.g. tacc_ns=80000000 mult=1280 */ if (card->csd.tacc_ns < 1000000) timeout_us = (card->csd.tacc_ns * mult) / 1000; else timeout_us = (card->csd.tacc_ns / 1000) * mult; /* * ios.clock is only a target. The real clock rate might be * less but not that much less, so fudge it by multiplying by 2. */ timeout_clks <<= 1; timeout_us += (timeout_clks * 1000) / (mmc_host_clk_rate(card->host) / 1000); erase_timeout = timeout_us / 1000; /* * Theoretically, the calculation could underflow so round up * to 1ms in that case. */ if (!erase_timeout) erase_timeout = 1; } /* Multiplier for secure operations */ if (arg & MMC_SECURE_ARGS) { if (arg == <API key>) erase_timeout *= card->ext_csd.sec_erase_mult; else erase_timeout *= card->ext_csd.sec_trim_mult; } erase_timeout *= qty; /* * Ensure at least a 1 second timeout for SPI as per * '<API key>()' */ if (mmc_host_is_spi(card->host) && erase_timeout < 1000) erase_timeout = 1000; return erase_timeout; } static unsigned int <API key>(struct mmc_card *card, unsigned int arg, unsigned int qty) { unsigned int erase_timeout; if (card->ssr.erase_timeout) { /* Erase timeout specified in SD Status Register (SSR) */ erase_timeout = card->ssr.erase_timeout * qty + card->ssr.erase_offset; } else { /* * Erase timeout not specified in SD Status Register (SSR) so * use 250ms per write block. */ erase_timeout = 250 * qty; } /* Must not be less than 1 second */ if (erase_timeout < 1000) erase_timeout = 1000; return erase_timeout; } static unsigned int mmc_erase_timeout(struct mmc_card *card, unsigned int arg, unsigned int qty) { if (mmc_card_sd(card)) return <API key>(card, arg, qty); else return <API key>(card, arg, qty); } static u32 mmc_get_erase_qty(struct mmc_card *card, u32 from, u32 to) { u32 qty = 0; /* * qty is used to calculate the erase timeout which depends on how many * erase groups (or allocation units in SD terminology) are affected. * We count erasing part of an erase group as one erase group. * For SD, the allocation units are always a power of 2. For MMC, the * erase group size is almost certainly also power of 2, but it does not * seem to insist on that in the JEDEC standard, so we fall back to * division in that case. SD may not specify an allocation unit size, * in which case the timeout is based on the number of write blocks. * * Note that the timeout for secure trim 2 will only be correct if the * number of erase groups specified is the same as the total of all * preceding secure trim 1 commands. Since the power may have been * lost since the secure trim 1 commands occurred, it is generally * impossible to calculate the secure trim 2 timeout correctly. */ if (card->erase_shift) qty += ((to >> card->erase_shift) - (from >> card->erase_shift)) + 1; else if (mmc_card_sd(card)) qty += to - from + 1; else qty += ((to / card->erase_size) - (from / card->erase_size)) + 1; return qty; } static int <API key>(struct mmc_cmdq_req *cmdq_req, struct mmc_card *card, u32 opcode, u32 arg, u32 qty) { struct mmc_command *cmd = cmdq_req->mrq.cmd; int err; memset(cmd, 0, sizeof(struct mmc_command)); cmd->opcode = opcode; cmd->arg = arg; if (cmd->opcode == MMC_ERASE) { cmd->flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC; cmd->busy_timeout = mmc_erase_timeout(card, arg, qty); } else { cmd->flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; } err = <API key>(card->host, cmdq_req); if (err) { pr_err("mmc_erase: group start error %d, status % err, cmd->resp[0]); return -EIO; } return 0; } static int mmc_cmdq_do_erase(struct mmc_cmdq_req *cmdq_req, struct mmc_card *card, unsigned int from, unsigned int to, unsigned int arg) { struct mmc_command *cmd = cmdq_req->mrq.cmd; unsigned int qty = 0; unsigned long timeout; unsigned int fr, nr; int err; fr = from; nr = to - from + 1; <API key>(arg, fr, nr); qty = mmc_get_erase_qty(card, from, to); if (!mmc_card_blockaddr(card)) { from <<= 9; to <<= 9; } err = <API key>(cmdq_req, card, <API key>, from, qty); if (err) goto out; err = <API key>(cmdq_req, card, MMC_ERASE_GROUP_END, to, qty); if (err) goto out; err = <API key>(cmdq_req, card, MMC_ERASE, arg, qty); if (err) goto out; timeout = jiffies + msecs_to_jiffies(MMC_CORE_TIMEOUT_MS); do { memset(cmd, 0, sizeof(struct mmc_command)); cmd->opcode = MMC_SEND_STATUS; cmd->arg = card->rca << 16; cmd->flags = MMC_RSP_R1 | MMC_CMD_AC; /* Do not retry else we can't see errors */ err = <API key>(card->host, cmdq_req); if (err || (cmd->resp[0] & 0xFDF92000)) { pr_err("error %d requesting status % err, cmd->resp[0]); err = -EIO; goto out; } /* Timeout if the device never becomes ready for data and * never leaves the program state. */ if (time_after(jiffies, timeout)) { pr_err("%s: Card stuck in programming state! %s\n", mmc_hostname(card->host), __func__); err = -EIO; goto out; } } while (!(cmd->resp[0] & R1_READY_FOR_DATA) || (R1_CURRENT_STATE(cmd->resp[0]) == R1_STATE_PRG)); out: <API key>(arg, fr, nr); return err; } static int mmc_do_erase(struct mmc_card *card, unsigned int from, unsigned int to, unsigned int arg) { struct mmc_command cmd = {0}; unsigned int qty = 0; unsigned long timeout; unsigned int fr, nr; int err; fr = from; nr = to - from + 1; <API key>(arg, fr, nr); qty = mmc_get_erase_qty(card, from, to); if (!mmc_card_blockaddr(card)) { from <<= 9; to <<= 9; } if (mmc_card_sd(card)) cmd.opcode = <API key>; else cmd.opcode = <API key>; cmd.arg = from; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; err = mmc_wait_for_cmd(card->host, &cmd, 0); if (err) { pr_err("mmc_erase: group start error %d, " "status %#x\n", err, cmd.resp[0]); err = -EIO; goto out; } memset(&cmd, 0, sizeof(struct mmc_command)); if (mmc_card_sd(card)) cmd.opcode = SD_ERASE_WR_BLK_END; else cmd.opcode = MMC_ERASE_GROUP_END; cmd.arg = to; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; err = mmc_wait_for_cmd(card->host, &cmd, 0); if (err) { pr_err("mmc_erase: group end error %d, status % err, cmd.resp[0]); err = -EIO; goto out; } memset(&cmd, 0, sizeof(struct mmc_command)); cmd.opcode = MMC_ERASE; cmd.arg = arg; cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC; cmd.busy_timeout = mmc_erase_timeout(card, arg, qty); err = mmc_wait_for_cmd(card->host, &cmd, 0); if (err) { pr_err("mmc_erase: erase error %d, status % err, cmd.resp[0]); err = -EIO; goto out; } if (mmc_host_is_spi(card->host)) goto out; timeout = jiffies + msecs_to_jiffies(MMC_CORE_TIMEOUT_MS); do { memset(&cmd, 0, sizeof(struct mmc_command)); cmd.opcode = MMC_SEND_STATUS; cmd.arg = card->rca << 16; cmd.flags = MMC_RSP_R1 | MMC_CMD_AC; /* Do not retry else we can't see errors */ err = mmc_wait_for_cmd(card->host, &cmd, 0); if (err || (cmd.resp[0] & 0xFDF92000)) { pr_err("error %d requesting status % err, cmd.resp[0]); err = -EIO; goto out; } /* Timeout if the device never becomes ready for data and * never leaves the program state. */ if (time_after(jiffies, timeout)) { pr_err("%s: Card stuck in programming state! %s\n", mmc_hostname(card->host), __func__); err = -EIO; goto out; } } while (!(cmd.resp[0] & R1_READY_FOR_DATA) || (R1_CURRENT_STATE(cmd.resp[0]) == R1_STATE_PRG)); out: <API key>(arg, fr, nr); return err; } int <API key>(struct mmc_card *card, unsigned int from, unsigned int nr, unsigned int arg) { if (!(card->host->caps & MMC_CAP_ERASE) || !(card->csd.cmdclass & CCC_ERASE)) return -EOPNOTSUPP; if (!card->erase_size) return -EOPNOTSUPP; if (mmc_card_sd(card) && arg != MMC_ERASE_ARG) return -EOPNOTSUPP; if ((arg & MMC_SECURE_ARGS) && !(card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN)) return -EOPNOTSUPP; if ((arg & MMC_TRIM_ARGS) && !(card->ext_csd.sec_feature_support & <API key>)) return -EOPNOTSUPP; if (arg == <API key>) { if (from % card->erase_size || nr % card->erase_size) return -EINVAL; } return 0; } int mmc_cmdq_erase(struct mmc_cmdq_req *cmdq_req, struct mmc_card *card, unsigned int from, unsigned int nr, unsigned int arg) { unsigned int rem, to = from + nr; int ret; ret = <API key>(card, from, nr, arg); if (ret) return ret; if (arg == MMC_ERASE_ARG) { rem = from % card->erase_size; if (rem) { rem = card->erase_size - rem; from += rem; if (nr > rem) nr -= rem; else return 0; } rem = nr % card->erase_size; if (rem) nr -= rem; } if (nr == 0) return 0; to = from + nr; if (to <= from) return -EINVAL; /* 'from' and 'to' are inclusive */ to -= 1; return mmc_cmdq_do_erase(cmdq_req, card, from, to, arg); } EXPORT_SYMBOL(mmc_cmdq_erase); /** * mmc_erase - erase sectors. * @card: card to erase * @from: first sector to erase * @nr: number of sectors to erase * @arg: erase command argument (SD supports only %MMC_ERASE_ARG) * * Caller must claim host before calling this function. */ int mmc_erase(struct mmc_card *card, unsigned int from, unsigned int nr, unsigned int arg) { unsigned int rem, to = from + nr; int ret; ret = <API key>(card, from, nr, arg); if (ret) return ret; if (arg == MMC_ERASE_ARG) { rem = from % card->erase_size; if (rem) { rem = card->erase_size - rem; from += rem; if (nr > rem) nr -= rem; else return 0; } rem = nr % card->erase_size; if (rem) nr -= rem; } if (nr == 0) return 0; to = from + nr; if (to <= from) return -EINVAL; /* 'from' and 'to' are inclusive */ to -= 1; return mmc_do_erase(card, from, to, arg); } EXPORT_SYMBOL(mmc_erase); int mmc_can_erase(struct mmc_card *card) { if ((card->host->caps & MMC_CAP_ERASE) && (card->csd.cmdclass & CCC_ERASE) && card->erase_size) return 1; return 0; } EXPORT_SYMBOL(mmc_can_erase); int mmc_can_trim(struct mmc_card *card) { if (card->ext_csd.sec_feature_support & <API key>) return 1; return 0; } EXPORT_SYMBOL(mmc_can_trim); int mmc_can_discard(struct mmc_card *card) { /* * As there's no way to detect the discard support bit at v4.5 * use the s/w feature support filed. */ if (card->ext_csd.feature_support & MMC_DISCARD_FEATURE) return 1; return 0; } EXPORT_SYMBOL(mmc_can_discard); int mmc_can_sanitize(struct mmc_card *card) { if (!mmc_can_trim(card) && !mmc_can_erase(card)) return 0; if (card->ext_csd.sec_feature_support & <API key>) return 1; return 0; } EXPORT_SYMBOL(mmc_can_sanitize); int <API key>(struct mmc_card *card) { if ((card->ext_csd.sec_feature_support & EXT_CSD_SEC_ER_EN) && !(card->quirks & <API key>)) return 1; return 0; } EXPORT_SYMBOL(<API key>); int <API key>(struct mmc_card *card, unsigned int from, unsigned int nr) { if (!card->erase_size) return 0; if (from % card->erase_size || nr % card->erase_size) return 0; return 1; } EXPORT_SYMBOL(<API key>); static unsigned int <API key>(struct mmc_card *card, unsigned int arg) { struct mmc_host *host = card->host; unsigned int max_discard, x, y, qty = 0, max_qty, timeout; unsigned int last_timeout = 0; if (card->erase_shift) max_qty = UINT_MAX >> card->erase_shift; else if (mmc_card_sd(card)) max_qty = UINT_MAX; else max_qty = UINT_MAX / card->erase_size; /* Find the largest qty with an OK timeout */ do { y = 0; for (x = 1; x && x <= max_qty && max_qty - x >= qty; x <<= 1) { timeout = mmc_erase_timeout(card, arg, qty + x); if (timeout > host->max_busy_timeout) break; if (timeout < last_timeout) break; last_timeout = timeout; y = x; } qty += y; } while (y); if (!qty) return 0; if (qty == 1) return 1; /* Convert qty to sectors */ if (card->erase_shift) max_discard = --qty << card->erase_shift; else if (mmc_card_sd(card)) max_discard = qty; else max_discard = --qty * card->erase_size; return max_discard; } unsigned int <API key>(struct mmc_card *card) { struct mmc_host *host = card->host; unsigned int max_discard, max_trim; if (!host->max_busy_timeout || (host->caps2 & <API key>)) return UINT_MAX; /* * Without erase_group_def set, MMC erase timeout depends on clock * frequence which can change. In that case, the best choice is * just the preferred erase size. */ if (mmc_card_mmc(card) && !(card->ext_csd.erase_group_def & 1)) return card->pref_erase; max_discard = <API key>(card, MMC_ERASE_ARG); if (mmc_can_trim(card)) { max_trim = <API key>(card, MMC_TRIM_ARG); if (max_trim < max_discard) max_discard = max_trim; } else if (max_discard < card->erase_size) { max_discard = 0; } pr_debug("%s: calculated max. discard sectors %u for timeout %u ms\n", mmc_hostname(host), max_discard, host->max_busy_timeout); return max_discard; } EXPORT_SYMBOL(<API key>); int mmc_set_blocklen(struct mmc_card *card, unsigned int blocklen) { struct mmc_command cmd = {0}; if (mmc_card_blockaddr(card) || mmc_card_ddr52(card)) return 0; cmd.opcode = MMC_SET_BLOCKLEN; cmd.arg = blocklen; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; return mmc_wait_for_cmd(card->host, &cmd, 5); } EXPORT_SYMBOL(mmc_set_blocklen); int mmc_set_blockcount(struct mmc_card *card, unsigned int blockcount, bool is_rel_write) { struct mmc_command cmd = {0}; cmd.opcode = MMC_SET_BLOCK_COUNT; cmd.arg = blockcount & 0x0000FFFF; if (is_rel_write) cmd.arg |= 1 << 31; cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC; return mmc_wait_for_cmd(card->host, &cmd, 5); } EXPORT_SYMBOL(mmc_set_blockcount); static void <API key>(struct mmc_host *host) { if (!(host->caps & MMC_CAP_HW_RESET) || !host->ops->hw_reset) return; mmc_host_clk_hold(host); host->ops->hw_reset(host); <API key>(host); } int mmc_can_reset(struct mmc_card *card) { u8 rst_n_function; if (mmc_card_sdio(card)) return 0; if (mmc_card_mmc(card) && (card->host->caps & MMC_CAP_HW_RESET)) { rst_n_function = card->ext_csd.rst_n_function; if ((rst_n_function & <API key>) != <API key>) return 0; } return 1; } EXPORT_SYMBOL(mmc_can_reset); static int mmc_do_hw_reset(struct mmc_host *host, int check) { struct mmc_card *card = host->card; int ret; if (!host->bus_ops->power_restore) return -EOPNOTSUPP; if (!card) return -EINVAL; if (!mmc_can_reset(card)) return -EOPNOTSUPP; mmc_host_clk_hold(host); mmc_set_clock(host, host->f_init); if (mmc_card_mmc(card) && host->ops->hw_reset) host->ops->hw_reset(host); else mmc_power_cycle(host, host->ocr_avail); /* If the reset has happened, then a status command will fail */ if (check) { struct mmc_command cmd = {0}; int err; cmd.opcode = MMC_SEND_STATUS; if (!mmc_host_is_spi(card->host)) cmd.arg = card->rca << 16; cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC; err = mmc_wait_for_cmd(card->host, &cmd, 0); if (!err) { <API key>(host); return -ENOSYS; } } if (mmc_host_is_spi(host)) { host->ios.chip_select = MMC_CS_HIGH; host->ios.bus_mode = <API key>; } else { host->ios.chip_select = MMC_CS_DONTCARE; host->ios.bus_mode = <API key>; } host->ios.bus_width = MMC_BUS_WIDTH_1; host->ios.timing = MMC_TIMING_LEGACY; mmc_set_ios(host); <API key>(host); mmc_claim_host(host); ret = host->bus_ops->power_restore(host); mmc_release_host(host); return ret; } /* * mmc_cmdq_hw_reset: Helper API for doing * reset_all of host and reinitializing card. * This must be called with mmc_claim_host * acquired by the caller. */ int mmc_cmdq_hw_reset(struct mmc_host *host) { if (!host->bus_ops->power_restore) return -EOPNOTSUPP; mmc_power_cycle(host, host->ocr_avail); mmc_select_voltage(host, host->card->ocr); return host->bus_ops->power_restore(host); } EXPORT_SYMBOL(mmc_cmdq_hw_reset); int mmc_hw_reset(struct mmc_host *host) { return mmc_do_hw_reset(host, 0); } EXPORT_SYMBOL(mmc_hw_reset); int mmc_hw_reset_check(struct mmc_host *host) { return mmc_do_hw_reset(host, 1); } EXPORT_SYMBOL(mmc_hw_reset_check); static int mmc_rescan_try_freq(struct mmc_host *host, unsigned freq) { host->f_init = freq; #ifdef CONFIG_MMC_DEBUG pr_info("%s: %s: trying to init card at %u Hz\n", mmc_hostname(host), __func__, host->f_init); #endif mmc_power_up(host, host->ocr_avail); /* * Some eMMCs (with VCCQ always on) may not be reset after power up, so * do a hardware reset if possible. */ <API key>(host); /* * sdio_reset sends CMD52 to reset card. Since we do not know * if the card is being re-initialized, just send it. CMD52 * should be ignored by SD/eMMC cards. */ sdio_reset(host); mmc_go_idle(host); mmc_send_if_cond(host, host->ocr_avail); /* Order's important: probe SDIO, then SD, then MMC */ if (!mmc_attach_sdio(host)) return 0; if (!mmc_attach_sd(host)) return 0; if (!mmc_attach_mmc(host)) return 0; mmc_power_off(host); return -EIO; } int <API key>(struct mmc_host *host) { int ret; if (host->caps & <API key>) return 0; if (!host->card || mmc_card_removed(host->card)) return 1; ret = host->bus_ops->alive(host); /* * Card detect status and alive check may be out of sync if card is * removed slowly, when card detect switch changes while card/slot * pads are still contacted in hardware (refer to "SD Card Mechanical * Addendum, Appendix C: Card Detection Switch"). So reschedule a * detect work 200ms later for this case. */ if (!ret && host->ops->get_cd && !host->ops->get_cd(host)) { mmc_detect_change(host, msecs_to_jiffies(200)); pr_debug("%s: card removed too slowly\n", mmc_hostname(host)); } if (ret) { <API key>(host->card); pr_debug("%s: card remove detected\n", mmc_hostname(host)); } return ret; } int <API key>(struct mmc_host *host) { struct mmc_card *card = host->card; int ret; WARN_ON(!host->claimed); if (!card) return 1; ret = mmc_card_removed(card); /* * The card will be considered unchanged unless we have been asked to * detect a change or host requires polling to provide card detection. */ if (!host->detect_change && !(host->caps & MMC_CAP_NEEDS_POLL)) return ret; host->detect_change = 0; if (!ret) { ret = <API key>(host); if (ret && (host->caps & MMC_CAP_NEEDS_POLL)) { /* * Schedule a detect work as soon as possible to let a * rescan handle the card removal. */ cancel_delayed_work(&host->detect); _mmc_detect_change(host, 0, false); } } return ret; } EXPORT_SYMBOL(<API key>); void mmc_rescan(struct work_struct *work) { struct mmc_host *host = container_of(work, struct mmc_host, detect.work); if (host->trigger_card_event && host->ops->card_event) { host->ops->card_event(host); host->trigger_card_event = false; } if (host->rescan_disable) return; /* If there is a non-removable card registered, only scan once */ if ((host->caps & <API key>) && host->rescan_entered) return; host->rescan_entered = 1; mmc_bus_get(host); /* * if there is a _removable_ card registered, check whether it is * still present */ if (host->bus_ops && !host->bus_dead && !(host->caps & <API key>)) host->bus_ops->detect(host); host->detect_change = 0; /* * Let mmc_bus_put() free the bus/bus_ops if we've found that * the card is no longer present. */ mmc_bus_put(host); mmc_bus_get(host); /* if there still is a card present, stop here */ if (host->bus_ops != NULL) { mmc_bus_put(host); goto out; } /* * Only we can add a new handler, so it's safe to * release the lock here. */ mmc_bus_put(host); if (!(host->caps & <API key>) && host->ops->get_cd && host->ops->get_cd(host) == 0) { mmc_claim_host(host); mmc_power_off(host); mmc_release_host(host); goto out; } mmc_claim_host(host); (void) mmc_rescan_try_freq(host, host->f_min); mmc_release_host(host); out: if (host->caps & MMC_CAP_NEEDS_POLL) <API key>(&host->detect, HZ); } void mmc_start_host(struct mmc_host *host) { mmc_claim_host(host); host->f_init = max(freqs[0], host->f_min); host->rescan_disable = 0; host->ios.power_mode = MMC_POWER_UNDEFINED; if (host->caps2 & <API key>) mmc_power_off(host); else mmc_power_up(host, host->ocr_avail); <API key>(host); mmc_release_host(host); _mmc_detect_change(host, 0, false); } void mmc_stop_host(struct mmc_host *host) { #ifdef CONFIG_MMC_DEBUG unsigned long flags; spin_lock_irqsave(&host->lock, flags); host->removed = 1; <API key>(&host->lock, flags); #endif if (host->slot.cd_irq >= 0) disable_irq(host->slot.cd_irq); host->rescan_disable = 1; <API key>(&host->detect); <API key>(); /* clear pm flags now and let card drivers set them as needed */ host->pm_flags = 0; mmc_bus_get(host); if (host->bus_ops && !host->bus_dead) { /* Calling bus_ops->remove() with a claimed host can deadlock */ host->bus_ops->remove(host); mmc_claim_host(host); mmc_detach_bus(host); mmc_power_off(host); mmc_release_host(host); mmc_bus_put(host); return; } mmc_bus_put(host); BUG_ON(host->card); mmc_power_off(host); } int mmc_power_save_host(struct mmc_host *host) { int ret = 0; #ifdef CONFIG_MMC_DEBUG pr_info("%s: %s: powering down\n", mmc_hostname(host), __func__); #endif mmc_bus_get(host); if (!host->bus_ops || host->bus_dead) { mmc_bus_put(host); return -EINVAL; } if (host->bus_ops->power_save) ret = host->bus_ops->power_save(host); mmc_bus_put(host); mmc_power_off(host); return ret; } EXPORT_SYMBOL(mmc_power_save_host); int <API key>(struct mmc_host *host) { int ret; #ifdef CONFIG_MMC_DEBUG pr_info("%s: %s: powering up\n", mmc_hostname(host), __func__); #endif mmc_bus_get(host); if (!host->bus_ops || host->bus_dead) { mmc_bus_put(host); return -EINVAL; } mmc_power_up(host, host->card->ocr); mmc_claim_host(host); ret = host->bus_ops->power_restore(host); mmc_release_host(host); mmc_bus_put(host); return ret; } EXPORT_SYMBOL(<API key>); /* * Add barrier request to the requests in cache */ int mmc_cache_barrier(struct mmc_card *card) { struct mmc_host *host = card->host; int err = 0; if (!card->ext_csd.cache_ctrl || (card->quirks & <API key>)) goto out; if (!mmc_card_mmc(card)) goto out; if (!card->ext_csd.barrier_en) return -ENOTSUPP; /* * If a device receives maximum supported barrier * requests, a barrier command is treated as a * flush command. Hence, it is betetr to use * flush timeout instead a generic CMD6 timeout */ err = mmc_switch(card, <API key>, EXT_CSD_FLUSH_CACHE, 0x2, 0); if (err) pr_err("%s: cache barrier error %d\n", mmc_hostname(host), err); out: return err; } EXPORT_SYMBOL(mmc_cache_barrier); /* * Flush the cache to the non-volatile storage. */ int mmc_flush_cache(struct mmc_card *card) { int err = 0; if (mmc_card_mmc(card) && (card->ext_csd.cache_size > 0) && (card->ext_csd.cache_ctrl & 1) && (!(card->quirks & <API key>))) { err = mmc_switch(card, <API key>, EXT_CSD_FLUSH_CACHE, 1, 0); if (err == -ETIMEDOUT) { pr_err("%s: cache flush timeout\n", mmc_hostname(card->host)); err = mmc_interrupt_hpi(card); if (err) { pr_err("%s: mmc_interrupt_hpi() failed (%d)\n", mmc_hostname(card->host), err); err = -ENODEV; } } else if (err) { pr_err("%s: cache flush error %d\n", mmc_hostname(card->host), err); } } return err; } EXPORT_SYMBOL(mmc_flush_cache); #ifdef CONFIG_PM /* Do the card removal on suspend if card is assumed removeable * Do that in pm notifier while userspace isn't yet frozen, so we will be able to sync the card. */ int mmc_pm_notify(struct notifier_block *notify_block, unsigned long mode, void *unused) { struct mmc_host *host = container_of( notify_block, struct mmc_host, pm_notify); unsigned long flags; int err = 0; switch (mode) { case <API key>: case PM_SUSPEND_PREPARE: case PM_RESTORE_PREPARE: spin_lock_irqsave(&host->lock, flags); host->rescan_disable = 1; <API key>(&host->lock, flags); <API key>(&host->detect); if (!host->bus_ops) break; /* Validate prerequisites for suspend */ if (host->bus_ops->pre_suspend) err = host->bus_ops->pre_suspend(host); if (!err) break; /* Calling bus_ops->remove() with a claimed host can deadlock */ host->bus_ops->remove(host); mmc_claim_host(host); mmc_detach_bus(host); mmc_power_off(host); mmc_release_host(host); host->pm_flags = 0; break; case PM_POST_SUSPEND: case PM_POST_HIBERNATION: case PM_POST_RESTORE: spin_lock_irqsave(&host->lock, flags); host->rescan_disable = 0; <API key>(&host->lock, flags); _mmc_detect_change(host, 0, false); } return 0; } #endif /** * <API key>() - init synchronization context * @host: mmc host * * Init struct context_info needed to implement asynchronous * request mechanism, used by mmc core, host driver and mmc requests * supplier. */ void <API key>(struct mmc_host *host) { spin_lock_init(&host->context_info.lock); host->context_info.is_new_req = false; host->context_info.is_done_rcv = false; host->context_info.is_waiting_last_req = false; init_waitqueue_head(&host->context_info.wait); } #ifdef <API key> void <API key>(struct mmc_host *host, struct sdio_cis *cis, struct sdio_cccr *cccr, struct sdio_embedded_func *funcs, int num_funcs) { host->embedded_sdio_data.cis = cis; host->embedded_sdio_data.cccr = cccr; host->embedded_sdio_data.funcs = funcs; host->embedded_sdio_data.num_funcs = num_funcs; } EXPORT_SYMBOL(<API key>); #endif static int __init mmc_init(void) { int ret; workqueue = <API key>("kmmcd", 0); if (!workqueue) return -ENOMEM; ret = mmc_register_bus(); if (ret) goto destroy_workqueue; ret = <API key>(); if (ret) goto unregister_bus; ret = sdio_register_bus(); if (ret) goto <API key>; return 0; <API key>: <API key>(); unregister_bus: mmc_unregister_bus(); destroy_workqueue: destroy_workqueue(workqueue); return ret; } static void __exit mmc_exit(void) { sdio_unregister_bus(); <API key>(); mmc_unregister_bus(); destroy_workqueue(workqueue); } subsys_initcall(mmc_init); module_exit(mmc_exit); MODULE_LICENSE("GPL");
<?php global $theme_options_data; $logo_id = $theme_options_data['thim_logo']; // The value may be a URL to the image (for the default parameter) // or an attachment ID to the selected image. $logo_src = $logo_id; // For the default value if ( is_numeric( $logo_id ) ) { $imageAttachment = <API key>( $logo_id, 'full' ); $logo_src = $imageAttachment[0]; } $sticky_logo_id = $theme_options_data['thim_sticky_logo']; // The value may be a URL to the image (for the default parameter) // or an attachment ID to the selected image. $sticky_logo_src = $sticky_logo_id; // For the default value if ( is_numeric( $sticky_logo_id ) ) { $imageAttachment = <API key>( $sticky_logo_id, 'full' ); $sticky_logo_src = $imageAttachment[0]; } ?> <?php if ( isset( $theme_options_data['<API key>'] ) && $theme_options_data['<API key>'] == 'header_after_slider' && is_active_sidebar( 'banner_header' ) ) { dynamic_sidebar( 'banner_header' ); } ?> <header id="masthead" class="site-header <?php if ( isset( $theme_options_data['<API key>'] ) && $theme_options_data['<API key>'] <> '' ) { echo $theme_options_data['<API key>']; } if ( isset( $theme_options_data['<API key>'] ) && $theme_options_data['<API key>'] <> '' ) { echo ' ' . $theme_options_data['<API key>']; } if ( isset( $theme_options_data['<API key>'] ) && $theme_options_data['<API key>'] <> '' ) { echo ' ' . $theme_options_data['<API key>']; } ?>" role="banner"> <?php if ( isset( $theme_options_data['thim_header_layout'] ) && $theme_options_data['thim_header_layout'] == 'boxed' ) { echo "<div class=\"container header_boxed\">"; } ?> <?php $<API key> = 5; if ( isset( $theme_options_data['<API key>'] ) ) { $<API key> = $theme_options_data['<API key>']; } $<API key> = 12 - $<API key>; if ( isset( $theme_options_data['thim_topbar_show'] ) && $theme_options_data['thim_topbar_show'] == '1' ) { ?> <?php if ( ( is_active_sidebar( 'top_right_sidebar' ) ) || ( is_active_sidebar( 'top_left_sidebar' ) ) ) : ?> <div class="top-header"> <?php if ( isset( $theme_options_data['thim_header_layout'] ) && $theme_options_data['thim_header_layout'] == 'wide' ) { echo "<div class=\"container\"><div class=\"row\">"; } ?> <?php if ( is_active_sidebar( 'top_left_sidebar' ) ) : ?> <div class="col-sm-<?php echo $<API key>; ?> top_left"> <ul class="top-left-menu"> <?php dynamic_sidebar( 'top_left_sidebar' ); ?> </ul> </div><!-- col-sm-6 --> <?php endif; ?> <?php if ( is_active_sidebar( 'top_right_sidebar' ) ) : ?> <div class="col-sm-<?php echo $<API key>; ?> top_right"> <ul class="top-right-menu"> <?php dynamic_sidebar( 'top_right_sidebar' ); ?> </ul> </div><!-- col-sm-6 --> <?php endif; ?> <?php if ( isset( $theme_options_data['thim_header_layout'] ) && $theme_options_data['thim_header_layout'] == 'wide' ) { echo "</div></div>"; } ?> </div><!--End/div.top <?php endif; } ?> <?php $width_logo = 3; if ( isset( $theme_options_data['thim_column_logo'] ) ) { $width_logo = $theme_options_data['thim_column_logo']; } $width_menu = 12 - $width_logo; ?> <div class="wapper_logo"> <div class="container tm-table"> <?php if ( is_active_sidebar( 'header_left' ) ) : ?> <div class="table_cell"> <div class="header_left"> <?php dynamic_sidebar( 'header_left' ); ?> </div> </div><!-- col-sm-6 --> <?php endif; ?> <div class="menu-mobile-effect navbar-toggle" data-effect="mobile-effect"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </div> <div class="table_cell table_cell-center sm-logo"> <?php if ( is_single() ) { echo '<h2 class="header_logo">'; } else { echo '<h1 class="header_logo">'; } ?> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?> - <?php bloginfo( 'description' ); ?>" rel="home"> <?php if ( isset( $logo_src ) && $logo_src ) { $aloxo_logo_size = @getimagesize( $logo_src ); $width = $aloxo_logo_size[0]; $height = $aloxo_logo_size[1]; $site_title = esc_attr( get_bloginfo( 'name', 'display' ) ); echo '<img src="' . $logo_src . '" alt="' . $site_title . '" width="' . $width . '" height="' . $height . '" />'; } else { bloginfo( 'name' ); } ?> </a> <?php if ( is_single() ) { echo '</h2>'; } else { echo '</h1>'; } ?> </div> <?php if ( is_active_sidebar( 'header_right' ) ) : ?> <div class="table_cell right_header"> <div class="header_right"> <?php dynamic_sidebar( 'header_right' ); ?> </div> </div><!-- col-sm-6 --> <?php endif; ?> <div id="<API key>" class="<API key>"> <form role="search" method="get" action="<?php echo get_site_url(); ?>"> <input type="text" value="" name="s" id="s" placeholder="<?php echo __( 'Search the site or press ESC to cancel.', 'aloxo' ); ?>" class="form-control ob-search-input" autocomplete="off" /> <span class="header-search-close"><i class="fa fa-times"></i></span> </form> <ul class="ob_list_search"> </ul> </div> </div> <!--end container tm-table </div> <!--end wapper-logo <div class="navigation affix-top" <?php if ( isset( $theme_options_data['thim_header_sticky'] ) && $theme_options_data['thim_header_sticky'] == 1 ) { echo 'data-spy="affix" data-offset-top="' . $theme_options_data['<API key>'] . '" '; } ?>> <!-- <div class="main-menu"> --> <div class="container tm-table"> <div class="col-sm-<?php echo $width_logo ?> table_cell sm-logo-affix"> <?php echo '<h2 class="header_logo">'; ?> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?> - <?php bloginfo( 'description' ); ?>" rel="home"> <?php if ( isset( $sticky_logo_src ) ) { if ( $sticky_logo_src ) { $aloxo_logo_size = @getimagesize( $sticky_logo_src ); $width = $aloxo_logo_size[0]; $height = $aloxo_logo_size[1]; $site_title = esc_attr( get_bloginfo( 'name', 'display' ) ); echo '<img src="' . $sticky_logo_src . '" alt="' . $site_title . '" width="' . $width . '" height="' . $height . '" />'; } else { $aloxo_logo_size = @getimagesize( $logo_src ); $width = $aloxo_logo_size[0]; $height = $aloxo_logo_size[1]; $site_title = esc_attr( get_bloginfo( 'name', 'display' ) ); echo '<img src="' . $logo_src . '" alt="' . $site_title . '" width="' . $width . '" height="' . $height . '" />'; } } ?> </a> <?php echo '</h2>'; ?> </div> <nav class="col-sm-<?php echo $width_menu ?> table_cell" role="navigation"> <?php get_template_part( 'inc/header/main_menu' ); ?> </nav> </div> <!-- </div> --> </div> <?php if ( isset( $theme_options_data['thim_header_layout'] ) && $theme_options_data['thim_header_layout'] == 'boxed' ) { echo "</div>"; } ?> </header>
# attack_csrf.rb # model of a cross-site request forgery attack require 'sdsl/view.rb' u = mod :User do stores set(:intentsA, :URI) invokes(:visitA, # user only types dest address that he/she intends to visit :when => [:intentsA.contains(o.destA)]) end goodServer = mod :TrustedServer do stores :cookies, :Op, :Cookie stores :addrA, :Hostname stores set(:protected, :Op) creates :DOM creates :Cookie exports(:httpReqA, :args => [item(:cookie, :Cookie), item(:addrA, :URI)], # if op is protected, only accept when it provides a valid cookie :when => [implies(:protected.contains(o), o.cookie.eq(:cookies[o]))]) invokes(:httpRespA, :when => [triggeredBy :httpReqA]) end badServer = mod :MaliciousServer do stores :addrA, :Hostname creates :DOM exports(:httpReqA2, :args => [item(:cookie, :Cookie), item(:addrA, :URI)]) invokes(:httpRespA, :when => [triggeredBy :httpReqA2]) end goodClient = mod :Client do stores :cookies, :URI, :Cookie exports(:visitA, :args => [item(:destA, :URI)]) exports(:httpRespA, :args => [item(:dom, :DOM), item(:addrA, :URI)]) invokes([:httpReqA, :httpReqA2], :when => [ # req always contains any associated cookie implies(some(:cookies[o.addrA]), o.cookie.eq(:cookies[o.addrA])), disj( # sends a http request only when # the user initiates a connection conj(triggeredBy(:visitA), o.addrA.eq(trig.destA)), # or in response to a src tag conjs([triggeredBy(:httpRespA), trig.dom.tags.src.contains(o.addrA)] )) ]) end dom = datatype :DOM do field set(:tags, :HTMLTag) extends :Payload end addr = datatype :Addr do end uri = datatype :URI do field item(:addr, :Addr) field set(:vals, :Payload) end imgTag = datatype :ImgTag do field item(:src, :URI) extends :HTMLTag end tag = datatype :HTMLTag do setAbstract end cookie = datatype :Cookie do extends :Payload end otherPayload = datatype :OtherPayload do extends :Payload end payload = datatype :Payload do setAbstract end VIEW_CSRF = view :AttackCSRF do modules u, goodServer, badServer, goodClient trusted goodServer, goodClient, u data uri, :Hostname, cookie, otherPayload, payload, dom, tag, imgTag, addr end drawView VIEW_CSRF, "csrf.dot" dumpAlloy VIEW_CSRF, "csrf.als" # puts goodServer # puts badServer # puts goodClient # writeDot mods
<?php /** Zend_Log */ require_once 'Zend/Log.php'; /** <API key> */ require_once 'Zend/Log/Writer/Abstract.php'; class <API key> extends <API key> { /** * Maps Zend_Log priorities to PHP's syslog priorities * * @var array */ protected $_priorities = array( Zend_Log::EMERG => LOG_EMERG, Zend_Log::ALERT => LOG_ALERT, Zend_Log::CRIT => LOG_CRIT, Zend_Log::ERR => LOG_ERR, Zend_Log::WARN => LOG_WARNING, Zend_Log::NOTICE => LOG_NOTICE, Zend_Log::INFO => LOG_INFO, Zend_Log::DEBUG => LOG_DEBUG, ); /** * The default log priority - for unmapped custom priorities * * @var string */ protected $_defaultPriority = LOG_NOTICE; /** * Last application name set by a syslog-writer instance * * @var string */ protected static $_lastApplication; /** * Last facility name set by a syslog-writer instance * * @var string */ protected static $_lastFacility; /** * Application name used by this syslog-writer instance * * @var string */ protected $_application = 'Zend_Log'; /** * Facility used by this syslog-writer instance * * @var int */ protected $_facility = LOG_USER; /** * Types of program available to logging of message * * @var array */ protected $_validFacilities = array(); /** * Class constructor * * @param array $params Array of options; may include "application" and "facility" keys * @return void */ public function __construct(array $params = array()) { if (isset($params['application'])) { $this->_application = $params['application']; } $runInitializeSyslog = true; if (isset($params['facility'])) { $this->setFacility($params['facility']); $runInitializeSyslog = false; } if ($runInitializeSyslog) { $this->_initializeSyslog(); } } /** * Create a new instance of <API key> * * @param array|Zend_Config $config * @return <API key> */ static public function factory($config) { return new self(self::_parseConfig($config)); } /** * Initialize values facilities * * @return void */ protected function <API key>() { $constants = array( 'LOG_AUTH', 'LOG_AUTHPRIV', 'LOG_CRON', 'LOG_DAEMON', 'LOG_KERN', 'LOG_LOCAL0', 'LOG_LOCAL1', 'LOG_LOCAL2', 'LOG_LOCAL3', 'LOG_LOCAL4', 'LOG_LOCAL5', 'LOG_LOCAL6', 'LOG_LOCAL7', 'LOG_LPR', 'LOG_MAIL', 'LOG_NEWS', 'LOG_SYSLOG', 'LOG_USER', 'LOG_UUCP' ); foreach ($constants as $constant) { if (defined($constant)) { $this->_validFacilities[] = constant($constant); } } } /** * Initialize syslog / set application name and facility * * @return void */ protected function _initializeSyslog() { self::$_lastApplication = $this->_application; self::$_lastFacility = $this->_facility; openlog($this->_application, LOG_PID, $this->_facility); } /** * Set syslog facility * * @param int $facility Syslog facility * @return <API key> * @throws Zend_Log_Exception for invalid log facility */ public function setFacility($facility) { if ($this->_facility === $facility) { return $this; } if (!count($this->_validFacilities)) { $this-><API key>(); } if (!in_array($facility, $this->_validFacilities)) { require_once 'Zend/Log/Exception.php'; throw new Zend_Log_Exception('Invalid log facility provided; please see http://php.net/openlog for a list of valid facility values'); } if ('WIN' == strtoupper(substr(PHP_OS, 0, 3)) && ($facility !== LOG_USER) ) { require_once 'Zend/Log/Exception.php'; throw new Zend_Log_Exception('Only LOG_USER is a valid log facility on Windows'); } $this->_facility = $facility; $this->_initializeSyslog(); return $this; } /** * Set application name * * @param string $application Application name * @return <API key> */ public function setApplicationName($application) { if ($this->_application === $application) { return $this; } $this->_application = $application; $this->_initializeSyslog(); return $this; } /** * Close syslog. * * @return void */ public function shutdown() { closelog(); } /** * Write a message to syslog. * * @param array $event event data * @return void */ protected function _write($event) { if (array_key_exists($event['priority'], $this->_priorities)) { $priority = $this->_priorities[$event['priority']]; } else { $priority = $this->_defaultPriority; } if ($this->_application !== self::$_lastApplication || $this->_facility !== self::$_lastFacility) { $this->_initializeSyslog(); } $message = $event['message']; if ($this->_formatter instanceof <API key>) { $message = $this->_formatter->format($event); } syslog($priority, $message); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using SirenOfShame.Lib; using SirenOfShame.Lib.Watcher; using log4net; namespace GoServices { public class GoBuildStatus : BuildStatus { private readonly IEnumerable<XElement> _pipeline; private static readonly ILog _log = MyLogManager.GetLogger(typeof(GoBuildStatus)); public GoBuildStatus(IEnumerable<XElement> pipeline) { _pipeline = pipeline; Name = GetPipelineName(); BuildDefinitionId = GetPipelineName(); BuildStatusEnum = GetBuildStatus(); BuildId = GetBuildId(); LocalStartTime = GetLocalStartTime(); Url = GetUrl(); if (BuildStatusEnum == BuildStatusEnum.Broken) { RequestedBy = GetRequestedBy(); } } private string GetPipelineName() { return _pipeline.First().Attribute("name").Value.Split(' ').First(); } private BuildStatusEnum GetBuildStatus() { if (_pipeline.Select(x => x.Attribute("activity").Value).Any(a => a == "Building")) { return BuildStatusEnum.InProgress; } if (_pipeline.Select(x => x.Attribute("activity").Value).Any(a => a == "Sleeping") && _pipeline.Select(x => x.Attribute("lastBuildStatus").Value).All(s => s == "Success")) { return BuildStatusEnum.Working; } if (_pipeline.Select(x => x.Attribute("activity").Value).Any(a => a == "Sleeping") && _pipeline.Select(x => x.Attribute("lastBuildStatus").Value).Any(s => s == "Failure")) { return BuildStatusEnum.Broken; } return BuildStatusEnum.Unknown; } private string GetBuildId() { return _pipeline.First().Attribute("lastBuildLabel").Value; } private DateTime GetLocalStartTime() { return Convert.ToDateTime(_pipeline.First().Attribute("lastBuildTime").Value); } private string GetUrl() { return _pipeline.First().Attribute("webUrl").Value; } private string GetRequestedBy() { var failedStage = _pipeline.FirstOrDefault(x => x.Element("messages") != null && x.Element("messages").Element("message") != null); try { return failedStage != null ? failedStage.Element("messages").Element("message").Attribute("text").Value : string.Empty; } catch (Exception) { return string.Empty; } } } }
// CategoryModel.h // healthfood #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface CategoryModel : NSObject @property (nonatomic, retain)NSString *title; @property (nonatomic, retain)UIImage *image; @property (nonatomic, retain)NSArray *idArray; -(instancetype)initWithTitle:(NSString *)title andImageName:(NSString *)imageName andIdArray:(NSArray *)array; @end
<?PHP // $Id: dbperformance.php,v 1.12 2008/06/09 18:48:28 skodak Exp $ // dbperformance.php - shows latest ADOdb stats for the current server require_once('../config.php'); error('TODO: rewrite db perf code'); // TODO: rewrite // disable moodle specific debug messages that would be breaking the frames disable_debugging(); $topframe = optional_param('topframe', 0, PARAM_BOOL); $bottomframe = optional_param('bottomframe', 0, PARAM_BOOL); $do = optional_param('do', '', PARAM_ALPHA); require_login(); require_capability('moodle/site:config', <API key>(CONTEXT_SYSTEM)); $<API key> = get_string("databaseperformance"); $stradministration = get_string("administration"); $site = get_site(); $navigation = build_navigation(array( array('name'=>$stradministration, 'link'=>'index.php', 'type'=>'misc'), array('name'=>$<API key>, 'link'=>null, 'type'=>'misc'))); if (!empty($topframe)) { print_header("$site->shortname: $<API key>", "$site->fullname", $navigation); exit; }