answer stringlengths 15 1.25M |
|---|
#ifndef __FAT_STRUCT_H__
#define __FAT_STRUCT_H__
#define ATTR_READ_ONLY (char)0x01
#define ATTR_HIDDEN (char)0x02
#define ATTR_SYSTEM (char)0x04
#define ATTR_VOLUME_ID (char)0x08
#define ATTR_DIRECTORY (char)0x10
#define ATTR_ARCHIVE (char)0x20
#define ATTR_LONG_NAME (char)(ATTR_READ_ONLY | ATTR_HIDDEN | ATTR_SYSTEM | ATTR_VOLUME_ID)
#define ATTR_LONG_NAME_MASK (char)(ATTR_READ_ONLY | ATTR_HIDDEN | ATTR_SYSTEM | ATTR_VOLUME_ID | ATTR_DIRECTORY | ATTR_ARCHIVE)
typedef std::basic_string<short> ustring;
#ifdef WIN32
#define PACK
#else
#define PACK __attribute__((packed))
#endif
/* | Structures inherent to FAT FileSystem | */
#ifdef WIN32
#pragma pack(1)
#endif
typedef struct <API key>
{
unsigned char JmpBoot[3];
unsigned char Name[8];
unsigned short BytesPerSector;
unsigned char SectorsPerCluster;
unsigned short ReservedSector;
unsigned char NumberOfFat;
unsigned short RootEntrySize;
unsigned short TotalSector16; //16 bits
unsigned char Media;
unsigned short FatSize; // in sector
unsigned short SectorPerTrack;
unsigned short NumHeads;
unsigned int HiddenSectors;
unsigned int TotalSector32; //32 bits
} PACK BiosParameterBlock;
#ifdef WIN32
#pragma pack(1)
#endif
typedef struct <API key>
{
unsigned char DiskId;
unsigned char not_use;
unsigned char Signature;
unsigned int Disk_serial;
unsigned char Disk_Name[11];
unsigned char FS_Type[8];
}PACK <API key>;
#ifdef WIN32
#pragma pack(1)
#endif
typedef struct <API key>
{
unsigned int FAT_sector_size;
unsigned short disk_attrib;
unsigned char Major_version;
unsigned char minor_version;
unsigned int root_dir_cluster;
unsigned short additional_info;
unsigned short Sector_of_BS;
unsigned char not_use[12];
unsigned char Disk_Id;
unsigned char not_use1;
unsigned char Signature;
unsigned int Disk_Serial;
unsigned char Disk_Name[11];
unsigned char FS_Type[8];
}PACK <API key>;
#ifdef WIN32
#pragma pack(1)
#endif
typedef struct s_RootDir
{
unsigned char Name[8];
unsigned char Ext[3];
unsigned char Attr;
unsigned char NtRes;
unsigned char CreatedTimeTenth;
unsigned short CreatedTime;
unsigned short CreatedDate;
unsigned short LastAccessedDate;
unsigned short FirstClusterHi;
unsigned short LastModifiedTime;
unsigned short LastModifiedDate;
unsigned short FirstClusterLo;
unsigned int FileSize;
}PACK RootDir;
#ifdef WIN32
#pragma pack(1)
#endif
typedef struct s_LongFileName
{
unsigned char order;
unsigned char fivechar[10];
unsigned char attrib;
unsigned char reserved;
unsigned char checksum;
unsigned char sixchar[12];
unsigned short cluster;
unsigned char twochar[4];
}PACK LongFileName;
#endif |
#ifndef __FTGL__
#define __FTGL__
typedef double FTGL_DOUBLE;
typedef float FTGL_FLOAT;
// Fixes for deprecated identifiers in 2.1.5
#ifndef FT_OPEN_MEMORY
#define FT_OPEN_MEMORY (FT_Open_Flags)1
#endif
#ifndef FT_RENDER_MODE_MONO
#define FT_RENDER_MODE_MONO ft_render_mode_mono
#endif
#ifndef <API key>
#define <API key> <API key>
#endif
#ifdef WIN32
// Under windows avoid including <windows.h> is overrated.
// Sure, it can be avoided and "name space pollution" can be
// avoided, but why? It really doesn't make that much difference
// these days.
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#ifndef __gl_h_
#include <GL/gl.h>
#include <GL/glu.h>
#endif
#else
// Non windows platforms - don't require nonsense as seen above :-)
#ifndef __gl_h_
#ifdef __APPLE_CC__
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#else
#include <GL/gl.h>
#include <GL/glu.h>
#endif
#endif
// Required for compatibility with glext.h style function definitions of
// OpenGL extensions, such as in src/osg/Point.cpp.
#ifndef APIENTRY
#define APIENTRY
#endif
#endif
// Compiler-specific conditional compilation
#ifdef _MSC_VER // MS Visual C++
// Disable various warning.
// 4786: template name too long
#pragma warning( disable : 4251 )
#pragma warning( disable : 4275 )
#pragma warning( disable : 4786 )
// The following definitions control how symbols are exported.
// If the target is a static library ensure that FTGL_LIBRARY_STATIC
// is defined. If building a dynamic library (ie DLL) ensure the
// FTGL_LIBRARY macro is defined, as it will mark symbols for
// export. If compiling a project to _use_ the _dynamic_ library
// version of the library, no definition is required.
#ifdef FTGL_LIBRARY_STATIC // static lib - no special export required
# define FTGL_EXPORT
#elif FTGL_LIBRARY // dynamic lib - must export/import symbols appropriately.
# define FTGL_EXPORT __declspec(dllexport)
#else
# define FTGL_EXPORT __declspec(dllimport)
#endif
#else
// Compiler that is not MS Visual C++.
// Ensure that the export symbol is defined (and blank)
#define FTGL_EXPORT
#endif
// lifted from glext.h, to remove dependancy on glext.h
#ifndef <API key>
#define <API key> 0x8066
#define <API key> 0x8067
#define <API key> 0x8068
#define <API key> 0x8069
#define <API key> 0x806A
#endif
#endif // __FTGL__ |
/*
Syntax error: Undefined variable: "$gray-lt".
on line 46 of /Users/Adam/Projects/Autoweek/autoweek-static/sass/pages/instaread.scss
Backtrace:
/Users/Adam/Projects/Autoweek/autoweek-static/sass/pages/instaread.scss:46
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/script/variable.rb:49:in `_perform'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/script/node.rb:40:in `perform'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/script/list.rb:70:in `_perform'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/script/list.rb:70:in `map'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/script/list.rb:70:in `_perform'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/script/node.rb:40:in `perform'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:298:in `visit_prop'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:37:in `send'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:37:in `visit'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:100:in `visit'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:53:in `visit_children'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:53:in `map'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:53:in `visit_children'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:109:in `visit_children'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:121:in `with_environment'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:108:in `visit_children'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:37:in `visit'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:320:in `visit_rule'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:37:in `send'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:37:in `visit'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:100:in `visit'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:53:in `visit_children'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:53:in `map'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:53:in `visit_children'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:109:in `visit_children'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:121:in `with_environment'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:108:in `visit_children'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:37:in `visit'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:320:in `visit_rule'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:37:in `send'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:37:in `visit'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:100:in `visit'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:53:in `visit_children'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:53:in `map'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:53:in `visit_children'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:109:in `visit_children'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:121:in `with_environment'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:108:in `visit_children'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:37:in `visit'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:128:in `visit_root'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:37:in `send'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/base.rb:37:in `visit'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:100:in `visit'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:7:in `send'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/visitors/perform.rb:7:in `visit'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/tree/root_node.rb:20:in `render'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/engine.rb:315:in `_render'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../../scss/lib/sass/../sass/engine.rb:262:in `render'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../lib/compass/compiler.rb:140:in `compile'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../lib/compass/compiler.rb:126:in `timed'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../lib/compass/compiler.rb:139:in `compile'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../lib/compass/logger.rb:45:in `red'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../lib/compass/compiler.rb:138:in `compile'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../lib/compass/compiler.rb:118:in `compile_if_required'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../lib/compass/compiler.rb:103:in `run'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../lib/compass/compiler.rb:101:in `each'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../lib/compass/compiler.rb:101:in `run'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../lib/compass/compiler.rb:126:in `timed'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../lib/compass/compiler.rb:100:in `run'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../lib/compass/commands/update_project.rb:45:in `perform'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../lib/compass/commands/stamp_pattern.rb:76:in `perform'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../lib/compass/commands/base.rb:18:in `execute'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../lib/compass/commands/project_base.rb:19:in `execute'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../lib/compass/exec/sub_command_ui.rb:43:in `perform!'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/../lib/compass/exec/sub_command_ui.rb:15:in `run!'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/compass:45
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/compass:59:in `call'
/Users/Adam/Applications/CodeKit.app/Contents/Resources/engines/compass/bin/compass:59
*/
body:before {
white-space: pre;
font-family: monospace;
content: "Syntax error: Undefined variable: \"$gray-lt\".\A on line 46 of /Users/Adam/Projects/Autoweek/autoweek-static/sass/pages/instaread.scss"; } |
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_11) on Mon Feb 25 22:12:12 EST 2008 -->
<TITLE>
Uses of Interface com.sleepycat.bind.tuple.<API key> (Oracle - Berkeley DB Java Edition API)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../style.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Interface com.sleepycat.bind.tuple.<API key> (Oracle - Berkeley DB Java Edition API)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../com/sleepycat/bind/tuple/<API key>.html" title="interface in com.sleepycat.bind.tuple"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<b>Berkeley DB Java Edition</b><br><font size="-1"> version 3.2.74</font>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?com/sleepycat/bind/tuple/\<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="<API key>.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<CENTER>
<H2>
<B>Uses of Interface<br>com.sleepycat.bind.tuple.<API key></B></H2>
</CENTER>
No usage of com.sleepycat.bind.tuple.<API key>
<P>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../com/sleepycat/bind/tuple/<API key>.html" title="interface in com.sleepycat.bind.tuple"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<b>Berkeley DB Java Edition</b><br><font size="-1"> version 3.2.74</font>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?com/sleepycat/bind/tuple/\<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="<API key>.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
<font size=1>Copyright 1996,2008 Oracle. All rights reserved.</font>
</BODY>
</HTML> |
<?php
// No direct access
defined('_HZEXEC_') or die();
?>
<div class="width-100">
<fieldset class="adminform">
<legend><span><?php echo Lang::txt('<API key>'); ?></span></legend>
<?php
foreach ($this->form->getFieldset('cookie') as $field):
?>
<div class="input-wrap">
<?php echo $field->label; ?>
<?php echo $field->input; ?>
</div>
<?php
endforeach;
?>
</fieldset>
</div> |
FROM sismics/jetty:9.3.11
MAINTAINER benjamin.gam@gmail.com
RUN echo "deb http:
&& echo "deb-src http:
&& apt-get update \
&& apt-get -y --force-yes -q install ffmpeg curl python
RUN curl -kL https://yt-dl.org/downloads/latest/youtube-dl -o /usr/local/bin/youtube-dl \
&& chmod a+x /usr/local/bin/youtube-dl
COPY music-web/target/music-web-*.war /opt/jetty/webapps/music.war
COPY <API key>/music.xml /opt/jetty/webapps/music.xml
COPY <API key>/start.ini /opt/jetty/start.ini |
# -*- coding: utf-8 -*-
# OpenERP, Open Source Management Solution
# This program is free software: you can redistribute it and/or modify
# published by the Free Software Foundation, either version 3 of the
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
from openerp.osv import osv, fields
class <API key>(osv.osv):
_inherit = 'res.partner'
_description = "Automatische Vergabe von Kundennummern"
_columns = {
'your_ref' : fields.char('Kunden/Lieferanten-Nr.', size=64),
'incoterm' : fields.many2one('stock.incoterms', 'Lieferbedingung'),
}
_defaults = {
'customer' : lambda self, cr, uid, context : context['customer'] if context and 'customer' in context else 1,
'supplier' : lambda self, cr, uid, context : context['supplier'] if context and 'supplier' in context else 0,
}
def create(self, cr, uid, vals, context=None):
# Only assert partner references to "real" customers not contacts and if
# reference ha not been entered manually already
if not vals.get('parent_id') and not vals.get('ref'):
# Get company id from vals if available
if vals.get('company_id'):
company = self.pool.get('res.company').browse(cr, uid, vals['company_id'], context=context)
# If no company is set, get company from user
else:
user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
company = self.pool.get('res.company').browse(cr, uid, user.company_id.id, context=context)
# Construct customer reference according to company
if company.name:
# Get sequence
if company.name == 'dreh24 AG':
ref = self.pool.get('ir.sequence').get(cr, uid, 'partner.ref.dreh24')
vals['ref'] = 'D' + str(ref)
else:
ref = self.pool.get('ir.sequence').get(cr, uid, 'partner.ref.weippert')
vals['ref'] = 'W' + str(ref)
return super(<API key>, self).create(cr, uid, vals, context=context)
<API key>() |
package com.caucho.server.admin;
import com.caucho.config.ConfigException;
import com.caucho.config.program.ContainerProgram;
import com.caucho.config.program.<API key>;
import com.caucho.config.types.RawString;
import com.caucho.server.dispatch.ServletMapping;
import com.caucho.server.hmux.HmuxRequest;
import com.caucho.server.host.HostConfig;
import com.caucho.server.security.AbstractConstraint;
import com.caucho.server.security.SecurityConstraint;
import com.caucho.server.security.AuthorizationResult;
import com.caucho.server.webapp.WebAppConfig;
import com.caucho.util.InetNetwork;
import com.caucho.util.L10N;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetAddress;
import java.net.<API key>;
import java.util.Enumeration;
import java.util.logging.Logger;
abstract public class ManagementService
{
private static final L10N L = new L10N(ManagementService.class);
protected final Logger log = Logger.getLogger(getClass().getName());
private final Management _management;
private final String _serviceName;
private String _password;
private InetNetwork[]_allowedNetworks;
protected ManagementService(Management management, String serviceName)
{
_management = management;
_serviceName = serviceName;
}
public void start()
{
_password = _management.getRemoteCookie();
if (_password == null) {
log.warning(L.l("jmx-remote disabled. jmx-remote requires at least one enabled management <user>"));
return;
}
HostConfig hostConfig = _management.getHostConfig();
WebAppConfig webAppConfig = new WebAppConfig();
webAppConfig.setId(_serviceName);
webAppConfig.setRootDirectory(new RawString("memory:/admin-dummy-root"));
hostConfig.addBuilderProgram(new <API key>("web-app", webAppConfig));
ServletMapping servlet = new ServletMapping();
servlet.setServletName(_serviceName); |
function savePost(){
jQuery('#error-box').hide();
if(validateFields()){
jQuery('#<API key> :input, #<API key> textarea').attr('disabled', true);
jQuery('#save-waiting').show();
if(jQuery("#mode").val() == "new"){
actionName="create_post";
}else{
actionName="update_post";
}
currentPostStatus = jQuery("#post-status").val();
if( jQuery('#publish-save').is(":checked") ||
currentPostStatus== "publish" ||
currentPostStatus== "pending"){
if(jQuery('#direct-workflow').val()){
status = "publish";
}else{
status = "pending";
}
}else{
status = "draft";
}
postTitle = jQuery("#post_title").val();
postContent = jQuery("#wysihtml5-editor").val();
postImage = jQuery("#image-name").val();
categoryId = jQuery("#categories-ids").val();
tagnames = jQuery("#tag-names").val();
postId = jQuery("#post-id").val();
jQuery.ajax({
type: 'post',
url: MyAjax.ajaxurl,
data: { action: actionName, post_title:postTitle, post_content:postContent, post_image:postImage, category_id:categoryId, tag_names:tagnames, status:status, post_id:postId},
success:
function(response) {
data = jQuery.parseJSON(response);
if(data.status == "ok"){
jQuery("#<API key>").hide();
jQuery('#view-article').click(
function () {
window.open(data.viewarticle, "_self");
}
)
jQuery('#new-article').click(
function () {
window.open(data.newarticle, "_self");
}
)
jQuery('#edit-article').click(
function () {
window.open(data.editarticle, "_self");
}
)
jQuery("#save-message").html(data.message);
if(jQuery("#post-status").val() == "new-post" && status== 'publish'){
jQuery("#articles span").html(parseInt(jQuery("#articles span").html())+1);
}
if(jQuery("#post-status").val() == "new-post" && status== 'draft'){
jQuery("#draft span").html(parseInt(jQuery("#draft span").html())+1);
}
if(jQuery("#post-status").val() == "new-post" && status== 'pending'){
jQuery("#under-review span").html(parseInt(jQuery("#under-review span").html())+1);
}
if(jQuery("#post-status").val() == "draft" && status== 'publish'){
jQuery("#articles span").html(parseInt(jQuery("#articles span").html())+1);
jQuery("#draft span").html(parseInt(jQuery("#draft span").html())-1);
}
if(jQuery("#post-status").val() == "draft" && status== 'pending'){
jQuery("#under-review span").html(parseInt(jQuery("#under-review span").html())+1);
jQuery("#draft span").html(parseInt(jQuery("#draft span").html())-1);
}
jQuery(".post-save-options").show();
jQuery('html, body').animate({scrollTop:0}, 'slow');
}else{
jQuery('#save-waiting').hide();
jQuery('#<API key> :input, #<API key> textarea').removeAttr('disabled');
showError(data.message);
}
}
});
}else{
jQuery('html, body').animate({scrollTop:0}, 'slow');
}
}
function getImageObject(urlImage){
return "<img id='image-container' src='"+urlImage+"'/>";
}
function cancelImage(){
jQuery("#image-name").val("");
jQuery("#<API key>").html("");
jQuery(".edit-controls").hide();
jQuery(".upload-controls").show();
}
/*category stuff*/
function showCategoryList(){
jQuery(".picker").hide();
jQuery(".white-picker").show();
jQuery(".<API key>").fadeIn();
}
function showTagsList(){
jQuery(".picker-t").hide();
jQuery(".white-picker-t").show();
jQuery(".tags-list-container").fadeIn();
}
function closeTagsList(){
setListsElements("tags-content","tag-names", "tag-ids","tags-selector");
jQuery(".picker-t").show();
jQuery(".white-picker-t").hide();
jQuery(".tags-list-container").fadeOut();
}
function closeCategoriesList(){
setListsElements("categories-content","categories-names", "categories-ids","categories-selector");
jQuery(".picker").show();
jQuery(".white-picker").hide();
jQuery(".<API key>").fadeOut();
}
function setListsElements(content, namesContainer, idsContainer, selector){
jQuery(function() {
names = "";
ids = "";
jQuery('.'+content +' input[type="radio"]:checked').each(function() {
names += jQuery(this).val() + ',';
ids += jQuery(this).attr('id') + ',';
});
jQuery('.'+content +' input[type="checkbox"]:checked').each(function() {
names += jQuery(this).val() + ',';
ids += jQuery(this).attr('id') + ',';
});
jQuery("#"+namesContainer).val(names.slice(0, -1));
jQuery("#"+idsContainer).val(ids.slice(0, -1));
names = names.slice(0, -1).substring(0, 25);
if( names.length >= 25 ){
names += "...";
}
jQuery("."+selector).html(names);
});
}
function <API key>(){
jQuery(function() {
name = "";
id = "";
jQuery('.<API key> input[type="radio"]:checked').each(function() {
name = jQuery(this).val();
id = jQuery(this).attr('id');
});
jQuery("#categories-ids").val(id);
jQuery(".categories-selector").html(name);
});
}
function hideCategoryList(){
jQuery(".picker").show();
jQuery(".<API key>").hide();
jQuery(".white-picker").hide();
}
jQuery('.<API key>').hover(
function () {
showCategoryList()
},
function () {
hideCategoryList();
}
);
function validateFields(){
send=true;
if(jQuery("#post_title").val()==""){
send=false;
jQuery("#post_title").addClass("error-field");
}
return send;
}
jQuery('#post_title').focus(
function () {
jQuery("#post_title").removeClass("error-field");
}
);
jQuery('.categories-selector').hover(
function () {
jQuery(".categories-selector").removeClass("error-field");
}
);
function showError(message){
jQuery("#error-box").html("<label>"+message+'</label>');
jQuery("#error-box").css('display', "block");
jQuery("#error-box").effect("highlight", {}, 3000);
}
function setImagePreview(){
if(jQuery("#feature-image-url").val() != ""){
jQuery(".edit-controls").show();
jQuery(".upload-controls").hide();
jQuery("#<API key>").html(getImageObject(jQuery("#feature-image-url").val()));
}
}
jQuery(document).ready(function() {
if(jQuery("#mode").val()=="edit"){
<API key>();
setListsElements("tags-content","tag-names","tag-ids","tags-selector");
setListsElements("categories-content","categories-names", "categories-ids", "categories-selector");
setImagePreview();
}
});
function getMoreArticles(){
jQuery("#<API key>").show();
jQuery.ajax({
type: 'post',
url: MyAjax.ajaxurl,
data: { action: "get_more_articles", offset:jQuery("#offset").val(), status:"publish"},
success:
function(response) {
jQuery("#<API key>").hide();
newOffset =parseInt(jQuery("#offset").val()) + jQuery("#inicialcount").val();
if(newOffset >= parseInt(jQuery("#postcount").val())){
jQuery(".<API key>").hide();
}else{
jQuery("#offset").val(newOffset);
}
jQuery("#<API key>").append(response);
}
});
}
function showContent(current){
switch(current)
{
case "publish":
jQuery("#publish-tab").addClass("current");
jQuery("#pending-tab, #draft-tab").removeClass("current");
jQuery(".publish-container").show();
jQuery(".pending-container, .draft-container").hide();
break;
case "pending":
jQuery("#pending-tab").addClass("current");
jQuery("#publish-tab, #draft-tab").removeClass("current");
jQuery(".pending-container").show();
jQuery(".publish-container, .draft-container").hide();
break;
case "draft":
jQuery("#draft-tab").addClass("current");
jQuery("#pending-tab, #publish-tab").removeClass("current");
jQuery(".draft-container").show();
jQuery(".pending-container, .publish-container").hide();
break;
}
jQuery("#current-state").val(current);
}
function deleteArticle(postId){
jQuery("#delete-"+postId).addClass("deleting");
jQuery.ajax({
type: 'post',
url: MyAjax.ajaxurl,
data: { action: "delete_article", post_id:postId},
success:
function(response) {
response = JSON.parse(response);
if(response.status == 'ok'){
jQuery("#"+response.post_status+" span").html(parseInt(jQuery("#"+response.post_status+" span").html())-1);
counterId = '#'+jQuery("#current-state").val() + '-count';
jQuery(counterId).html(parseInt(jQuery(counterId).html())-1);
jQuery("#"+postId).hide();
}
}
});
} |
"""Tests for missing-yield-doc and <API key>"""
# pylint: disable=<API key>, unused-argument, function-redefined
# Ignore no docstring
def my_func(self):
yield False
# Ignore unrecognized style docstring
def my_func(self):
"""This is a docstring."""
yield False |
vti_encoding:SR|utf8-nl
<API key>:TR|07 Nov 2011 16:42:00 -0000
vti_extenderversion:SR|12.0.0.0
vti_author:SR|Eric-PC\\Eric
vti_modifiedby:SR|Eric-PC\\Eric
vti_timecreated:TR|07 Nov 2011 16:42:00 -0000
vti_cacheddtm:TX|07 Nov 2011 16:42:00 -0000
vti_filesize:IR|8440
vti_backlinkinfo:VX| |
// Markus Foote
// u0717506
#ifndef <API key>
#define <API key>
#include <stdio.h>
#endif /* defined(<API key>) */
double positivePower( double base, unsigned int exponent);
bool nearlyEqual( double num1, double num2, double eps); |
<?php
// Table Name
$tablename = 'tbl_wall_posts';
//Options line for comments, encoding and character set
$options = array('comment' => 'Wall posts', 'collate' => 'utf8_general_ci', 'character_set' => 'utf8');
// Fields
$fields = array(
'id' => array(
'type' => 'text',
'length' => 32
),
'datecreated' => array(
'type' => 'timestamp'
),
'posterid' => array(
'type' => 'text',
'length' => 50,
),
'walltype' => array(
'type' => 'text',
'length' => 50,
),
'identifier' => array(
'type' => 'text',
'length' => 50,
),
'ownerid' => array(
'type' => 'text',
'length' => 50,
),
'wallpost' => array(
'type' => 'clob',
),
);
//create other indexes here...
$name = 'ownerid';
$indexes = array(
'fields' => array(
'ownerid' => array(),
)
);
?> |
package util;
import java.io.<API key>;
import java.io.<API key>;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class <API key> implements Serializer {
@Override
public void serialize(Serializable serializable, File filePath) throws IOException {
<API key> <API key> = new <API key>();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(<API key>);
objectOutputStream.writeObject(serializable);
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
fileOutputStream.write(Base64.encodeToByte(<API key>.toByteArray(), true));
fileOutputStream.close();
objectOutputStream.close();
<API key>.close();
}
@Override
public Object deSerialize(File filePath) throws IOException, <API key> {
FileInputStream fileInputStream = new FileInputStream(filePath);
DataInputStream dataInputStream = new DataInputStream(fileInputStream);
byte[] byteContent = new byte[dataInputStream.available()];
dataInputStream.readFully(byteContent);
byteContent = Base64.decode(byteContent);
<API key> <API key> = new <API key>(byteContent);
ObjectInputStream objectInputStream = new ObjectInputStream(<API key>);
return objectInputStream.readObject();
}
} |
/**
* @file FSR_Version.c
* @brief This file contains the version of FSR.
* @author SongHo Yoon
* @date 10-JAN-2007
* @remark
* REVISION HISTORY
* @n 10-JAN-2007 [SongHo Yoon] : first writing
*
*/
#define <API key>
#define <API key>
#include "FSR.h"
/** FSR verion code and string macro */
FSR_VERSION(FSR_VER_MAJOR, FSR_VER_MINOR1, FSR_VER_MINOR2, FSR_VER_PATCHLEVEL, FSR_BUILD_NUMBER)
/**
* @brief this function gets FSR version and returns FSR version string
*
* @param[out] *pnVerCode : version code
*
* @return FSR version string ("FSR_v1.1.0p0_release")
*
* @author SongHo Yoon
* @version 1.0.0
* @remark this function gets FSR version and
* returns FSR version string
*
*/
PUBLIC UINT8 *
FSR_Version(UINT32 *pnVerCode)
{
*pnVerCode = gnFSRVerCode;
return (UINT8 *) gpaFSRVerStr;
}
/**
* @brief this function returns FSR version code
*
* @return FSR version code (v1.2.3p4 : 0x01020304)
*
* @author SongHo Yoon
* @version 1.0.0
*
*/
PUBLIC UINT32
FSR_VersionCode(VOID)
{
return gnFSRVerCode;
}
/**
* @brief this function returns FSR build number
*
* @return FSR build number
*
* @author SongHo Yoon
* @version 1.0.0
*
*/
PUBLIC UINT32
FSR_BuildNumber(VOID)
{
return FSR_BUILD_NUMBER;
} |
#include "../orcom_bin/Globals.h"
#include <string>
#include "DnarchFile.h"
#include "CompressedBlockData.h"
#include "../orcom_bin/Exception.h"
DnarchFileWriter::DnarchFileWriter()
: metaStream(NULL)
, dataStream(NULL)
{}
DnarchFileWriter::~DnarchFileWriter()
{
if (metaStream != NULL)
delete metaStream;
if (dataStream != NULL)
delete dataStream;
}
void DnarchFileWriter::StartCompress(const std::string &fileName_, const MinimizerParameters &minParams_, const CompressorParams& compParams_)
{
ASSERT(metaStream == NULL);
metaStream = new FileStreamWriter(fileName_ + ".cmeta");
metaStream->SetBuffering(true);
dataStream = new FileStreamWriter(fileName_ + ".cdna");
streamSizes.resize(DnaCompressedBin::BuffersNum, 0);
// clear header and footer
std::fill((uchar*)&fileHeader, (uchar*)&fileHeader + sizeof(DnarchFileHeader), 0);
fileHeader.minParams = minParams_;
compParams = compParams_;
fileFooter.blockSizes.clear();
// skip header pos
metaStream->SetPosition(DnarchFileHeader::HeaderSize);
}
void DnarchFileWriter::WriteNextBin(const CompressedDnaBlock *bin_)
{
ASSERT(bin_->dataBuffer.size > 0);
for (uint32 i = 0; i < DnaCompressedBin::BuffersNum; ++i)
{
streamSizes[i] += bin_->bufferSizes[i];
}
fileFooter.blockSizes.push_back(bin_->dataBuffer.size);
dataStream->Write(bin_->dataBuffer.data.Pointer(), bin_->dataBuffer.size);
}
void DnarchFileWriter::FinishCompress()
{
ASSERT(metaStream != NULL);
ASSERT(dataStream != NULL);
// prepare header and write footer
fileHeader.footerOffset = metaStream->Position();
WriteFileFooter();
// fill header and write
fileHeader.footerSize = metaStream->Position() - fileHeader.footerOffset;
metaStream->SetPosition(0);
WriteFileHeader();
// cleanup exit
metaStream->Close();
delete metaStream;
metaStream = NULL;
dataStream->Close();
delete dataStream;
dataStream = NULL;
}
void DnarchFileWriter::WriteFileHeader()
{
metaStream->Write((byte*)&fileHeader, DnarchFileHeader::HeaderSize);
}
void DnarchFileWriter::WriteFileFooter()
{
uint32 blockCount = fileFooter.blockSizes.size();
metaStream->Write((byte*)&blockCount, sizeof(uint32));
metaStream->Write((byte*)fileFooter.blockSizes.data(), fileFooter.blockSizes.size() * sizeof(uint64));
}
DnarchFileReader::DnarchFileReader()
: metaStream(NULL)
, dataStream(NULL)
, blockIdx(0)
{}
DnarchFileReader::~DnarchFileReader()
{
if (metaStream != NULL)
delete metaStream;
if (dataStream != NULL)
delete dataStream;
}
void DnarchFileReader::StartDecompress(const std::string &fileName_, MinimizerParameters &minParams_)
{
ASSERT(metaStream == NULL);
metaStream = new FileStreamReader(fileName_ + ".cmeta");
metaStream->SetBuffering(true);
dataStream = new FileStreamReader(fileName_ + ".cdna");
if (metaStream->Size() == 0 || dataStream->Size() == 0)
throw Exception("Empty archive.");
// Read file header
std::fill((uchar*)&fileHeader, (uchar*)&fileHeader + sizeof(DnarchFileHeader), 0);
ReadFileHeader();
if (fileHeader.footerOffset + (uint64)fileHeader.footerSize > metaStream->Size())
{
delete metaStream;
metaStream = NULL;
throw Exception("Corrupted archive.");
}
// clean footer
fileFooter.blockSizes.clear();
metaStream->SetPosition(fileHeader.footerOffset);
ReadFileFooter();
metaStream->SetPosition(DnarchFileHeader::HeaderSize);
minParams_ = fileHeader.minParams;
}
void DnarchFileReader::ReadFileHeader()
{
metaStream->Read((byte*)&fileHeader, DnarchFileHeader::HeaderSize);
}
void DnarchFileReader::ReadFileFooter()
{
uint32 blockCount = 0;
metaStream->Read((byte*)&blockCount, sizeof(uint32));
ASSERT(blockCount > 0);
fileFooter.blockSizes.resize(blockCount);
metaStream->Read((byte*)fileFooter.blockSizes.data(), fileFooter.blockSizes.size() * sizeof(uint64));
}
bool DnarchFileReader::ReadNextBin(CompressedDnaBlock *bin_)
{
if (blockIdx >= fileFooter.blockSizes.size())
return false;
const uint64 bs = fileFooter.blockSizes[blockIdx];
if (bin_->dataBuffer.data.Size() < bs)
bin_->dataBuffer.data.Extend(bs + (bs / 8));
dataStream->Read(bin_->dataBuffer.data.Pointer(), bs);
bin_->dataBuffer.size = bs;
blockIdx++;
return true;
}
void DnarchFileReader::FinishDecompress()
{
ASSERT(metaStream != NULL);
ASSERT(dataStream != NULL);
metaStream->Close();
delete metaStream;
metaStream = NULL;
dataStream->Close();
delete dataStream;
dataStream = NULL;
} |
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="ru">
<head>
<title>EscherGraphics (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="EscherGraphics (POI API Documentation)";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/EscherGraphics.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/poi/hssf/usermodel/DVConstraint.FormulaPair.html" title="class in org.apache.poi.hssf.usermodel"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics2d.html" title="class in org.apache.poi.hssf.usermodel"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/poi/hssf/usermodel/EscherGraphics.html" target="_top">Frames</a></li>
<li><a href="EscherGraphics.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<div class="subTitle">org.apache.poi.hssf.usermodel</div>
<h2 title="Class EscherGraphics" class="title">Class EscherGraphics</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>java.awt.Graphics</li>
<li>
<ul class="inheritance">
<li>org.apache.poi.hssf.usermodel.EscherGraphics</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong">EscherGraphics</span>
extends java.awt.Graphics</pre>
<div class="block">Translates Graphics calls into escher calls. The translation is lossy so
many features are not supported and some just aren't implemented yet. If
in doubt test the specific calls you wish to make. Graphics calls are
always performed into an EscherGroup so one will need to be created.
<p>
<b>Important:</b>
<blockquote>
One important concept worth considering is that of font size. One of the
difficulties in converting Graphics calls into escher drawing calls is that
Excel does not have the concept of absolute pixel positions. It measures
it's cell widths in 'characters' and the cell heights in points.
Unfortunately it's not defined exactly what a type of character it's
measuring. Presumably this is due to the fact that the Excel will be
using different fonts on different platforms or even within the same
platform.
<p>
Because of this constraint we've had to calculate the
<API key>. This the amount the font should be scaled by when
you issue commands such as drawString(). A good way to calculate this
is to use the follow formula:
<p>
<pre>
multipler = groupHeightInPoints / heightOfGroup
</pre>
<p>
The height of the group is calculated fairly simply by calculating the
difference between the y coordinates of the bounding box of the shape. The
height of the group can be calculated by using a convenience called
<code>HSSFClientAnchor.<API key>()</code>.
</blockquote></div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#EscherGraphics(org.apache.poi.hssf.usermodel.HSSFShapeGroup, org.apache.poi.hssf.usermodel.HSSFWorkbook, java.awt.Color, float)">EscherGraphics</a></strong>(<a href="../../../../../org/apache/poi/hssf/usermodel/HSSFShapeGroup.html" title="class in org.apache.poi.hssf.usermodel">HSSFShapeGroup</a> escherGroup,
<a href="../../../../../org/apache/poi/hssf/usermodel/HSSFWorkbook.html" title="class in org.apache.poi.hssf.usermodel">HSSFWorkbook</a> workbook,
java.awt.Color forecolor,
float <API key>)</code>
<div class="block">Construct an escher graphics object.</div>
</td>
</tr>
</table>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method_summary">
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#clearRect(int, int, int, int)">clearRect</a></strong>(int x,
int y,
int width,
int height)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#clipRect(int, int, int, int)">clipRect</a></strong>(int x,
int y,
int width,
int height)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#copyArea(int, int, int, int, int, int)">copyArea</a></strong>(int x,
int y,
int width,
int height,
int dx,
int dy)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.awt.Graphics</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#create()">create</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#dispose()">dispose</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#drawArc(int, int, int, int, int, int)">drawArc</a></strong>(int x,
int y,
int width,
int height,
int startAngle,
int arcAngle)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#drawImage(java.awt.Image, int, int, java.awt.Color, java.awt.image.ImageObserver)">drawImage</a></strong>(java.awt.Image image,
int i,
int j,
java.awt.Color color,
java.awt.image.ImageObserver imageobserver)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#drawImage(java.awt.Image, int, int, java.awt.image.ImageObserver)">drawImage</a></strong>(java.awt.Image image,
int i,
int j,
java.awt.image.ImageObserver imageobserver)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#drawImage(java.awt.Image, int, int, int, int, java.awt.Color, java.awt.image.ImageObserver)">drawImage</a></strong>(java.awt.Image image,
int i,
int j,
int k,
int l,
java.awt.Color color,
java.awt.image.ImageObserver imageobserver)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#drawImage(java.awt.Image, int, int, int, int, java.awt.image.ImageObserver)">drawImage</a></strong>(java.awt.Image image,
int i,
int j,
int k,
int l,
java.awt.image.ImageObserver imageobserver)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#drawImage(java.awt.Image, int, int, int, int, int, int, int, int, java.awt.Color, java.awt.image.ImageObserver)">drawImage</a></strong>(java.awt.Image img,
int dx1,
int dy1,
int dx2,
int dy2,
int sx1,
int sy1,
int sx2,
int sy2,
java.awt.Color bgcolor,
java.awt.image.ImageObserver observer)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#drawImage(java.awt.Image, int, int, int, int, int, int, int, int, java.awt.image.ImageObserver)">drawImage</a></strong>(java.awt.Image img,
int dx1,
int dy1,
int dx2,
int dy2,
int sx1,
int sy1,
int sx2,
int sy2,
java.awt.image.ImageObserver observer)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#drawLine(int, int, int, int)">drawLine</a></strong>(int x1,
int y1,
int x2,
int y2)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#drawLine(int, int, int, int, int)">drawLine</a></strong>(int x1,
int y1,
int x2,
int y2,
int width)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#drawOval(int, int, int, int)">drawOval</a></strong>(int x,
int y,
int width,
int height)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#drawPolygon(int[], int[], int)">drawPolygon</a></strong>(int[] xPoints,
int[] yPoints,
int nPoints)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#drawPolyline(int[], int[], int)">drawPolyline</a></strong>(int[] xPoints,
int[] yPoints,
int nPoints)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#drawRect(int, int, int, int)">drawRect</a></strong>(int x,
int y,
int width,
int height)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#drawRoundRect(int, int, int, int, int, int)">drawRoundRect</a></strong>(int x,
int y,
int width,
int height,
int arcWidth,
int arcHeight)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#drawString(java.text.<API key>, int, int)">drawString</a></strong>(java.text.<API key> iterator,
int x,
int y)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#drawString(java.lang.String, int, int)">drawString</a></strong>(java.lang.String str,
int x,
int y)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#fillArc(int, int, int, int, int, int)">fillArc</a></strong>(int x,
int y,
int width,
int height,
int startAngle,
int arcAngle)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#fillOval(int, int, int, int)">fillOval</a></strong>(int x,
int y,
int width,
int height)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#fillPolygon(int[], int[], int)">fillPolygon</a></strong>(int[] xPoints,
int[] yPoints,
int nPoints)</code>
<div class="block">Fills a (closed) polygon, as defined by a pair of arrays, which
hold the <i>x</i> and <i>y</i> coordinates.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#fillRect(int, int, int, int)">fillRect</a></strong>(int x,
int y,
int width,
int height)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#fillRoundRect(int, int, int, int, int, int)">fillRoundRect</a></strong>(int x,
int y,
int width,
int height,
int arcWidth,
int arcHeight)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.awt.Color</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#getBackground()">getBackground</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.awt.Shape</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#getClip()">getClip</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.awt.Rectangle</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#getClipBounds()">getClipBounds</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.awt.Rectangle</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#getClipRect()">getClipRect</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.awt.Color</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#getColor()">getColor</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.awt.Font</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#getFont()">getFont</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.awt.FontMetrics</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#getFontMetrics(java.awt.Font)">getFontMetrics</a></strong>(java.awt.Font f)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#setBackground(java.awt.Color)">setBackground</a></strong>(java.awt.Color background)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#setClip(int, int, int, int)">setClip</a></strong>(int x,
int y,
int width,
int height)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#setClip(java.awt.Shape)">setClip</a></strong>(java.awt.Shape shape)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#setColor(java.awt.Color)">setColor</a></strong>(java.awt.Color color)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#setFont(java.awt.Font)">setFont</a></strong>(java.awt.Font f)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#setPaintMode()">setPaintMode</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#setXORMode(java.awt.Color)">setXORMode</a></strong>(java.awt.Color color)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics.html#translate(int, int)">translate</a></strong>(int x,
int y)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="<API key>.awt.Graphics">
</a>
<h3>Methods inherited from class java.awt.Graphics</h3>
<code>create, draw3DRect, drawBytes, drawChars, drawPolygon, fill3DRect, fillPolygon, finalize, getClipBounds, getFontMetrics, hitClip, toString</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="<API key>.lang.Object">
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
</a>
<h3>Constructor Detail</h3>
<a name="EscherGraphics(org.apache.poi.hssf.usermodel.HSSFShapeGroup, org.apache.poi.hssf.usermodel.HSSFWorkbook, java.awt.Color, float)">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>EscherGraphics</h4>
<pre>public EscherGraphics(<a href="../../../../../org/apache/poi/hssf/usermodel/HSSFShapeGroup.html" title="class in org.apache.poi.hssf.usermodel">HSSFShapeGroup</a> escherGroup,
<a href="../../../../../org/apache/poi/hssf/usermodel/HSSFWorkbook.html" title="class in org.apache.poi.hssf.usermodel">HSSFWorkbook</a> workbook,
java.awt.Color forecolor,
float <API key>)</pre>
<div class="block">Construct an escher graphics object.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>escherGroup</code> - The escher group to write the graphics calls into.</dd><dd><code>workbook</code> - The workbook we are using.</dd><dd><code>forecolor</code> - The foreground color to use as default.</dd><dd><code><API key></code> - The font multiplier. (See class description for information on how this works.).</dd></dl>
</li>
</ul>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method_detail">
</a>
<h3>Method Detail</h3>
<a name="clearRect(int, int, int, int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>clearRect</h4>
<pre>public void clearRect(int x,
int y,
int width,
int height)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>clearRect</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="clipRect(int, int, int, int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>clipRect</h4>
<pre>public void clipRect(int x,
int y,
int width,
int height)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>clipRect</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="copyArea(int, int, int, int, int, int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>copyArea</h4>
<pre>public void copyArea(int x,
int y,
int width,
int height,
int dx,
int dy)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>copyArea</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="create()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>create</h4>
<pre>public java.awt.Graphics create()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>create</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="dispose()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>dispose</h4>
<pre>public void dispose()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>dispose</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="drawArc(int, int, int, int, int, int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>drawArc</h4>
<pre>public void drawArc(int x,
int y,
int width,
int height,
int startAngle,
int arcAngle)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>drawArc</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="drawImage(java.awt.Image, int, int, int, int, int, int, int, int, java.awt.Color, java.awt.image.ImageObserver)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>drawImage</h4>
<pre>public boolean drawImage(java.awt.Image img,
int dx1,
int dy1,
int dx2,
int dy2,
int sx1,
int sy1,
int sx2,
int sy2,
java.awt.Color bgcolor,
java.awt.image.ImageObserver observer)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>drawImage</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="drawImage(java.awt.Image, int, int, int, int, int, int, int, int, java.awt.image.ImageObserver)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>drawImage</h4>
<pre>public boolean drawImage(java.awt.Image img,
int dx1,
int dy1,
int dx2,
int dy2,
int sx1,
int sy1,
int sx2,
int sy2,
java.awt.image.ImageObserver observer)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>drawImage</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="drawImage(java.awt.Image, int, int, int, int, java.awt.Color, java.awt.image.ImageObserver)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>drawImage</h4>
<pre>public boolean drawImage(java.awt.Image image,
int i,
int j,
int k,
int l,
java.awt.Color color,
java.awt.image.ImageObserver imageobserver)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>drawImage</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="drawImage(java.awt.Image, int, int, int, int, java.awt.image.ImageObserver)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>drawImage</h4>
<pre>public boolean drawImage(java.awt.Image image,
int i,
int j,
int k,
int l,
java.awt.image.ImageObserver imageobserver)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>drawImage</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="drawImage(java.awt.Image, int, int, java.awt.Color, java.awt.image.ImageObserver)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>drawImage</h4>
<pre>public boolean drawImage(java.awt.Image image,
int i,
int j,
java.awt.Color color,
java.awt.image.ImageObserver imageobserver)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>drawImage</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="drawImage(java.awt.Image, int, int, java.awt.image.ImageObserver)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>drawImage</h4>
<pre>public boolean drawImage(java.awt.Image image,
int i,
int j,
java.awt.image.ImageObserver imageobserver)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>drawImage</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="drawLine(int, int, int, int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>drawLine</h4>
<pre>public void drawLine(int x1,
int y1,
int x2,
int y2)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>drawLine</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="drawLine(int, int, int, int, int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>drawLine</h4>
<pre>public void drawLine(int x1,
int y1,
int x2,
int y2,
int width)</pre>
</li>
</ul>
<a name="drawOval(int, int, int, int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>drawOval</h4>
<pre>public void drawOval(int x,
int y,
int width,
int height)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>drawOval</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="drawPolygon(int[], int[], int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>drawPolygon</h4>
<pre>public void drawPolygon(int[] xPoints,
int[] yPoints,
int nPoints)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>drawPolygon</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="drawPolyline(int[], int[], int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>drawPolyline</h4>
<pre>public void drawPolyline(int[] xPoints,
int[] yPoints,
int nPoints)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>drawPolyline</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="drawRect(int, int, int, int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>drawRect</h4>
<pre>public void drawRect(int x,
int y,
int width,
int height)</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>drawRect</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="drawRoundRect(int, int, int, int, int, int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>drawRoundRect</h4>
<pre>public void drawRoundRect(int x,
int y,
int width,
int height,
int arcWidth,
int arcHeight)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>drawRoundRect</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="drawString(java.lang.String, int, int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>drawString</h4>
<pre>public void drawString(java.lang.String str,
int x,
int y)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>drawString</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="drawString(java.text.<API key>, int, int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>drawString</h4>
<pre>public void drawString(java.text.<API key> iterator,
int x,
int y)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>drawString</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="fillArc(int, int, int, int, int, int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>fillArc</h4>
<pre>public void fillArc(int x,
int y,
int width,
int height,
int startAngle,
int arcAngle)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>fillArc</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="fillOval(int, int, int, int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>fillOval</h4>
<pre>public void fillOval(int x,
int y,
int width,
int height)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>fillOval</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="fillPolygon(int[], int[], int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>fillPolygon</h4>
<pre>public void fillPolygon(int[] xPoints,
int[] yPoints,
int nPoints)</pre>
<div class="block">Fills a (closed) polygon, as defined by a pair of arrays, which
hold the <i>x</i> and <i>y</i> coordinates.
<p>
This draws the polygon, with <code>nPoint</code> line segments.
The first <code>nPoint - 1</code> line segments are
drawn between sequential points
(<code>xPoints[i],yPoints[i],xPoints[i+1],yPoints[i+1]</code>).
The final line segment is a closing one, from the last point to
the first (assuming they are different).
<p>
The area inside of the polygon is defined by using an
even-odd fill rule (also known as the alternating rule), and
the area inside of it is filled.</div>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>fillPolygon</code> in class <code>java.awt.Graphics</code></dd>
<dt><span class="strong">Parameters:</span></dt><dd><code>xPoints</code> - array of the <code>x</code> coordinates.</dd><dd><code>yPoints</code> - array of the <code>y</code> coordinates.</dd><dd><code>nPoints</code> - the total number of points in the polygon.</dd><dt><span class="strong">See Also:</span></dt><dd><code>Graphics.drawPolygon(int[], int[], int)</code></dd></dl>
</li>
</ul>
<a name="fillRect(int, int, int, int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>fillRect</h4>
<pre>public void fillRect(int x,
int y,
int width,
int height)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>fillRect</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="fillRoundRect(int, int, int, int, int, int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>fillRoundRect</h4>
<pre>public void fillRoundRect(int x,
int y,
int width,
int height,
int arcWidth,
int arcHeight)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>fillRoundRect</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="getClip()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>getClip</h4>
<pre>public java.awt.Shape getClip()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>getClip</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="getClipBounds()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>getClipBounds</h4>
<pre>public java.awt.Rectangle getClipBounds()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>getClipBounds</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="getClipRect()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>getClipRect</h4>
<pre>public java.awt.Rectangle getClipRect()</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>getClipRect</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="getColor()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>getColor</h4>
<pre>public java.awt.Color getColor()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>getColor</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="getFont()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>getFont</h4>
<pre>public java.awt.Font getFont()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>getFont</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="getFontMetrics(java.awt.Font)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>getFontMetrics</h4>
<pre>public java.awt.FontMetrics getFontMetrics(java.awt.Font f)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>getFontMetrics</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="setClip(int, int, int, int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setClip</h4>
<pre>public void setClip(int x,
int y,
int width,
int height)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>setClip</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="setClip(java.awt.Shape)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setClip</h4>
<pre>public void setClip(java.awt.Shape shape)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>setClip</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="setColor(java.awt.Color)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setColor</h4>
<pre>public void setColor(java.awt.Color color)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>setColor</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="setFont(java.awt.Font)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setFont</h4>
<pre>public void setFont(java.awt.Font f)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>setFont</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="setPaintMode()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setPaintMode</h4>
<pre>public void setPaintMode()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>setPaintMode</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="setXORMode(java.awt.Color)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setXORMode</h4>
<pre>public void setXORMode(java.awt.Color color)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>setXORMode</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="translate(int, int)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>translate</h4>
<pre>public void translate(int x,
int y)</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>translate</code> in class <code>java.awt.Graphics</code></dd>
</dl>
</li>
</ul>
<a name="getBackground()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>getBackground</h4>
<pre>public java.awt.Color getBackground()</pre>
</li>
</ul>
<a name="setBackground(java.awt.Color)">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>setBackground</h4>
<pre>public void setBackground(java.awt.Color background)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/EscherGraphics.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/poi/hssf/usermodel/DVConstraint.FormulaPair.html" title="class in org.apache.poi.hssf.usermodel"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/poi/hssf/usermodel/EscherGraphics2d.html" title="class in org.apache.poi.hssf.usermodel"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/poi/hssf/usermodel/EscherGraphics.html" target="_top">Frames</a></li>
<li><a href="EscherGraphics.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
</a></div>
<p class="legalCopy"><small>
<i>Copyright 2014 The Apache Software Foundation or
its licensors, as applicable.</i>
</small></p>
</body>
</html> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ChannelMagic.Enums;
namespace ChannelMagic.Models
{
public class ScheduleItemModel
{
public int ScheduleId { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public int MediaId { get; set; }
public int ChannelId { get; set; }
public string ChannelName { get; set; }
public MediaTypeEnum MediaType { get; set; }
public string Title { get; set; }
public string SubTitle { get; set; }
}
} |
SimplePyRay
========
basic seismic ray tracer, for teaching purposes |
#ifndef LP_LOWPIX_H
#define LP_LOWPIX_H
#include <stdint.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
#define LP_ALIGN(x, a) (void*)(((uintptr_t)(x) + (a) - (uintptr_t)1) & ~((a) - (uintptr_t)1))
#define LP_MIN(a, b) (((a) < (b)) ? (a) : (b))
// MEM
// define LP_ALLOC_CUSTOM to override with your own
extern void* lp_alloc(void* ptr, size_t nsize);
extern void* lp_zalloc(size_t size); // init mem to 0
struct LPFileMap { void* mem; uint64_t size; };
extern struct LPFileMap* lp_mmap(const char* filename);
extern void lp_munmap(struct LPFileMap* fmap);
static inline uint16_t lp_read_u16_le(void* p)
{ uint8_t* s = (uint8_t*)p; uint16_t v = s[0] | s[1]<<8; return v; }
static inline uint32_t lp_read_u32_le(void* p)
{ uint8_t* s = (uint8_t*)p; uint32_t v = s[0] | s[1]<<8 | s[2]<<16 | s[3]<<24; return v; }
static inline uint16_t lp_read_u16_lep(void** p)
{ uint8_t* s = (uint8_t*)*p; uint16_t v = s[0] | s[1]<<8; *p = s + 2; return v; }
static inline uint32_t lp_read_u32_lep(void** p)
{ uint8_t* s = (uint8_t*)*p; uint32_t v = s[0] | s[1]<<8 | s[2]<<16 | s[3]<<24; *p = s + 4; return v; }
static inline uint16_t lp_read_u16_be(void* p)
{ uint8_t* s = (uint8_t*)p; uint16_t v = s[0]<<8 | s[1]; return v; }
static inline uint32_t lp_read_u32_be(void* p)
{ uint8_t* s = (uint8_t*)p; uint32_t v = s[0]<<24 | s[1]<<16 | s[2]<<8 | s[3]; return v; }
// CODEC
extern void* lp_cod_rle(void* data, size_t* data_sz);
extern void* lp_dec_rle(void* data, size_t* data_sz);
extern void* lp_cod_huf4(void* data, size_t* data_sz);
extern void* lp_cod_huf8(void* data, size_t* data_sz);
extern void* lp_cod_lz77(void* data, size_t* data_sz);
extern void* lp_dec_lz77(void* data, size_t* data_sz);
// PALETTE
enum LPPaletteFormat
{
<API key> = -1, // use filename extension to select format - defaults to bin if unmatched
<API key> = 0, // raw binary with unlimited color count
<API key>, // for Photoshop / raw binary limited to 256 colors
<API key>, // for Gimp
<API key>, // .s/.h for GBA in 5-5-5 bpp
LP_PALETTEFORMAT_C, // GBA 5-5-5 bpp C file used both as header and compilation unit (define <palettename>_IMPLEMENTATION to compile data)
};
struct LPPalette { uint32_t col_count; uint32_t col[1]; /* overallocated */ };
extern uint16_t lp_col5(uint32_t col);
extern uint32_t lp_col8(uint16_t col);
extern uint32_t lp_colf(float r, float g, float b);
extern uint32_t lp_col_lerp(uint32_t col1, uint32_t col2, float x);
extern int lp_pal_save(struct LPPalette* pal, const char* fn, enum LPPaletteFormat format);
extern struct LPPalette* lp_pal_load(const char* fn, void* data, size_t sz);
extern struct LPPalette* lp_pal_clone(struct LPPalette* pal);
extern struct LPPalette* lp_pal_concat(struct LPPalette* pal1, struct LPPalette* pal2);
extern struct LPPalette* lp_pal_unique(struct LPPalette* pal);
extern struct LPPalette* lp_pal_restrict(struct LPPalette* pal);
extern struct LPPalette* lp_pal_lerp(struct LPPalette* pal1, struct LPPalette* pal2, float x);
#ifdef __cplusplus
}
#endif
#endif |
#ifndef IMAINWINDOW_HPP
#define IMAINWINDOW_HPP
#include <utils/noncopiable.hpp>
#include <point.hpp>
#include <string>
#include <list>
class iMainWindow : public utils::noncopiable
{
public:
virtual void popUpInt(const std::string& title, const std::string& message, int value) =0;
virtual void markGroup(const std::list<Point>& points) =0;
static iMainWindow& instance();
protected:
iMainWindow() = default;
~iMainWindow() = default;
static void setInstance(iMainWindow* instance);
private:
static iMainWindow* s_instance;
};
#endif // IMAINWINDOW_HPP |
/* ScriptDev Frost Sapphire Studios */
#include "precompiled.h"
#include "utgarde_pinnacle.h"
enum
{
SAY_AGGRO = -1575015,
SAY_SLAY_1 = -1575016,
SAY_SLAY_2 = -1575017,
SAY_DEATH = -1575018,
SPELL_ARCING_SMASH = 48260,
SPELL_IMPALE_N = 48261,
SPELL_IMPALE_H = 59268,
<API key> = 48256,
<API key> = 59267,
SPELL_FREEZE_ANIM = 16245,
// Massive Jormungar
SPELL_ACID_SPIT = 48132,
<API key> = 48136,
<API key> = 59272,
<API key> = 48133,
<API key> = 59271,
NPC_JORMUNGAR_WORM = 27228,
// Ferocious Rhino
SPELL_GORE_N = 48130,
SPELL_GORE_H = 59264,
<API key> = 48105,
<API key> = 59263,
SPELL_STOMP = 48131,
// Ravenous Furbolg
<API key> = 48140,
<API key> = 59273,
SPELL_CRAZED = 48139,
<API key> = 48144,
// Frenzied Worgen
<API key> = 48137,
<API key> = 59265,
SPELL_ENRAGE_1 = 48138,
SPELL_ENRAGE_2 = 48142
};
struct MANGOS_DLL_DECL boss_gortokAI : public ScriptedAI
{
uint32 m_uiAnimalCounter;
uint32 <API key>;
boss_gortokAI(Creature* pCreature) : ScriptedAI(pCreature)
{
pInstance = pCreature->GetInstanceData();
m_difficulty = pCreature->GetMap()->GetDifficulty();
Reset();
}
bool m_difficulty;
MobEventTasks Tasks;
void Reset()
{
Tasks.SetObjects(this,me);
Tasks.AddEvent(SPELL_ARCING_SMASH,15000,13000,4000);
if(m_difficulty)
{
Tasks.AddEvent(<API key>,10000,8000,4000,TARGET_ME);
Tasks.AddEvent(SPELL_IMPALE_H,12000,8000,4000);
}
else
{
Tasks.AddEvent(<API key>,10000,8000,4000,TARGET_ME);
Tasks.AddEvent(SPELL_IMPALE_N,12000,8000,4000);
}
m_uiAnimalCounter = 0;
<API key> = 500;
DoCastMe(SPELL_FREEZE_ANIM);
if (pInstance)
{
if(me->isAlive())
{
SetInstanceData(TYPE_GORTOK, NOT_STARTED);
FreezeMob(true,me);
}
Unit* pTemp = NULL;
if (pTemp = Unit::GetUnit((*me),pInstance->GetData64(<API key>)))
{
if (pTemp->isDead())
((Creature*)pTemp)->Respawn();
FreezeMob(true,(Creature*)pTemp);
}
if (pTemp = Unit::GetUnit((*me),pInstance->GetData64(<API key>)))
{
if (pTemp->isDead())
((Creature*)pTemp)->Respawn();
FreezeMob(true,(Creature*)pTemp);
}
if (pTemp = Unit::GetUnit((*me),pInstance->GetData64(<API key>)))
{
if (pTemp->isDead())
((Creature*)pTemp)->Respawn();
FreezeMob(true,(Creature*)pTemp);
}
if (pTemp = Unit::GetUnit((*me),pInstance->GetData64(<API key>)))
{
if (pTemp->isDead())
((Creature*)pTemp)->Respawn();
FreezeMob(true,(Creature*)pTemp);
}
}
}
void Aggro(Unit* pWho)
{
DoScriptText(SAY_AGGRO, me);
}
void AttackStart(Unit* pWho)
{
if (m_uiAnimalCounter < 5)
return;
if (!pWho || pWho == me)
return;
if (me->Attack(pWho, true))
{
me->AddThreat(pWho, 0.0f);
me->SetInCombatWith(pWho);
pWho->SetInCombatWith(me);
DoStartMovement(pWho);
}
}
void MoveInLineOfSight(Unit* pWho)
{
if (!pWho)
return;
if (pWho-><API key>() && pWho-><API key>(me) && me->IsHostileTo(pWho) &&
!m_uiAnimalCounter && pWho->GetTypeId() == TYPEID_PLAYER && me->IsWithinDistInMap(pWho, 25))
{
if(pInstance)
SetInstanceData(TYPE_GORTOK, IN_PROGRESS);
++m_uiAnimalCounter;
}
}
void KilledUnit(Unit* pVictim)
{
DoScriptText(urand(0, 1) ? SAY_SLAY_1 : SAY_SLAY_2, me);
}
void JustDied(Unit* pKiller)
{
DoScriptText(SAY_DEATH, me);
if(pInstance)
SetInstanceData(TYPE_GORTOK, DONE);
GiveEmblemsToGroup(m_difficulty ? HEROISME : 0,1,true);
}
void UpdateAI(const uint32 diff)
{
if (m_uiAnimalCounter)
{
if(<API key> < diff)
{
Creature* pTemp = NULL;
switch(m_uiAnimalCounter)
{
case 1:
pTemp = (Creature*)Unit::GetUnit(*me, pInstance->GetData64(<API key>));
break;
case 2:
pTemp = (Creature*)Unit::GetUnit(*me, pInstance->GetData64(<API key>));
break;
case 3:
pTemp = (Creature*)Unit::GetUnit(*me, pInstance->GetData64(<API key>));
break;
case 4:
pTemp = (Creature*)Unit::GetUnit(*me, pInstance->GetData64(<API key>));
break;
}
if (pTemp)
{
if (!pTemp->isAlive())
++m_uiAnimalCounter;
else
{
if(!pTemp->getVictim())
{
FreezeMob(false,pTemp);
((Unit*)pTemp)->SetStandState(<API key>);
pTemp->AI()->AttackStart(SelectUnit(<API key>,0));
}
}
}
if (m_uiAnimalCounter == 5)
{
FreezeMob(false,me);
((Unit*)me)->SetStandState(<API key>);
<API key> = 10000000;
AttackStart(SelectUnit(<API key>,0));
}
else
{
<API key> = 1000;
return;
}
}
else
<API key> -= diff;
}
if (!CanDoSomething())
return;
Tasks.UpdateEvent(diff);
<API key>();
}
};
struct MANGOS_DLL_DECL <API key> : public ScriptedAI
{
<API key>(Creature* pCreature) : ScriptedAI(pCreature)
{
pInstance = (pCreature->GetInstanceData());
m_difficulty = pCreature->GetMap()->GetDifficulty();
Reset();
}
bool m_difficulty;
uint32 AcidSplatter_timer;
MobEventTasks Tasks;
void Reset() {
Tasks.SetObjects(this,me);
Tasks.CleanMyAdds();
Tasks.AddEvent(SPELL_ACID_SPIT,3000,2000,2000);
Tasks.AddEvent(m_difficulty ? <API key> : <API key>,10000,10000,4000);
AcidSplatter_timer = 12000;
if (pInstance)
if (Creature* pPalehoof = (Creature*)Unit::GetUnit(*me, pInstance->GetData64(<API key>)))
((boss_gortokAI*)pPalehoof->AI())->EnterEvadeMode();
FreezeMob(true,me);
}
void AttackStart(Unit* pWho)
{
if (!pWho || pWho == me)
return;
if (me->HasFlag(UNIT_FIELD_FLAGS, <API key>))
return;
if (me->Attack(pWho, true))
{
me->AddThreat(pWho, 0.0f);
me->SetInCombatWith(pWho);
pWho->SetInCombatWith(me);
DoStartMovement(pWho);
}
}
void UpdateAI(const uint32 diff)
{
//Return since we have no target
if (!CanDoSomething())
return;
// Acid Splatter
if(AcidSplatter_timer <= diff)
{
DoCastMe( m_difficulty ? <API key> : <API key>);
for(uint8 i = 0; i<6; ++i)
Tasks.CallCreature(NPC_JORMUNGAR_WORM);
AcidSplatter_timer = urand(10000,14000);
}
else
AcidSplatter_timer -= diff;
Tasks.UpdateEvent(diff);
<API key>();
}
};
struct MANGOS_DLL_DECL <API key> : public ScriptedAI
{
<API key>(Creature* pCreature) : ScriptedAI(pCreature)
{
pInstance = (pCreature->GetInstanceData());
m_difficulty = pCreature->GetMap()->GetDifficulty();
Reset();
}
bool m_difficulty;
MobEventTasks Tasks;
void Reset()
{
Tasks.SetObjects(this,me);
Tasks.AddEvent(SPELL_STOMP,10000,8000,4000,TARGET_MAIN);
if(m_difficulty)
{
Tasks.AddEvent(SPELL_GORE_H,15000,13000,4000,TARGET_MAIN);
Tasks.AddEvent(<API key>,20000,18000,4000);
}
else
{
Tasks.AddEvent(SPELL_GORE_N,15000,13000,4000,TARGET_MAIN);
Tasks.AddEvent(<API key>,20000,18000,4000);
}
if (pInstance)
if (Creature* pPalehoof = (Creature*)Unit::GetUnit(*me, pInstance->GetData64(<API key>)))
((boss_gortokAI*)pPalehoof->AI())->EnterEvadeMode();
FreezeMob(true,me);
}
void AttackStart(Unit* pWho)
{
if (!pWho || pWho == me)
return;
if (me->HasFlag(UNIT_FIELD_FLAGS, <API key>))
return;
if (me->Attack(pWho, true))
{
me->AddThreat(pWho, 0.0f);
me->SetInCombatWith(pWho);
pWho->SetInCombatWith(me);
DoStartMovement(pWho);
}
}
void UpdateAI(const uint32 diff)
{
//Return since we have no target
if (!CanDoSomething())
return;
Tasks.UpdateEvent(diff);
<API key>();
}
};
struct MANGOS_DLL_DECL <API key> : public ScriptedAI
{
<API key>(Creature* pCreature) : ScriptedAI(pCreature) {
pInstance = (pCreature->GetInstanceData());
m_difficulty = pCreature->GetMap()->GetDifficulty();
Reset();
}
float percent;
bool m_difficulty;
MobEventTasks Tasks;
void Reset()
{
Tasks.SetObjects(this,me);
Tasks.AddEvent(m_difficulty ? <API key> : <API key>,10000,9000,6000);
Tasks.AddEvent(<API key>,9000,10000,10000,TARGET_MAIN);
if (pInstance)
if (Creature* pPalehoof = (Creature*)Unit::GetUnit(*me, pInstance->GetData64(<API key>)))
((boss_gortokAI*)pPalehoof->AI())->EnterEvadeMode();
FreezeMob(true,me);
}
void AttackStart(Unit* pWho)
{
if (!pWho || pWho == me)
return;
if (me->HasFlag(UNIT_FIELD_FLAGS, <API key>))
return;
if (me->Attack(pWho, true))
{
me->AddThreat(pWho, 0.0f);
me->SetInCombatWith(pWho);
pWho->SetInCombatWith(me);
DoStartMovement(pWho);
}
}
void UpdateAI(const uint32 diff)
{
//Return since we have no target
if (!CanDoSomething())
return;
// Crazed
if(percent < 20 && !me->HasAura(SPELL_CRAZED))
DoCastMe( SPELL_CRAZED);
Tasks.UpdateEvent(diff);
<API key>();
}
};
struct MANGOS_DLL_DECL <API key> : public ScriptedAI
{
<API key>(Creature* pCreature) : ScriptedAI(pCreature) {
pInstance = (pCreature->GetInstanceData());
m_difficulty = pCreature->GetMap()->GetDifficulty();
Reset();
}
bool m_difficulty;
MobEventTasks Tasks;
void Reset()
{
Tasks.SetObjects(this,me);
Tasks.AddEvent(m_difficulty ? <API key> : <API key>,5000,4000,5000,TARGET_MAIN);
Tasks.AddEvent(SPELL_ENRAGE_2,10000,10000,0,TARGET_ME);
if (pInstance)
if (Creature* pPalehoof = (Creature*)Unit::GetUnit(*me, pInstance->GetData64(<API key>)))
((boss_gortokAI*)pPalehoof->AI())->EnterEvadeMode();
FreezeMob(true,me);
}
void AttackStart(Unit* pWho)
{
if (!pWho || pWho == me)
return;
if (me->HasFlag(UNIT_FIELD_FLAGS, <API key>))
return;
if (me->Attack(pWho, true))
{
me->AddThreat(pWho, 0.0f);
me->SetInCombatWith(pWho);
pWho->SetInCombatWith(me);
DoStartMovement(pWho);
}
}
void UpdateAI(const uint32 diff)
{
//Return since we have no target
if (!CanDoSomething())
return;
// Enrage1
if(CheckPercentLife(20) && !me->HasAura(SPELL_ENRAGE_1,0))
DoCastMe( SPELL_ENRAGE_1);
Tasks.UpdateEvent(diff);
<API key>();
}
};
CreatureAI* GetAI_boss_gortok(Creature* pCreature)
{
return new boss_gortokAI(pCreature);
}
CreatureAI* <API key>(Creature* pCreature)
{
return new <API key> (pCreature);
}
CreatureAI* <API key>(Creature* pCreature)
{
return new <API key> (pCreature);
}
CreatureAI* <API key>(Creature* pCreature)
{
return new <API key> (pCreature);
}
CreatureAI* <API key>(Creature* pCreature)
{
return new <API key> (pCreature);
}
void AddSC_boss_gortok()
{
Script *newscript;
newscript = new Script;
newscript->Name = "boss_gortok";
newscript->GetAI = &GetAI_boss_gortok;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "<API key>";
newscript->GetAI = &<API key>;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "mob_ferocious_rhino";
newscript->GetAI = &<API key>;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "<API key>";
newscript->GetAI = &<API key>;
newscript->RegisterSelf();
newscript = new Script;
newscript->Name = "mob_frenzied_worgen";
newscript->GetAI = &<API key>;
newscript->RegisterSelf();
} |
#ifndef <API key>
#define <API key>
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include "FLAC/metadata.h"
#include "utils.h"
#include "share/compat.h"
/* WATCHOUT: these enums are used to index internal arrays */
typedef enum {
<API key> = 0, /* for AIFF and AIFF-C */
<API key> = 1, /* for WAVE and RF64 */
<API key> = 2 /* only for Sony's flavor */
} <API key>;
typedef struct {
/* for encoding, this will be the offset in the WAVE/AIFF file of the chunk */
/* for decoding, this will be the offset in the FLAC file of the chunk data inside the APPLICATION block */
FLAC__off_t offset;
/* size is the actual size in bytes of the chunk to be stored/recreated. */
/* It includes the 8 bytes of chunk type and size, and any padding byte for alignment. */
/* For 'data'/'SSND' chunks, the size does not include the actual sound or padding bytes */
/* because these are not stored, they are recreated from the compressed FLAC stream. */
/* So for RIFF 'data', size is 8, and for AIFF 'SSND', size is 8 + 8 + ssnd_offset_size */
/* 32 bit size is OK because we only care about the non-sound data and FLAC metadata */
/* only supports a few megs anyway. */
FLAC__uint32 size;
} foreign_block_t;
typedef struct {
<API key> type; /* currently we don't support multiple foreign types in a stream (and maybe never will) */
foreign_block_t *blocks;
size_t num_blocks;
size_t format_block; /* block number of 'fmt ' or 'COMM' chunk */
size_t audio_block; /* block number of 'data' or 'SSND' chunk */
FLAC__bool is_rf64; /* always false if type!=RIFF */
FLAC__uint32 ssnd_offset_size; /* 0 if type!=AIFF */
} foreign_metadata_t;
foreign_metadata_t *<API key>(<API key> type);
void <API key>(foreign_metadata_t *fm);
FLAC__bool <API key>(foreign_metadata_t *fm, const char *filename, const char **error);
FLAC__bool <API key>(foreign_metadata_t *fm, const char *filename, const char **error);
FLAC__bool <API key>(foreign_metadata_t *fm, const char *filename, const char **error);
FLAC__bool <API key>(foreign_metadata_t *fm, const char *infilename, const char *outfilename, const char **error);
FLAC__bool <API key>(foreign_metadata_t *fm, const char *filename, const char **error);
FLAC__bool <API key>(foreign_metadata_t *fm, const char *infilename, const char *outfilename, FLAC__off_t offset1, FLAC__off_t offset2, FLAC__off_t offset3, const char **error);
#endif |
#ifndef __LS_UNIT_TEST_H
#define __LS_UNIT_TEST_H
#ifdef NDEBUG
#define UNIT_TEST static __attribute__((unused))
#define UNIT_TEST1(priority) static __attribute__((unused))
#else
#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR >= 3)
#define UNIT_TEST static __attribute__((constructor))
#define UNIT_TEST1(priority) static __attribute__((constructor(priority + 101)))
#else
#define UNIT_TEST static __attribute__((constructor))
#endif
#endif
#endif /* __LS_UNIT_TEST_H */ |
using ProjNet.CoordinateSystems;
namespace SharpMap.Geometries
{
<summary>
Defines basic interface for a Geometry
</summary>
public interface IGeometry
{
#region "Basic Methods on Geometry"
<summary>
Gets or sets the spatial reference system associated with the <see cref="Geometry"/>.
A <see cref="Geometry"/> may not have had a spatial reference system defined for
it, in which case *spatialRef will be NULL.
</summary>
ICoordinateSystem SpatialReference { get; set; }
<summary>
The inherent dimension of this <see cref="Geometry"/> object, which must be less than or equal to the coordinate dimension.
</summary>
int Dimension { get; }
<summary>
The minimum bounding box for this Geometry, returned as a <see cref="Geometry"/>. The
polygon is defined by the corner points of the bounding box ((MINX, MINY), (MAXX, MINY), (MAXX,
MAXY), (MINX, MAXY), (MINX, MINY)).
</summary>
Geometry Envelope();
<summary>
The minimum <see cref="BoundingBox"/> for this <see cref="Geometry"/>.
</summary>
<returns><see cref="BoundingBox"/> for this <see cref="Geometry"/></returns>
BoundingBox GetBoundingBox();
<summary>
Exports this <see cref="Geometry"/> to a specific well-known text representation of <see cref="Geometry"/>.
</summary>
string AsText();
<summary>
Exports this <see cref="Geometry"/> to a specific well-known binary representation of <see cref="Geometry"/>.
</summary>
byte[] AsBinary();
<summary>
Returns a WellKnownText representation of the <see cref="Geometry"/>
</summary>
<returns>Well-known text</returns>
string ToString();
<summary>
If true, then this <see cref="Geometry"/> represents the empty point set, ? for the coordinate space.
</summary>
<returns>Returns 'true' if this <see cref="Geometry"/> is the empty geometry</returns>
bool IsEmpty();
<summary>
Returns 'true' if this <see cref="Geometry"/> has no anomalous geometric points, such as self
intersection or self tangency. The description of each instantiable geometric class will include the specific
conditions that cause an instance of that class to be classified as not simple.
</summary>
<returns>true if the <see cref="Geometry"/> is simple</returns>
bool IsSimple();
<summary>
Returns the closure of the combinatorial boundary of this <see cref="Geometry"/>. The
combinatorial boundary is defined as described in section 3.12.3.2 of [1]. Because the result of this function
is a closure, and hence topologically closed, the resulting boundary can be represented using
representational geometry primitives
</summary>
<returns>Closure of the combinatorial boundary of this <see cref="Geometry"/></returns>
Geometry Boundary();
<summary>
Returns 'true' if this <see cref="Geometry"/> is spatially related to another <see cref="Geometry"/>, by testing
for intersections between the Interior, Boundary and Exterior of the two geometries
as specified by the values in the <API key>
</summary>
<param name="other"><see cref="Geometry"/> to relate to</param>
<param name="intersectionPattern">Intersection Pattern</param>
<returns>True if spatially related</returns>
bool Relate(Geometry other, string intersectionPattern);
#endregion
#region "Methods for testing Spatial Relations between geometric objects"
<summary>
Returns 'true' if this <see cref="Geometry"/> is 'spatially equal' to another <see cref="Geometry"/>
</summary>
bool Equals(Geometry geom);
<summary>
Returns 'true' if this <see cref="Geometry"/> is 'spatially disjoint' from another <see cref="Geometry"/>
</summary>
bool Disjoint(Geometry geom);
<summary>
Returns 'true' if this <see cref="Geometry"/> 'spatially intersects' another <see cref="Geometry"/>
</summary>
bool Intersects(Geometry geom);
<summary>
Returns 'true' if this <see cref="Geometry"/> 'spatially touches' another <see cref="Geometry"/>.
</summary>
bool Touches(Geometry geom);
<summary>
Returns 'true' if this <see cref="Geometry"/> 'spatially crosses' another <see cref="Geometry"/>.
</summary>
bool Crosses(Geometry geom);
<summary>
Returns 'true' if this <see cref="Geometry"/> is 'spatially within' another <see cref="Geometry"/>.
</summary>
bool Within(Geometry geom);
<summary>
Returns 'true' if this <see cref="Geometry"/> 'spatially contains' another <see cref="Geometry"/>.
</summary>
bool Contains(Geometry geom);
<summary>
Returns 'true' if this <see cref="Geometry"/> 'spatially overlaps' another <see cref="Geometry"/>.
</summary>
bool Overlaps(Geometry geom);
#endregion
#region "Methods that support Spatial Analysis"
<summary>
Returns the shortest distance between any two points in the two geometries
as calculated in the spatial reference system of this <see cref="Geometry"/>.
</summary>
<param name="geom"><see cref="Geometry"/> to calculate distance to</param>
<returns>Shortest distance between any two points in the two geometries</returns>
double Distance(Geometry geom);
<summary>
Returns a <see cref="Geometry"/> that represents all points whose distance from this <see cref="Geometry"/>
is less than or equal to distance. Calculations are in the Spatial Reference
System of this <see cref="Geometry"/>.
</summary>
<param name="d">Buffer distance</param>
<returns>Buffer around <see cref="Geometry"/></returns>
Geometry Buffer(double d);
<summary>
Returns a <see cref="Geometry"/> that represents the convex hull of this <see cref="Geometry"/>.
</summary>
<returns>The convex hull</returns>
Geometry ConvexHull();
<summary>
Returns a <see cref="Geometry"/> that represents the point set intersection of this <see cref="Geometry"/>
with another <see cref="Geometry"/>.
</summary>
<param name="geom"><see cref="Geometry"/> to intersect with</param>
<returns>Returns a <see cref="Geometry"/> that represents the point set intersection of this <see cref="Geometry"/> with another <see cref="Geometry"/>.</returns>
Geometry Intersection(Geometry geom);
<summary>
Returns a <see cref="Geometry"/> that represents the point set union of this <see cref="Geometry"/> with anotherGeometry.
</summary>
<param name="geom">Geometry to union with</param>
<returns>Unioned <see cref="Geometry"/></returns>
Geometry Union(Geometry geom);
<summary>
Returns a <see cref="Geometry"/> that represents the point set difference of this <see cref="Geometry"/> with anotherGeometry.
</summary>
<param name="geom"><see cref="Geometry"/> to compare to</param>
<returns><see cref="Geometry"/></returns>
Geometry Difference(Geometry geom);
<summary>
Returns a geometry that represents the point set symmetric difference of this <see cref="Geometry"/> with anotherGeometry.
</summary>
<param name="geom"><see cref="Geometry"/> to compare to</param>
<returns><see cref="Geometry"/></returns>
Geometry SymDifference(Geometry geom);
#endregion
}
} |
package TrampoDb.Ex18;
import java.awt.*;
public abstract class MyLimitedShape extends MyShape {
private boolean fill;
public MyLimitedShape() {
setFill(false);
}
public MyLimitedShape(int x1, int y1, int x2, int y2,
Color color, boolean fill) {
super(x1, y1, x2, y2, color);
setFill(fill);
}
public void setFill(boolean f) {
fill = f;
}
public boolean isFilled() {
return fill;
}
public int getUpperLeftX() {
return Math.min(getX1(), getX2());
}
public int getUpperLeftY() {
return Math.min(getY1(), getY2());
}
public int getWidth() {
return Math.abs(getX1() - getX2());
}
public int getHeight() {
return Math.abs(getY1() - getY2());
}
} |
<?php
require('prodAllLanes.php');
require('barcode.php');
include('../db.php');
function itemParse($upc,$dupe='no',$description='',$prefix=false)
{
global $sql;
$logged_in = checkLogin();
$p_columns = '
p.upc,
p.description,
p.normal_price,
p.pricemethod,
p.quantity,
p.groupprice,
p.special_price,
p.end_date,
p.department,
p.tax,
p.foodstamp,
p.scale,
p.qttyEnforced,
p.discount,
p.modified,
p.local
'; // last comma omitted on purpose
$savedUPC="";
$queryItem = "";
$args = array();
$numType = (isset($_REQUEST['ntype'])?$_REQUEST['ntype']:'UPC');
if (is_numeric($upc)){
switch($numType){
case 'UPC':
$upc = str_pad($upc,13,0,STR_PAD_LEFT);
$savedUPC = $upc;
$queryItem = "SELECT {$p_columns},x.distributor,x.manufacturer,
u.brand,u.description as udesc,u.sizing,u.photo,
u.long_text,u.enableOnline,e.expires
FROM products as p left join
prodExtra as x on p.upc=x.upc
LEFT JOIN productUser as u
ON p.upc=u.upc LEFT JOIN productExpires
AS e ON p.upc=e.upc
WHERE p.upc = ? or x.upc = ?";
$args = array($upc, $upc);
break;
case 'SKU':
$queryItem = "SELECT {$p_columns},x.distributor,x.manufacturer,
u.brand,u.description as udesc,u.sizing,u.photo,
u.long_text,u.enableOnline,e.expires
FROM products as p inner join
vendorItems as v ON p.upc=v.upc
left join prodExtra as x on p.upc=x.upc
LEFT JOIN productUser as u
ON p.upc=u.upc LEFT JOIN productExpires
AS e ON p.upc=e.upc
WHERE v.sku=?";
$args = array($upc);
break;
case 'Brand Prefix':
$queryItem = "SELECT {$p_columns},x.distributor,x.manufacturer,
u.brand,u.description as udesc,u.sizing,u.photo,
u.long_text,u.enableOnline,e.expires
FROM products as p
left join prodExtra as x on p.upc=x.upc
LEFT JOIN productUser as u
ON p.upc=u.upc LEFT JOIN productExpires
AS e ON p.upc=e.upc
WHERE p.upc like ? order by p.upc";
$args = array('%'.$upc.'%');
break;
}
}
else{
$queryItem = "SELECT {$p_columns},x.distributor,x.manufacturer,
u.brand,u.description as udesc,u.sizing,u.photo,
u.long_text,u.enableOnline,e.expires
FROM products as p left join
prodExtra as x on p.upc=x.upc
LEFT JOIN productUser as u
ON p.upc=u.upc LEFT JOIN productExpires
AS e ON p.upc=e.upc
WHERE p.description LIKE ? OR
u.description LIKE ? ORDER BY p.description";
$args = array('%'.$upc.'%', '%'.$upc.'%');
}
//echo $queryItem;
echo "<script type=\"text/javascript\">";
echo "function shelftag(u){";
echo "testwindow= window.open (\"../../item/addShelfTag.php?upc=\"+u, \"New Shelftag\",\"location=0,status=1,scrollbars=1,width=300,height=220\");";
echo "testwindow.moveTo(50,50);";
echo "}";
echo "</script>";
$barcodeUPC = ltrim($upc,"0");
echo "<script language=JavaScript>";
echo "function popup(){";
echo "testwindow= window.open (\"addLikeCode.php\", \"Add Like Code\",\"location=0,status=1,scrollbars=1,width=200,height=200\");";
echo "testwindow.moveTo(50,50);";
echo "}";
echo "</script>";
echo "<script language=JavaScript>";
echo "function newTagCheck(){";
echo "if (document.getElementById('newTag').checked)";
//echo "shelftag();";
echo "}";
echo "</script>";
$num = 0;
$prepItem = $sql->prepare($queryItem);
$resultItem = $sql->execute($prepItem, $args);
$num = $sql->num_rows($resultItem);
$likeCodeQ = $sql->prepare("SELECT u.*,l.likeCodeDesc FROM upcLike as u, likeCodes as l
WHERE u.likeCode = l.likeCode and u.upc = ?");
$likeCodeR = $sql->execute($likeCodeQ, array($upc));
$likeCodeRow= $sql->fetch_row($likeCodeR);
$likeCodeNum = $sql->num_rows($likeCodeR);
$listCodeQ = "SELECT * from likeCodes";
$listCodeR = $sql->query($listCodeQ);
$listCodeRow = $sql->fetch_row($likeCodeR);
if($num == 0)
{
noItem();
echo "<head><title>Enter New Item</title></head>";
echo "<BODY onLoad='putFocus(0,1);'>";
printMods($savedUPC);
echo "Item not found, would you like to enter it?";
echo "<form action=enterTestItem.php method=post onsubmit=\"newTagCheck();\">";
echo "<table>";
echo "<tr><td align=right><b>UPC</b></td><td><font color='red'></font>
<input type=text value=$upc name=upc maxlength=13></td>";
echo "</tr><tr><td><b>Description</b></td><td>
<input type=text size=35 name=descript maxlength=30></td>";
echo "<td><b>Price</b></td><td>$<input type=text name=price></td></tr>";
echo "<tr><td><b>Manufacturer</b></td><td><input type=text size=35 value=\"\" name=manufacturer /></td>";
echo "<td><b>Distributor</b></td><td> <input type=text value=\"\" name=distributor /></td></tr>";
echo "</table>";
echo "<table border=0><tr>";
echo "<th>Dept<th>Tax<th>FS<th>Scale<th>QtyFrc<th>NoDisc<th>Local<th>Like Code<th>Shelf Tag</b>";
echo "</tr>";
echo "<tr>";
$query2 = "SELECT * FROM departments as d,
MasterSuperDepts AS s WHERE s.dept_ID=d.dept_no AND dept_no NOT IN (60,225)
ORDER BY superID, dept_no";
echo "<td>";
$upc_split = substr($upc,0,7);
$guessQ = $sql->prepare("select department from products where upc like ?
group by department
order by count(*) desc");
$guessR = $sql->execute($guessQ, array($upc_split.'%'));
$guess = 60;
if ($sql->num_rows($guessR) > 0)
$guessW = $sql->fetch_array($guessR);
$guess = $guessW['department'];
echo '<select name="dept">';
$result2 = $sql->query($query2);
while($row2 = $sql->fetch_row($result2)) {
printf('<option %s value="%d">%d %s</option>',
($row2['dept_no'] == $guess ? 'selected' : ''),
$row2['dept_no'], $row2['dept_no'], $row2['dept_name']);
}
echo '</select>';
echo " </td>";
echo "<td align=right>Reg";
echo "<input type=radio name=tax value=1><br>";
echo "Deli<input type=radio name=tax value=2><br>";
echo "No Tax<input type=radio name=tax value=0";
echo "></td><td align=center><input type=checkbox value=1 name=FS";
echo "></td><td align=center><input type=checkbox value=1 name=Scale";
echo "></td><td align=center><input type=checkbox value=1 name=ForcQty";
echo "></td><td align=center><input type=checkbox value=1 name=NoDisc";
echo "></td><td align=center><select name=local><option value=0>No</option>
<option value=1>SC</option><option value=2>300mi</option></select>";
echo "<input type=hidden value=1 name=inUse";
echo "><td align=center>";
//echo "<input type=text align=right size=4 name=likeCode>";
echo "<select name=likeCode style=\"{width: 175px;}\">";
echo "<option value=\"\">(none)</option>";
$likelistQ = "select * from likeCodes order by likecode";
$likelistR = $sql->query($likelistQ);
while ($llRow = $sql->fetch_array($likelistR)){
echo "<option value={$llRow[0]}";
if (isset($likecode) && $llRow[0] == $likecode){
echo " selected";
}
echo ">{$llRow[0]} {$llRow[1]}</option>";
}
echo "</select>";
echo "</td><td align=center><input type=checkbox value=1 id=newTag name=shelftag></td></tr>";
if ($logged_in){
echo "<tr><td><input type='submit' name='submit' value='submit'>";
}
else {
echo "<tr><td>Please <a href=/auth/ui/loginform.php?redirect=/queries/productTest.php?upc=$upc>";
echo "login</a> to add items";
}
echo "</td></tr> ";
echo "</tr></table>";
}elseif($num > 1){
moreItems($upc);
$upcs = array();
$descriptions = array();
for($i=0;$i < $num;$i++){
$rowItem= $sql->fetch_array($resultItem);
$upcs[$i] = $rowItem['upc'];
$descriptions[$i] = $rowItem['description'];
$modified[$i] = $rowItem['modified'];
//echo "<a href='productTest.php?upc=$upc'>" . $upc . " </a>- " . $rowItem['description'] . "<br>";
}
for ($i=0;$i<$num;$i++){
$dupe = false;
for ($j=0; $j<$num; $j++){
if ($i != $j and $upcs[$i] == $upcs[$j]){
$enc = base64_encode($descriptions[$i]);
echo "<a href=productTest.php?upc=$upcs[$i]&duplicate=yes&description={$enc}>{$upcs[$i]}</a>-{$descriptions[$i]} - <b>DUPLICATE</b> - ";
echo "<a href=javascript:delete_popup(\"$upcs[$i]\",\"$enc\")><img src=trash.png border=0/></a><br />";
$j = $num;
$dupe = true;
}
}
if (!$dupe){
echo "<a href=productTest.php?upc={$upcs[$i]}>{$upcs[$i]}</a>-{$descriptions[$i]}<br />";
}
}
}else{
oneItem($upc);
$rowItem = $sql->fetch_array($resultItem);
$upc = $rowItem['upc'];
$currentDepartment = $rowItem['department'];
$prev = $next = 0;
$modified = $rowItem['modified'];
deptPrevNext($currentDepartment,$upc,$prev,$next);
$modDate = $modified;
$likecode = '';
if(!empty($likeCodeRow[1]))
$likecode = $likeCodeRow[1];
echo "<head><title>Update Item</title></head>";
echo "<BODY onLoad='putFocus(0,2);'>";
printMods($savedUPC);
echo "<form action=updateItemTest.php method=post>";
echo "<table>";
echo "<tr><td align=right><b>UPC</b></td><td><font color='red'>".$rowItem['upc']."</font><input type=hidden value='{$rowItem['upc']}' name=upc>";
if ($prev != -1)
echo " <a href=productTest.php?upc=$prev>Previous</a>";
if ($next != -1)
echo " <a href=productTest.php?upc=$next>Next</a>";
echo "</td>";
echo "</tr><tr><td><b>Description</b></td><td><input type=text size=35 maxlength=30 value=\"{$rowItem['description']}\" name=descript></td>";
echo "<td><b>Price</b></td><td>$<input type=text value='{$rowItem['normal_price']}' name=price></td></tr>";
echo "<tr><td colspan=2 align=right><b>Enable Volume Price</b> <input type=checkbox name=doVolume ";
echo ($rowItem['pricemethod'] != 0 ? "checked" : "")." /></td><td colspan=2>";
echo "<input type=hidden name=pricemethod value=\"{$rowItem['pricemethod']}\">";
echo "<input type=text size=4 name=vol_qtty value=".($rowItem['quantity'] != 0 ? $rowItem['quantity'] : "\"\"")." />";
echo " for $<input type=text size=4 name=vol_price value=".($rowItem['groupprice'] != 0 ? $rowItem['groupprice'] : "\"\"")." /></td></tr>";
echo "<tr><td><b>Manufacturer</b></td><td><input type=text size=35 value=\"{$rowItem['manufacturer']}\" name=manufacturer /></td>";
echo "<td><b>Distributor</b></td><td> <input type=text value=\"{$rowItem['distributor']}\" name=distributor /></td></tr>";
echo "<a href=/git/fannie/reports/PriceHistory/?upc={$rowItem['upc']} target=blank>Click for Price History</a>";
if($rowItem['special_price'] <> 0){
echo "<tr><td><font size=+1 color=green><b>Sale Price:</b></font></td><td><font size=+1 color=green>{$rowItem['special_price']}</font>";
echo "<td colspan=2><font size=+1 color=green>End Date: {$rowItem['end_date']}</font></td><tr>";
$findBatchQ = $sql->prepare("select batchName from batches as b, batchList as l
where b.batchID = l.batchID and l.upc like ?
and ".$sql->curdate()." BETWEEN b.startDate AND b.endDate");
$findBatchR = $sql->execute($findBatchQ, array($upc));
$batchName = ($sql->num_rows($findBatchR) == 0) ? "Unknown" :array_pop($sql->fetch_array($findBatchR));
if ($batchName == "Unknown" && $likecode != ""){
$findBatchQ = $sql->prepare("select batchName from batches as b, batchList as l
where b.batchID=l.batchID and l.upc = ?
and ".$sql->curdate()." BETWEEN b.startDate AND b.endDate");
$findBatchR = $sql->execute($findBatchQ, array('LC'.$likecode));
$batchName = ($sql->num_rows($findBatchR) == 0) ? "Unknown" :array_pop($sql->fetch_array($findBatchR));
}
echo "<tr><td colspan=4><b>Batch: $batchName</b> ";
if (validateUserQuiet('pricechange') || substr($upc,0,3) == "002" ){
echo "(<a href=unsale.php?upc=$upc><font color=red>Take this item off sale now</font></a>)</td>";
}
}
echo "</table>";
echo "<table border=0><tr>";
echo "<th>Dept<th>Tax<th>FS<th>Scale<th>QtyFrc<th>NoDisc<th>Local<th>Like Code<th> </b>";
echo "</tr>";
echo "<tr align=top>";
//$dept=$row1[3];
$query2 = "SELECT * FROM departments as d,
MasterSuperDepts AS s WHERE s.dept_ID=d.dept_no AND dept_no NOT IN (60,225)
ORDER BY superID, dept_no";
echo "<td>";
$query3 = $sql->prepare("SELECT dept_no,superID FROM departments as d
LEFT JOIN MasterSuperDepts AS s ON d.dept_no=s.dept_ID
WHERE dept_no = ?");
$result3 = $sql->execute($query3, $rowItem['department']);
$row3 = $sql->fetch_array($result3);
echo '<select name="dept">';
$result2 = $sql->query($query2);
while($row2 = $sql->fetch_row($result2)) {
printf('<option %s value="%d">%d %s</option>',
($row2['dept_no'] == $rowItem['department'] ? 'selected' : ''),
$row2['dept_no'], $row2['dept_no'], $row2['dept_name']);
}
echo '</select>';
echo " </td>";
echo "<td align=right>Reg ";
echo "<input type=radio name=tax value=1";
if($rowItem['tax']==1){
echo " checked";
}
echo "><br>Deli <input type=radio name=tax value=2";
if($rowItem['tax']==2){
echo " checked";
}
echo "><br>NoTax <input type=radio name=tax value=0";
if($rowItem['tax']==0){
echo " checked";
}
echo "></td><td align=center><input type=checkbox value=1 name=FS";
if($rowItem['foodstamp']==1){
echo " checked";
}
echo "></td><td align=center><input type=checkbox value=1 name=Scale";
if($rowItem['scale']==1){
echo " checked";
}
echo "></td><td align=center><input type=checkbox value=1 name=QtyFrc";
if($rowItem['qttyEnforced']==1){
echo " checked";
}
echo "></td><td align=center><input type=checkbox value=0 name=NoDisc";
if($rowItem['discount']==0){
echo " checked";
}
echo ">" . "</td><input type=hidden value=1 name=inUse";
echo "></td><td align=center><select name=local>";
printf("<option value=0 %s>No</option>",($rowItem['local']==0?'selected':''));
printf("<option value=1 %s>SC</option>",($rowItem['local']==1?'selected':''));
printf("<option value=2 %s>300mi</option>",($rowItem['local']==2?'selected':''));
echo "</select><td align=center>";
//echo "<input type=text align=right size=4 value='$likecode' name=likeCode>";
echo "<select name=likeCode style=\"{width: 175px;}\">";
echo "<option value=-1>(none)</option>";
$likelistQ = "select * from likeCodes order by likecode";
$likelistR = $sql->query($likelistQ);
while ($llRow = $sql->fetch_array($likelistR)){
echo "<option value={$llRow[0]}";
if ($llRow[0] == $likecode){
echo " selected";
}
echo ">{$llRow[0]} {$llRow[1]}</option>";
}
echo "</select>";
echo "</td><td>";
echo "<a href=javascript:popup()>Add like code</a>";
echo "</td>";
echo "<a href=javascript:shelftag('$upc')>New Shelf Tag</a>";
echo "</tr>";
echo "</tr>";
echo "<tr><td align=right><font size=-1 color=purple><i><b>Last Modified: </b></i></font></td>";
echo "<td colspan=3><font size=-1 color=purple><i>$modDate</i></td>";
echo"<td colspan=5><a href=/git/fannie/reports/RecentSales/index.php?upc=$upc target=blank>Click for History</a></td></tr>";
echo "<tr><td colspan=4>";
// kick out a scale input for upcs starting with 002
// pass variables with prefix s_
if (preg_match("/^002/",$rowItem['upc']) && $row3[1] == 3){
$scaleQuery = $sql->prepare("select * from scaleItems where plu=?");
$scaleRes = $sql->execute($scaleQuery, array($upc));
$scaleRow = $sql->fetch_row($scaleRes);
echo "<table border=1 cellspacing=0 cellpadding=7><tr>";
echo "<td bgcolor=\"#FFFFCC\">";
echo "Scale Information:<br />";
echo "UPC: <font color=red>{$rowItem['upc']}</font><p />";
echo "<input type=hidden name=s_plu value={$rowItem['upc']}>";
echo "Longer description:";
// only show a longer description if the description differs
echo " <input type=text name=s_longdesc size=40 maxlength=100";
if ($rowItem['description'] != $scaleRow[2]){
echo " value='{$scaleRow[2]}'";
}
echo ">";
echo "<p />";
// EXCEPTION PRICE?
// Unnecessary to users but expected by csv package
echo "<input type=hidden name=s_exception value=0.00>";
echo "<table border=1 cellspacing=0 cellpadding=7><tr>";
echo "<th>Weight</th><th>By Count</th><th>Tare</th><th>Shelf Life</th><th>Net Wt (oz)</th><th>Label</th><th>Safehandling</th>";
echo "</tr><tr><td>";
echo "<input type=radio name=s_type value=\"Random Weight\"";
if ($scaleRow[4] == 0){
echo " checked> Random<br />";
}
else {
echo "> Random<br />";
}
echo "<input type=radio name=s_type value=\"Fixed Weight\"";
if ($scaleRow[4] == 1){
echo " checked> Fixed<br />";
}
else {
echo "> Fixed<br />";
}
echo "</td><td align=center>";
echo "<input type=checkbox name=s_bycount";
if ($scaleRow['bycount'] == 1){
echo " checked>";
}
else {
echo ">";
}
echo "</td><td>";
echo "<input type=text name=s_tare size=5 value={$scaleRow['tare']}>";
echo "</td><td>";
echo "<input type=text name=s_shelflife size=5 value={$scaleRow['shelflife']}>";
echo "</td><td>";
echo "<input type=text name=s_netwt size=5 value={$scaleRow['netWeight']}>";
echo "</td><td>";
echo "<select name=s_label size=2>";
if ($scaleRow['label'] == 133 || $scaleRow['label'] == 63)
echo "<option value=horizontal selected>Horizontal</option>";
else
echo "<option value=horizontal>Horizontal</option>";
if ($scaleRow['label'] == 103 || $scaleRow['label'] == 53 || $scaleRow['label'] == 23)
echo "<option value=vertical selected>Vertical</option>";
else
echo "<option value=vertical>Vertical</option>";
echo "</select>";
echo "</td><td align=center>";
if ($scaleRow['graphics'] == 0)
echo "<input type=checkbox name=s_graphics />";
else
echo "<input type=checkbox name=s_graphics checked />";
echo "</td>";
echo "</td></tr></table><br />";
echo "<p />Expanded text:<br /><textarea name=s_text rows=4
cols=40>{$scaleRow['text']}</textarea>";
echo "<p /></td></tr></table>";
}
echo "<br /></td></tr><tr><td>";
echo "Like Code Linked Items</td><td> </td><td><input type=checkbox name=update value='no'></td><td colspan=4>Check to not update like code items</td></tr><tr><td>";
if($likeCodeNum > 0){
$selLikeQ = "SELECT p.upc,p.description,p.normal_price FROM products as p, upcLike as u WHERE u.upc = p.upc and u.likeCode = ?";
likedtotable($selLikeQ,$likeCodeRow[0],0,'FFFFCC');
echo"<td valign=top colspan=3><a href=/git/fannie/reports/PriceHistory/?likecode=$likeCodeRow[1] target=lc_hist>Click for Like Code History</a></td>";
}
if ($logged_in || (preg_match("/^002/",$rowItem['upc']) && $row3[1] == 3)){
echo "</td></tr><tr><td colspan=4><input type='submit' name='submit' value='submit'> ";
echo " <a href=../../item/DeleteItemPage.php?id=$upc>Delete this item</a> | ";
}
else {
echo "</td></tr><tr><td colspan=4>Please <a href=/auth/ui/loginform.php?redirect=/queries/productTest.php?upc=$upc>";
echo "login</a> to change prices";
}
echo " <a href=javascript:back()>Back</a></td></tr> ";
echo "<tr><td colspan=5>";
echo '<a href="" onclick="$(\'#topSecret\').toggle();return false;">Extra</a>';
echo "<div id=\"topSecret\" style=\"display:none;\">";
echo "<div style=\"float:left;width:500px;\">";
echo "<b>Sane Brand & Description</b>: ";
printf("<input name=\"u_brand\" value=\"%s\" />
<input name=\"u_desc\" value=\"%s\" /><br />",
$rowItem["brand"],$rowItem["udesc"]);
printf("<b>Size</b>: <input name=\"u_size\" value=\"%s\" />",
$rowItem["sizing"]);
printf(' <input type="checkbox" name="u_enableOnline" %s />Sell online<br />',
($rowItem['enableOnline']==1 ? 'checked' : ''));
printf("<b>Expires</b>: <input name=\"u_expires\" value=\"%s\" />",
$rowItem["expires"]);
printf('<p><b>Page Text</b><br /><textarea rows=15 cols=80 name=u_long_text>%s</textarea></p>',str_replace("<br />","\n",$rowItem['long_text']));
echo "</div>";
if (!empty($rowItem["photo"])){
echo "<div style=\"float:left;\">";
printf("<a href=\"/git/fannie/item/images/done/%s\"><img src=\"/git/fannie/item/images/done/%s\" /></a>",
$rowItem["photo"],str_replace("png","thumb.png",$rowItem["photo"]));
echo "</div>";
}
echo "<div style=\"clear:left;\"></div>";
echo "</div>";
echo "</tr>";
echo "<tr><td height=5> </td></tr><tr><td bgcolor=#ddffdd colspan=3>";
allLanes($upc);
echo "</td></tr>";
}
return $num;
}
function likedtotable($query,$args,$border,$bgcolor)
{
global $sql;
$prep = $sql->prepare($query);
$results = $sql->execute($prep, $args);
$number_cols = $sql->num_fields($results);
//display query
//echo "<b>query: $query</b>";
//layout table header
echo "<table border = $border bgcolor=$bgcolor>\n";
echo "<tr align left>\n";
/*for($i=0; $i<5; $i++)
{
echo "<th>" . $sql->fieldName($results,$i). "</th>\n";
}
echo "</tr>\n"; *///end table header
//layout table body
while($row = $sql->fetch_row($results))
{
echo "<tr align=left>\n";
echo "<td >";
if(!isset($row[0]))
{
echo "NULL";
}else{
?>
<a href="productTest.php?upc=<?php echo $row[0]; ?>">
<?php echo $row[0]; ?></a>
<?php echo "</td>";
}
for ($i=1;$i<$number_cols-1; $i++)
{
echo "<td>";
if(!isset($row[$i])) //test for null value
{
echo "NULL";
}else{
echo $row[$i];
}
echo "</td>\n";
} echo "</tr>\n";
} echo "</table>\n";
}
function noItem()
{
echo "No Items Found <br>";
}
function moreItems($upc)
{
echo "More than 1 item found for: " . $upc . "<br>";
}
function oneItem($upc)
{
//echo "One item found for: " . $upc . "<br>";
}
function upcCheck($upc){
$sum=0;
for($i=1;$i<=11;$i+=2)
$sum+=3*$barcode{$i};
for($i=0;$i<=10;$i+=2)
$sum+=$barcode{$i};
$check = 10 - ($sum)%10;
return $check;
}
function upcCheckOld($upc)
{
$dig1 = substr($upc,0,1);
$dig2 = substr($upc,1,1);
$dig3 = substr($upc,2,1);
$dig4 = substr($upc,3,1);
$dig5 = substr($upc,4,1);
$dig6 = substr($upc,5,1);
$dig7 = substr($upc,6,1);
$dig8 = substr($upc,7,1);
$dig9 = substr($upc,8,1);
$dig10 = substr($upc,9,1);
$dig11 = substr($upc,10,1);
$dig12 = substr($upc,11,1);
$dig13 = substr($upc,12,1);
//echo $upc . ": ". $dig1 . " ". $dig2 . " ". $dig3. " ". $dig13 . "<br>";
$mult1 = 3*dig1;
$mult2 = 3*dig2;
$mult3 = 3*dig3;
$mult5 = 3*dig5;
$mult7 = 3*dig7;
$mult9 = 3*dig9;
$mult11 = 3*dig11;
$mult13 = 3*dig13;
$mod = 10;
//$preCheck = $mult1+$dig2+$multi3+$dig4+$multi5+$dig6+$multi7+$dig8+$multi9+$dig10+$multi11+$dig12+$mult13;
//echo $upc . " ";
$odd = $dig13+$dig11+$dig9+$dig7+$dig5+$dig3+$dig1;
//echo $odd . " ";
$odd3 = $odd * 3;
//echo $odd3 . " ";
$even = $dig12+$dig10+$dig8+$dig6+$dig4+$dig2;
//echo $even . " ";
$precheck = $odd3+$even;
//echo $precheck . " ";
$modTen = $precheck % $mod;
//echo $modTen . " ";
$checkDigit = 10-$modTen;
//echo $checkDigit . "<BR>";
return $checkDigit;
}
/* for a given upc in a given department, find
* the previous and next upcs in that department
* -1 for a upc value indicates no previous or
* next item. Returns true
*/
function deptPrevNext($dept,$upc,&$prev,&$next){
global $sql;
$deptQ = $sql->prepare("select upc from products where department = ? order by upc");
$deptR = $sql->execute($deptQ, array($dept));
$p = -1;
while ($row = $sql->fetch_array($deptR)){
if ($upc == $row[0]){
$prev = $p;
break;
}
$p = $row[0];
}
$row = $sql->fetch_array($deptR);
if ($row)
$next = $row[0];
else
$next = -1;
return true;
} |
jQuery(document).ready(function($) {
$(".main-menu li").click(function() {
var link = $(this).attr('rel');
$('html, body').animate({
scrollTop: $("#"+link).offset().top
}, 400);
});
}); |
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#if USE_GNOME
# include <gnome.h>
#else
# include <gtk/gtk.h>
#endif
#include <errno.h>
#include "main.h"
#include "pop.h"
#include "net.h"
#include "debug.h"
#include "utils.h"
#include "error.h"
#include "init.h"
#include "mailbox.h"
#include "message.h"
#include "search.h"
#include "gui-window_checking.h"
#include "gui-window_main.h"
#include "gui-utils.h"
enum {
DOWNLOAD_LIST_TOTAL,
DOWNLOAD_LIST_UIDL,
DOWNLOAD_LIST_TOP,
DOWNLOAD_LIST_LAST
};
enum {
HEADER_SUBJECT,
HEADER_FROM,
HEADER_DATE,
HEADER_LAST
};
static int
pop_check_answer (const char *buf, const Account *account,
int timedout);
static gboolean
gui_message_big_new (const char *from, const char *subject,
const char *date, const char *account,
const char *kbytes);
static gboolean
gui_ask_password (Account *account);
void *
check_pop_main (Account *account) {
char *buf = NULL, *buf2, *buf3;
C2ResolveNode *resolve;
int sock;
int timedout = FALSE;
struct sockaddr_in server;
int messages = 0, bytes = 0, downloaded_bytes = 0, i = 0, password_errors = 3;
GList *download[DOWNLOAD_LIST_LAST], *uidl_search = NULL, *top_search = NULL;
GList *list;
gboolean supports_uidl = FALSE;
mid_t mid;
FILE *index;
FILE *mail;
Message message;
char *mailbox;
Mailbox *mbox;
GString *strmsg;
char *header[HEADER_LAST];
gboolean reading_header = TRUE;
gboolean with_attachs = FALSE;
char *content_type;
char *row[8];
GtkStyle *style, *style2;
gboolean clisted = FALSE;
<API key> (account, NULL);
<API key> (account->type == C2_ACCOUNT_POP, NULL);
download[DOWNLOAD_LIST_TOTAL] = NULL;
download[DOWNLOAD_LIST_UIDL] = NULL;
download[DOWNLOAD_LIST_TOP] = NULL;
resolve = c2_resolve (account->protocol.pop.host, &buf);
if (buf) {
gdk_threads_enter ();
<API key> (C2_CHECK_ERR, account->acc_name, buf);
gdk_threads_leave ();
return NULL;
}
sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
gdk_threads_enter ();
<API key> (C2_CHECK_ERR, account->acc_name, _("Failed to create socket"));
gdk_threads_leave ();
return NULL;
}
server.sin_family = AF_INET;
server.sin_port = htons (account->protocol.pop.host_port);
server.sin_addr.s_addr= inet_addr (resolve->ip);
if (connect (sock, (struct sockaddr *)&server, sizeof (server)) < 0) {
buf = g_strerror (errno);
gdk_threads_enter ();
<API key> (C2_CHECK_ERR, account->acc_name, buf);
gdk_threads_leave ();
return NULL;
}
/* Guten Morgen, Herr Server! */
buf = sock_read (sock, &timedout);
if (pop_check_answer (buf, account, timedout) < 0) {
if (timedout) goto run_for_your_life;
goto bye_bye_server;
}
c2_free (buf);
/* Log In */
gdk_threads_enter ();
<API key> (GTK_PROGRESS (window_checking->mail_progress),
_("Logging in..."));
gdk_threads_leave ();
retry_login:
if (sock_printf (sock, "USER %s\r\n", account->protocol.pop.usr_name) < 0) {
buf = g_strerror (errno);
gdk_threads_enter ();
<API key> (C2_CHECK_ERR, account->acc_name, buf);
gdk_threads_leave ();
goto bye_bye_server;
}
buf = sock_read (sock, &timedout);
if (pop_check_answer (buf, account, timedout) < 0) {
if (timedout) goto run_for_your_life;
goto bye_bye_server;
}
c2_free (buf);
if (sock_printf (sock, "PASS %s\r\n", account->protocol.pop.pass) < 0) {
buf = g_strerror (errno);
gdk_threads_enter ();
<API key> (C2_CHECK_ERR, account->acc_name, buf);
gdk_threads_leave ();
goto bye_bye_server;
}
buf = sock_read (sock, &timedout);
if (strnne (buf, "+OK", 3)) {
if (--password_errors < 0) {
if (pop_check_answer (buf, account, timedout) < 0) {
if (timedout) goto run_for_your_life;
goto bye_bye_server;
}
}
gdk_threads_enter ();
if (!gui_ask_password (account)) {
gdk_threads_leave ();
if (pop_check_answer (buf, account, timedout) < 0) {
if (timedout) goto run_for_your_life;
goto bye_bye_server;
}
} else {
gdk_threads_leave ();
goto retry_login;
}
}
c2_free (buf);
/* STAT */
gdk_threads_enter ();
<API key> (GTK_PROGRESS (window_checking->mail_progress),
_("Checking for number of mails in server..."));
gdk_threads_leave ();
if (sock_printf (sock, "STAT\r\n") < 0) {
buf = g_strerror (errno);
gdk_threads_enter ();
<API key> (C2_CHECK_ERR, account->acc_name, buf);
gdk_threads_leave ();
goto bye_bye_server;
}
buf = sock_read (sock, &timedout);
if (pop_check_answer (buf, account, timedout) < 0) {
if (timedout) goto run_for_your_life;
goto bye_bye_server;
}
sscanf (buf, "+OK %d ", &messages);
c2_free (buf);
if (!messages) {
gdk_threads_enter ();
<API key> (GTK_PROGRESS (window_checking->mail_progress),
_("No messages in server"));
<API key> (C2_CHECK_OK, account->acc_name, _("No messages to download"));
gdk_threads_leave ();
clisted = TRUE;
goto bye_bye_server;
}
else if (messages != 1)
buf = g_strdup_printf (_("%d messages in server"), messages);
else
buf = g_strdup_printf (_("1 message in server"));
gdk_threads_enter ();
<API key> (GTK_PROGRESS (window_checking->mail_progress),
buf);
gdk_threads_leave ();
c2_free (buf);
/* UIDL */
if (!account->keep_copy) {
dont_use_uidl:
/* Without UIDL*/
for (i = 1; i <= messages; i++) {
buf = g_strdup_printf ("%d", i);
download[DOWNLOAD_LIST_UIDL] = g_list_append (download[DOWNLOAD_LIST_UIDL], (gpointer) buf);
}
} else {
/* With UIDL */
if (sock_printf (sock, "UIDL\r\n") < 0) {
buf = g_strerror (errno);
gdk_threads_enter ();
<API key> (C2_CHECK_ERR, account->acc_name, buf);
gdk_threads_leave ();
goto bye_bye_server;
}
for (i = 0;; i++) {
buf = sock_read (sock, &timedout);
if (!i && strnne (buf, "+OK", 3)) {
/* UIDL is optional for POP servers,
* so I won't complain if server doesn't like it */
buf2 = g_strdup_printf (_("The POP server of the account %s doesn't support UIDL."),
account->acc_name);
gdk_threads_enter ();
<API key> (GNOME_APPBAR (WMain->appbar), buf2);
gdk_threads_leave ();
supports_uidl = FALSE;
goto dont_use_uidl;
}
supports_uidl = TRUE;
if (!i) continue;
if (streq (buf, ".\r\n")) break;
buf2 = str_get_word (1, buf, ' ');
buf3 = str_strip (buf2, '\r');
buf2 = str_strip (buf3, '\n');
if (!uidl_check (buf2, account->acc_name)) {
download[DOWNLOAD_LIST_UIDL] = g_list_append (download[DOWNLOAD_LIST_UIDL], buf);
}
}
}
/* TOP */
if (!config->message_bigger) {
/* Without TOP */
dont_use_list:
dont_use_top:
for (i = 1; i <= messages; i++)
download[DOWNLOAD_LIST_TOP] = g_list_append (download[DOWNLOAD_LIST_TOP], (gpointer) i);
} else {
/* With TOP */
char *subject, *from, *date, *kbytes;
if (sock_printf (sock, "LIST\r\n") < 0) {
buf = g_strerror (errno);
gdk_threads_enter ();
<API key> (C2_CHECK_ERR, account->acc_name, buf);
gdk_threads_leave ();
goto bye_bye_server;
}
for (i = 0;; i++) {
buf = sock_read (sock, &timedout);
if (!i && strnne (buf, "+OK", 3)) {
buf2 = g_strdup_printf (_("The POP server of the account %s doesn't support LIST."),
account->acc_name);
gdk_threads_enter ();
<API key> (GNOME_APPBAR (WMain->appbar), buf2);
gdk_threads_leave ();
goto dont_use_list;
}
if (!i) continue;
if (streq (buf, ".\r\n")) break;
buf2 = str_get_word (1, buf, ' ');
str_strip (buf2, '\r');
str_strip (buf2, '\n');
download[DOWNLOAD_LIST_TOP] = g_list_append (download[DOWNLOAD_LIST_TOP], buf);
c2_free (buf2);
}
for (list = download[DOWNLOAD_LIST_TOP]; list; list = list->next) {
if (sock_printf (sock, "TOP %d 0\r\n", atoi (CHAR (list->data))) < 0) {
buf = g_strerror (errno);
gdk_threads_enter ();
<API key> (C2_CHECK_ERR, account->acc_name, buf);
gdk_threads_leave ();
goto bye_bye_server;
}
strmsg = g_string_new (NULL);
for (i = 0;; i++) {
buf = sock_read (sock, &timedout);
if (!i && strnne (buf, "+OK", 3)) {
buf2 = g_strdup_printf (_("The POP server of the account %s doesn't support TOP."),
account->acc_name);
gdk_threads_enter ();
<API key> (GNOME_APPBAR (WMain->appbar), buf2);
gdk_threads_leave ();
goto dont_use_top;
}
if (!i) continue;
if (streq (buf, ".\r\n")) break;
g_string_append (strmsg, buf);
c2_free (buf);
}
subject = <API key> (NULL, strmsg->str, "\nSubject:");
from = <API key> (NULL, strmsg->str, "From:");
date = <API key> (NULL, strmsg->str, "\nDate:");
kbytes = str_get_word (1, CHAR (list->data), ' '); str_strip (kbytes, '\r');str_strip (kbytes, '\n');
gdk_threads_enter ();
if ((atoi (kbytes) >= config->message_bigger*1024) &&
(!gui_message_big_new (from, subject, date, account->acc_name, kbytes))) {
gdk_threads_leave ();
c2_free (list->data);
list->data = NULL;
download[DOWNLOAD_LIST_TOP] = g_list_remove_link (download[DOWNLOAD_LIST_TOP], list);
} else gdk_threads_leave ();
}
}
/* Learn messages to download */
if (!account->keep_copy && !config->message_bigger) { /* !UIDL AND !TOP */
download[DOWNLOAD_LIST_TOTAL] = download[DOWNLOAD_LIST_UIDL];
}
else if (account->keep_copy && !config->message_bigger) { /* UIDL AND !TOP */
for (list = download[DOWNLOAD_LIST_UIDL]; list; list = list->next) {
download[DOWNLOAD_LIST_TOTAL] = g_list_append (download[DOWNLOAD_LIST_TOTAL],
str_get_word (0, CHAR (list->data), ' '));
}
}
else if (!account->keep_copy && config->message_bigger) { /* !UIDL AND TOP */
download[DOWNLOAD_LIST_TOTAL] = download[DOWNLOAD_LIST_TOP];
}
else if (account->keep_copy && config->message_bigger) { /* UIDL AND TOP */
for (uidl_search = download[DOWNLOAD_LIST_UIDL]; !uidl_search; uidl_search = uidl_search->next) {
for (top_search = download[DOWNLOAD_LIST_TOP]; !top_search; top_search = top_search->next) {
printf ("%d %d\n", (int) uidl_search->data, (int) top_search->data); /* TODO */
}
}
}
messages = g_list_length (download[DOWNLOAD_LIST_TOTAL]);
gdk_threads_enter ();
<API key> (GTK_PROGRESS (window_checking->mail_progress), 0, 0, messages);
<API key> (GTK_PROGRESS (window_checking->mail_progress),
_("%p%% downloaded (%v of %u messages)"));
gdk_threads_leave ();
strmsg = g_string_new (NULL);
message.message = message.header = NULL;
for (list = download[DOWNLOAD_LIST_TOTAL]; list; list = list->next) {
buf = str_get_word (0, CHAR (list->data), ' ');
i = atoi (buf);
c2_free (buf);
/* Ask for the mail */
if (sock_printf (sock, "RETR %d\r\n", i) < 0) {
buf = g_strerror (errno);
gdk_threads_enter ();
<API key> (C2_CHECK_ERR, account->acc_name, buf);
gdk_threads_leave ();
goto bye_bye_server;
}
/* Read the first line */
buf = sock_read (sock, &timedout);
if (pop_check_answer (buf, account, timedout) < 0) {
if (timedout) goto run_for_your_life;
goto bye_bye_server;
}
/* Learn bytes in the messages */
sscanf (buf, "+OK %d octets\r\n", &bytes);
if (bytes) {
gdk_threads_enter ();
<API key> (GTK_PROGRESS (window_checking->bytes_progress), 0, 0, bytes);
gtk_widget_show (window_checking->bytes_progress);
gdk_threads_leave ();
} else {
gdk_threads_enter ();
gtk_widget_hide (window_checking->bytes_progress);
gdk_threads_leave ();
}
c2_free (buf);
/* Get the mail */
reading_header = TRUE;
for (;;) {
buf = sock_read (sock, &timedout);
if (bytes) {
downloaded_bytes += strlen (buf);
gdk_threads_enter ();
<API key> (GTK_PROGRESS (window_checking->bytes_progress), downloaded_bytes);
gdk_threads_leave ();
}
if (streq (buf, ".\r\n")) {
message.message = g_strdup (strmsg->str);
g_string_assign (strmsg, "");
str_strip (message.message, '\r');
break;
}
if (reading_header && strlen (buf) > 2) {
char *buf2;
buf2 = decode_8bit (buf);
c2_free (buf);
buf = buf2;
}
if (reading_header && strlen (buf) == 2) { /* Still reading header and is an empty line */
buf2 = g_strdup_printf ("X-CronosII-Account: %s\r\n", account->acc_name);
g_string_append (strmsg, buf2);
c2_free (buf2);
reading_header = FALSE;
}
g_string_append (strmsg, buf);
}
<API key> (GTK_PROGRESS (window_checking->bytes_progress), 1);
/* Write to the mail file */
mailbox = account->mailbox->name;
#if USE_PLUGINS
<API key> (<API key>, &message,
&mailbox, NULL, NULL, NULL);
#endif
mbox = search_mailbox_name (config->mailbox_head, mailbox);
if (!mbox) {
/* Mailbox couldn't be found, going with the default */
mbox = account->mailbox;
}
mid = <API key> (mbox);
buf = <API key> (mailbox, mid);
if ((mail = fopen (buf, "w")) == NULL) {
gdk_threads_enter ();
<API key> (C2_CHECK_ERR, account->acc_name,
_("Error opening the file where to store the new mail"));
cronos_error (errno, _("Opening the mail file"), ERROR_WARNING);
gdk_threads_leave ();
c2_free (buf);
continue;
}
c2_free (buf);
fprintf (mail, "%s", message.message);
fclose (mail);
/* Write to the index file */
buf = <API key> (mailbox);
if ((index = fopen (buf, "a")) == NULL) {
gdk_threads_enter ();
<API key> (C2_CHECK_ERR, account->acc_name,
_("Error opening the main DB file to store the new mail"));
cronos_error (errno, _("Opening the main DB file"), ERROR_WARNING);
gdk_threads_leave ();
c2_free (buf);
goto bye_bye_server;
}
header[HEADER_SUBJECT] = <API key> (&message, NULL, "\nSubject:");
header[HEADER_FROM] = <API key> (&message, NULL, "\nFrom:");
header[HEADER_DATE] = <API key> (&message, NULL, "\nDate:");
content_type = <API key> (&message, NULL, "\nContent-Type:");
with_attachs = FALSE;
/* if (content_type) {
<API key> (content_type, &type, &subtype, ¶meter);
if (streq (type, "multipart")) {
GList *s;
MimeHash *mime;
message_mime_parse (&message, NULL);
for (s = message.mime; s != NULL; s = s->next) {
mime = MIMEHASH (s->data);
if (!mime) continue;
if (strneq (mime->disposition, "attachment", 10)) with_attachs = TRUE;
}
}
}*/
if (!header[HEADER_SUBJECT]) header[HEADER_SUBJECT] = "";
if (!header[HEADER_FROM]) header[HEADER_FROM] = "";
if (!header[HEADER_DATE]) header[HEADER_DATE] = "";
fprintf (index, "N\r\r%s\r%s\r%s\r%s\r%s\r%d\n",
with_attachs ? "1" : "", header[HEADER_SUBJECT], header[HEADER_FROM], header[HEADER_DATE],
account->acc_name, mid);
fclose (index);
c2_free (message.message);
c2_free (message.header);
message.message = message.header = NULL;
if (!account->keep_copy) {
/* Delete the message */
if (sock_printf (sock, "DELE %d\r\n", i) < 0) {
buf = g_strerror (errno);
gdk_threads_enter ();
<API key> (C2_CHECK_ERR, account->acc_name, buf);
gdk_threads_leave ();
goto bye_bye_server;
}
buf = sock_read (sock, &timedout);
if (pop_check_answer (buf, account, timedout) < 0) {
if (timedout) goto run_for_your_life;
goto bye_bye_server;
}
}
if (streq (selected_mbox, mailbox)) {
row[0] = "";
row[1] = "";
row[2] = "";
row[3] = header[HEADER_SUBJECT];
row[4] = header[HEADER_FROM];
row[5] = header[HEADER_DATE];
row[6] = account->acc_name;
row[7] = g_strdup_printf ("%d", mid);
gdk_threads_enter ();
gtk_clist_freeze (GTK_CLIST (WMain->clist));
gtk_clist_append (GTK_CLIST (WMain->clist), row);
style = <API key> (WMain->clist);
style2 = gtk_style_copy (style);
style2->font = font_unread;
<API key> (GTK_CLIST (WMain->clist), GTK_CLIST (WMain->clist)->rows-1, style2);
<API key> (GTK_CLIST (WMain->clist), GTK_CLIST (WMain->clist)->rows-1, 0, pixmap_unread, mask_unread);
if (with_attachs) <API key> (GTK_CLIST (WMain->clist), GTK_CLIST (WMain->clist)->rows-1, 2, pixmap_attach, mask_attach);
new_messages++;
gtk_clist_thaw (GTK_CLIST (WMain->clist));
<API key> (GTK_CLIST (WMain->clist), GTK_CLIST (WMain->clist)->rows-1, (gpointer) "N");
update_wm_title ();
<API key> (GTK_PROGRESS (window_checking->mail_progress), i);
gdk_threads_leave ();
clisted = TRUE;
}
gdk_threads_enter ();
<API key> (GTK_PROGRESS (window_checking->mail_progress),
<API key> (GTK_PROGRESS (window_checking->mail_progress))+1);
gdk_threads_leave ();
}
if (supports_uidl) {
GList *llist;
for (llist = download[DOWNLOAD_LIST_UIDL]; llist != NULL; llist = llist->next) {
char *uidl;
uidl = CHAR (llist->data);
buf2 = str_get_word (1, uidl, ' ');
buf3 = str_strip (buf2, '\r');
buf2 = str_strip (buf3, '\n');
if (buf2) {
uidl_register (buf2, account->acc_name);
}
}
}
if (messages != 1)
buf = g_strdup_printf (_("%d messages downloaded."), messages);
else
buf = g_strdup_printf (_("1 message downloaded."));
gdk_threads_enter ();
<API key> (GTK_PROGRESS (window_checking->mail_progress), messages, 0, messages);
<API key> (GTK_PROGRESS (window_checking->mail_progress),
buf);
<API key> (C2_CHECK_OK, account->acc_name, buf);
gdk_threads_leave ();
bye_bye_server:
if (sock_printf (sock, "QUIT\r\n") < 0) {
buf = g_strerror (errno);
}
buf = sock_read (sock, &timedout);
if (pop_check_answer (buf, account, timedout) < 0) {
if (timedout) goto run_for_your_life;
}
run_for_your_life:
close (sock);
return NULL;
}
char *
decode_8bit (const char *text) {
const char *ptr;
char *buf;
GString *str;
int words = 0, i;
<API key> (text, NULL);
str = g_string_new (NULL);
/* Count the words */
for (ptr = text; *ptr != '\0'; ptr++) {
if (*ptr == ' ' && *(ptr+1) != ' ') words++;
}
for (i = 0; i <= words; i++) {
if ((buf = str_get_word (i, text, ' ')) == NULL) break;
if (i) g_string_append_c (str, ' ');
/* Check if the word is wrong */
if (strneq (buf, "=?iso-8859-1?Q?", 15)) {
for (ptr = buf+15; *ptr != '\0'; ptr++) {
if (strneq (ptr, "?=", 2)) break;
if (*ptr == '=') {
int num;
ptr += sscanf (ptr, "=%X", &num)+1;
g_string_append_c (str, (char)num);
} else g_string_append_c (str, *ptr);
}
c2_free (buf);
} else {
g_string_append (str, buf);
c2_free (buf);
}
}
if (*(str->str+strlen (str->str)-1) != '\n') g_string_append_c (str, '\n');
buf = str->str;
g_string_free (str, FALSE);
return buf;
}
static int
pop_check_answer (const char *buf, const Account *account, int timedout) {
<API key> (account, -1);
<API key> (buf, -1);
if (timedout) {
gdk_threads_enter ();
<API key> (C2_CHECK_ERR, account->acc_name,
_("Operation timeout."));
gdk_threads_leave ();
return -1;
}
if (strneq (buf, "+OK", 3))
return 0;
else if (strneq (buf, "-ERR", 4)) {
gdk_threads_enter ();
<API key> (C2_CHECK_ERR, account->acc_name, buf+5);
gdk_threads_leave ();
return -1;
} else {
gdk_threads_enter ();
<API key> (C2_CHECK_ERR, account->acc_name, buf);
gdk_threads_leave ();
return -1;
}
return -1;
}
gboolean uidl_check (const char *uidl, const char *account) {
char *db_uidl;
char *path;
FILE *fd;
<API key> (uidl, FALSE);
<API key> (account, FALSE);
path = g_strconcat (getenv ("HOME"), ROOT, "/", account, ".uidl", NULL);
if ((fd = fopen (path, "r")) == NULL) {
if (errno == ENOENT) {
if ((fd = fopen (path, "w")) == NULL) {
cronos_error (errno, _("Creating the UIDL database"), ERROR_WARNING);
return FALSE;
}
fclose (fd);
fd = fopen (path, "r");
} else {
cronos_error (errno, _("Opening the UIDL database"), ERROR_WARNING);
return FALSE;
}
}
c2_free (path);
for (;;) {
if ((db_uidl = fd_get_line (fd)) == NULL) {
fclose (fd);
return FALSE;
}
if (streq (db_uidl, uidl)) {
fclose (fd);
return TRUE;
}
}
return FALSE;
}
void uidl_register (const char *uidl, const char *account) {
char *path;
FILE *fd;
g_return_if_fail (uidl);
g_return_if_fail (account);
path = g_strconcat (getenv ("HOME"), ROOT, "/", account, ".uidl", NULL);
if ((fd = fopen (path, "a")) == NULL) {
cronos_error (errno, _("Opening the UIDL database"), ERROR_WARNING);
return;
}
c2_free (path);
fprintf (fd, "%s\n", uidl);
fclose (fd);
}
GtkWidget *window;
gboolean gbool = TRUE;
gboolean go = FALSE;
static void cb (GtkWidget *widget, gpointer data) {
if (*((char *) data) == 'Y') gbool = TRUE;
else gbool = FALSE;
gtk_widget_destroy (window);
go = TRUE;
}
static gboolean gui_message_big_new (const char *from, const char *subject, const char *date, const char *account, const char *kbytes) {
GtkWidget *vbox, *hbox;
GtkWidget *table;
GtkWidget *label;
GtkWidget *hsep;
GtkStyle *style1;
GtkStyle *style2;
char *buf;
GtkWidget *xpm;
go = FALSE;
gbool = TRUE;
window = gnome_dialog_new (_("Confirm message downloading"),
<API key>, <API key>, NULL);
<API key> (GTK_WINDOW (window), TRUE);
<API key> (GTK_WINDOW (window), GTK_WINDOW (WMain->window));
<API key> (GNOME_DIALOG (window), 0);
vbox = GNOME_DIALOG (window)->vbox;
label = gtk_label_new (_("There's a message bigger than what you allowed to automatically download."));
gtk_widget_show (label);
gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE, 0);
table = gtk_table_new (5, 2, FALSE);
gtk_widget_show (table);
gtk_box_pack_start (GTK_BOX (vbox), table, TRUE, TRUE, 0);
<API key> (GTK_TABLE (table), 2);
<API key> (GTK_TABLE (table), 2);
if (from && subject && date) {
label = gtk_label_new (_("From:"));
gtk_widget_show (label);
gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1,
(GtkAttachOptions) (GTK_FILL),
(GtkAttachOptions) (0), 0, 0);
<API key> (GTK_MISC (label), 0, 0.5);
style1 = <API key> (label);
style2 = gtk_style_copy (style1);
style2->font = gdk_font_load ("-<API key>-*-*-120-*-*-p-*-iso8859-1");
<API key> (label, style2);
label = gtk_label_new (from);
gtk_widget_show (label);
gtk_table_attach (GTK_TABLE (table), label, 1, 2, 0, 1,
(GtkAttachOptions) (GTK_EXPAND | GTK_FILL),
(GtkAttachOptions) (0), 0, 0);
<API key> (GTK_MISC (label), 7.45058e-09, 0.5);
style1 = <API key> (label);
style2 = gtk_style_copy (style1);
style2->font = gdk_font_load ("-<API key>-*-*-120-*-*-m-*-iso8859-1");
<API key> (label, style2);
label = gtk_label_new (_("Date:"));
gtk_widget_show (label);
gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2,
(GtkAttachOptions) (GTK_FILL),
(GtkAttachOptions) (0), 0, 0);
<API key> (GTK_MISC (label), 7.45058e-09, 0.5);
style1 = <API key> (label);
style2 = gtk_style_copy (style1);
style2->font = gdk_font_load ("-<API key>-*-*-120-*-*-p-*-iso8859-1");
<API key> (label, style2);
label = gtk_label_new (date);
gtk_widget_show (label);
gtk_table_attach (GTK_TABLE (table), label, 1, 2, 1, 2,
(GtkAttachOptions) (GTK_EXPAND | GTK_FILL),
(GtkAttachOptions) (0), 0, 0);
<API key> (GTK_MISC (label), 7.45058e-09, 0.5);
style1 = <API key> (label);
style2 = gtk_style_copy (style1);
style2->font = gdk_font_load ("-<API key>-*-*-120-*-*-m-*-iso8859-1");
<API key> (label, style2);
} else {
label = gtk_label_new (_("Since the server doesn't support advanced POP commands very little information about this message could be extracted."));
gtk_widget_show (label);
gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1,
(GtkAttachOptions) (GTK_FILL),
(GtkAttachOptions) (0), 0, 0);
}
label = gtk_label_new (_("Account:"));
gtk_widget_show (label);
gtk_table_attach (GTK_TABLE (table), label, 0, 1, 3, 4,
(GtkAttachOptions) (GTK_FILL),
(GtkAttachOptions) (0), 0, 0);
<API key> (GTK_MISC (label), 7.45058e-09, 0.5);
style1 = <API key> (label);
style2 = gtk_style_copy (style1);
style2->font = gdk_font_load ("-<API key>-*-*-120-*-*-p-*-iso8859-1");
<API key> (label, style2);
if (from && subject && date) {
label = gtk_label_new (_("Subject:"));
gtk_widget_show (label);
gtk_table_attach (GTK_TABLE (table), label, 0, 1, 4, 5,
(GtkAttachOptions) (GTK_FILL),
(GtkAttachOptions) (0), 0, 0);
<API key> (GTK_MISC (label), 7.45058e-09, 0.5);
style1 = <API key> (label);
style2 = gtk_style_copy (style1);
style2->font = gdk_font_load ("-<API key>-*-*-120-*-*-p-*-iso8859-1");
<API key> (label, style2);
label = gtk_label_new (subject);
gtk_widget_show (label);
gtk_table_attach (GTK_TABLE (table), label, 1, 2, 4, 5,
(GtkAttachOptions) (GTK_EXPAND | GTK_FILL),
(GtkAttachOptions) (0), 0, 0);
<API key> (GTK_MISC (label), 7.45058e-09, 0.5);
style1 = <API key> (label);
style2 = gtk_style_copy (style1);
style2->font = gdk_font_load ("-<API key>-*-*-120-*-*-m-*-iso8859-1");
<API key> (label, style2);
}
label = gtk_label_new (_("Size:"));
gtk_widget_show (label);
gtk_table_attach (GTK_TABLE (table), label, 0, 1, 2, 3,
(GtkAttachOptions) (GTK_FILL),
(GtkAttachOptions) (0), 0, 0);
<API key> (GTK_MISC (label), 7.45058e-09, 0.5);
style1 = <API key> (label);
style2 = gtk_style_copy (style1);
style2->font = gdk_font_load ("-<API key>-*-*-120-*-*-p-*-iso8859-1");
<API key> (label, style2);
buf = g_strdup_printf ("%s (%d Kb)", kbytes, atoi (kbytes)/1024);
label = gtk_label_new (buf);
c2_free (buf);
gtk_widget_show (label);
gtk_table_attach (GTK_TABLE (table), label, 1, 2, 2, 3,
(GtkAttachOptions) (GTK_EXPAND | GTK_FILL),
(GtkAttachOptions) (0), 0, 0);
<API key> (GTK_MISC (label), 7.45058e-09, 0.5);
style1 = <API key> (label);
style2 = gtk_style_copy (style1);
style2->font = gdk_font_load ("-<API key>-*-*-120-*-*-m-*-iso8859-1");
<API key> (label, style2);
label= gtk_label_new (account);
gtk_widget_show (label);
gtk_table_attach (GTK_TABLE (table), label, 1, 2, 3, 4,
(GtkAttachOptions) (GTK_EXPAND | GTK_FILL),
(GtkAttachOptions) (0), 0, 0);
<API key> (GTK_MISC (label), 7.45058e-09, 0.5);
style1 = <API key> (label);
style2 = gtk_style_copy (style1);
style2->font = gdk_font_load ("-<API key>-*-*-120-*-*-m-*-iso8859-1");
<API key> (label, style2);
hsep = gtk_hseparator_new ();
gtk_widget_show (hsep);
gtk_box_pack_start (GTK_BOX (vbox), hsep, FALSE, TRUE, 0);
hbox = gtk_hbox_new (FALSE, 0);
gtk_widget_show (hbox);
gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, TRUE, 0);
buf = <API key>("gnome-question.png");
if (buf) {
xpm = <API key>(buf);
c2_free(buf);
gtk_widget_show (xpm);
gtk_box_pack_start (GTK_BOX (hbox), xpm, FALSE, FALSE, 0);
}
label = gtk_label_new (_("Do you want to download it?"));
gtk_widget_show (label);
gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, TRUE, 0);
<API key> (GNOME_DIALOG (window), 0, GTK_SIGNAL_FUNC (cb), (gpointer) "Y");
<API key> (GNOME_DIALOG (window), 0, GDK_Y, 0);
<API key> (GNOME_DIALOG (window), 1, GTK_SIGNAL_FUNC (cb), (gpointer) "N");
<API key> (GNOME_DIALOG (window), 1, GDK_N, 0);
gtk_widget_show (window);
gdk_threads_leave ();
while (!go) usleep (500);
gdk_threads_enter ();
return gbool;
}
GtkWidget *password_window;
GtkWidget *password_entry;
gboolean password_go = FALSE;
gboolean password_gbool = TRUE;
static void password_cb (GtkWidget *widget, gpointer data) {
if (*((char *) data) == 'Y') password_gbool = TRUE;
else password_gbool = FALSE;
gtk_widget_hide (password_window);
password_go = TRUE;
}
static gboolean
gui_ask_password (Account *account) {
GtkWidget *table;
GtkWidget *label;
GtkWidget *vbox;
char *buf;
password_go = FALSE;
password_gbool = TRUE;
password_window = gnome_dialog_new (_("Incorrect Password"),
<API key>, <API key>, NULL);
vbox = GNOME_DIALOG (password_window)->vbox;
buf = g_strdup_printf (_("The password of the account %s is wrong"), account->acc_name);
label = gtk_label_new (buf);
gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE, 0);
gtk_widget_show (label);
c2_free (buf);
table = gtk_table_new (2, 2, FALSE);
gtk_box_pack_start (GTK_BOX (vbox), table, TRUE, TRUE, 0);
gtk_widget_show (table);
label = gtk_label_new (_("Username:"));
<API key> (GTK_TABLE (table), label,
0, 1, 0, 1);
gtk_widget_show (label);
label = gtk_label_new (_("Password:"));
<API key> (GTK_TABLE (table), label,
0, 1, 1, 2);
gtk_widget_show (label);
label = gtk_label_new (account->protocol.pop.usr_name);
<API key> (GTK_TABLE (table), label,
1, 2, 0, 1);
gtk_widget_show (label);
<API key> (GTK_MISC (label), 7.45058e-09, 0.5);
password_entry = gtk_entry_new ();
<API key> (GTK_ENTRY (password_entry), FALSE);
<API key> (GTK_TABLE (table), password_entry,
1, 2, 1, 2);
gtk_widget_show (password_entry);
gtk_widget_show (password_window);
<API key> (GNOME_DIALOG (password_window), 0, GTK_SIGNAL_FUNC (password_cb), (gpointer) "Y");
<API key> (GNOME_DIALOG (password_window), 1, GTK_SIGNAL_FUNC (password_cb), (gpointer) "N");
gdk_threads_leave ();
while (!password_go) usleep (500);
if (!password_gbool) return FALSE;
buf = gtk_entry_get_text (GTK_ENTRY (password_entry));
gdk_threads_enter ();
if (!buf) return FALSE;
c2_free (account->protocol.pop.pass);
account->protocol.pop.pass = g_strdup (buf);
gtk_widget_destroy (password_window);
return TRUE;
} |
<html>
<HEAD>
<LINK REL="StyleSheet" TYPE="text/css" HREF="<API key>.css"></LINK>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<TITLE>Infinite Crisis #5A</TITLE>
</HEAD>
<BODY onload="initPage();">
<div align="center">
<div class="navigation" align="center">
<div class="navigationline">
<div class="navlink" id="first">
<a href="14178.html">First</a>
</div>
<div class="navlink" id="prev">
<a href="14300.html">Previous</a>
</div>
<div class="navlink" id="up">
<a href="../index7.html">Up</a>
</div>
<div class="navlink" id="next">
<a href="14304.html">Next</a>
</div>
<div class="navlink" id="last">
<a href="23761.html">Last</a>
</div>
</div>
</div>
</div>
<div id="frontcover">
<a href="../images/14302f.jpg">
<img src="../images/14302f.jpg" class="coverimage"/>
</a>
</div>
<div id="backcover">
<a href="../images/14302b.jpg">
<img src="../images/14302b.jpg" class="coverimage"/>
</a>
</div>
<table border="0" class="opacity">
<tr>
<td id="maintitle">Infinite Crisis #5A</td>
</tr>
<tr>
<td class="publisher">DC Comics</td>
</tr>
<tr>
<td style="padding-top:4px;">Wanted
<br/>
<span id="indexvalue">#1036</span>
<div>
<span class="fieldvaluelarge">0*
</span>
</div>
</td>
</tr>
<tr>
<td class="fieldvaluelarge" style="padding-top:7px;">Infinite Crisis - Faith</td>
</tr>
<tr>
<td class="fieldvaluelarge" style="padding-top:1px;">
<b>April 2006</b> 
George Perez Cover</td>
</tr>
<tr>
<td class="fieldvaluelarge" style="padding-top:1px;">
<b>Comic</b> 
Modern Age $3.99</td>
</tr>
<tr>
<td class="fieldvaluelarge" style="padding-top:1px;">
<b>Read It: Yes</b> 40 Pages</td>
</tr>
</table>
<br style="clear:both;"/>
<div id="notes" class="opacity">Earth-2 has reappeared, but the Lois Lane from that world has still passed away. That Superman can't take it, but the Earth-1 Superman and Wonder Woman get through to him well enough to make him see the true threat, and the real plan behind the entire Crisis.</div>
<div>
<table border="0" width="100%" style="margin-top:5px;">
<tr>
<td valign="top" width="40%">
<div id="productdetails">
<table border="0" cellspacing="0" cellpadding="0" class="opacity">
<tr>
<td class="header" colspan="2">Creators</td>
</tr>
<tr>
<td>
<tr valign="top">
<td nowrap="1" class="fieldlabel">Writer</td>
<td class="fieldvalue">Geoff Johns</td>
</tr>
<tr valign="top">
<td nowrap="1" class="fieldlabel">Penciller</td>
<td class="fieldvalue">Jerry Ordway, Ivan Reis, Phil Jimenez</td>
</tr>
<tr valign="top">
<td nowrap="1" class="fieldlabel">Inker</td>
<td class="fieldvalue">Jerry Ordway, Art Thibert, Andy Lanning</td>
</tr>
<tr valign="top">
<td nowrap="1" class="fieldlabel">Colorist</td>
<td class="fieldvalue">Rod Reis, Guy Major, Jeromy Cox</td>
</tr>
<tr valign="top">
<td nowrap="1" class="fieldlabel">Letterer</td>
<td class="fieldvalue">Nick J. Napolitano</td>
</tr>
<tr valign="top">
<td nowrap="1" class="fieldlabel">Editor</td>
<td class="fieldvalue">Eddie Berganza</td>
</tr>
</td>
</tr>
</table>
</div>
</td>
<td valign="top">
<div id="productdetails">
<table border="0" cellspacing="0" cellpadding="0" class="opacity">
<tr>
<td class="header" colspan="2">Characters</td>
</tr>
<tr>
<td class="character">Batman (Bruce Wayne)
<br/>Beast Boy (Garfield Logan)
<br/>Black Adam (Teth-Adam / Theo Adam)
<br/>Black Canary (Dinah Laurel Lance)
<br/>Black Lightning (Jefferson Pierce)
<br/>Blue Beetle (Jaime Reyes)
<br/>Blue Devil (Daniel Patrick Cassidy)
<br/>Booster Gold (Michael Jon Carter)
<br/>Breach (Tim Zanetti)
<br/>Captain Marvel Jr. (Freddy Freeman)
<br/>Detective Chimp (Bobo T. Chimpanzee)
<br/>Dr. Light (Kimiyo Hoshi)
<br/>Firehawk (Lorraine Reilly)
<br/>Firestorm (Jason Rusch)
<br/>Flamebird (Bette Kane)
<br/>Flash (Bart Allen)
<br/>Flash (Jay Garrick)
<br/>Geo-Force (Brion Markov)
<br/>Green Lantern (Hal Jordan)
<br/>Green Lantern (Alan Scott)
<br/>Green Lantern (John Stewart)
<br/>Gypsy (Cynthia 'Cindy' Reynolds)
<br/>Hourman (Rick Tyler)
<br/>Huntress (Helena Bertinelli)
<br/>Joto (Isaiah Crockett)
<br/>Katana (Tatsu Yamashiro)
<br/>Lady Quark (Tashanna)
<br/>Lois Lane (Earth-2)
<br/>Lex Luthor
<br/>Martian Manhunter (J'onn J'onzz)
<br/>Mary Marvel (Mary Batson)
<br/>Metamorpho (Rex Mason)
<br/>Mirage (Miriam Delgado)
<br/>Mr. Miracle (Scott Free)
<br/>Mr. Terrific (Michael Holt)
<br/>Nightmaster (Jim Rook)
<br/>Nightshade (Eve Eden)
<br/>Nightwing (Dick Grayson)
<br/>O.M.A.C.s
<br/>Jimmy Olsen (Earth-2)
<br/>Power Girl (Kara / Karen Zor-L / Starr)
<br/>Psycho-Pirate (Roger Hayden)
<br/>Ragman (Rory Regan)
<br/>Raven (Rachel Roth)
<br/>Red Tornado (Ulthoon / John Smith)
<br/>Robin (Tim Drake)
<br/>S.T.R.I.P.E. (Pat Dugan)
<br/>Sand (Sanderson 'Sandy' Hawkins)
<br/>Skeets
<br/>Speedy (Mia Dearden)
<br/>Starfire (Koriand'r / Kory Anders)
<br/>Superboy (Kon-El / Conner Kent)
<br/>Superboy-Prime (Clark Kent)
<br/>Superman (Earth-2) (Kal-L / Clark Kent)
<br/>Superman (Kal-El / Clark Kent)
<br/>George Taylor (Earth-2)
<br/>Terra (Tara Markov)
<br/>Wildcat (Ted Grant)
<br/>Wonder Woman (Earth-2) (Diana Prince)
<br/>Wonder Woman (Diana Prince)
<br/>Zauriel
<br/>
</td>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td valign="top">
<p></p>
<div id="productdetails">
<table border="0" cellspacing="0" cellpadding="0" class="opacity">
<tr>
<td class="header" colspan="2">Product Details</td>
</tr>
<tr valign="top">
<td class="fieldlabel" width="10%" nowrap="1">Series Group</td>
<td class="fieldvalue">Infinite Crisis</td>
</tr>
<tr valign="top">
<td class="fieldlabel" width="10%" nowrap="1">Genre</td>
<td class="fieldvalue">Super-Heroes</td>
</tr>
<tr valign="top">
<td class="fieldlabel" width="10%" nowrap="1">Color</td>
<td class="fieldvalue">Color</td>
</tr>
<tr valign="top">
<td class="fieldlabel" width="10%" nowrap="1">Country</td>
<td class="fieldvalue">USA</td>
</tr>
<tr valign="top">
<td class="fieldlabel" width="10%" nowrap="1">Language</td>
<td class="fieldvalue">English</td>
</tr>
<tr valign="top">
<td class="fieldlabel" width="10%" nowrap="1">Release Date</td>
<td class="fieldvalue">April 2006</td>
</tr>
</table>
</div>
</td>
<td valign="top">
<p></p>
<div id="personaldetails">
<table border="0" cellspacing="0" cellpadding="0" class="opacity">
<tr>
<td class="header" colspan="2">Personal Details</td>
</tr>
<tr valign="top">
<td class="fieldlabel" width="10%" nowrap="1">Collection Status</td>
<td class="fieldvalue">Wanted</td>
</tr>
<tr valign="top">
<td class="fieldlabel" width="10%" nowrap="1">Links</td>
<td class="fieldvalue">
<a href="http://connect.collectorz.com/comics/database/infinite-crisis/5a-128751" class="link">Infinite Crisis #5A at Comic Collector Connect</a>
<br/>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
<p></p>
</div>
</BODY>
</html> |
// ScreenDimensions.cpp
// oscope_app
#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>
#include <stdio.h>
#include <stdlib.h>
bool getScreenDimensions(int *width, int *height) {
Display *display = XOpenDisplay(NULL);
if (display == NULL) {
fprintf(stderr, "Failed to XOpenDisplay\n");
exit(-1);
}
Screen *screen = ScreenOfDisplay(display, 0);
if (screen == NULL) {
fprintf(stderr, "Failed to ScreenOfDisplay\n");
exit(-1);
}
*width = (int)WidthOfScreen(screen);
*height = (int)HeightOfScreen(screen);
return true;
} |
<ul class="nav-list">
<li class="nav-elem nav-left nav-head">
<a href="/">John (Wei Shi)</a>
</li>
<li class="nav-elem nav-left">
<a href="/about.html">About</a>
</li>
<li class="nav-elem nav-left $if(on-news)$ nav-active $endif$">
<a href="/news.html">News</a>
</li>
<li class="nav-elem nav-left $if(on-publications)$ nav-active $endif$">
<a href="/research.html">Research</a>
</li>
<li class="nav-elem nav-left $if(on-industry)$ nav-active $endif$">
<a href="/projects.html">Projects</a>
</li>
<li class="nav-elem nav-left $if(on-perso)$ nav-active $endif$">
<a href="/blog.html">My Blog</a>
</li>
<li class="nav-elem nav-right">
<a href="https://github.com/shi2wei3">GitHub</a>
</li>
<li class="nav-elem nav-right">
<a href="/404.html">CV</a>
</li>
</ul> |
# export AWS_ACCESS_KEY="Your-Access-Key"
# export AWS_SECRET_KEY="Your-Secret-Key"
today=`date +"%d-%m-%Y","%T"`
logfile="/awslog/<API key>.log"
# Grab all Instance IDs for REBOOT action and export the IDs to a text file
sudo aws ec2 describe-instances --filters Name=tag:reboot-time,Values=12-00 Name=tag:bash-profile,Values=ad --query Reservations[*].Instances[*].[InstanceId] --output text > ~/tmp/<API key>.txt 2>&1
# Take list of rebooting instances
for instance_id in $(cat ~/tmp/<API key>.txt)
do
# Reboot instances
rebootresult=$(sudo aws ec2 reboot-instances --instance-ids $instance_id)
# Put info into log file
echo Atempt to reboot $today instances by AWS CLI with result $rebootresult --EMPTY FOR NO RESULT-- >> $logfile
done |
#ifndef __KERNEL__
#include <string.h>
#include "hal_local.h"
#include "si_common.h"
#else
#ifdef DEBUG
#define TRACE_INT_TIME
#endif
#ifdef TRACE_INT_TIME
#include <linux/jiffies.h>
#endif
#include <linux/string.h>
#endif
#include <linux/delay.h>
#include "si_cra.h"
#include "si_cra_cfg.h"
#include "si_mhl_defs.h"
#include "si_mhl_tx_api.h"
#include "<API key>.h"
#include "si_8338_regs.h"
#include "si_drv_mhl_tx.h"
#include "si_platform.h"
#include "smartbook.h"
#include <linux/hrtimer.h>
#include <linux/ktime.h>
#include <mach/mt_gpio.h>
#include <cust_gpio_usage.h>
#include <cust_eint.h>
#include "si_drv_mdt_tx.h"
#include "si_mdt_inputdev.h"
#include "hdmitx_i2c.h"
#include <mach/mt_pm_ldo.h>
static ktime_t <API key>;
unsigned long delay_in_ms;
#define MS_TO_NS(x) (x * 1E6L)
extern struct hrtimer <API key>;
#define <API key> 322
#define POWER_STATE_D3 3
#define <API key> 2
#define POWER_STATE_D0_MHL 0
#define <API key> 0xFF
#define TX_HW_RESET_PERIOD 10
#define TX_HW_RESET_DELAY 100
static uint8_t fwPowerState = <API key>;
static bool_t mscCmdInProgress;
bool_t mscAbortFlag = false;
static uint8_t dsHpdStatus = 0;
#define WriteByteCBUS(offset,value) SiiRegWrite(TX_PAGE_CBUS | (uint16_t)offset,value)
#define ReadByteCBUS(offset) SiiRegRead( TX_PAGE_CBUS | (uint16_t)offset)
#define SET_BIT(offset,bitnumber) SiiRegModify(offset,(1<<bitnumber),(1<<bitnumber))
#define CLR_BIT(offset,bitnumber) SiiRegModify(offset,(1<<bitnumber),0x00)
#define DISABLE_DISCOVERY SiiRegModify(TX_PAGE_3 | 0x0010,BIT0,0)
#define ENABLE_DISCOVERY SiiRegModify(TX_PAGE_3 | 0x0010,BIT0,BIT0)
#define STROBE_POWER_ON SiiRegModify(TX_PAGE_3 | 0x0010,BIT1,0)
#define INTR_1_DESIRED_MASK (BIT7|BIT6)
#define <API key> SiiRegWrite(TX_PAGE_L0| 0x0075, INTR_1_DESIRED_MASK)
#define <API key> SiiRegWrite(TX_PAGE_L0| 0x0075, 0x00)
#define INTR_2_DESIRED_MASK (BIT1)
#define <API key> SiiRegWrite(TX_PAGE_L0| 0x0076, INTR_2_DESIRED_MASK)
#define INTR_4_DESIRED_MASK (BIT0 | BIT2 | BIT3 | BIT4 | BIT5 | BIT6)
#define <API key> SiiRegWrite(TX_PAGE_3 | 0x0022, INTR_4_DESIRED_MASK)
#define <API key> SiiRegWrite(TX_PAGE_3 | 0x0022, 0x00)
#define INTR_5_DESIRED_MASK 0//(BIT2 | BIT3 | BIT4)
#define <API key> SiiRegWrite(TX_PAGE_3 | 0x0024, INTR_5_DESIRED_MASK)
#define <API key> SiiRegWrite(TX_PAGE_3 | 0x0024, 0x00)
#define <API key> (BIT2 | BIT3 | BIT4 | BIT5 | BIT6)
#define <API key> SiiRegWrite(TX_PAGE_CBUS | 0x0009, <API key>)
#define <API key> SiiRegWrite(TX_PAGE_CBUS | 0x0009, 0x00)
#define <API key> (BIT0 | BIT2 | BIT3)
#define <API key> SiiRegWrite(TX_PAGE_CBUS | 0x001F, <API key>)
#define <API key> SiiRegWrite(TX_PAGE_CBUS | 0x001F, 0x00)
#define I2C_INACCESSIBLE -1
#define I2C_ACCESSIBLE 1
#define SIZE_AVI_INFOFRAME 17
static void Int1Isr (void);
static int Int4Isr( void );
static void Int5Isr (void);
static void MhlCbusIsr( void );
static void CbusReset(void);
static void SwitchToD0( void );
void SwitchToD3( void );
static void <API key> ( void );
static void InitCBusRegs( void );
static void <API key> ( void );
static void <API key> ( void );
static void <API key> ( void );
static void <API key> ( void );
static bool_t tmdsPowRdy;
video_data_t video_data;
static AVMode_t AVmode = {VM_INVALID, AUD_INVALID};
static void AudioVideoIsr(bool_t force_update);
static uint8_t <API key> (uint8_t *infoFrameData);
static void SendAviInfoframe (void);
static void <API key> (void);
static void SetAudioMode(inAudioTypes_t audiomode);
static void SetACRNValue (void);
static void SendAudioInfoFrame (void);
void SiiMhlTxHwReset(uint16_t hwResetPeriod,uint16_t hwResetDelay);
#ifdef __KERNEL__
static SiiOsTimer_t MscAbortTimer = NULL;
static void <API key>(void * pArg)
{
SiiOsTimerDelete(MscAbortTimer);
MscAbortTimer = NULL;
mscAbortFlag = false;
<API key>();
}
uint8_t SiiCheckDevice(uint8_t dev)
{
#ifdef _RGB_BOARD
if(HalI2cReadByte(0x60,0x70)==0xff)
return false;
#endif
if(dev == 0)
{
if(POWER_STATE_D3 != fwPowerState&&HalI2cReadByte(0x9a,0x21)==0xff)
return false;
}
else if(dev ==1)
{
if(POWER_STATE_D3 == fwPowerState)
return false;
}
return true;
}
void <API key>(void)
{
SiiRegBitsSet(TX_PAGE_3 | 0x0020,BIT3,true);
HalTimerWait(5);
SiiRegBitsSet(TX_PAGE_3 | 0x0020,BIT3,false);
}
#endif
#ifdef MDT_SUPPORT
enum mdt_state g_state_for_mdt = IDLE;
extern struct msc_request g_prior_msc_request;
#endif
static void Int1Isr(void)
{
uint8_t regIntr1;
regIntr1 = SiiRegRead(TX_PAGE_L0| 0x0071);
if (regIntr1)
{
SiiRegWrite(TX_PAGE_L0| 0x0071,regIntr1);
if (BIT6 & regIntr1)
{
uint8_t cbusStatus;
cbusStatus = SiiRegRead(TX_PAGE_CBUS | 0x000D);
TX_DEBUG_PRINT(("Drv: dsHpdStatus =%02X\n", (int) dsHpdStatus));
if(BIT6 & (dsHpdStatus ^ cbusStatus))
{
uint8_t status = cbusStatus & BIT6;
TX_DEBUG_PRINT(("Drv: Downstream HPD changed to: %02X\n", (int) cbusStatus));
<API key>( status );
if(status)
{
AudioVideoIsr(true);
}
dsHpdStatus = cbusStatus;
}
}
if(BIT7 & regIntr1)
{
TX_DEBUG_PRINT(("MHL soft interrupt triggered \n"));
}
}
}
static int Int2Isr( void )
{
if(SiiRegRead(TX_PAGE_L0| 0x0072) & INTR_2_DESIRED_MASK)
{
SiiRegWrite(TX_PAGE_L0| 0x0072, INTR_2_DESIRED_MASK);
if(SiiRegRead(TX_PAGE_L0 | 0x0009) & BIT1)
{
TX_DEBUG_PRINT(("PCLK is STABLE\n"));
if (tmdsPowRdy)
{
SendAudioInfoFrame();
SendAviInfoframe();
}
}
}
return 0;
}
bool_t <API key> ( void )
{
unsigned int initState = 0,g_chipRevId=0;
tmdsPowRdy = false;
mscCmdInProgress = false;
dsHpdStatus = 0;
fwPowerState = <API key>;
<API key>(<API key>);
//memset(&video_data, 0x00, sizeof(video_data));
video_data.inputColorSpace = COLOR_SPACE_RGB;
video_data.outputColorSpace = COLOR_SPACE_RGB;
video_data.outputVideoCode = 2;
video_data.<API key> = 0x18;
video_data.<API key> = 0x18;
video_data.output_AR = 0;
//SiiMhlTxHwReset(TX_HW_RESET_PERIOD,TX_HW_RESET_DELAY);
//SiiCraInitialize();
g_chipRevId = SiiRegRead(TX_PAGE_L0 | 0x04);
initState = (SiiRegRead(TX_PAGE_L0 | 0x03) << 8) | SiiRegRead(TX_PAGE_L0 | 0x02);
TX_DEBUG_PRINT(("Drv: <API key>:%04X,g_chipRevId=0x%x\n", initState,g_chipRevId));
if((initState&0xFF)!=0x52){
SwitchToD3();
return false;;
}
<API key>();
#ifndef __KERNEL__
<API key>();
#endif
SwitchToD3();
if (0xFFFF == initState)//0x8356
{
return false;
}
return true;
}
typedef enum{
<API key>,
HDMI_STATE_ACTIVE,
<API key>
}HDMI_STATE;
extern void hdmi_state_callback(HDMI_STATE state);
void SiiMhlTxDeviceIsr( void )
{
uint8_t intMStatus, i;
#ifdef TRACE_INT_TIME
unsigned long K1;
unsigned long K2;
printk("
K1 = get_jiffies_64();
#endif
i=0;
do
{
TX_DEBUG_PRINT(("Drv: SiiMhlTxDeviceIsr %d \n", fwPowerState));
#ifdef MDT_SUPPORT
if (g_state_for_mdt != IDLE) {
//TX_DEBUG_PRINT(("g_state_for_mdt=%d,<API key>=%d
while ((sii8338_irq_for_mdt(&g_state_for_mdt) == MDT_EVENT_HANDLED)||(g_state_for_mdt != WAIT_FOR_REQ_WRT)){
//TX_DEBUG_PRINT(("g_state_for_mdt=%d\n",g_state_for_mdt));
Int4Isr();
if(fwPowerState == POWER_STATE_D3)
return;
}//&&(SiiRegRead(TX_PAGE_L0| 0x0070)&0x01));//
//&& (HalGpioGetTxIntPin() == <API key>));
//TX_DEBUG_PRINT(("g_state_for_mdt=%d,HalGpioGetTxIntPin=%d@@@@@@@@@@@@@@@@@@@@@@\n",g_state_for_mdt,HalGpioGetTxIntPin()));
//if (HalGpioGetTxIntPin() != <API key>) {
//MHL_log_event(IRQ_RECEIVED, 1, HalGpioGetTxIntPin());
//if(!(SiiRegRead(TX_PAGE_L0| 0x0070)&0x01))
//return;
}
//TX_DEBUG_PRINT(("g_state_for_mdt=%d,<API key>=%d
MHL_log_event(ISR_FULL_BEGIN, 0, HalGpioGetTxIntPin());
#endif
if( POWER_STATE_D0_MHL != fwPowerState )
{
if(I2C_INACCESSIBLE == Int4Isr())
{
TX_DEBUG_PRINT(("Drv: I2C_INACCESSIBLE in Int4Isr in not D0 mode\n"));
return;
}
}
else if( POWER_STATE_D0_MHL == fwPowerState )
{
#if 0
TX_DEBUG_PRINT(("********* EXITING ISR *************\n"));
TX_DEBUG_PRINT(("Drv: INT1 Status = %02X\n", (int) SiiRegRead((TX_PAGE_L0 | 0x0071))));
TX_DEBUG_PRINT(("Drv: INT2 Status = %02X\n", (int) SiiRegRead((TX_PAGE_L0 | 0x0072))));
TX_DEBUG_PRINT(("Drv: INT3 Status = %02X\n", (int) SiiRegRead((TX_PAGE_L0 | 0x0073))));
TX_DEBUG_PRINT(("Drv: INT4 Status = %02X\n", (int) SiiRegRead(TX_PAGE_3 | 0x0021)));
TX_DEBUG_PRINT(("Drv: INT5 Status = %02X\n", (int) SiiRegRead(TX_PAGE_3 | 0x0023)));
TX_DEBUG_PRINT(("Drv: cbusInt Status = %02X\n", (int) SiiRegRead(TX_PAGE_CBUS | 0x0008)));
TX_DEBUG_PRINT(("Drv: CBUS INTR_2: 0x1E: %02X\n", (int) SiiRegRead(TX_PAGE_CBUS | 0x001E)));
TX_DEBUG_PRINT(("Drv: A0 INT Set = %02X\n", (int) SiiRegRead((TX_PAGE_CBUS | 0x00A0))));
TX_DEBUG_PRINT(("Drv: A1 INT Set = %02X\n", (int) SiiRegRead((TX_PAGE_CBUS | 0x00A1))));
TX_DEBUG_PRINT(("Drv: A2 INT Set = %02X\n", (int) SiiRegRead((TX_PAGE_CBUS | 0x00A2))));
TX_DEBUG_PRINT(("Drv: A3 INT Set = %02X\n", (int) SiiRegRead((TX_PAGE_CBUS | 0x00A3))));
TX_DEBUG_PRINT(("Drv: B0 STATUS Set = %02X\n", (int) SiiRegRead((TX_PAGE_CBUS | 0x00B0))));
TX_DEBUG_PRINT(("Drv: B1 STATUS Set = %02X\n", (int) SiiRegRead((TX_PAGE_CBUS | 0x00B1))));
TX_DEBUG_PRINT(("Drv: B2 STATUS Set = %02X\n", (int) SiiRegRead((TX_PAGE_CBUS | 0x00B2))));
TX_DEBUG_PRINT(("Drv: B3 STATUS Set = %02X\n", (int) SiiRegRead((TX_PAGE_CBUS | 0x00B3))));
TX_DEBUG_PRINT(("Drv: E0 STATUS Set = %02X\n", (int) SiiRegRead((TX_PAGE_CBUS | 0x00E0))));
TX_DEBUG_PRINT(("Drv: E1 STATUS Set = %02X\n", (int) SiiRegRead((TX_PAGE_CBUS | 0x00E1))));
TX_DEBUG_PRINT(("Drv: E2 STATUS Set = %02X\n", (int) SiiRegRead((TX_PAGE_CBUS | 0x00E2))));
TX_DEBUG_PRINT(("Drv: E3 STATUS Set = %02X\n", (int) SiiRegRead((TX_PAGE_CBUS | 0x00E3))));
TX_DEBUG_PRINT(("Drv: F0 INT Set = %02X\n", (int) SiiRegRead((TX_PAGE_CBUS | 0x00F0))));
TX_DEBUG_PRINT(("Drv: F1 INT Set = %02X\n", (int) SiiRegRead((TX_PAGE_CBUS | 0x00F1))));
TX_DEBUG_PRINT(("Drv: F2 INT Set = %02X\n", (int) SiiRegRead((TX_PAGE_CBUS | 0x00F2))));
TX_DEBUG_PRINT(("Drv: F3 INT Set = %02X\n", (int) SiiRegRead((TX_PAGE_CBUS | 0x00F3))));
TX_DEBUG_PRINT(("********* END OF EXITING ISR *************\n"));
#endif
if(I2C_INACCESSIBLE == Int4Isr())
{
TX_DEBUG_PRINT(("Drv: I2C_INACCESSIBLE in Int4Isr in D0 mode\n"));
return;
}
MhlCbusIsr();
Int5Isr();
Int1Isr();
Int2Isr();
}
if( POWER_STATE_D3 != fwPowerState )
{
MhlTxProcessEvents();
}
intMStatus = SiiRegRead(TX_PAGE_L0| 0x0070);
if(0xFF == intMStatus)
{
intMStatus = 0;
TX_DEBUG_PRINT(("Drv: EXITING ISR DUE TO intMStatus - 0xFF loop = [%02X] intMStatus = [%02X] \n\n", (int) i, (int)intMStatus));
}
i++;
intMStatus &= 0x01;
if(i>60)
{
TX_DEBUG_PRINT(("force exit SiiMhlTxDeviceIsr \n"));
break;
}
else if(i> 50)
{
TX_DEBUG_PRINT(("something error in SiiMhlTxDeviceIsr \n"));
}
} while (intMStatus);
#ifdef TRACE_INT_TIME
K2 = get_jiffies_64();
printk("
#endif
}
void SiiExtDeviceIsr(void)
{
if( fwPowerState <= <API key> )
{
#ifdef TRACE_INT_TIME
unsigned long K1;
unsigned long K2;
K1 = get_jiffies_64();
#endif
AudioVideoIsr(false);
#ifdef TRACE_INT_TIME
K2 = get_jiffies_64();
#endif
}
else
{
TX_DEBUG_PRINT(("in D3 mode , SiiExtDeviceIsr not handled\n"));
}
}
void <API key> (bool_t enable)
{
if (enable)
{
#ifdef MDT_SUPPORT
mdt_init();
#endif
tmdsPowRdy = true;
SiiRegModify(TX_PAGE_L1 | 0x2F, BIT0, SET_BITS);
if (1)//(<API key>())
{
SiiRegModify(TX_PAGE_L0 | 0x0080, BIT4, SET_BITS);
SendAudioInfoFrame();
SendAviInfoframe();
TX_DEBUG_PRINT(("TMDS Output Enabled\n"));
//Timon
#ifdef <API key>
SiiHandshakeCommand(Init);
#endif
}
else
{
TX_DEBUG_PRINT(("TMDS Output not Enabled due to invalid input\n"));
}
}
else
{
SiiRegModify(TX_PAGE_L0 | 0x0080, BIT4, CLEAR_BITS);
SiiRegModify(TX_PAGE_L1 | 0x2F, BIT0, CLEAR_BITS);
tmdsPowRdy = false;
TX_DEBUG_PRINT(("TMDS Ouput Disabled\n"));
#ifdef MDT_SUPPORT
mdt_deregister();
#endif
}
}
void <API key> ( void )
{
TX_DEBUG_PRINT(("<API key>\n"));
SiiDrvMhlTxReadEdid();
}
bool_t <API key> ( cbus_req_t *pReq )
{
bool_t success = true;
uint8_t i, startbit;
if( (POWER_STATE_D0_MHL != fwPowerState ) || (mscCmdInProgress))
{
TX_DEBUG_PRINT(("Error: fwPowerState: %02X, or CBUS(0x0A):%02X mscCmdInProgress = %d\n",
(int) fwPowerState,
(int) SiiRegRead(TX_PAGE_CBUS | 0x000A),
(int) mscCmdInProgress));
return false;
}
mscCmdInProgress = true;
TX_DEBUG_PRINT(("Sending MSC command %02X, %02X, %02X\n",
(int)pReq->command,
(int)((MHL_MSC_MSG == pReq->command)?pReq->payload_u.msgData[0]:pReq->offsetData),
(int)((MHL_MSC_MSG == pReq->command)?pReq->payload_u.msgData[1]:pReq->payload_u.msgData[0])));
SiiRegWrite(TX_PAGE_CBUS | 0x0013, pReq->offsetData);
SiiRegWrite(TX_PAGE_CBUS | 0x0014, pReq->payload_u.msgData[0]);
startbit = 0x00;
switch ( pReq->command )
{
case MHL_SET_INT:
startbit = 0x01 << 3;
break;
case MHL_WRITE_STAT:
startbit = 0x01 << 3;
break;
case MHL_READ_DEVCAP:
startbit = 0x01 << 2;
break;
case MHL_GET_STATE:
case MHL_GET_VENDOR_ID:
case MHL_SET_HPD:
case MHL_CLR_HPD:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
SiiRegWrite(TX_PAGE_CBUS | 0x0013, pReq->command );
startbit = 0x01 << 0;
break;
case MHL_MSC_MSG:
SiiRegWrite(TX_PAGE_CBUS | 0x0015, pReq->payload_u.msgData[1] );
SiiRegWrite(TX_PAGE_CBUS | 0x0013, pReq->command );
startbit = 0x01 << 1;
break;
case MHL_WRITE_BURST:
SiiRegWrite(TX_PAGE_CBUS | 0x0020, pReq->length -1 );
uint8_t *pData = pReq->payload_u.msgData;
TX_DEBUG_PRINT(("\nWriting data into scratchpad\n\n"));
for ( i = 0; i < pReq->length; i++ ){
SiiRegWrite(<API key> + i, *pData++ );
}
startbit = <API key>;
break;
default:
success = false;
break;
}
if ( success )
{
SiiRegWrite(TX_PAGE_CBUS | 0x0012, startbit );
}
else
{
TX_DEBUG_PRINT(("\<API key> failed\n\n"));
}
return( success );
}
bool_t SiiMhlTxDrvCBusBusy(void)
{
return mscCmdInProgress ? true :false;
}
static void <API key> ( void )
{
TX_DEBUG_PRINT(("<API key>\n"));
SiiRegWrite(TX_PAGE_L1 | 0x003D, 0x3F);
SiiRegWrite(TX_PAGE_3 | 0x0035, 0xBC);
SiiRegWrite(TX_PAGE_3 | 0x0031, 0x3C);
SiiRegWrite(TX_PAGE_3 | 0x0033, 0xC8);
SiiRegWrite(TX_PAGE_3 | 0x0036, 0x03);
SiiRegWrite(TX_PAGE_3 | 0x0037, 0x0A);
SiiRegWrite(TX_PAGE_L0 | 0x0080, 0x08);
SiiRegWrite(TX_PAGE_L0 | 0x00F7, 0x03);
SiiRegWrite(TX_PAGE_L0 | 0x00F8, 0x8C);
#ifdef MHL_SET_24PIN_MODE
SiiRegWrite(TX_PAGE_L0 | 0x0008, 0x35);
#else
SiiRegWrite(TX_PAGE_L0 | 0x0008, 0x31);
#endif
SiiRegWrite(TX_PAGE_3 | 0x0014, 0x57);
SiiRegWrite(TX_PAGE_3 | 0x0018, 0x04); ////0x24 -->0x4 for some smartbook will disconnect.
SiiRegWrite(TX_PAGE_3 | 0x0010, 0x27);
SiiRegWrite(TX_PAGE_3 | 0x0012, 0x86);
CbusReset();
InitCBusRegs();
SiiRegModify(TX_PAGE_L0 | 0x00C7, BIT5, SET_BITS);
SiiRegModify(TX_PAGE_L1 | 0x2F, BIT2, SET_BITS);
}
static void InitCBusRegs( void )
{
SiiRegWrite(TX_PAGE_CBUS | 0x0007, 0xF2);
SiiRegWrite(TX_PAGE_CBUS | 0x0030, 0x01);
SiiRegWrite(TX_PAGE_CBUS | 0x0031, 0x2D);
SiiRegWrite(TX_PAGE_CBUS | 0x0036, 0x0a);
SiiRegWrite(TX_PAGE_CBUS | 0x0040, 0x03);
SiiRegWrite(TX_PAGE_CBUS | 0x002E , 0x11);
SiiRegWrite(TX_PAGE_CBUS | 0x0022, 0x0F);
#define DEVCAP_REG(x) (TX_PAGE_CBUS | 0x0080 | DEVCAP_OFFSET_
SiiRegWrite(DEVCAP_REG(DEV_STATE ) ,<API key> );
SiiRegWrite(DEVCAP_REG(MHL_VERSION ) ,<API key> );
SiiRegWrite(DEVCAP_REG(DEV_CAT ) ,DEVCAP_VAL_DEV_CAT );
SiiRegWrite(DEVCAP_REG(ADOPTER_ID_H ) ,<API key> );
SiiRegWrite(DEVCAP_REG(ADOPTER_ID_L ) ,<API key> );
SiiRegWrite(DEVCAP_REG(VID_LINK_MODE ) ,<API key> );
SiiRegWrite(DEVCAP_REG(AUD_LINK_MODE ) ,<API key> );
SiiRegWrite(DEVCAP_REG(VIDEO_TYPE ) ,<API key> );
SiiRegWrite(DEVCAP_REG(LOG_DEV_MAP ) ,<API key> );
SiiRegWrite(DEVCAP_REG(BANDWIDTH ) ,<API key> );
SiiRegWrite(DEVCAP_REG(FEATURE_FLAG ) ,<API key> );
SiiRegWrite(DEVCAP_REG(DEVICE_ID_H ) ,<API key> );
SiiRegWrite(DEVCAP_REG(DEVICE_ID_L ) ,<API key> );
SiiRegWrite(DEVCAP_REG(SCRATCHPAD_SIZE) ,<API key> );
SiiRegWrite(DEVCAP_REG(INT_STAT_SIZE ) ,<API key> );
SiiRegWrite(DEVCAP_REG(RESERVED ) ,DEVCAP_VAL_RESERVED );
}
static void <API key> ( void )
{
DISABLE_DISCOVERY;
SiiRegModify(TX_PAGE_3 | 0x0015, BIT6, BIT6);
SiiRegWrite(TX_PAGE_3 | 0x0012, 0x86);
}
static void <API key> ( void )
{
HalTimerWait(15);
SiiRegModify(TX_PAGE_3 | 0x0015, BIT6, 0x00);
ENABLE_DISCOVERY;
}
void <API key>( void )
{
SiiRegModify(TX_PAGE_3 | 0x0018, BIT0, BIT0);
}
void ProcessRgnd (void)
{
uint8_t rgndImpedance;
rgndImpedance = SiiRegRead(TX_PAGE_3 | 0x001C) & 0x03;
TX_DEBUG_PRINT(("RGND = %02X : \n", (int)rgndImpedance));
if (0x02 == rgndImpedance)
{
TX_DEBUG_PRINT(("(MHL Device)\n"));
<API key>();
}
else
{
SiiRegModify(TX_PAGE_3 | 0x0018, BIT3, BIT3);
TX_DEBUG_PRINT(("(Non-MHL Device)\n"));
}
}
void SwitchToD0( void )
{
TX_DEBUG_PRINT(("Switch to D0\n"));
<API key>();
STROBE_POWER_ON;
fwPowerState = <API key>;
AudioVideoIsr(true);
}
extern void CBusQueueReset(void);
void SwitchToD3( void )
{
if(POWER_STATE_D3 != fwPowerState)
{
TX_DEBUG_PRINT(("Switch To D3\n"));
SiiRegWrite(TX_PAGE_2|0x0001, 0x03);
SiiRegWrite(TX_PAGE_3 | 0x0030, 0xD0);
SiiRegWrite(TX_PAGE_L0| 0x0071,0xFF);
SiiRegWrite(TX_PAGE_L0| 0x0072,0xFF);
SiiRegWrite(TX_PAGE_3 | 0x0021,0xBF);
SiiRegWrite(TX_PAGE_3 | 0x0023,0xFF);
SiiRegWrite(TX_PAGE_CBUS | 0x0008,0xFF);
SiiRegWrite(TX_PAGE_CBUS | 0x001E,0xFF);
<API key>();
//HalTimerWait(50);
<API key>();
CLR_BIT(TX_PAGE_L1 | 0x003D, 0);
CBusQueueReset();
#ifdef MDT_SUPPORT //MDT initialization.
//SiiRegWrite(TX_PAGE_CBUS | 0x00F0,
//MHL_INT_REQ_WRT | MHL_INT_DCAP_CHG); // handle DSCR_CHG as part of REQ_WRT
g_state_for_mdt = IDLE;
g_prior_msc_request.offset = 0;
g_prior_msc_request.first_data = 0;
#endif
fwPowerState = POWER_STATE_D3;
}
}
void ForceSwitchToD3( void )
{
#ifdef MDT_SUPPORT //MDT initialization.
//SiiRegWrite(TX_PAGE_CBUS | 0x00F0,
// MHL_INT_REQ_WRT | MHL_INT_DCAP_CHG); // handle DSCR_CHG as part of REQ_WRT
g_state_for_mdt = IDLE;
g_prior_msc_request.offset = 0;
g_prior_msc_request.first_data = 0;
#endif
CLR_BIT(TX_PAGE_L1 | 0x003D, 0);
CBusQueueReset();
fwPowerState = POWER_STATE_D3;
}
static int Int4Isr( void )
{
uint8_t int4Status;
int4Status = SiiRegRead(TX_PAGE_3 | 0x0021);
if(!int4Status)
{
}
else if(0xFF == int4Status)
{
return I2C_INACCESSIBLE;
}else
{
TX_DEBUG_PRINT(("INT4 Status = %02X\n", (int) int4Status));
if(int4Status & BIT0)
{
<API key>();
}
if(int4Status & BIT2)
{
<API key>();
}
else if(int4Status & BIT3)
{
TX_DEBUG_PRINT(("uUSB-A type device detected.\n"));
SiiRegWrite(TX_PAGE_3 | 0x001C, 0x80);
SwitchToD3();
return I2C_INACCESSIBLE;
}
if (int4Status & BIT5)
{
<API key>();
return I2C_INACCESSIBLE;
}
if((POWER_STATE_D0_MHL != fwPowerState) && (int4Status & BIT6))
{
SwitchToD0();
ProcessRgnd();
}
if(fwPowerState != POWER_STATE_D3)
{
if (int4Status & BIT4)
{
TX_DEBUG_PRINT(("CBus Lockout\n"));
<API key>();
<API key>();
}
}
}
SiiRegWrite(TX_PAGE_3 | 0x0021, int4Status);
return I2C_ACCESSIBLE;
}
static void Int5Isr (void)
{
uint8_t int5Status;
int5Status = SiiRegRead(TX_PAGE_3 | 0x0023);
if (int5Status)
{
#if 0//(SYSTEM_BOARD == SB_STARTER_KIT_X01)
if((int5Status & BIT3) || (int5Status & BIT2))
{
TX_DEBUG_PRINT (("** Apply MHL FIFO Reset\n"));
SiiRegModify(TX_PAGE_3 | 0x0000, BIT4, SET_BITS);
SiiRegModify(TX_PAGE_3 | 0x0000, BIT4, CLEAR_BITS);
}
#endif
if (int5Status & BIT4)
{
TX_DEBUG_PRINT (("** PXL Format changed\n"));
}
SiiRegWrite(TX_PAGE_3 | 0x0023, int5Status);
}
}
static void <API key> ( void )
{
TX_DEBUG_PRINT (("MHL Cable Connected. CBUS:0x0A = %02X\n", (int) SiiRegRead(TX_PAGE_CBUS | 0x000A)));
if( POWER_STATE_D0_MHL == fwPowerState )
{
return;
}
SiiRegWrite(TX_PAGE_3 | 0x0030, 0x10);
fwPowerState = POWER_STATE_D0_MHL;
// change TMDS termination to 50 ohm termination(default)
//bits 1:0 set to 00
SiiRegWrite(TX_PAGE_2|0x0001, 0x00);
ENABLE_DISCOVERY;
<API key>(true);
}
static void <API key> ( void )
{
TX_DEBUG_PRINT(("<API key>\n"));
SiiRegWrite(TX_PAGE_3 | 0x0021, SiiRegRead(TX_PAGE_3 | 0x0021));
dsHpdStatus &= ~BIT6;
SiiRegWrite(TX_PAGE_CBUS | 0x000D, dsHpdStatus);
<API key>(0);
if( POWER_STATE_D0_MHL == fwPowerState )
{
<API key>(false);
}
SwitchToD3();
}
void CbusReset (void)
{
uint8_t idx;
TX_DEBUG_PRINT( ("CBUS reset!!!\n"));
SET_BIT(TX_PAGE_3 | 0x0000, 3);
HalTimerWait(2);
CLR_BIT(TX_PAGE_3 | 0x0000, 3);
mscCmdInProgress = false;
<API key>;
#if (SYSTEM_BOARD == SB_STARTER_KIT_X01)
<API key>;
<API key>;
<API key>;
#else
<API key>;
<API key>;
#endif
<API key>;
<API key>;
for(idx=0; idx < 4; idx++)
{
WriteByteCBUS((0xE0 + idx), 0xFF);
WriteByteCBUS((0xF0 + idx), 0xFF);
}
#ifdef MDT_SUPPORT //MDT initialization.
SiiRegWrite(TX_PAGE_CBUS | 0x00F0,
MHL_INT_REQ_WRT | MHL_INT_DCAP_CHG); // handle DSCR_CHG as part of REQ_WRT
g_state_for_mdt = IDLE;
g_prior_msc_request.offset = 0;
g_prior_msc_request.first_data = 0;
#endif
}
static uint8_t CBusProcessErrors( uint8_t intStatus )
{
uint8_t result = 0;
uint8_t abortReason = 0;
intStatus &= (BIT6 | BIT5 | BIT2);
if ( intStatus )
{
if( intStatus & BIT2 )
{
abortReason |= SiiRegRead(TX_PAGE_CBUS | 0x000B);
TX_DEBUG_PRINT( ("CBUS:: DDC ABORT happened. Clearing 0x0C\n"));
SiiRegWrite(TX_PAGE_CBUS | 0x000B, 0xFF);
}
if ( intStatus & BIT5 )
{
abortReason |= SiiRegRead(TX_PAGE_CBUS | 0x000D );
TX_DEBUG_PRINT( ("CBUS:: MSC Requester ABORTED. Clearing 0x0D\n"));
SiiRegWrite(TX_PAGE_CBUS | 0x000D , 0xFF);
}
if ( intStatus & BIT6 )
{
abortReason |= SiiRegRead(TX_PAGE_CBUS | 0x000E );
TX_DEBUG_PRINT( ("CBUS:: MSC Responder ABORT. Clearing 0x0E\n"));
SiiRegWrite(TX_PAGE_CBUS | 0x000E , 0xFF);
}
if ( abortReason & (BIT0|BIT1|BIT2|BIT3|BIT4|BIT7) )
{
TX_DEBUG_PRINT( ("CBUS:: Reason for ABORT is ....0x%02X \n", (int)abortReason ));
if ( abortReason &(0x01 << 0))
{
TX_DEBUG_PRINT( ("Retry threshold exceeded\n"));
}
if ( abortReason & (0x01 << 1))
{
TX_DEBUG_PRINT( ("Protocol Error\n"));
}
if ( abortReason & (0x01 << 2))
{
TX_DEBUG_PRINT( ("Translation layer timeout\n"));
}
if ( abortReason & (0x01 << 3))
{
TX_DEBUG_PRINT( ("Undefined opcode\n"));
}
if ( abortReason & (0x01 << 4))
{
TX_DEBUG_PRINT( ("Undefined offset\n"));
}
if ( abortReason & (0x01 << 5))
{
TX_DEBUG_PRINT( ("Opposite device is busy\n"));
}
if ( abortReason & (0x01 << 7))
{
#ifndef __KERNEL__
HalTimerSet(TIMER_ABORT, T_ABORT_NEXT);
mscAbortFlag = true;
#else
if(MscAbortTimer)
{
SiiOsTimerDelete(MscAbortTimer);
MscAbortTimer = NULL;
}
mscAbortFlag = true;
// SiiOsTimerCreate("Abort Time Out", <API key>, NULL, true,
// 2000, false, &MscAbortTimer);
delay_in_ms = 2000L;
<API key> = ktime_set( 0, MS_TO_NS(delay_in_ms) );
printk(KERN_INFO "Starting timer to fire in <API key> %ldms (%ld)\n", delay_in_ms, jiffies );
hrtimer_start( &<API key>, <API key>, HRTIMER_MODE_REL );
#endif
TX_DEBUG_PRINT( ("Peer sent an abort, start 2s timer abort_next\n"));
}
}
}
return( result );
}
void <API key>(uint8_t startReg,uint8_t *pData,uint8_t length)
{
int i;
for (i = 0; i < length;++i,++startReg)
{
*pData++ = SiiRegRead((TX_PAGE_CBUS | 0x00C0) + startReg);
}
}
static void MhlCbusIsr( void )
{
uint8_t cbusInt;
uint8_t gotData[4];
uint8_t i;
cbusInt = SiiRegRead(TX_PAGE_CBUS | 0x001E);
if(cbusInt == 0xFF)
{
return;
}
if( cbusInt )
{
#ifdef <API key>
if ( BIT0 & cbusInt)
{
<API key>( cbusInt );
}
#endif
//TX_DEBUG_PRINT(("g_state_for_mdt=%d^^^^^^^^^^^^^^^^^^^^\n",g_state_for_mdt));
#ifdef MDT_SUPPORT
if((g_state_for_mdt!=<API key>)&&(g_state_for_mdt!=WAIT_FOR_REQ_WRT)&&(g_state_for_mdt!=<API key>))
{
if (BIT0 & cbusInt)
{
<API key>( cbusInt );
g_state_for_mdt = WAIT_FOR_REQ_WRT;
SiiRegWrite(TX_PAGE_CBUS | 0x00A0,
(MHL_INT_REQ_WRT | MHL_INT_DSCR_CHG));
//TX_DEBUG_PRINT(("g_state_for_mdt=%d$$$$$$$$$$$$$$$$$$$$$$$$\n",g_state_for_mdt));
}
#endif // <API key>
if(cbusInt & BIT2)
{
uint8_t intr[4]={0};
TX_DEBUG_PRINT(("MHL INTR Received\n"));
SiiRegReadBlock(TX_PAGE_CBUS | 0x00A0, intr, 4);
SiiMhlTxGotMhlIntr( intr[0], intr[1] );
SiiRegWriteBlock(TX_PAGE_CBUS | 0x00A0, intr, 4);
}
#ifdef MDT_SUPPORT
}
#endif
if(cbusInt & BIT3)
{
uint8_t status[4]={0};
TX_DEBUG_PRINT(("MHL STATUS Received\n"));
for (i = 0; i < 4;++i)
{
status[i] = SiiRegRead((TX_PAGE_CBUS | 0x00B0) + i);
SiiRegWrite(((TX_PAGE_CBUS | 0x00B0) + i), 0xFF );
}
<API key>( status[0], status[1] );
}
#ifdef MDT_SUPPORT
if((g_state_for_mdt==<API key>)||(g_state_for_mdt==WAIT_FOR_REQ_WRT)||(g_state_for_mdt==<API key>))
{
SiiRegWrite(TX_PAGE_CBUS | 0x001E, (cbusInt&0xFE));
TX_DEBUG_PRINT(("Drv: Clear CBUS INTR_2: %02X,g_state_for_mdt=%d\n", (int) (cbusInt&0xFE),g_state_for_mdt));
}
else
#endif
{
SiiRegWrite(TX_PAGE_CBUS | 0x001E, cbusInt);
TX_DEBUG_PRINT(("Drv: Clear CBUS INTR_2: %02X\n", (int) cbusInt));
}
}
cbusInt = SiiRegRead(TX_PAGE_CBUS | 0x0008);
if (cbusInt)
{
#ifdef MDT_SUPPORT
if((g_state_for_mdt==<API key>)||(g_state_for_mdt==WAIT_FOR_REQ_WRT)||(g_state_for_mdt==<API key>))
{
SiiRegWrite(TX_PAGE_CBUS | 0x0008, (cbusInt&0xEF));
TX_DEBUG_PRINT(("Drv: Clear CBUS INTR_1: %02X,g_state_for_mdt=%d\n", (int) (cbusInt&0xEF),g_state_for_mdt));
}
else
#endif
{
SiiRegWrite(TX_PAGE_CBUS | 0x0008, cbusInt);
TX_DEBUG_PRINT(("Drv: Clear CBUS INTR_1: %02X,g_state_for_mdt=%d\n", (int) cbusInt,g_state_for_mdt));
}
}
if((cbusInt & BIT3))
{
uint8_t mscMsg[2];
TX_DEBUG_PRINT(("MSC_MSG Received\n"));
mscMsg[0] = SiiRegRead(TX_PAGE_CBUS | 0x0018);
mscMsg[1] = SiiRegRead(TX_PAGE_CBUS | 0x0019);
TX_DEBUG_PRINT(("MSC MSG: %02X %02X\n", (int)mscMsg[0], (int)mscMsg[1] ));
<API key>( mscMsg[0], mscMsg[1] );
}
if (cbusInt & (BIT6 | BIT5 | BIT2))
{
gotData[0] = CBusProcessErrors(cbusInt);
mscCmdInProgress = false;
}
#ifdef MDT_SUPPORT
if((g_state_for_mdt!=<API key>)&&(g_state_for_mdt!=WAIT_FOR_REQ_WRT)&&(g_state_for_mdt!=<API key>))
#endif
{
if(cbusInt & BIT4)
{
TX_DEBUG_PRINT(("MSC_REQ_DONE\n"));
mscCmdInProgress = false;
<API key>( SiiRegRead(TX_PAGE_CBUS | 0x0016) );
}
}
if (cbusInt & BIT7)
{
TX_DEBUG_PRINT(("Parity error count reaches 15\n"));
SiiRegWrite(TX_PAGE_CBUS | 0x0038, 0x00);
}
}
static void <API key> (void)
{
}
void <API key> (bool_t enable)
{
if (enable)
{
SiiRegModify(TX_PAGE_3 | 0x0017, BIT2, SET_BITS);
TX_DEBUG_PRINT(("POW bit 0->1, set DISC_CTRL8[2] = 1\n"));
}
}
void <API key>(uint8_t clkMode)
{
TX_DEBUG_PRINT(("<API key>:0x%02x\n",(int)clkMode));
}
static void SendAviInfoframe (void)
{
uint8_t ifData[SIZE_AVI_INFOFRAME];
extern uint8_t <API key>;
ifData[0] = 0x82;
ifData[1] = 0x02;
ifData[2] = 0x0D;
ifData[3] = 0x00;
ifData[4] = video_data.outputColorSpace << 5;
ifData[5] = video_data.<API key>;
if(<API key>){
ifData[6] = 0x04;
TX_DEBUG_PRINT(("<API key> = true, limited range\n"));
}
else{
ifData[6] = 0x00;
TX_DEBUG_PRINT(("<API key>= false. defult range\n"));
}
//ifData[4] = video_data.outputColorSpace << 5;
ifData[7] = video_data.inputVideoCode;
TX_DEBUG_PRINT(("video_data.inputVideoCode:0x%02x, video_data.outputVideoCode=0x%x\n",(int)video_data.inputVideoCode,video_data.outputVideoCode));
//ifData[7] = video_data.outputVideoCode;
ifData[8] = 0x00;
ifData[9] = 0x00;
ifData[10] = 0x00;
ifData[11] = 0x00;
ifData[12] = 0x00;
ifData[13] = 0x00;
ifData[14] = 0x00;
ifData[15] = 0x00;
ifData[16] = 0x00;
ifData[3] = <API key>(ifData);
SiiRegModify(TX_PAGE_L1 | 0x3E, BIT0|BIT1, CLEAR_BITS);
SiiRegWriteBlock(TX_PAGE_L1 | 0x0040, ifData, SIZE_AVI_INFOFRAME);
SiiRegModify(TX_PAGE_L1 | 0x3E, BIT0|BIT1, SET_BITS);
}
static uint8_t <API key> (uint8_t *infoFrameData)
{
uint8_t i, checksum;
checksum = 0x00;
for (i = 0; i < SIZE_AVI_INFOFRAME; i++)
{
checksum += infoFrameData[i];
}
checksum = 0x100 - checksum;
return checksum;
}
PLACE_IN_CODE_SEG const audioConfig_t audioData[AUD_TYP_NUM] =
{
{0x11, 0x40, 0x0E, 0x03, 0x00, 0x05},
{0x11, 0x40, 0x0A, 0x01, 0x00, 0x05},
{0x11, 0x40, 0x02, 0x00, 0x00, 0x05},
{0x11, 0x40, 0x0C, 0x03, 0x00, 0x05},
{0x11, 0x40, 0x08, 0x01, 0x00, 0x05},
{0x11, 0x40, 0x00, 0x00, 0x00, 0x05},
{0x11, 0x40, 0x03, 0x00, 0x00, 0x05},
{0x11, 0x40, 0x0E, 0x03, 0x03, 0x05},
{0x11, 0x40, 0x0A, 0x01, 0x03, 0x05},
{0x11, 0x40, 0x02, 0x00, 0x03, 0x05},
{0x11, 0x40, 0x0C, 0x03, 0x03, 0x05},
{0x11, 0x40, 0x08, 0x01, 0x03, 0x05},
{0x11, 0x40, 0x00, 0x00, 0x03, 0x05},
{0x11, 0x40, 0x03, 0x00, 0x03, 0x05},
{0xF1, 0x40, 0x0E, 0x00, 0x03, 0x07},
{0x03, 0x00, 0x00, 0x00, 0x00, 0x05}
};
static void SetAudioMode(inAudioTypes_t audiomode)
{
if (audiomode >= AUD_TYP_NUM)
audiomode = I2S_48;
SiiRegWrite(TX_PAGE_L1 | 0x2F, audioData[audiomode].regAUD_path);
SiiRegWrite(TX_PAGE_L1 | 0x14, audioData[audiomode].regAUD_mode);
SiiRegWrite(TX_PAGE_L1 | 0x1D, audioData[audiomode].regAUD_ctrl);
SiiRegWrite(TX_PAGE_L1 | 0x21, audioData[audiomode].regAUD_freq);
SiiRegWrite(TX_PAGE_L1 | 0x23, audioData[audiomode].regAUD_src);
SiiRegWrite(TX_PAGE_L1 | 0x28, audioData[audiomode].regAUD_tdm_ctrl);
// SiiRegWrite(TX_PAGE_L1 | 0x22, 0x0B);
//0x02 for word length=16bits
SiiRegWrite(TX_PAGE_L1 | 0x22, 0x02);
SiiRegWrite(TX_PAGE_L1 | 0x24,0x02);
SiiRegWrite(TX_PAGE_L1 | 0x15, 0x00);
//0x7A:0x24 = 0x0B for word lenth is defult 24bit
TX_DEBUG_PRINT(("SiiRegRead(TX_PAGE_L1 | 0x21)=0x%x\n",SiiRegRead(TX_PAGE_L1 | 0x21)));
TX_DEBUG_PRINT(("SiiRegRead(TX_PAGE_L1 | 0x1D)=0x%x\n",SiiRegRead(TX_PAGE_L1 | 0x1D)));
}
static void SetACRNValue (void)
{
uint8_t audioFs;
if ((SiiRegRead(TX_PAGE_L1 | 0x14) & BIT1) && !(SiiRegRead(TX_PAGE_L1 | 0x15) & BIT1))
audioFs = SiiRegRead(TX_PAGE_L1 | 0x18) & 0x0F;
else
audioFs = SiiRegRead(TX_PAGE_L1 | 0x21) & 0x0F;
switch (audioFs)
{
case 0x03:
SiiRegWrite(TX_PAGE_L1 | 0x05, (uint8_t)(ACR_N_value_32k >> 16));
SiiRegWrite(TX_PAGE_L1 | 0x04, (uint8_t)(ACR_N_value_32k >> 8));
SiiRegWrite(TX_PAGE_L1 | 0x03, (uint8_t)(ACR_N_value_32k));
break;
case 0x00:
SiiRegWrite(TX_PAGE_L1 | 0x05, (uint8_t)(ACR_N_value_44k >> 16));
SiiRegWrite(TX_PAGE_L1 | 0x04, (uint8_t)(ACR_N_value_44k >> 8));
SiiRegWrite(TX_PAGE_L1 | 0x03, (uint8_t)(ACR_N_value_44k));
break;
case 0x02:
SiiRegWrite(TX_PAGE_L1 | 0x05, (uint8_t)(ACR_N_value_48k >> 16));
SiiRegWrite(TX_PAGE_L1 | 0x04, (uint8_t)(ACR_N_value_48k >> 8));
SiiRegWrite(TX_PAGE_L1 | 0x03, (uint8_t)(ACR_N_value_48k));
break;
case 0x08:
SiiRegWrite(TX_PAGE_L1 | 0x05, (uint8_t)(ACR_N_value_88k >> 16));
SiiRegWrite(TX_PAGE_L1 | 0x04, (uint8_t)(ACR_N_value_88k >> 8));
SiiRegWrite(TX_PAGE_L1 | 0x03, (uint8_t)(ACR_N_value_88k));
break;
case 0x0A:
SiiRegWrite(TX_PAGE_L1 | 0x05, (uint8_t)(ACR_N_value_96k >> 16));
SiiRegWrite(TX_PAGE_L1 | 0x04, (uint8_t)(ACR_N_value_96k >> 8));
SiiRegWrite(TX_PAGE_L1 | 0x03, (uint8_t)(ACR_N_value_96k));
break;
case 0x0C:
SiiRegWrite(TX_PAGE_L1 | 0x05, (uint8_t)(ACR_N_value_176k >> 16));
SiiRegWrite(TX_PAGE_L1 | 0x04, (uint8_t)(ACR_N_value_176k >> 8));
SiiRegWrite(TX_PAGE_L1 | 0x03, (uint8_t)(ACR_N_value_176k));
break;
case 0x0E:
SiiRegWrite(TX_PAGE_L1 | 0x05, (uint8_t)(ACR_N_value_192k >> 16));
SiiRegWrite(TX_PAGE_L1 | 0x04, (uint8_t)(ACR_N_value_192k >> 8));
SiiRegWrite(TX_PAGE_L1 | 0x03, (uint8_t)(ACR_N_value_192k));
break;
default:
SiiRegWrite(TX_PAGE_L1 | 0x05, (uint8_t)(ACR_N_value_default >> 16));
SiiRegWrite(TX_PAGE_L1 | 0x04, (uint8_t)(ACR_N_value_default >> 8));
SiiRegWrite(TX_PAGE_L1 | 0x03, (uint8_t)(ACR_N_value_default));
break;
}
SiiRegModify(TX_PAGE_L1 | 0x2F, BIT2, CLEAR_BITS);
}
static void SendAudioInfoFrame (void)
{
SiiRegModify(TX_PAGE_L1 | 0x3E, BIT4|BIT5, CLEAR_BITS);
SiiRegWrite(TX_PAGE_L1 | 0x80, 0x84);
SiiRegWrite(TX_PAGE_L1 | 0x81, 0x01);
SiiRegWrite(TX_PAGE_L1 | 0x82, 0x0A);
SiiRegWrite(TX_PAGE_L1 | 0x83, 0x70);
SiiRegWrite(TX_PAGE_L1 | 0x84, 0x01);
SiiRegWrite(TX_PAGE_L1 | 0x8D, 0x00);
SiiRegModify(TX_PAGE_L1 | 0x3E, BIT4|BIT5, SET_BITS);
}
static void AudioVideoIsr(bool_t force_update)
{
AVModeChange_t mode_change = {false, false};
//static AVMode_t mode = {VM_INVALID, AUD_INVALID};
if (force_update)
{
if (1)//(<API key>())
{TX_DEBUG_PRINT(("<API key>,audio_changed,video_changed\n"));
mode_change.audio_change = true;
mode_change.video_change = true;
}
}
else
{ TX_DEBUG_PRINT(("force_update=false...............\n"));
//AVModeDetect(&mode_change, &AVmode);
}
if (mode_change.audio_change)
{
TX_DEBUG_PRINT(("SetAudioMode & SetACRNValue\n"));
//SetAudioMode(mode.audio_mode);
SetAudioMode(AVmode.audio_mode);
SetACRNValue();
}
if(mode_change.video_change)// && <API key>())
{
TX_DEBUG_PRINT(("mode_change.video_changed =true\n "));
SiiRegModify(TX_PAGE_L0 | 0x00C7, BIT5, SET_BITS);
SiiRegModify(TX_PAGE_3 | 0x0000, BIT0, SET_BITS);
//video_data.outputColorSpace = video_data.inputColorSpace;
video_data.outputVideoCode = video_data.inputVideoCode;
video_data.<API key> = video_data.<API key>;
SiiRegModify(TX_PAGE_3 | 0x0000, BIT0, CLEAR_BITS);
SiiRegModify(TX_PAGE_L0 | 0x00C7, BIT5, CLEAR_BITS);
}
if ((mode_change.video_change || mode_change.audio_change) && tmdsPowRdy)
{
if (1)//(<API key>())
{
SiiRegModify(TX_PAGE_L0 | 0x0080, BIT4, SET_BITS);
SendAudioInfoFrame();
TX_DEBUG_PRINT(("((mode_change.video_change || mode_change.audio_change) && tmdsPowRdy) \n"));
SendAviInfoframe();
}
else
{
SiiRegModify(TX_PAGE_L0 | 0x0080, BIT4, CLEAR_BITS);
TX_DEBUG_PRINT (("TMDS Ouput Disabled due to invalid input\n"));
}
}
}
#if 0///!defined GPIO_MHL_RST_B_PIN
#error GPIO_MHL_RST_B_PIN no defined
#endif
void <API key>(void)
{
printk("%s,%d\n", __func__, __LINE__);
#ifdef GPIO_MHL_RST_B_PIN
mt_set_gpio_out(GPIO_MHL_RST_B_PIN, GPIO_OUT_ZERO);
#else
printk("%s,%d Error: GPIO_MHL_RST_B_PIN is not defined\n", __func__, __LINE__);
#endif
}
void SiiMhlTxHwReset(uint16_t hwResetPeriod,uint16_t hwResetDelay)
{
#ifdef GPIO_MHL_RST_B_PIN
printk("%s,%d\n", __func__, __LINE__);
mt_set_gpio_mode(GPIO_MHL_RST_B_PIN,GPIO_MODE_00);
mt_set_gpio_dir(GPIO_MHL_RST_B_PIN, GPIO_DIR_OUT);
<API key>(GPIO_MHL_RST_B_PIN,true);
mt_set_gpio_out(GPIO_MHL_RST_B_PIN, GPIO_OUT_ONE);
msleep(hwResetPeriod);
mt_set_gpio_out(GPIO_MHL_RST_B_PIN, GPIO_OUT_ZERO);
msleep(hwResetPeriod);
mt_set_gpio_out(GPIO_MHL_RST_B_PIN, GPIO_OUT_ONE);
msleep(hwResetDelay);
#else
printk("%s,%d Error: GPIO_MHL_RST_B_PIN is not defined\n", __func__, __LINE__);
#endif
}
#if 0
//mt6577
void <API key>(void)
{
#if 1 ///Ning mask
int i;
u32 gpio_a[]={
GPIO0, GPIO1, GPIO2, GPIO3, GPIO4,
GPIO5, GPIO6, GPIO7, GPIO39, GPIO40,
GPIO41, GPIO42, GPIO43, GPIO44, GPIO45,
GPIO46,GPIO18,GPIO19,GPIO20
};
u32 gpio_b[]={
GPIO0, GPIO1, GPIO2, GPIO3, GPIO4,
GPIO5, GPIO6, GPIO7, GPIO39, GPIO40,
GPIO41, GPIO42, GPIO43, GPIO44, GPIO45,
GPIO46,GPIO105,GPIO106,GPIO107
};
printk("%s,%d\n", __func__, __LINE__);
if(0)//(Tfa9890_IsFound())
{
for(i=0; i<ARRAY_SIZE(gpio_a); i++){
mt_set_gpio_mode((gpio_a[i] | 0x80000000), GPIO_MODE_00);
mt_set_gpio_dir((gpio_a[i] | 0x80000000), GPIO_DIR_IN);
<API key>((gpio_a[i] | 0x80000000), GPIO_PULL_DOWN);
<API key>((gpio_a[i] | 0x80000000), GPIO_PULL_ENABLE);
}
}
else
{
for(i=0; i<ARRAY_SIZE(gpio_b); i++){
mt_set_gpio_mode((gpio_b[i] | 0x80000000), GPIO_MODE_00);
mt_set_gpio_dir((gpio_b[i] | 0x80000000), GPIO_DIR_IN);
<API key>((gpio_b[i] | 0x80000000), GPIO_PULL_DOWN);
<API key>((gpio_b[i] | 0x80000000), GPIO_PULL_ENABLE);
}
}
hwPowerDown(MT6322_POWER_LDO_VM, "mhl_sii8338");
#endif
}
#else
void <API key>(void)
{
#if 1 ///Ning mask
int i;
u32 gpio[]={
GPIO0, GPIO1, GPIO2, GPIO3, GPIO4,
GPIO5, GPIO6, GPIO7, GPIO39, GPIO40,
GPIO41, GPIO42, GPIO43, GPIO44, GPIO45,
GPIO46,GPIO105,GPIO106,GPIO107
};
printk("%s,%d\n", __func__, __LINE__);
for(i=0; i<ARRAY_SIZE(gpio); i++){
mt_set_gpio_mode((gpio[i] | 0x80000000), GPIO_MODE_00);
mt_set_gpio_dir((gpio[i] | 0x80000000), GPIO_DIR_IN);
<API key>((gpio[i] | 0x80000000), GPIO_PULL_DOWN);
<API key>((gpio[i] | 0x80000000), GPIO_PULL_ENABLE);
}
hwPowerDown(MT6322_POWER_LDO_VM, "mhl_sii8338");
#endif
}
#endif
#if 0
//mt6577
void <API key>(void)
{
#if 1
int i;
u32 gpio_rgb[]={
GPIO0, GPIO1, GPIO2, GPIO3, GPIO4,
GPIO5, GPIO6, GPIO7, GPIO39, GPIO40,
GPIO41, GPIO42, GPIO43, GPIO44, GPIO45,
GPIO46
};
u32 gpio_i2s[]={GPIO18, GPIO19, GPIO20};
u32 gpio_i2s2[]={GPIO105, GPIO106, GPIO107};
printk("%s,%d\n", __func__, __LINE__);
hwPowerOn(MT6322_POWER_LDO_VM, VOL_1200, "mhl_sii8338");
for(i=0; i<ARRAY_SIZE(gpio_rgb); i++){
mt_set_gpio_mode((gpio_rgb[i]|0x80000000), GPIO_MODE_02);
<API key>((gpio_rgb[i]|0x80000000), GPIO_PULL_DISABLE);
}
#if 0
for(i=0; i<ARRAY_SIZE(gpio_i2s); i++){
mt_set_gpio_mode((gpio_i2s[i]|0x80000000), GPIO_MODE_03);
<API key>((gpio_i2s[i]|0x80000000), GPIO_PULL_DOWN);
<API key>((gpio_i2s[i]|0x80000000), GPIO_PULL_ENABLE);
}
#else
for(i=0; i<ARRAY_SIZE(gpio_i2s2); i++){
mt_set_gpio_mode((gpio_i2s2[i]|0x80000000), GPIO_MODE_03);
<API key>((gpio_i2s2[i]|0x80000000), GPIO_PULL_DOWN);
<API key>((gpio_i2s2[i]|0x80000000), GPIO_PULL_ENABLE);
}
#endif
#endif
}
#else
void <API key>(void)
{
#if 1////Ning mask
int i;
u32 gpio_rgb[]={
GPIO0, GPIO1, GPIO2, GPIO3, GPIO4,
GPIO5, GPIO6, GPIO7, GPIO39, GPIO40,
GPIO41, GPIO42, GPIO43, GPIO44, GPIO45,
GPIO46
};
u32 gpio_i2s[]={GPIO105, GPIO106, GPIO107};
hwPowerOn(MT6322_POWER_LDO_VM, VOL_1200, "mhl_sii8338");
printk("%s,%d\n", __func__, __LINE__);
for(i=0; i<ARRAY_SIZE(gpio_rgb); i++){
mt_set_gpio_mode((gpio_rgb[i] | 0x80000000), GPIO_MODE_02);
<API key>((gpio_rgb[i] | 0x80000000), GPIO_PULL_DISABLE);
}
for(i=0; i<ARRAY_SIZE(gpio_i2s); i++){
mt_set_gpio_mode((gpio_i2s[i] | 0x80000000), GPIO_MODE_04);
<API key>((gpio_i2s[i] | 0x80000000), GPIO_PULL_DOWN);
<API key>((gpio_i2s[i] | 0x80000000), GPIO_PULL_ENABLE);
}
#endif
}
#endif
#if defined(USE_PROC)&&defined(__KERNEL__)
void drv_mhl_seq_show(struct seq_file *s)
{
int gpio_value;
switch(fwPowerState)
{
case POWER_STATE_D3:
seq_printf(s, "MHL POWER STATE [D3]\n");
break;
case <API key>:
seq_printf(s, "MHL POWER STATE [D0_NO_MHL]\n");
break;
case POWER_STATE_D0_MHL:
seq_printf(s, "MHL POWER STATE [D0_MHL]\n");
break;
case <API key>:
seq_printf(s, "MHL POWER STATE [FIRST_INIT]\n");
break;
default:break;
}
if(tmdsPowRdy)
seq_printf(s, "TMDS [ON]\n");
else
seq_printf(s, "TMDS [OFF]\n");
HalGpioGetPin(GPIO_SRC_VBUS_ON,&gpio_value);
if(gpio_value)
seq_printf(s, "SRC BUS [ON]\n");
else
seq_printf(s, "SRC BUS [OFF]\n");
HalGpioGetPin(GPIO_SINK_VBUS_ON,&gpio_value);
if(gpio_value)
seq_printf(s, "SINK BUS [ON]\n");
else
seq_printf(s, "SINK BUS [OFF]\n");
}
#endif
// Function Name: siHdmiTx_VideoSel()
// Function Description: Select output video mode
// Accepts: Video mode
// Returns: none
// Globals: none
void siHdmiTx_VideoSel (int vmode)
{
int AspectRatio = 0;
video_data.inputColorSpace = COLOR_SPACE_RGB;
video_data.outputColorSpace = COLOR_SPACE_RGB;
video_data.inputVideoCode = vmode;
//siHdmiTx.ColorDepth = <API key>;
//siHdmiTx.SyncMode = EXTERNAL_HSVSDE;
switch (vmode)
{
case HDMI_480I60_4X3:
case HDMI_576I50_4X3:
AspectRatio = <API key>;
break;
case HDMI_480I60_16X9:
case HDMI_576I50_16X9:
AspectRatio = <API key>;
break;
case HDMI_480P60_4X3:
case HDMI_576P50_4X3:
case HDMI_640X480P:
AspectRatio = <API key>;
break;
case HDMI_480P60_16X9:
case HDMI_576P50_16X9:
AspectRatio = <API key>;
break;
case HDMI_720P60:
case HDMI_720P50:
case HDMI_1080I60:
case HDMI_1080I50:
case HDMI_1080P24:
case HDMI_1080P25:
case HDMI_1080P30:
AspectRatio = <API key>;
break;
default:
break;
}
if (AspectRatio == <API key>)
video_data.<API key> = 0x18;
else video_data.<API key> = 0x28;
video_data.input_AR = AspectRatio;
}
// Function Name: siHdmiTx_AudioSel()
// Function Description: Select output audio mode
// Accepts: Audio Fs
// Returns: none
// Globals: none
void siHdmiTx_AudioSel (int AduioMode)
{
AVmode.audio_mode = AduioMode;
/*
siHdmiTx.AudioChannels = ACHANNEL_2CH;
siHdmiTx.AudioFs = Afs;
siHdmiTx.AudioWordLength = ALENGTH_24BITS;
siHdmiTx.AudioI2SFormat = (MCLK256FS << 4) |<API key> |0x00; //last num 0x00-->0x02
*/
}
// Function Name: siMhlTx_AudioSet()
// Function Description: Set the 9022/4 audio interface to basic audio.
// Accepts: none
// Returns: Success message if audio changed successfully.
// Error Code if resolution change failed
// Globals: mhlTxAv
uint8_t siMhlTx_AudioSet (void)
{
TX_DEBUG_PRINT(("[MHL]: >>siMhlTx_AudioSet()\n"));
//SetAudioMute(AUDIO_MUTE_MUTED); // mute output
SetAudioMode(AVmode.audio_mode);
SetACRNValue();
return 0;
}
// Function Name: <API key>()
// Function Description: Set the 9022/4 video resolution
// Accepts: none
// Returns: Success message if video resolution changed successfully.
// Error Code if resolution change failed
// Globals: mhlTxAv
#define T_RES_CHANGE_DELAY 128 // delay between turning TMDS bus off and changing output resolution
uint8_t <API key> (void)
{
TX_DEBUG_PRINT(("[MHL]: >><API key>()\n"));
SiiRegModify(TX_PAGE_L1 | 0xDF, BIT0, SET_BITS);
<API key>( false );
HalTimerWait(T_RES_CHANGE_DELAY); // allow control InfoFrames to pass through to the sink device.
//siMhlTx_AudioSet();
AudioVideoIsr(true);
//siMhlTx_Init();
SiiRegModify(TX_PAGE_L1 | 0xDF, BIT0, CLEAR_BITS);
SiiMhlTxTmdsEnable();
return 0;
} |
(function( window, undefined ) {
var cachedruns,
assertGetIdNotName,
Expr,
getText,
isXML,
contains,
compile,
sortOrder,
hasDuplicate,
outermostContext,
expando = "sizzle" + -(new Date()),
strundefined = typeof undefined,
// Used in sorting
MAX_NEGATIVE = 1 << 31,
baseHasDuplicate = true,
Token = String,
document = window.document,
docElem = document.documentElement,
dirruns = 0,
done = 0,
// Array methods
arr = [],
pop = arr.pop,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Augment a function for special use by Sizzle
markFunction = function( fn, value ) {
fn[ expando ] = value == null || value;
return fn;
},
createCache = function() {
var cache = {},
keys = [];
return markFunction(function( key, value ) {
// Only keep the most recent entries
if ( keys.push( key ) > Expr.cacheLength ) {
delete cache[ keys.shift() ];
}
// Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157)
return (cache[ key + " " ] = value);
}, cache );
},
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// Regex
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors)
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#<API key>
identifier = characterEncoding.replace( "w", "w
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[\x20\t\r\n\f]*[+~]/,
rheader = /h\d/i,
rinputs = /input|select|textarea|button/i,
rbackslash = /\\(?!\\)/g,
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
// Support
// Used for testing something on an element
assert = function( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
},
// Check if <API key>("*") returns only elements
<API key> = assert(function( div ) {
div.appendChild( document.createComment("") );
return !div.<API key>("*").length;
}),
// Check if getAttribute returns normalized href attributes
<API key> = assert(function( div ) {
div.innerHTML = "<a href='
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "
}),
// Check if attributes should be retrieved by attribute nodes
assertAttributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
}),
// Check if <API key> can be trusted
<API key> = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.<API key> || !div.<API key>("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.<API key>("e").length === 2;
}),
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
assertUsableName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = document.getElementsByName &&
// buggy browsers will return fewer than the correct 2
document.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
document.getElementsByName( expando + 0 ).length;
assertGetIdNotName = !document.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// Use a stripped-down slice if we can't use a native one
try {
slice.call( docElem.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem,
results = [];
for ( ; (elem = this[i]); i++ ) {
results.push( elem );
}
return results;
};
}
function Sizzle( selector, context, results, seed ) {
results = results || [];
context = context || document;
var match, elem, xml, m,
nodeType = context.nodeType;
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( nodeType !== 1 && nodeType !== 9 ) {
return [];
}
xml = isXML( context );
if ( !xml && !seed ) {
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.<API key>( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && <API key> && context.<API key> ) {
push.apply( results, slice.call(context.<API key>( m ), 0) );
return results;
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed, xml );
}
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function <API key>( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Element contains another
contains = Sizzle.contains = docElem.contains || docElem.<API key> ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.<API key> && a.<API key>( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
Sizzle.attr = function( elem, name ) {
var val,
xml = isXML( elem );
if ( !xml ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( xml || assertAttributes ) {
return elem.getAttribute( name );
}
return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ?
name :
val && val.specified ? val.value : null;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
// IE6/7 return a modified href
attrHandle: <API key> ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
},
find: {
"ID": assertGetIdNotName ?
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
} :
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
},
"TAG": <API key> ?
function( tag, context ) {
if ( typeof context.<API key> !== strundefined ) {
return context.<API key>( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.<API key>( tag );
// Filter out possible comments
if ( tag === "*" ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
},
"NAME": assertUsableName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
},
"CLASS": <API key> && function( className, context, xml ) {
if ( typeof context.<API key> !== strundefined && !xml ) {
return context.<API key>( className );
}
}
},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( rbackslash, "" );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[4] ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"ID": assertGetIdNotName ?
function( id ) {
var attrId = id.replace( rbackslash, "" );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
} :
function( id ) {
var attrId = id.replace( rbackslash, "" );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
},
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( rbackslash, "" ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ expando ][ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.substr( result.length - check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/<API key>/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "
var node;
for ( node = elem.firstChild; node; node = node.nextSibling ) {
if ( node.nodeName > "@" || node.nodeType === 3 || node.nodeType === 4 ) {
return false;
}
}
return true;
},
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Input types
"radio": createInputPseudo("radio"),
"checkbox": createInputPseudo("checkbox"),
"file": createInputPseudo("file"),
"<API key>("password"),
"image": createInputPseudo("image"),
"submit": createButtonPseudo("submit"),
"reset": createButtonPseudo("reset"),
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"focus": function( elem ) {
var doc = elem.ownerDocument;
return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
"active": function( elem ) {
return elem === elem.ownerDocument.activeElement;
},
// Positional types
"first": <API key>(function() {
return [ 0 ];
}),
"last": <API key>(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": <API key>(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": <API key>(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": <API key>(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": <API key>(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": <API key>(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
function siblingCheck( a, b ) {
var cur = a && b && a.nextSibling;
for ( ; cur; cur = cur.nextSibling ) {
if ( cur === b ) {
return -1;
}
}
return a ? 1 : -1;
}
sortOrder = docElem.<API key> ?
function( a, b ) {
var compare;
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( (compare = b.<API key> && a.<API key> && a.<API key>( b )) ) {
if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) {
if ( a === document || contains( document, a ) ) {
return -1;
}
if ( b === document || contains( document, b ) ) {
return 1;
}
return 0;
}
return compare & 4 ? -1 : 1;
}
return a.<API key> ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return ( ~b.sourceIndex || MAX_NEGATIVE ) - ( contains( document, a ) && ~a.sourceIndex || MAX_NEGATIVE );
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === document ? -1 :
b === document ? 1 :
aup ? -1 :
bup ? 1 :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === document ? -1 :
bp[i] === document ? 1 :
0;
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
[0, 0].sort( sortOrder );
baseHasDuplicate = !hasDuplicate;
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
i = 1,
j = 0;
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
j = duplicates.push( i );
}
}
while ( j
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ expando ][ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
tokens.push( matched = new Token( match.shift() ) );
soFar = soFar.slice( matched.length );
// Cast descendant combinators to space
matched.type = match[0].replace( rtrim, " " );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
tokens.push( matched = new Token( match.shift() ) );
soFar = soFar.slice( matched.length );
matched.type = type;
matched.matches = match;
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && combinator.dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && tokens.join("")
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function <API key>( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Nested matchers should use non-integer dirruns
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
for ( j = 0; (matcher = elementMatchers[j]); j++ ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
// `i` starts as a string, so matchedCount would equal "00" if there are no elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
for ( j = 0; (matcher = setMatchers[j]); j++ ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ expando ][ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, <API key>( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed, xml ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !xml &&
Expr.relative[ tokens[1].type ] ) {
context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().length );
}
// Fetch a seed set for right-to-left matching
for ( i = matchExpr["needsContext"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( rbackslash, "" ),
rsibling.test( tokens[0].type ) && context.parentNode || context,
xml
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && tokens.join("");
if ( !selector ) {
push.apply( results, slice.call( seed, 0 ) );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
xml,
results,
rsibling.test( selector )
);
return results;
}
if ( document.querySelectorAll ) {
(function() {
var disconnectedMatch,
oldSelect = select,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ],
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
// A support test would require too much code (would include document ready)
// just skip matchesSelector for :active
rbuggyMatches = [ ":active" ],
matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.<API key> ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector;
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/<API key>/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE9 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<p test=''></p>";
if ( div.querySelectorAll("[test^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
div.innerHTML = "<input type='hidden'/>";
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
rbuggyQSA = new RegExp( rbuggyQSA.join("|") );
select = function( selector, context, results, seed, xml ) {
// Only use querySelectorAll when not filtering,
// when this is not xml,
// and when no QSA bugs apply
if ( !seed && !xml && !rbuggyQSA.test( selector ) ) {
var groups, i,
old = true,
nid = expando,
newContext = context,
newSelector = context.nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i
groups[i] = nid + groups[i].join("");
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results, slice.call( newContext.querySelectorAll(
newSelector
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
return oldSelect( selector, context, results, seed, xml );
};
if ( matches ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[test!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
rbuggyMatches = new RegExp( rbuggyMatches.join("|") );
Sizzle.matchesSelector = function( elem, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyMatches always contains :active, so no need for an existence check
if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
}
})();
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Easy API for creating new setFilters
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// EXPOSE
if ( typeof define === "function" && define.amd ) {
define(function() { return Sizzle; });
} else {
window.Sizzle = Sizzle;
}
// EXPOSE
})( window ); |
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="assets/stylesheet-sa.css" />
</head>
<body>
<div class='verse' id='BG_C06_V38' type='shloka'>
<div class='versetext'>कच्चिन्नोभयविभ्रष्टश्छिन्नाभ्रमिव नश्यति । <br/>अप्रतिष्ठो महाबाहो विमूढो ब्रह्मणः पथि ॥ ३८ ॥ </div>
<div class='bhashya' id='BG_C06_V38_B01'>कच्चित् किं न उभयविभ्रष्टः कर्ममार्गात् योगमार्गाच्च विभ्रष्टः सन् छिन्नाभ्रमिव नश्यति, किं वा न नश्यति अप्रतिष्ठो निराश्रयः हे महाबाहो विमूढः सन् ब्रह्मणः पथि ब्रह्मप्राप्तिमार्गे ॥ ३८ ॥ </div>
</div>
</body>
</html> |
<?php
defined('_JEXEC') or die;
// SEF url fix
function LinkrBuildRoute( &$q )
{
$parts = array();
$token = JUtility::getToken();
if (!isset( $q[$token] )) {
JError::raiseError( 403, 'Invalid Token' );
}
$name = !empty( $q['e_name'] ) ? $q['e_name'] : 'text';
$parts[] = $token;
$parts[] = $name;
foreach ($q as $k => $v) {
if ($k != 'option') {
unset( $q[$k] );
}
}
return $parts;
}
function LinkrParseRoute( $s )
{
$vars = array(
$s[0] => '1',
'e_name' => $s[1],
'tmpl' => 'component',
'view' => 'articles'
);
return $vars;
} |
<?php
//classes loading begin
function classLoad ($myClass) {
if(file_exists('model/'.$myClass.'.php')){
include('model/'.$myClass.'.php');
}
elseif(file_exists('controller/'.$myClass.'.php')){
include('controller/'.$myClass.'.php');
}
}
<API key>("classLoad");
include('config.php');
//classes loading end
session_start();
if(isset($_SESSION['userMerlaTrav'])){
//classes managers
$usersManager = new UserManager($pdo);
$mailManager = new MailManager($pdo);
$todoManager = new TodoProjetManager($pdo);
$societeManager = new SocieteManager($pdo);
$projetManager = new ProjetManager($pdo);
//classes and vars
//users number
$users = $usersManager->getUsers();
//$mails = $mailManager->getMails();
$projets = $projetManager->getProjets();
$todos = 0;//$todoManager->getTodosNotHidden();
$societes = $societeManager->getSocietes();
if ( isset($_POST['idSociete']) ) {
$idSociete = htmlentities($_POST['idSociete']);
$todos = $todoManager-><API key>($idSociete);
}
else if ( isset($_GET['idSociete']) ) {
$idSociete = htmlentities($_GET['idSociete']);
$todos = $todoManager-><API key>($idSociete);
}
?>
<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9"> <![endif]-->
<!--[if !IE]><!--> <html lang="en"> <!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<meta charset="UTF-8" />
<title>ImmoERP - Management Application</title>
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
<meta content="" name="description" />
<meta content="" name="author" />
<link href="assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<link href="assets/css/metro.css" rel="stylesheet" />
<link href="assets/bootstrap/css/<API key>.min.css" rel="stylesheet" />
<link href="assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
<link href="assets/fullcalendar/fullcalendar/<API key>.css" rel="stylesheet" />
<link href="assets/css/style.css" rel="stylesheet" />
<link href="assets/css/style_responsive.css" rel="stylesheet" />
<link href="assets/css/style_default.css" rel="stylesheet" id="style_color" />
<link rel="stylesheet" type="text/css" href="assets/chosen-bootstrap/chosen/chosen.css" />
<link rel="stylesheet" type="text/css" href="assets/uniform/css/uniform.default.css" />
<link rel="stylesheet" type="text/css" href="assets/gritter/css/jquery.gritter.css" />
<link rel="shortcut icon" href="favicon.ico" />
</head>
<!-- END HEAD -->
<!-- BEGIN BODY -->
<body class="fixed-top">
<!-- BEGIN HEADER -->
<div class="header navbar navbar-inverse navbar-fixed-top">
<!-- BEGIN TOP NAVIGATION BAR -->
<?php
include("include/top-menu.php");
?>
<!-- END TOP NAVIGATION BAR -->
</div>
<!-- END HEADER -->
<!-- BEGIN CONTAINER -->
<div class="page-container row-fluid sidebar-closed">
<!-- BEGIN SIDEBAR -->
<?php include("include/sidebar.php"); ?>
<!-- END SIDEBAR -->
<!-- BEGIN PAGE -->
<div class="page-content">
<!-- BEGIN PAGE CONTAINER-->
<div class="container-fluid">
<!-- BEGIN PAGE HEADER-->
<div class="row-fluid">
<div class="span12">
<!-- BEGIN PAGE TITLE & BREADCRUMB-->
<h3 class="page-title">
Gestion des tâches en cours
</h3>
<ul class="breadcrumb">
<li>
<i class="icon-dashboard"></i>
<a href="dashboard.php">Accueil</a>
<i class="icon-angle-right"></i>
</li>
<li>
<i class="icon-check"></i>
<a href="tasks.php">Gestion des tâches</a>
<i class="icon-angle-right"></i>
</li>
<li>
<i class="icon-check-empty"></i>
<a>Les tâches en cours</a>
</li>
</ul>
<!-- END PAGE TITLE & BREADCRUMB-->
</div>
</div>
<!-- END PAGE HEADER-->
<!-- BEGIN PAGE CONTENT-->
<!-- BEGIN PORTLET-->
<div class="row-fluid">
<div class="span12">
<div class="portlet">
<div class="portlet-title line">
<h4>Choisir société</h4>
<!--div class="tools">
<a href="javascript:;" class="collapse"></a>
<a href="javascript:;" class="remove"></a>
</div
</div>
<div class="portlet-body" id="chats">
<form action="" method="POST" enctype="multipart/form-data">
<div class="control-group">
<div class="controls">
<select name="idSociete" class="m-wrap" >
<?php foreach($societes as $societe){ ?>
<option value="<?= $societe->id() ?>"><?= $societe->raisonSociale() ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="btn-cont">
<button type="submit" class="btn blue icn-only"><i class="icon-search icon-white"></i> Chercher</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<div class="portlet">
<div class="portlet-title line">
<h4><i class="icon-check"></i>Ajouter une tâche</h4>
<!--div class="tools">
<a href="javascript:;" class="collapse"></a>
<a href="javascript:;" class="remove"></a>
</div
</div>
<div class="portlet-body" id="chats">
<div class="chat-form">
<form action="controller/<API key>.php" method="POST">
<div class="input-cont">
<input style="width: 300px" class="span4 m-wrap" type="text" name="todo" placeholder="Tâche" />
<input style="width: 150px" class="span4 m-wrap" type="text" name="responsable" placeholder="Responsable" />
<select style="width: 120px" class="m-wrap" name="priority">
<option value="Todo">Todo</option>
<option value="InternalProcess">InternalProcess</option>
<option value="ExternalProcess">ExternalProcess</option>
<option value="Done">Done</option>
<option value="Done-Hide">Done-Hide</option>
</select>
<select style="width: 250px" class="m-wrap" name="idProjet" id="projet-choice">
<?php foreach($projets as $projet){ ?>
<option value="<?= $projet->id() ?>"><?= $projet->nom() ?></option>
<?php } ?>
<option value="0">Autre</option>
</select>
<select style="width: 250px; display: none" class="m-wrap" name="idSociete" id="societe-choice">
<?php foreach($societes as $societe){ ?>
<option value="<?= $societe->id() ?>"><?= $societe->raisonSociale() ?></option>
<?php } ?>
</select>
<input style="width: 300px" class="span4 m-wrap" type="text" name="description" placeholder="Description" />
</div>
<div class="btn-cont">
<input type="hidden" name="action" value="add" />
<span class="arrow"></span>
<button type="submit" class="btn blue icn-only"><i class="icon-ok icon-white"></i></button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<!-- BEGIN INLINE NOTIFICATIONS PORTLET-->
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Todo</th>
<th>InternalProcess</th>
<th>ExternalProcess</th>
<th>Done</th>
</tr>
</thead>
<tbody>
<?php
if ( $todos != 0 ){
foreach($todos as $todo){
$projetName = "";
if ($todo->idProjet() == 0) {
$projetName = "Autre";
}
else{
$projetName = $projetManager->getProjetById($todo->idProjet())->nom();
}
$color = "";
$priorityOption = "";
if ( $todo->priority() == "Todo" ) {
$color = "red";
}
else if ( $todo->priority() == "InternalProcess" ) {
$color = "yellow";
}
else if ( $todo->priority() == "ExternalProcess" ) {
$color = "green";
}
else if ( $todo->priority() == "Done" ) {
$color = "blue";
}
?>
<tr>
<td>
<?php if ( $todo->priority() == "Todo" ) { ?>
<a href="include/delete-task-projet.php?idTask=<?= $todo->id() ?>&idSociete=<?= $idSociete ?>"><i class="icon-remove"></i></a>
<a title="Responsable : <?= $todo->responsable() ?> | Description : <?= $todo->description() ?> | Projet : <?= $projetName ?>" href="#updateTodo<?= $todo->id() ?>" data-toggle="modal" data-id="<?= $todo->id() ?>" class="btn <?= $color ?> get-down delete-checkbox"><?= $todo->todo() ?></a>
<br />
<a><?= date('d/m/Y', strtotime($todo->created())) ?></a>
<?php } ?>
</td>
<td>
<?php if ( $todo->priority() == "InternalProcess" ) { ?>
<a href="include/delete-task-projet.php?idTask=<?= $todo->id() ?>&idSociete=<?= $idSociete ?>"><i class="icon-remove"></i></a>
<a title="Responsable : <?= $todo->responsable() ?> | Description : <?= $todo->description() ?> | Projet : <?= $projetName ?>" href="#updateTodo<?= $todo->id() ?>" data-toggle="modal" data-id="<?= $todo->id() ?>" class="btn <?= $color ?> get-down delete-checkbox"><?= $todo->todo() ?></a>
<br />
<a><?= date('d/m/Y', strtotime($todo->created())) ?></a>
<?php } ?>
</td>
<td>
<?php if ( $todo->priority() == "ExternalProcess" ) { ?>
<a href="include/delete-task-projet.php?idTask=<?= $todo->id() ?>&idSociete=<?= $idSociete ?>"><i class="icon-remove"></i></a>
<a title="Responsable : <?= $todo->responsable() ?> | Description : <?= $todo->description() ?> | Projet : <?= $projetName ?>" href="#updateTodo<?= $todo->id() ?>" data-toggle="modal" data-id="<?= $todo->id() ?>" class="btn <?= $color ?> get-down delete-checkbox"><?= $todo->todo() ?></a>
<br />
<a><?= date('d/m/Y', strtotime($todo->created())) ?></a>
<?php } ?>
</td>
<td>
<?php if ( $todo->priority() == "Done" ) { ?>
<a href="include/delete-task-projet.php?idTask=<?= $todo->id() ?>&idSociete=<?= $idSociete ?>"><i class="icon-remove"></i></a>
<a title="Responsable : <?= $todo->responsable() ?> | Description : <?= $todo->description() ?> | Projet : <?= $projetName ?>" href="#updateTodo<?= $todo->id() ?>" data-toggle="modal" data-id="<?= $todo->id() ?>" class="btn <?= $color ?> get-down delete-checkbox"><?= $todo->todo() ?></a>
<br />
<a><?= date('d/m/Y', strtotime($todo->created())) ?></a>
<?php } ?>
</td>
<!-- updateTodo box begin-->
<div id="updateTodo<?= $todo->id() ?>" class="modal hide fade in" tabindex="-1" role="dialog" aria-labelledby="login" aria-hidden="false" >
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h3>Modifier Todo Projet</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" action="controller/<API key>.php" method="post">
<div class="control-group">
<label class="control-label">Todo</label>
<div class="controls">
<input type="text" name="todo" value="<?= $todo->todo() ?>" />
</div>
</div>
<div class="control-group">
<label class="control-label">Responsable</label>
<div class="controls">
<input type="text" name="responsable" value="<?= $todo->responsable() ?>" />
</div>
</div>
<div class="control-group">
<label class="control-label">Status</label>
<div class="controls">
<select name="priority">
<option value="<?= $todo->priority() ?>"><?= $todo->priority() ?></option>
<option disabled="disabled">
<option value="Todo">Todo</option>
<option value="InternalProcess">InternalProcess</option>
<option value="ExternalProcess">ExternalProcess</option>
<option value="Done">Done</option>
<option value="Done-Hide">Done-Hide</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">Projet</label>
<div class="controls">
<select class="m-wrap project-choice" name="idProjet">
<option value="<?= $todo->idProjet() ?>"><?= $projetName ?></option>
<option disabled="disabled">
<?php foreach($projets as $projet){ ?>
<option value="<?= $projet->id() ?>"><?= $projet->nom() ?></option>
<?php } ?>
<option value="x">Autre</option>
</select>
</div>
</div>
<div class="control-group societes-choice" style="display: none" >
<label class="control-label">Société</label>
<div class="controls">
<select class="m-wrap" name="idSocieteNew">
<?php foreach($societes as $societe){ ?>
<option value="<?= $societe->id() ?>"><?= $societe->raisonSociale() ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">Description</label>
<div class="controls">
<input type="text" name="description" value="<?= $todo->description() ?>" />
</div>
</div>
<div class="modal-footer">
<div class="control-group">
<input type="hidden" name="idTodo" value="<?= $todo->id() ?>" />
<input type="hidden" name="idSociete" value="<?= $idSociete ?>" />
<input type="hidden" name="action" value="update" />
<div class="controls">
<button class="btn" data-dismiss="modal"aria-hidden="true">Non</button>
<button type="submit" class="btn red" aria-hidden="true">Oui</button>
</div>
</div>
</div>
</form>
</div>
</div>
<!-- updateTodo box end -->
</tr>
<?php
}//end for
}//end if
?>
</tbody>
</table>
<!-- END INLINE NOTIFICATIONS PORTLET-->
</div>
</div>
<!-- END PORTLET-->
<!-- END PAGE CONTENT-->
</div>
<!-- END PAGE CONTAINER-->
</div>
<!-- END PAGE -->
</div>
<!-- END CONTAINER -->
<!-- BEGIN FOOTER -->
<div class="footer">
2015 © ImmoERP. Management Application.
<div class="span pull-right">
<span class="go-top"><i class="icon-angle-up"></i></span>
</div>
</div>
<!-- END FOOTER -->
<!-- BEGIN JAVASCRIPTS -->
<!-- Load javascripts at bottom, this will reduce page load time -->
<script src="assets/js/jquery-1.8.3.min.js"></script>
<script src="assets/breakpoints/breakpoints.js"></script>
<script src="assets/jquery-slimscroll/jquery-ui-1.9.2.custom.min.js"></script>
<script src="assets/jquery-slimscroll/jquery.slimscroll.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/js/jquery.blockui.js"></script>
<script src="assets/js/jquery.cookie.js"></script>
<script src="assets/fullcalendar/fullcalendar/fullcalendar.min.js"></script>
<script type="text/javascript" src="assets/uniform/jquery.uniform.min.js"></script>
<script type="text/javascript" src="assets/chosen-bootstrap/chosen/chosen.jquery.min.js"></script>
<script src="assets/jquery-knob/js/jquery.knob.js"></script>
<script src="assets/<API key>/jquery.ui.touch-punch.min.js"></script>
<script type="text/javascript" src="assets/gritter/js/jquery.gritter.js"></script>
<script type="text/javascript" src="assets/js/jquery.pulsate.min.js"></script>
<!-- ie8 fixes -->
<!--[if lt IE 9]>
<script src="assets/js/excanvas.js"></script>
<script src="assets/js/respond.js"></script>
<![endif]
<script src="assets/js/app.js"></script>
<script>
jQuery(document).ready(function() {
// initiate layout and plugins
App.setPage("table_managed"); // set current page
App.init();
$('#projet-choice').on('change',function(){
if( $(this).val()==="0"){
$("#societe-choice").show();
}
else{
$("#societe-choice").hide();
}
});
$('.project-choice').on('change',function(){
if( $(this).val()==="x"){
$(".societes-choice").show();
}
else{
$(".societes-choice").hide();
}
});
});
</script>
<!-- END JAVASCRIPTS -->
</body>
<!-- END BODY -->
</html>
<?php
}
else{
header('Location:index.php');
}
?> |
package de.steinberg.gyp.gui.icons;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public abstract class IconView extends ImageView {
int height = 16;
int width = 16;
public IconView(Image image) {
super(image);
setFitHeight(height);
setFitWidth(width);
}
} |
#include <vos_mq.h>
#include <vos_api.h>
#include <aniGlobal.h>
#include <sirTypes.h>
#include <halTypes.h>
#include <limApi.h>
#include <sme_Api.h>
#include <wlan_qct_sys.h>
#include <wlan_qct_tl.h>
#include "vos_sched.h"
#include <wlan_hdd_power.h>
#include "wlan_qct_wda.h"
#include "wlan_qct_pal_msg.h"
#include <linux/spinlock.h>
#include <linux/kthread.h>
#define <API key> INFINITE
/* Milli seconds to delay SSR thread when an Entry point is Active */
#define SSR_WAIT_SLEEP_TIME 100
/* MAX iteration count to wait for Entry point to exit before
* we proceed with SSR in WD Thread
*/
#define <API key> 200
static atomic_t <API key>;
static pVosSchedContext gpVosSchedContext;
static pVosWatchdogContext <API key>;
static int VosMCThread(void *Arg);
static int VosWDThread(void *Arg);
static int VosTXThread(void *Arg);
static int VosRXThread(void *Arg);
void <API key>(pVosSchedContext SchedContext);
extern v_VOID_t vos_core_return_msg(v_PVOID_t pVContext, pVosMsgWrapper pMsgWrapper);
VOS_STATUS
vos_sched_open
(
v_PVOID_t pVosContext,
pVosSchedContext pSchedContext,
v_SIZE_t SchedCtxSize
)
{
VOS_STATUS vStatus = VOS_STATUS_SUCCESS;
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Opening the VOSS Scheduler",__func__);
// Sanity checks
if ((pVosContext == NULL) || (pSchedContext == NULL)) {
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Null params being passed",__func__);
return <API key>;
}
if (sizeof(VosSchedContext) != SchedCtxSize)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Incorrect VOS Sched Context size passed",__func__);
return VOS_STATUS_E_INVAL;
}
vos_mem_zero(pSchedContext, sizeof(VosSchedContext));
pSchedContext->pVContext = pVosContext;
vStatus = vos_sched_init_mqs(pSchedContext);
if (!<API key>(vStatus))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to initialize VOS Scheduler MQs",__func__);
return vStatus;
}
// Initialize the helper events and event queues
init_completion(&pSchedContext->McStartEvent);
init_completion(&pSchedContext->TxStartEvent);
init_completion(&pSchedContext->RxStartEvent);
init_completion(&pSchedContext->McShutdown);
init_completion(&pSchedContext->TxShutdown);
init_completion(&pSchedContext->RxShutdown);
init_completion(&pSchedContext->ResumeMcEvent);
init_completion(&pSchedContext->ResumeTxEvent);
init_completion(&pSchedContext->ResumeRxEvent);
spin_lock_init(&pSchedContext->McThreadLock);
spin_lock_init(&pSchedContext->TxThreadLock);
spin_lock_init(&pSchedContext->RxThreadLock);
init_waitqueue_head(&pSchedContext->mcWaitQueue);
pSchedContext->mcEventFlag = 0;
init_waitqueue_head(&pSchedContext->txWaitQueue);
pSchedContext->txEventFlag= 0;
init_waitqueue_head(&pSchedContext->rxWaitQueue);
pSchedContext->rxEventFlag= 0;
/*
** This initialization is critical as the threads will later access the
** global contexts normally,
**
** I shall put some memory barrier here after the next piece of code but
** I am keeping it simple for now.
*/
gpVosSchedContext = pSchedContext;
//Create the VOSS Main Controller thread
pSchedContext->McThread = kthread_create(VosMCThread, pSchedContext,
"VosMCThread");
if (IS_ERR(pSchedContext->McThread))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Could not Create VOSS Main Thread Controller",__func__);
goto <API key>;
}
wake_up_process(pSchedContext->McThread);
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: VOSS Main Controller thread Created",__func__);
pSchedContext->TxThread = kthread_create(VosTXThread, pSchedContext,
"VosTXThread");
if (IS_ERR(pSchedContext->TxThread))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Could not Create VOSS TX Thread",__func__);
goto <API key>;
}
wake_up_process(pSchedContext->TxThread);
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
("VOSS TX thread Created"));
pSchedContext->RxThread = kthread_create(VosRXThread, pSchedContext,
"VosRXThread");
if (IS_ERR(pSchedContext->RxThread))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Could not Create VOSS RX Thread",__func__);
goto <API key>;
}
wake_up_process(pSchedContext->RxThread);
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
("VOSS RX thread Created"));
/*
** Now make sure all threads have started before we exit.
** Each thread should normally ACK back when it starts.
*/
<API key>(&pSchedContext->McStartEvent);
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: VOSS MC Thread has started",__func__);
<API key>(&pSchedContext->TxStartEvent);
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: VOSS Tx Thread has started",__func__);
<API key>(&pSchedContext->RxStartEvent);
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: VOSS Rx Thread has started",__func__);
/*
** We're good now: Let's get the ball rolling!!!
*/
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: VOSS Scheduler successfully Opened",__func__);
return VOS_STATUS_SUCCESS;
<API key>:
//Try and force the Tx thread controller to exit
set_bit(<API key>, &pSchedContext->txEventFlag);
set_bit(MC_POST_EVENT_MASK, &pSchedContext->txEventFlag);
<API key>(&pSchedContext->txWaitQueue);
//Wait for TX to exit
<API key>(&pSchedContext->TxShutdown);
<API key>:
//Try and force the Main thread controller to exit
set_bit(<API key>, &pSchedContext->mcEventFlag);
set_bit(MC_POST_EVENT_MASK, &pSchedContext->mcEventFlag);
<API key>(&pSchedContext->mcWaitQueue);
//Wait for MC to exit
<API key>(&pSchedContext->McShutdown);
<API key>:
//De-initialize all the message queues
<API key>(pSchedContext);
return <API key>;
} /* vos_sched_open() */
VOS_STATUS vos_watchdog_open
(
v_PVOID_t pVosContext,
pVosWatchdogContext pWdContext,
v_SIZE_t wdCtxSize
)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Opening the VOSS Watchdog module",__func__);
//Sanity checks
if ((pVosContext == NULL) || (pWdContext == NULL)) {
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Null params being passed",__func__);
return <API key>;
}
if (sizeof(VosWatchdogContext) != wdCtxSize)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Incorrect VOS Watchdog Context size passed",__func__);
return VOS_STATUS_E_INVAL;
}
vos_mem_zero(pWdContext, sizeof(VosWatchdogContext));
pWdContext->pVContext = pVosContext;
<API key> = pWdContext;
//Initialize the helper events and event queues
init_completion(&pWdContext->WdStartEvent);
init_completion(&pWdContext->WdShutdown);
init_waitqueue_head(&pWdContext->wdWaitQueue);
pWdContext->wdEventFlag = 0;
// Initialize the lock
spin_lock_init(&pWdContext->wdLock);
//Create the Watchdog thread
pWdContext->WdThread = kthread_create(VosWDThread, pWdContext,"VosWDThread");
if (IS_ERR(pWdContext->WdThread))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Could not Create Watchdog thread",__func__);
return <API key>;
}
else
{
wake_up_process(pWdContext->WdThread);
}
/*
** Now make sure thread has started before we exit.
** Each thread should normally ACK back when it starts.
*/
<API key>(&pWdContext->WdStartEvent);
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: VOSS Watchdog Thread has started",__func__);
return VOS_STATUS_SUCCESS;
} /* vos_watchdog_open() */
static int
VosMCThread
(
void * Arg
)
{
pVosSchedContext pSchedContext = (pVosSchedContext)Arg;
pVosMsgWrapper pMsgWrapper = NULL;
tpAniSirGlobal pMacContext = NULL;
tSirRetStatus macStatus = eSIR_SUCCESS;
VOS_STATUS vStatus = VOS_STATUS_SUCCESS;
int retWaitStatus = 0;
v_BOOL_t shutdown = VOS_FALSE;
hdd_context_t *pHddCtx = NULL;
v_CONTEXT_t pVosContext = NULL;
if (Arg == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Bad Args passed", __func__);
return 0;
}
set_user_nice(current, -2);
#if (LINUX_VERSION_CODE < KERNEL_VERSION(3,8,0))
daemonize("MC_Thread");
#endif
/*
** Ack back to the context from which the main controller thread has been
** created.
*/
complete(&pSchedContext->McStartEvent);
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: MC Thread %d (%s) starting up",__func__, current->pid, current->comm);
/* Get the Global VOSS Context */
pVosContext = <API key>(VOS_MODULE_ID_SYS, NULL);
if(!pVosContext) {
hddLog(<API key>,"%s: Global VOS context is Null", __func__);
return 0;
}
/* Get the HDD context */
pHddCtx = (hdd_context_t *)vos_get_context(VOS_MODULE_ID_HDD, pVosContext );
if(!pHddCtx) {
hddLog(<API key>,"%s: HDD context is Null",__func__);
return 0;
}
while(!shutdown)
{
// This implements the execution model algorithm
retWaitStatus = <API key>(pSchedContext->mcWaitQueue,
test_bit(MC_POST_EVENT_MASK, &pSchedContext->mcEventFlag) ||
test_bit(<API key>, &pSchedContext->mcEventFlag));
if(retWaitStatus == -ERESTARTSYS)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: <API key> returned -ERESTARTSYS", __func__);
break;
}
clear_bit(MC_POST_EVENT_MASK, &pSchedContext->mcEventFlag);
while(1)
{
// Check if MC needs to shutdown
if(test_bit(<API key>, &pSchedContext->mcEventFlag))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: MC thread signaled to shutdown", __func__);
shutdown = VOS_TRUE;
/* Check for any Suspend Indication */
if (test_and_clear_bit(<API key>,
&pSchedContext->mcEventFlag))
{
/* Unblock anyone waiting on suspend */
complete(&pHddCtx->mc_sus_event_var);
}
break;
}
/*
** Check the WDI queue
** Service it till the entire queue is empty
*/
if (!vos_is_mq_empty(&pSchedContext->wdiMcMq))
{
wpt_msg *pWdiMsg;
/*
** Service the WDI message queue
*/
VOS_TRACE(VOS_MODULE_ID_WDI, <API key>,
("Servicing the VOS MC WDI Message queue"));
pMsgWrapper = vos_mq_get(&pSchedContext->wdiMcMq);
if (pMsgWrapper == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: pMsgWrapper is NULL", __func__);
VOS_BUG(0);
break;
}
pWdiMsg = (wpt_msg *)pMsgWrapper->pVosMsg->bodyptr;
if(pWdiMsg == NULL || pWdiMsg->callback == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: WDI Msg or Callback is NULL", __func__);
VOS_BUG(0);
break;
}
pWdiMsg->callback(pWdiMsg);
/*
** return message to the Core
*/
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
continue;
}
// Check the SYS queue first
if (!vos_is_mq_empty(&pSchedContext->sysMcMq))
{
// Service the SYS message queue
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Servicing the VOS SYS MC Message queue",__func__);
pMsgWrapper = vos_mq_get(&pSchedContext->sysMcMq);
if (pMsgWrapper == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: pMsgWrapper is NULL", __func__);
VOS_ASSERT(0);
break;
}
vStatus = sysMcProcessMsg(pSchedContext->pVContext,
pMsgWrapper->pVosMsg);
if (!<API key>(vStatus))
{
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: Issue Processing SYS message",__func__);
}
//return message to the Core
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
continue;
}
// Check the WDA queue
if (!vos_is_mq_empty(&pSchedContext->wdaMcMq))
{
// Service the WDA message queue
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Servicing the VOS WDA MC Message queue",__func__);
pMsgWrapper = vos_mq_get(&pSchedContext->wdaMcMq);
if (pMsgWrapper == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: pMsgWrapper is NULL", __func__);
VOS_ASSERT(0);
break;
}
vStatus = WDA_McProcessMsg( pSchedContext->pVContext, pMsgWrapper->pVosMsg);
if (!<API key>(vStatus))
{
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: Issue Processing WDA message",__func__);
}
// return message to the Core
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
continue;
}
// Check the PE queue
if (!vos_is_mq_empty(&pSchedContext->peMcMq))
{
// Service the PE message queue
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Servicing the VOS PE MC Message queue",__func__);
pMsgWrapper = vos_mq_get(&pSchedContext->peMcMq);
if (NULL == pMsgWrapper)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: pMsgWrapper is NULL", __func__);
VOS_ASSERT(0);
break;
}
/* Need some optimization*/
pMacContext = vos_get_context(VOS_MODULE_ID_PE, pSchedContext->pVContext);
if (NULL == pMacContext)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"MAC Context not ready yet");
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
continue;
}
macStatus = peProcessMessages( pMacContext, (tSirMsgQ*)pMsgWrapper->pVosMsg);
if (eSIR_SUCCESS != macStatus)
{
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: Issue Processing PE message",__func__);
}
// return message to the Core
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
continue;
}
/** Check the SME queue **/
if (!vos_is_mq_empty(&pSchedContext->smeMcMq))
{
/* Service the SME message queue */
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Servicing the VOS SME MC Message queue",__func__);
pMsgWrapper = vos_mq_get(&pSchedContext->smeMcMq);
if (NULL == pMsgWrapper)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: pMsgWrapper is NULL", __func__);
VOS_ASSERT(0);
break;
}
/* Need some optimization*/
pMacContext = vos_get_context(VOS_MODULE_ID_SME, pSchedContext->pVContext);
if (NULL == pMacContext)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"MAC Context not ready yet");
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
continue;
}
vStatus = sme_ProcessMsg( (tHalHandle)pMacContext, pMsgWrapper->pVosMsg);
if (!<API key>(vStatus))
{
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: Issue Processing SME message",__func__);
}
// return message to the Core
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
continue;
}
/** Check the TL queue **/
if (!vos_is_mq_empty(&pSchedContext->tlMcMq))
{
// Service the TL message queue
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
("Servicing the VOS TL MC Message queue"));
pMsgWrapper = vos_mq_get(&pSchedContext->tlMcMq);
if (pMsgWrapper == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: pMsgWrapper is NULL", __func__);
VOS_ASSERT(0);
break;
}
vStatus = WLANTL_McProcessMsg( pSchedContext->pVContext,
pMsgWrapper->pVosMsg);
if (!<API key>(vStatus))
{
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: Issue Processing TL message",__func__);
}
// return message to the Core
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
continue;
}
/* Check for any Suspend Indication */
if (test_and_clear_bit(<API key>,
&pSchedContext->mcEventFlag))
{
spin_lock(&pSchedContext->McThreadLock);
/* Mc Thread Suspended */
complete(&pHddCtx->mc_sus_event_var);
INIT_COMPLETION(pSchedContext->ResumeMcEvent);
spin_unlock(&pSchedContext->McThreadLock);
/* Wait foe Resume Indication */
<API key>(&pSchedContext->ResumeMcEvent);
}
break; //All queues are empty now
} // while message loop processing
} // while TRUE
// If we get here the MC thread must exit
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: MC Thread exiting!!!!", __func__);
complete_and_exit(&pSchedContext->McShutdown, 0);
} /* VosMCThread() */
v_BOOL_t isWDresetInProgress(void)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Reset is in Progress...",__func__);
if(<API key>!=NULL)
{
return <API key>->resetInProgress;
}
else
{
return FALSE;
}
}
v_BOOL_t isSsrPanicOnFailure(void)
{
hdd_context_t *pHddCtx = NULL;
v_CONTEXT_t pVosContext = NULL;
/* Get the Global VOSS Context */
pVosContext = <API key>(VOS_MODULE_ID_SYS, NULL);
if(!pVosContext)
{
hddLog(<API key>,"%s: Global VOS context is Null", __func__);
return FALSE;
}
/* Get the HDD context */
pHddCtx = (hdd_context_t *)vos_get_context(VOS_MODULE_ID_HDD, pVosContext);
if((NULL == pHddCtx) || (NULL == pHddCtx->cfg_ini))
{
hddLog(<API key>,"%s: HDD context is Null", __func__);
return FALSE;
}
return (pHddCtx->cfg_ini-><API key>);
}
static int
VosWDThread
(
void * Arg
)
{
pVosWatchdogContext pWdContext = (pVosWatchdogContext)Arg;
int retWaitStatus = 0;
v_BOOL_t shutdown = VOS_FALSE;
int count = 0;
VOS_STATUS vosStatus = VOS_STATUS_SUCCESS;
hdd_context_t *pHddCtx = NULL;
v_CONTEXT_t pVosContext = NULL;
set_user_nice(current, -3);
if (Arg == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Bad Args passed", __func__);
return 0;
}
/* Get the Global VOSS Context */
pVosContext = <API key>(VOS_MODULE_ID_SYS, NULL);
if(!pVosContext)
{
hddLog(<API key>,"%s: Global VOS context is Null", __func__);
return 0;
}
/* Get the HDD context */
pHddCtx = (hdd_context_t *)vos_get_context(VOS_MODULE_ID_HDD, pVosContext );
if(!pHddCtx)
{
hddLog(<API key>,"%s: HDD context is Null",__func__);
return 0;
}
#if (LINUX_VERSION_CODE < KERNEL_VERSION(3,8,0))
daemonize("WD_Thread");
#endif
/*
** Ack back to the context from which the Watchdog thread has been
** created.
*/
complete(&pWdContext->WdStartEvent);
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Watchdog Thread %d (%s) starting up",__func__, current->pid, current->comm);
while(!shutdown)
{
// This implements the Watchdog execution model algorithm
retWaitStatus = <API key>(pWdContext->wdWaitQueue,
test_bit(WD_POST_EVENT_MASK, &pWdContext->wdEventFlag));
if(retWaitStatus == -ERESTARTSYS)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: <API key> returned -ERESTARTSYS", __func__);
break;
}
clear_bit(WD_POST_EVENT_MASK, &pWdContext->wdEventFlag);
while(1)
{
/* Check for any Active Entry Points
* If active, delay SSR until no entry point is active or
* delay until count is decremented to ZERO
*/
count = <API key>;
while (count)
{
if (!atomic_read(&<API key>))
{
/* no external threads are executing */
break;
}
/* at least one external thread is executing */
if (--count)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Waiting for active entry points to exit", __func__);
msleep(SSR_WAIT_SLEEP_TIME);
}
}
/* at least one external thread is executing */
if (!count)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Continuing SSR when %d Entry points are still active",
__func__, atomic_read(&<API key>));
}
// Check if Watchdog needs to shutdown
if(test_bit(<API key>, &pWdContext->wdEventFlag))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Watchdog thread signaled to shutdown", __func__);
clear_bit(<API key>, &pWdContext->wdEventFlag);
shutdown = VOS_TRUE;
break;
}
/* subsystem restart: shutdown event handler */
else if(test_bit(<API key>, &pWdContext->wdEventFlag))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Watchdog thread signaled to perform WLAN shutdown",__func__);
clear_bit(<API key>, &pWdContext->wdEventFlag);
//Perform WLAN shutdown
if(!pWdContext->resetInProgress)
{
pWdContext->resetInProgress = true;
vosStatus = hdd_wlan_shutdown();
if (! <API key>(vosStatus))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to shutdown WLAN",__func__);
VOS_ASSERT(0);
goto err_reset;
}
}
}
/* subsystem restart: re-init event handler */
else if(test_bit(<API key>, &pWdContext->wdEventFlag))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Watchdog thread signaled to perform WLAN re-init",__func__);
clear_bit(<API key>, &pWdContext->wdEventFlag);
//Perform WLAN re-init
if(!pWdContext->resetInProgress)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Do WLAN re-init only when it is shutdown !!",__func__);
break;
}
vosStatus = hdd_wlan_re_init();
if (! <API key>(vosStatus))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to re-init WLAN",__func__);
VOS_ASSERT(0);
pWdContext->isFatalError = true;
}
else
{
pWdContext->isFatalError = false;
}
atomic_set(&pHddCtx->isRestartInProgress, 0);
pWdContext->resetInProgress = false;
complete(&pHddCtx->ssr_comp_var);
}
else
{
//Unnecessary wakeup - Should never happen!!
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Watchdog thread woke up unnecessarily",__func__);
}
break;
} // while message loop processing
} // while shutdown
// If we get here the Watchdog thread must exit
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: Watchdog Thread exiting !!!!", __func__);
complete_and_exit(&pWdContext->WdShutdown, 0);
err_reset:
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: Watchdog Thread Failed to Reset, Exiting!!!!", __func__);
return 0;
} /* VosMCThread() */
static int VosTXThread ( void * Arg )
{
pVosSchedContext pSchedContext = (pVosSchedContext)Arg;
pVosMsgWrapper pMsgWrapper = NULL;
VOS_STATUS vStatus = VOS_STATUS_SUCCESS;
int retWaitStatus = 0;
v_BOOL_t shutdown = VOS_FALSE;
hdd_context_t *pHddCtx = NULL;
v_CONTEXT_t pVosContext = NULL;
set_user_nice(current, -1);
#ifdef <API key>
set_wake_up_idle(true);
#endif
if (Arg == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s Bad Args passed", __func__);
return 0;
}
#if (LINUX_VERSION_CODE < KERNEL_VERSION(3,8,0))
daemonize("TX_Thread");
#endif
/*
** Ack back to the context from which the main controller thread has been
** created.
*/
complete(&pSchedContext->TxStartEvent);
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: TX Thread %d (%s) starting up!",__func__, current->pid, current->comm);
/* Get the Global VOSS Context */
pVosContext = <API key>(VOS_MODULE_ID_SYS, NULL);
if(!pVosContext) {
hddLog(<API key>,"%s: Global VOS context is Null", __func__);
return 0;
}
/* Get the HDD context */
pHddCtx = (hdd_context_t *)vos_get_context(VOS_MODULE_ID_HDD, pVosContext );
if(!pHddCtx) {
hddLog(<API key>,"%s: HDD context is Null",__func__);
return 0;
}
while(!shutdown)
{
// This implements the execution model algorithm
retWaitStatus = <API key>(pSchedContext->txWaitQueue,
test_bit(TX_POST_EVENT_MASK, &pSchedContext->txEventFlag) ||
test_bit(<API key>, &pSchedContext->txEventFlag));
if(retWaitStatus == -ERESTARTSYS)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: <API key> returned -ERESTARTSYS", __func__);
break;
}
clear_bit(TX_POST_EVENT_MASK, &pSchedContext->txEventFlag);
while(1)
{
if(test_bit(<API key>, &pSchedContext->txEventFlag))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: TX thread signaled to shutdown", __func__);
shutdown = VOS_TRUE;
/* Check for any Suspend Indication */
if (test_and_clear_bit(<API key>,
&pSchedContext->txEventFlag))
{
/* Unblock anyone waiting on suspend */
complete(&pHddCtx->tx_sus_event_var);
}
break;
}
// Check the SYS queue first
if (!vos_is_mq_empty(&pSchedContext->sysTxMq))
{
// Service the SYS message queue
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Servicing the VOS SYS TX Message queue",__func__);
pMsgWrapper = vos_mq_get(&pSchedContext->sysTxMq);
if (pMsgWrapper == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: pMsgWrapper is NULL", __func__);
VOS_ASSERT(0);
break;
}
vStatus = sysTxProcessMsg( pSchedContext->pVContext,
pMsgWrapper->pVosMsg);
if (!<API key>(vStatus))
{
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: Issue Processing TX SYS message",__func__);
}
// return message to the Core
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
continue;
}
// Check now the TL queue
if (!vos_is_mq_empty(&pSchedContext->tlTxMq))
{
// Service the TL message queue
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Servicing the VOS TL TX Message queue",__func__);
pMsgWrapper = vos_mq_get(&pSchedContext->tlTxMq);
if (pMsgWrapper == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: pMsgWrapper is NULL", __func__);
VOS_ASSERT(0);
break;
}
vStatus = WLANTL_TxProcessMsg( pSchedContext->pVContext,
pMsgWrapper->pVosMsg);
if (!<API key>(vStatus))
{
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: Issue Processing TX TL message",__func__);
}
// return message to the Core
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
continue;
}
// Check the WDI queue
if (!vos_is_mq_empty(&pSchedContext->wdiTxMq))
{
wpt_msg *pWdiMsg;
pMsgWrapper = vos_mq_get(&pSchedContext->wdiTxMq);
if (pMsgWrapper == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: pMsgWrapper is NULL", __func__);
VOS_BUG(0);
break;
}
pWdiMsg = (wpt_msg *)pMsgWrapper->pVosMsg->bodyptr;
if(pWdiMsg == NULL || pWdiMsg->callback == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: WDI Msg or Callback is NULL", __func__);
VOS_BUG(0);
break;
}
pWdiMsg->callback(pWdiMsg);
// return message to the Core
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
continue;
}
/* Check for any Suspend Indication */
if (test_and_clear_bit(<API key>,
&pSchedContext->txEventFlag))
{
spin_lock(&pSchedContext->TxThreadLock);
/* Tx Thread Suspended */
complete(&pHddCtx->tx_sus_event_var);
INIT_COMPLETION(pSchedContext->ResumeTxEvent);
spin_unlock(&pSchedContext->TxThreadLock);
/* Wait foe Resume Indication */
<API key>(&pSchedContext->ResumeTxEvent);
}
break; //All queues are empty now
} // while message loop processing
} // while TRUE
// If we get here the TX thread must exit
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: TX Thread exiting!!!!", __func__);
complete_and_exit(&pSchedContext->TxShutdown, 0);
} /* VosTxThread() */
static int VosRXThread ( void * Arg )
{
pVosSchedContext pSchedContext = (pVosSchedContext)Arg;
pVosMsgWrapper pMsgWrapper = NULL;
int retWaitStatus = 0;
v_BOOL_t shutdown = VOS_FALSE;
hdd_context_t *pHddCtx = NULL;
v_CONTEXT_t pVosContext = NULL;
VOS_STATUS vStatus = VOS_STATUS_SUCCESS;
set_user_nice(current, -1);
#ifdef <API key>
set_wake_up_idle(true);
#endif
if (Arg == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s Bad Args passed", __func__);
return 0;
}
#if (LINUX_VERSION_CODE < KERNEL_VERSION(3,8,0))
daemonize("RX_Thread");
#endif
/*
** Ack back to the context from which the main controller thread has been
** created.
*/
complete(&pSchedContext->RxStartEvent);
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: RX Thread %d (%s) starting up!",__func__, current->pid, current->comm);
/* Get the Global VOSS Context */
pVosContext = <API key>(VOS_MODULE_ID_SYS, NULL);
if(!pVosContext) {
hddLog(<API key>,"%s: Global VOS context is Null", __func__);
return 0;
}
/* Get the HDD context */
pHddCtx = (hdd_context_t *)vos_get_context(VOS_MODULE_ID_HDD, pVosContext );
if(!pHddCtx) {
hddLog(<API key>,"%s: HDD context is Null",__func__);
return 0;
}
while(!shutdown)
{
// This implements the execution model algorithm
retWaitStatus = <API key>(pSchedContext->rxWaitQueue,
test_bit(RX_POST_EVENT_MASK, &pSchedContext->rxEventFlag) ||
test_bit(<API key>, &pSchedContext->rxEventFlag));
if(retWaitStatus == -ERESTARTSYS)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: <API key> returned -ERESTARTSYS", __func__);
break;
}
clear_bit(RX_POST_EVENT_MASK, &pSchedContext->rxEventFlag);
while(1)
{
if(test_bit(<API key>, &pSchedContext->rxEventFlag))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: RX thread signaled to shutdown", __func__);
shutdown = VOS_TRUE;
/* Check for any Suspend Indication */
if (test_and_clear_bit(<API key>,
&pSchedContext->rxEventFlag))
{
/* Unblock anyone waiting on suspend */
complete(&pHddCtx->rx_sus_event_var);
}
break;
}
// Check the SYS queue first
if (!vos_is_mq_empty(&pSchedContext->sysRxMq))
{
// Service the SYS message queue
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Servicing the VOS SYS RX Message queue",__func__);
pMsgWrapper = vos_mq_get(&pSchedContext->sysRxMq);
if (pMsgWrapper == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: pMsgWrapper is NULL", __func__);
VOS_ASSERT(0);
break;
}
vStatus = sysRxProcessMsg( pSchedContext->pVContext,
pMsgWrapper->pVosMsg);
if (!<API key>(vStatus))
{
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: Issue Processing TX SYS message",__func__);
}
// return message to the Core
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
continue;
}
// Check now the TL queue
if (!vos_is_mq_empty(&pSchedContext->tlRxMq))
{
// Service the TL message queue
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Servicing the VOS TL RX Message queue",__func__);
pMsgWrapper = vos_mq_get(&pSchedContext->tlRxMq);
if (pMsgWrapper == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: pMsgWrapper is NULL", __func__);
VOS_ASSERT(0);
break;
}
vStatus = WLANTL_RxProcessMsg( pSchedContext->pVContext,
pMsgWrapper->pVosMsg);
if (!<API key>(vStatus))
{
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: Issue Processing RX TL message",__func__);
}
// return message to the Core
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
continue;
}
// Check the WDI queue
if (!vos_is_mq_empty(&pSchedContext->wdiRxMq))
{
wpt_msg *pWdiMsg;
pMsgWrapper = vos_mq_get(&pSchedContext->wdiRxMq);
if ((NULL == pMsgWrapper) || (NULL == pMsgWrapper->pVosMsg))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: wdiRxMq message is NULL", __func__);
VOS_BUG(0);
// we won't return this wrapper since it is corrupt
}
else
{
pWdiMsg = (wpt_msg *)pMsgWrapper->pVosMsg->bodyptr;
if ((NULL == pWdiMsg) || (NULL == pWdiMsg->callback))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: WDI Msg or callback is NULL", __func__);
VOS_BUG(0);
}
else
{
// invoke the message handler
pWdiMsg->callback(pWdiMsg);
}
// return message to the Core
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
}
continue;
}
/* Check for any Suspend Indication */
if (test_and_clear_bit(<API key>,
&pSchedContext->rxEventFlag))
{
spin_lock(&pSchedContext->RxThreadLock);
/* Rx Thread Suspended */
complete(&pHddCtx->rx_sus_event_var);
INIT_COMPLETION(pSchedContext->ResumeRxEvent);
spin_unlock(&pSchedContext->RxThreadLock);
/* Wait for Resume Indication */
<API key>(&pSchedContext->ResumeRxEvent);
}
break; //All queues are empty now
} // while message loop processing
} // while TRUE
// If we get here the RX thread must exit
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: RX Thread exiting!!!!", __func__);
complete_and_exit(&pSchedContext->RxShutdown, 0);
} /* VosRxThread() */
VOS_STATUS vos_sched_close ( v_PVOID_t pVosContext )
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: invoked", __func__);
if (gpVosSchedContext == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: gpVosSchedContext == NULL",__func__);
return <API key>;
}
// shut down MC Thread
set_bit(<API key>, &gpVosSchedContext->mcEventFlag);
set_bit(MC_POST_EVENT_MASK, &gpVosSchedContext->mcEventFlag);
<API key>(&gpVosSchedContext->mcWaitQueue);
//Wait for MC to exit
wait_for_completion(&gpVosSchedContext->McShutdown);
gpVosSchedContext->McThread = 0;
// shut down TX Thread
set_bit(<API key>, &gpVosSchedContext->txEventFlag);
set_bit(TX_POST_EVENT_MASK, &gpVosSchedContext->txEventFlag);
<API key>(&gpVosSchedContext->txWaitQueue);
//Wait for TX to exit
wait_for_completion(&gpVosSchedContext->TxShutdown);
gpVosSchedContext->TxThread = 0;
// shut down RX Thread
set_bit(<API key>, &gpVosSchedContext->rxEventFlag);
set_bit(RX_POST_EVENT_MASK, &gpVosSchedContext->rxEventFlag);
<API key>(&gpVosSchedContext->rxWaitQueue);
//Wait for RX to exit
wait_for_completion(&gpVosSchedContext->RxShutdown);
gpVosSchedContext->RxThread = 0;
//Clean up message queues of TX and MC thread
<API key>(gpVosSchedContext);
<API key>(gpVosSchedContext);
<API key>(gpVosSchedContext);
//Deinit all the queues
<API key>(gpVosSchedContext);
return VOS_STATUS_SUCCESS;
} /* vox_sched_close() */
VOS_STATUS vos_watchdog_close ( v_PVOID_t pVosContext )
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: vos_watchdog closing now", __func__);
if (<API key> == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: <API key> is NULL",__func__);
return <API key>;
}
set_bit(<API key>, &<API key>->wdEventFlag);
set_bit(WD_POST_EVENT_MASK, &<API key>->wdEventFlag);
<API key>(&<API key>->wdWaitQueue);
//Wait for Watchdog thread to exit
wait_for_completion(&<API key>->WdShutdown);
return VOS_STATUS_SUCCESS;
} /* vos_watchdog_close() */
VOS_STATUS vos_sched_init_mqs ( pVosSchedContext pSchedContext )
{
VOS_STATUS vStatus = VOS_STATUS_SUCCESS;
// Now intialize all the message queues
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Initializing the WDA MC Message queue",__func__);
vStatus = vos_mq_init(&pSchedContext->wdaMcMq);
if (! <API key>(vStatus))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to init WDA MC Message queue",__func__);
VOS_ASSERT(0);
return vStatus;
}
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Initializing the PE MC Message queue",__func__);
vStatus = vos_mq_init(&pSchedContext->peMcMq);
if (! <API key>(vStatus))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to init PE MC Message queue",__func__);
VOS_ASSERT(0);
return vStatus;
}
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Initializing the SME MC Message queue", __func__);
vStatus = vos_mq_init(&pSchedContext->smeMcMq);
if (! <API key>(vStatus))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to init SME MC Message queue",__func__);
VOS_ASSERT(0);
return vStatus;
}
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Initializing the TL MC Message queue",__func__);
vStatus = vos_mq_init(&pSchedContext->tlMcMq);
if (! <API key>(vStatus))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to init TL MC Message queue",__func__);
VOS_ASSERT(0);
return vStatus;
}
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Initializing the SYS MC Message queue",__func__);
vStatus = vos_mq_init(&pSchedContext->sysMcMq);
if (! <API key>(vStatus))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to init SYS MC Message queue",__func__);
VOS_ASSERT(0);
return vStatus;
}
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Initializing the WDI MC Message queue",__func__);
vStatus = vos_mq_init(&pSchedContext->wdiMcMq);
if (! <API key>(vStatus))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to init WDI MC Message queue",__func__);
VOS_ASSERT(0);
return vStatus;
}
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Initializing the TL Tx Message queue",__func__);
vStatus = vos_mq_init(&pSchedContext->tlTxMq);
if (! <API key>(vStatus))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to init TL TX Message queue",__func__);
VOS_ASSERT(0);
return vStatus;
}
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Initializing the TL Rx Message queue",__func__);
vStatus = vos_mq_init(&pSchedContext->tlRxMq);
if (! <API key>(vStatus))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to init TL RX Message queue",__func__);
VOS_ASSERT(0);
return vStatus;
}
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Initializing the WDI Tx Message queue",__func__);
vStatus = vos_mq_init(&pSchedContext->wdiTxMq);
if (! <API key>(vStatus))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to init WDI TX Message queue",__func__);
VOS_ASSERT(0);
return vStatus;
}
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Initializing the WDI Rx Message queue",__func__);
vStatus = vos_mq_init(&pSchedContext->wdiRxMq);
if (! <API key>(vStatus))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to init WDI RX Message queue",__func__);
VOS_ASSERT(0);
return vStatus;
}
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Initializing the SYS Tx Message queue",__func__);
vStatus = vos_mq_init(&pSchedContext->sysTxMq);
if (! <API key>(vStatus))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to init SYS TX Message queue",__func__);
VOS_ASSERT(0);
return vStatus;
}
vStatus = vos_mq_init(&pSchedContext->sysRxMq);
if (! <API key>(vStatus))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Failed to init SYS RX Message queue",__func__);
VOS_ASSERT(0);
return vStatus;
}
return VOS_STATUS_SUCCESS;
} /* vos_sched_init_mqs() */
void <API key> ( pVosSchedContext pSchedContext )
{
// Now de-intialize all message queues
// MC WDA
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s De-Initializing the WDA MC Message queue",__func__);
vos_mq_deinit(&pSchedContext->wdaMcMq);
//MC PE
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s De-Initializing the PE MC Message queue",__func__);
vos_mq_deinit(&pSchedContext->peMcMq);
//MC SME
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s De-Initializing the SME MC Message queue",__func__);
vos_mq_deinit(&pSchedContext->smeMcMq);
//MC TL
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s De-Initializing the TL MC Message queue",__func__);
vos_mq_deinit(&pSchedContext->tlMcMq);
//MC SYS
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s De-Initializing the SYS MC Message queue",__func__);
vos_mq_deinit(&pSchedContext->sysMcMq);
// MC WDI
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s De-Initializing the WDI MC Message queue",__func__);
vos_mq_deinit(&pSchedContext->wdiMcMq);
//Tx TL
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s De-Initializing the TL Tx Message queue",__func__);
vos_mq_deinit(&pSchedContext->tlTxMq);
//Rx TL
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s De-Initializing the TL Rx Message queue",__func__);
vos_mq_deinit(&pSchedContext->tlRxMq);
//Tx WDI
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: DeInitializing the WDI Tx Message queue",__func__);
vos_mq_deinit(&pSchedContext->wdiTxMq);
//Rx WDI
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: DeInitializing the WDI Rx Message queue",__func__);
vos_mq_deinit(&pSchedContext->wdiRxMq);
//Tx SYS
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: DeInitializing the SYS Tx Message queue",__func__);
vos_mq_deinit(&pSchedContext->sysTxMq);
//Rx SYS
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: DeInitializing the SYS Rx Message queue",__func__);
vos_mq_deinit(&pSchedContext->sysRxMq);
} /* <API key>() */
void <API key> ( pVosSchedContext pSchedContext )
{
pVosMsgWrapper pMsgWrapper = NULL;
pVosContextType vosCtx;
/*
** Here each of the MC thread MQ shall be drained and returned to the
** Core. Before returning a wrapper to the Core, the VOS message shall be
** freed first
*/
VOS_TRACE( VOS_MODULE_ID_VOSS,
<API key>,
("Flushing the MC Thread message queue") );
if (NULL == pSchedContext)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: pSchedContext is NULL", __func__);
return;
}
vosCtx = (pVosContextType)(pSchedContext->pVContext);
if (NULL == vosCtx)
{
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: vosCtx is NULL", __func__);
return;
}
/* Flush the SYS Mq */
while( NULL != (pMsgWrapper = vos_mq_get(&pSchedContext->sysMcMq) ))
{
VOS_TRACE( VOS_MODULE_ID_VOSS,
<API key>,
"%s: Freeing MC SYS message type %d ",__func__,
pMsgWrapper->pVosMsg->type );
sysMcFreeMsg(pSchedContext->pVContext, pMsgWrapper->pVosMsg);
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
}
/* Flush the WDA Mq */
while( NULL != (pMsgWrapper = vos_mq_get(&pSchedContext->wdaMcMq) ))
{
if(pMsgWrapper->pVosMsg != NULL)
{
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: Freeing MC WDA MSG message type %d",
__func__, pMsgWrapper->pVosMsg->type );
if (pMsgWrapper->pVosMsg->bodyptr) {
vos_mem_free((v_VOID_t*)pMsgWrapper->pVosMsg->bodyptr);
}
pMsgWrapper->pVosMsg->bodyptr = NULL;
pMsgWrapper->pVosMsg->bodyval = 0;
pMsgWrapper->pVosMsg->type = 0;
}
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
}
/* Flush the WDI Mq */
while( NULL != (pMsgWrapper = vos_mq_get(&pSchedContext->wdiMcMq) ))
{
if(pMsgWrapper->pVosMsg != NULL)
{
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: Freeing MC WDI MSG message type %d",
__func__, pMsgWrapper->pVosMsg->type );
/* MSG body pointer is not NULL
* and MSG type is 0
* This MSG is not posted by SMD NOTIFY
* We have to free MSG body */
if ((pMsgWrapper->pVosMsg->bodyptr) && (!pMsgWrapper->pVosMsg->type))
{
vos_mem_free((v_VOID_t*)pMsgWrapper->pVosMsg->bodyptr);
}
/* MSG body pointer is not NULL
* and MSG type is not 0
* This MSG is posted by SMD NOTIFY
* We should not free MSG body */
else if ((pMsgWrapper->pVosMsg->bodyptr) && pMsgWrapper->pVosMsg->type)
{
VOS_TRACE( VOS_MODULE_ID_VOSS, <API key>,
"%s: SMD NOTIFY MSG, do not free body",
__func__);
}
pMsgWrapper->pVosMsg->bodyptr = NULL;
pMsgWrapper->pVosMsg->bodyval = 0;
pMsgWrapper->pVosMsg->type = 0;
}
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
}
/* Flush the PE Mq */
while( NULL != (pMsgWrapper = vos_mq_get(&pSchedContext->peMcMq) ))
{
VOS_TRACE( VOS_MODULE_ID_VOSS,
<API key>,
"%s: Freeing MC PE MSG message type %d",__func__,
pMsgWrapper->pVosMsg->type );
peFreeMsg(vosCtx->pMACContext, (tSirMsgQ*)pMsgWrapper->pVosMsg);
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
}
/* Flush the SME Mq */
while( NULL != (pMsgWrapper = vos_mq_get(&pSchedContext->smeMcMq) ))
{
VOS_TRACE( VOS_MODULE_ID_VOSS,
<API key>,
"%s: Freeing MC SME MSG message type %d", __func__,
pMsgWrapper->pVosMsg->type );
sme_FreeMsg(vosCtx->pMACContext, pMsgWrapper->pVosMsg);
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
}
/* Flush the TL Mq */
while( NULL != (pMsgWrapper = vos_mq_get(&pSchedContext->tlMcMq) ))
{
VOS_TRACE( VOS_MODULE_ID_VOSS,
<API key>,
"%s: Freeing MC TL message type %d",__func__,
pMsgWrapper->pVosMsg->type );
WLANTL_McFreeMsg(pSchedContext->pVContext, pMsgWrapper->pVosMsg);
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
}
} /* <API key>() */
void <API key> ( pVosSchedContext pSchedContext )
{
pVosMsgWrapper pMsgWrapper = NULL;
/*
** Here each of the TX thread MQ shall be drained and returned to the
** Core. Before returning a wrapper to the Core, the VOS message shall
** be freed first
*/
VOS_TRACE( VOS_MODULE_ID_VOSS,
<API key>,
"%s: Flushing the TX Thread message queue",__func__);
if (NULL == pSchedContext)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: pSchedContext is NULL", __func__);
return;
}
/* Flush the SYS Mq */
while( NULL != (pMsgWrapper = vos_mq_get(&pSchedContext->sysTxMq) ))
{
VOS_TRACE( VOS_MODULE_ID_VOSS,
<API key>,
"%s: Freeing TX SYS message type %d",__func__,
pMsgWrapper->pVosMsg->type );
sysTxFreeMsg(pSchedContext->pVContext, pMsgWrapper->pVosMsg);
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
}
/* Flush the TL Mq */
while( NULL != (pMsgWrapper = vos_mq_get(&pSchedContext->tlTxMq) ))
{
VOS_TRACE( VOS_MODULE_ID_VOSS,
<API key>,
"%s: Freeing TX TL MSG message type %d",__func__,
pMsgWrapper->pVosMsg->type );
WLANTL_TxFreeMsg(pSchedContext->pVContext, pMsgWrapper->pVosMsg);
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
}
/* Flush the WDI Mq */
while( NULL != (pMsgWrapper = vos_mq_get(&pSchedContext->wdiTxMq) ))
{
VOS_TRACE( VOS_MODULE_ID_VOSS,
<API key>,
"%s: Freeing TX WDI MSG message type %d",__func__,
pMsgWrapper->pVosMsg->type );
sysTxFreeMsg(pSchedContext->pVContext, pMsgWrapper->pVosMsg);
vos_core_return_msg(pSchedContext->pVContext, pMsgWrapper);
}
} /* <API key>() */
void <API key> ( pVosSchedContext pSchedContext )
{
pVosMsgWrapper pMsgWrapper = NULL;
/*
** Here each of the RX thread MQ shall be drained and returned to the
** Core. Before returning a wrapper to the Core, the VOS message shall
** be freed first
*/
VOS_TRACE( VOS_MODULE_ID_VOSS,
<API key>,
"%s: Flushing the RX Thread message queue",__func__);
if (NULL == pSchedContext)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: pSchedContext is NULL", __func__);
return;
}
while( NULL != (pMsgWrapper = vos_mq_get(&pSchedContext->wdiRxMq) ))
{
VOS_TRACE( VOS_MODULE_ID_VOSS,
<API key>,
"%s: Freeing RX WDI MSG message type %d",__func__,
pMsgWrapper->pVosMsg->type );
sysTxFreeMsg(pSchedContext->pVContext, pMsgWrapper->pVosMsg);
}
while( NULL != (pMsgWrapper = vos_mq_get(&pSchedContext->tlRxMq) ))
{
VOS_TRACE( VOS_MODULE_ID_VOSS,
<API key>,
"%s: Freeing RX TL MSG message type %d",__func__,
pMsgWrapper->pVosMsg->type );
sysTxFreeMsg(pSchedContext->pVContext, pMsgWrapper->pVosMsg);
}
while( NULL != (pMsgWrapper = vos_mq_get(&pSchedContext->sysRxMq) ))
{
VOS_TRACE( VOS_MODULE_ID_VOSS,
<API key>,
"%s: Freeing RX SYS MSG message type %d",__func__,
pMsgWrapper->pVosMsg->type );
sysTxFreeMsg(pSchedContext->pVContext, pMsgWrapper->pVosMsg);
}
}/* <API key>() */
int <API key>(int threadID)
{
// Make sure that Vos Scheduler context has been initialized
VOS_ASSERT( NULL != gpVosSchedContext);
if (gpVosSchedContext == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: gpVosSchedContext == NULL",__func__);
return 0;
}
return ((gpVosSchedContext->TxThread) && (threadID == gpVosSchedContext->TxThread->pid));
}
int <API key>(int threadID)
{
// Make sure that Vos Scheduler context has been initialized
VOS_ASSERT( NULL != gpVosSchedContext);
if (gpVosSchedContext == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: gpVosSchedContext == NULL",__func__);
return 0;
}
return ((gpVosSchedContext->RxThread) && (threadID == gpVosSchedContext->RxThread->pid));
}
pVosSchedContext get_vos_sched_ctxt(void)
{
//Make sure that Vos Scheduler context has been initialized
if (gpVosSchedContext == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: gpVosSchedContext == NULL",__func__);
}
return (gpVosSchedContext);
}
pVosWatchdogContext <API key>(void)
{
//Make sure that Vos Scheduler context has been initialized
if (<API key> == NULL)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: <API key> == NULL",__func__);
}
return (<API key>);
}
/**
@brief <API key>()
This function is called to shutdown WLAN driver during SSR.
Adapters are disabled, and the watchdog task will be signalled
to shutdown WLAN driver.
@param
NONE
@return
VOS_STATUS_SUCCESS - Operation completed successfully.
<API key> - Operation failed.
*/
VOS_STATUS <API key>(void)
{
v_CONTEXT_t pVosContext = NULL;
hdd_context_t *pHddCtx = NULL;
if (NULL == <API key>)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Watchdog not enabled. LOGP ignored.", __func__);
return <API key>;
}
if (<API key>->isFatalError)
{
/* If we hit this, it means wlan driver is in bad state and needs
* driver unload and load.
*/
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Driver in bad state and need unload and load", __func__);
return <API key>;
}
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: WLAN driver is shutting down ", __func__);
pVosContext = <API key>(VOS_MODULE_ID_HDD, NULL);
pHddCtx = (hdd_context_t *)vos_get_context(VOS_MODULE_ID_HDD, pVosContext );
if (NULL == pHddCtx)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Invalid HDD Context", __func__);
return <API key>;
}
/* Take the lock here */
spin_lock(&<API key>->wdLock);
/* reuse the existing 'reset in progress' */
if (<API key>->resetInProgress)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Shutdown already in Progress. Ignoring signaling Watchdog",
__func__);
/* Release the lock here */
spin_unlock(&<API key>->wdLock);
return <API key>;
}
/* reuse the existing 'logp in progress', eventhough it is not
* exactly the same */
else if (pHddCtx->isLogpInProgress)
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: shutdown/re-init already in Progress. Ignoring signaling Watchdog",
__func__);
/* Release the lock here */
spin_unlock(&<API key>->wdLock);
return <API key>;
}
if (<API key>(pHddCtx))
{
VOS_TRACE(VOS_MODULE_ID_VOSS, <API key>,
"%s: Load/unload in Progress. Ignoring signaling Watchdog",
__func__);
/* wcnss has crashed, and SSR has alredy been started by Kernel driver.
* So disable SSR from WLAN driver */
<API key>( HDD_SSR_DISABLED );
/* Release the lock here before returning */
spin_unlock(&<API key>->wdLock);
return <API key>;
}
/* Set the flags so that all commands from userspace get blocked right away */
<API key>(VOS_MODULE_ID_VOSS, TRUE);
<API key>(VOS_MODULE_ID_VOSS, FALSE);
pHddCtx->isLogpInProgress = TRUE;
/* Release the lock here */
spin_unlock(&<API key>->wdLock);
/* Update Riva Reset Statistics */
pHddCtx->hddRivaResetStats++;
#ifdef <API key>
if(VOS_STATUS_SUCCESS != <API key>())
{
VOS_ASSERT(0);
}
#endif
set_bit(<API key>, &<API key>->wdEventFlag);
set_bit(WD_POST_EVENT_MASK, &<API key>->wdEventFlag);
<API key>(&<API key>->wdWaitQueue);
return VOS_STATUS_SUCCESS;
}
/**
@brief <API key>()
This function is called to re-initialize WLAN driver, and this is
called when Riva SS reboots.
@param
NONE
@return
VOS_STATUS_SUCCESS - Operation completed successfully.
<API key> - Operation failed.
*/
VOS_STATUS <API key>(void)
{
/* watchdog task is still running, it is not closed in shutdown */
set_bit(<API key>, &<API key>->wdEventFlag);
set_bit(WD_POST_EVENT_MASK, &<API key>->wdEventFlag);
<API key>(&<API key>->wdWaitQueue);
return VOS_STATUS_SUCCESS;
}
/**
@brief vos_ssr_protect()
This function is called to keep track of active driver entry points
@param
caller_func - Name of calling function.
@return
void
*/
void vos_ssr_protect(const char *caller_func)
{
int count;
count = atomic_inc_return(&<API key>);
VOS_TRACE(VOS_MODULE_ID_HDD, <API key>,
"%s: ENTRY ACTIVE %d", caller_func, count);
}
/**
@brief vos_ssr_unprotect()
@param
caller_func - Name of calling function.
@return
void
*/
void vos_ssr_unprotect(const char *caller_func)
{
int count;
count = atomic_dec_return(&<API key>);
VOS_TRACE(VOS_MODULE_ID_HDD, <API key>,
"%s: ENTRY INACTIVE %d", caller_func, count);
} |
#include <gio/gio.h>
#include <glib/gi18n.h>
#include "conf.h"
#include "notify.h"
#include "tr-prefs.h"
#include "util.h"
#define <API key> "org.freedesktop.Notifications"
#define <API key> "/org/freedesktop/Notifications"
#define <API key> "org.freedesktop.Notifications"
static GDBusProxy *proxy = NULL;
static GHashTable *<API key> = NULL;
static gboolean <API key> = FALSE;
typedef struct _TrNotification
{
guint id;
TrCore * core;
int torrent_id;
}
TrNotification;
static void
<API key> (gpointer data)
{
TrNotification * n = data;
if (n->core)
g_object_unref (G_OBJECT (n->core));
g_free (n);
}
static void
<API key> (GObject * source,
GAsyncResult * res,
gpointer user_data UNUSED)
{
int i;
char ** caps;
GVariant * result;
result = <API key> (G_DBUS_PROXY (source), res, NULL);
if (!result || !<API key> (result, G_VARIANT_TYPE ("(as)")))
{
if (result)
g_variant_unref (result);
return;
}
g_variant_get (result, "(^a&s)", &caps);
for (i=0; caps[i]; i++)
{
if (g_strcmp0 (caps[i], "actions") == 0)
{
<API key> = TRUE;
break;
}
}
g_free (caps);
g_variant_unref (result);
}
static void
g_signal_callback (GDBusProxy * proxy UNUSED,
char * sender_name UNUSED,
char * signal_name,
GVariant * params,
gpointer user_data UNUSED)
{
guint id;
TrNotification * n;
g_return_if_fail (<API key> (params, G_VARIANT_TYPE ("(u*)")));
g_variant_get (params, "(u*)", &id, NULL);
n = g_hash_table_lookup (<API key>,
GINT_TO_POINTER ((int *) &id));
if (n == NULL)
return;
if (g_strcmp0 (signal_name, "NotificationClosed") == 0)
{
g_hash_table_remove (<API key>,
GINT_TO_POINTER ((int *) &n->id));
}
else if (g_strcmp0 (signal_name, "ActionInvoked") == 0 &&
<API key> (params, G_VARIANT_TYPE ("(us)")))
{
char * action;
tr_torrent * tor;
tor = <API key> (n->core, n->torrent_id);
if (tor == NULL)
return;
g_variant_get (params, "(u&s)", NULL, &action);
if (g_strcmp0 (action, "folder") == 0)
{
<API key> (n->core, n->torrent_id);
}
else if (g_strcmp0 (action, "file") == 0)
{
const tr_info * inf = tr_torrentInfo (tor);
const char * dir = <API key> (tor);
char * path = g_build_filename (dir, inf->files[0].name, NULL);
gtr_open_file (path);
g_free (path);
}
}
}
static void
<API key> (GObject * source UNUSED,
GAsyncResult * res,
gpointer user_data UNUSED)
{
proxy = <API key> (res, NULL);
if (proxy == NULL)
{
g_warning ("Failed to create proxy for %s", <API key>);
return;
}
g_signal_connect (proxy, "g-signal",
G_CALLBACK (g_signal_callback), NULL);
g_dbus_proxy_call (proxy,
"GetCapabilities",
g_variant_new ("()"),
<API key>, -1, NULL,
<API key>, NULL);
}
void
gtr_notify_init (void)
{
<API key> = <API key> (g_int_hash, g_int_equal,
NULL, <API key>);
<API key> (G_BUS_TYPE_SESSION,
<API key>,
NULL,
<API key>,
<API key>,
<API key>,
NULL, <API key>, NULL);
}
static void
notify_callback (GObject * source,
GAsyncResult * res,
gpointer user_data)
{
GVariant * result;
TrNotification * n = user_data;
result = <API key> (G_DBUS_PROXY (source), res, NULL);
if (!result || !<API key> (result, G_VARIANT_TYPE ("(u)")))
{
if (result)
g_variant_unref (result);
<API key> (n);
return;
}
g_variant_get (result, "(u)", &n->id);
g_hash_table_insert (<API key>,
GINT_TO_POINTER ((int *)&n->id), n);
g_variant_unref (result);
}
void
<API key> (TrCore * core, int torrent_id)
{
GVariantBuilder actions_builder;
TrNotification * n;
tr_torrent * tor;
const char * cmd = gtr_pref_string_get (<API key>);
if (gtr_pref_flag_get (<API key>))
<API key> (cmd, NULL);
if (!gtr_pref_flag_get (<API key>))
return;
g_return_if_fail (G_IS_DBUS_PROXY (proxy));
tor = <API key> (core, torrent_id);
n = g_new0 (TrNotification, 1);
n->core = g_object_ref (G_OBJECT (core));
n->torrent_id = torrent_id;
<API key> (&actions_builder, G_VARIANT_TYPE ("as"));
if (<API key>)
{
const tr_info * inf = tr_torrentInfo (tor);
if (inf->fileCount == 1)
{
<API key> (&actions_builder, "s", "file");
<API key> (&actions_builder, "s", _("Open File"));
}
else
{
<API key> (&actions_builder, "s", "folder");
<API key> (&actions_builder, "s", _("Open Folder"));
}
}
g_dbus_proxy_call (proxy,
"Notify",
g_variant_new ("(susssasa{sv}i)",
"Transmission", n->id, "transmission",
_("Torrent Complete"),
tr_torrentName (tor),
&actions_builder, NULL, -1),
<API key>, -1, NULL,
notify_callback, n);
}
void
<API key> (const char * name)
{
TrNotification * n;
g_return_if_fail (G_IS_DBUS_PROXY (proxy));
if (!gtr_pref_flag_get (<API key>))
return;
n = g_new0 (TrNotification, 1);
g_dbus_proxy_call (proxy,
"Notify",
g_variant_new ("(susssasa{sv}i)",
"Transmission", 0, "transmission",
_("Torrent Added"), name,
NULL, NULL, -1),
<API key>, -1, NULL,
notify_callback, n);
} |
class Hello
{
public static void main (String [] args)
{
System.out.println("Hello World") ;
}
} |
({"displayName":"\u091c\u093e\u092a\u093e\u0928\u0940 \u092f\u0947\u0928","symbol":"\xa5"}); |
# <API key>: GPL-2.0+
# Wolfgang Denk, DENX Software Engineering, wd@denx.de.
# Rick Chen, Andes Technology Corporation <rick@andestech.com>
obj-$(CONFIG_CMD_BOOTM) += bootm.o
obj-$(CONFIG_CMD_GO) += boot.o
obj-y += cache.o
obj-y += interrupts.o |
<?php
/**
* WordPress Installer
*
* @package WordPress
* @subpackage Administration
*/
// Sanity check.
if ( false ) {
?>
<!DOCTYPE html>
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Error: PHP is not running</title>
</head>
<body class="wp-core-ui">
<h1 id="logo"><a href="https://wordpress.org/">WordPress</a></h1>
<h2>Error: PHP is not running</h2>
<p>WordPress requires that your web server is running PHP. Your server does not have PHP installed, or PHP is turned off.</p>
</body>
</html>
<?php
}
/**
* We are installing WordPress.
*
* @since 1.5.1
* @var bool
*/
define( 'WP_INSTALLING', true );
/** Load WordPress Bootstrap */
require_once(dirname(dirname(__FILE__)) . '/wp-load.php');
/** Load WordPress Administration Upgrade API */
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
/** Load WordPress Translation Install API */
require_once(ABSPATH . 'wp-admin/includes/translation-install.php');
/** Load wpdb */
require_once(ABSPATH . WPINC . '/wp-db.php');
nocache_headers();
$step = isset( $_GET['step'] ) ? (int) $_GET['step'] : 0;
/**
* Display install header.
*
* @since 2.5.0
*/
function display_header( $body_classes = '' ) {
header( 'Content-Type: text/html; charset=utf-8' );
if ( is_rtl() ) {
$body_classes .= 'rtl';
}
if ( $body_classes ) {
$body_classes = ' ' . $body_classes;
}
?>
<!DOCTYPE html>
<html xmlns="http:
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php _e( 'WordPress › Installation' ); ?></title>
<?php
wp_admin_css( 'install', true );
?>
</head>
<body class="wp-core-ui<?php echo $body_classes ?>">
<h1 id="logo"><a href="<?php echo esc_url( __( 'https://wordpress.org/' ) ); ?>" tabindex="-1"><?php _e( 'WordPress' ); ?></a></h1>
<?php
} // end display_header()
/**
* Display installer setup form.
*
* @since 2.8.0
*/
function display_setup_form( $error = null ) {
global $wpdb;
$sql = $wpdb->prepare( "SHOW TABLES LIKE %s", $wpdb->esc_like( $wpdb->users ) );
$user_table = ( $wpdb->get_var( $sql ) != null );
// Ensure that Blogs appear in search engines by default.
$blog_public = 1;
if ( isset( $_POST['weblog_title'] ) ) {
$blog_public = isset( $_POST['blog_public'] );
}
$weblog_title = isset( $_POST['weblog_title'] ) ? trim( wp_unslash( $_POST['weblog_title'] ) ) : '';
$user_name = isset($_POST['user_name']) ? trim( wp_unslash( $_POST['user_name'] ) ) : '';
$admin_email = isset( $_POST['admin_email'] ) ? trim( wp_unslash( $_POST['admin_email'] ) ) : '';
if ( ! is_null( $error ) ) {
?>
<p class="message"><?php echo $error; ?></p>
<?php } ?>
<form id="setup" method="post" action="install.php?step=2" novalidate="novalidate">
<table class="form-table">
<tr>
<th scope="row"><label for="weblog_title"><?php _e( 'Site Title' ); ?></label></th>
<td><input name="weblog_title" type="text" id="weblog_title" size="25" value="<?php echo esc_attr( $weblog_title ); ?>" /></td>
</tr>
<tr>
<th scope="row"><label for="user_login"><?php _e('Username'); ?></label></th>
<td>
<?php
if ( $user_table ) {
_e('User(s) already exists.');
echo '<input name="user_name" type="hidden" value="admin" />';
} else {
?><input name="user_name" type="text" id="user_login" size="25" value="<?php echo esc_attr( sanitize_user( $user_name, true ) ); ?>" />
<p><?php _e( 'Usernames can have only alphanumeric characters, spaces, underscores, hyphens, periods and the @ symbol.' ); ?></p>
<?php
} ?>
</td>
</tr>
<?php if ( ! $user_table ) : ?>
<tr>
<th scope="row">
<label for="pass1"><?php _e('Password, twice'); ?></label>
<p><?php _e('A password will be automatically generated for you if you leave this blank.'); ?></p>
</th>
<td>
<input name="admin_password" type="password" id="pass1" size="25" value="" />
<p><input name="admin_password2" type="password" id="pass2" size="25" value="" /></p>
<div id="<API key>"><?php _e('Strength indicator'); ?></div>
<p><?php _e('Hint: The password should be at least seven characters long. To make it stronger, use upper and lower case letters, numbers, and symbols like ! " ? $ % ^ & ).'); ?></p>
</td>
</tr>
<?php endif; ?>
<tr>
<th scope="row"><label for="admin_email"><?php _e( 'Your E-mail' ); ?></label></th>
<td><input name="admin_email" type="email" id="admin_email" size="25" value="<?php echo esc_attr( $admin_email ); ?>" />
<p><?php _e( 'Double-check your email address before continuing.' ); ?></p></td>
</tr>
<tr>
<th scope="row"><label for="blog_public"><?php _e( 'Privacy' ); ?></label></th>
<td colspan="2"><label><input type="checkbox" name="blog_public" id="blog_public" value="1" <?php checked( $blog_public ); ?> /> <?php _e( 'Allow search engines to index this site.' ); ?></label></td>
</tr>
</table>
<p class="step"><input type="submit" name="Submit" value="<?php esc_attr_e( 'Install WordPress' ); ?>" class="button button-large" /></p>
<input type="hidden" name="language" value="<?php echo isset( $_REQUEST['language'] ) ? esc_attr( $_REQUEST['language'] ) : ''; ?>" />
</form>
<?php
} // end display_setup_form()
// Let's check to make sure WP isn't already installed.
if ( is_blog_installed() ) {
display_header();
die( '<h1>' . __( 'Already Installed' ) . '</h1><p>' . __( 'You appear to have already installed WordPress. To reinstall please clear your old database tables first.' ) . '</p><p class="step"><a href="../wp-login.php" class="button button-large">' . __( 'Log In' ) . '</a></p></body></html>' );
}
$php_version = phpversion();
$mysql_version = $wpdb->db_version();
$php_compat = version_compare( $php_version, $<API key>, '>=' );
$mysql_compat = version_compare( $mysql_version, $<API key>, '>=' ) || file_exists( WP_CONTENT_DIR . '/db.php' );
if ( !$mysql_compat && !$php_compat )
$compat = sprintf( __( 'You cannot install because <a href="http://codex.wordpress.org/Version_%1$s">WordPress %1$s</a> requires PHP version %2$s or higher and MySQL version %3$s or higher. You are running PHP version %4$s and MySQL version %5$s.' ), $wp_version, $<API key>, $<API key>, $php_version, $mysql_version );
elseif ( !$php_compat )
$compat = sprintf( __( 'You cannot install because <a href="http://codex.wordpress.org/Version_%1$s">WordPress %1$s</a> requires PHP version %2$s or higher. You are running version %3$s.' ), $wp_version, $<API key>, $php_version );
elseif ( !$mysql_compat )
$compat = sprintf( __( 'You cannot install because <a href="http://codex.wordpress.org/Version_%1$s">WordPress %1$s</a> requires MySQL version %2$s or higher. You are running version %3$s.' ), $wp_version, $<API key>, $mysql_version );
if ( !$mysql_compat || !$php_compat ) {
display_header();
die( '<h1>' . __( 'Insufficient Requirements' ) . '</h1><p>' . $compat . '</p></body></html>' );
}
if ( ! is_string( $wpdb->base_prefix ) || '' === $wpdb->base_prefix ) {
display_header();
die( '<h1>' . __( 'Configuration Error' ) . '</h1><p>' . __( 'Your <code>wp-config.php</code> file has an empty database table prefix, which is not supported.' ) . '</p></body></html>' );
}
$language = '';
if ( ! empty( $_REQUEST['language'] ) ) {
$language = preg_replace( '/[^a-zA-Z_]/', '', $_REQUEST['language'] );
} elseif ( isset( $GLOBALS['wp_local_package'] ) ) {
$language = $GLOBALS['wp_local_package'];
}
switch($step) {
case 0: // Step 0
if ( <API key>() && empty( $language ) && ( $languages = <API key>() ) ) {
display_header( 'language-chooser' );
echo '<form id="setup" method="post" action="?step=1">';
<API key>( $languages );
echo '</form>';
break;
}
// Deliberately fall through if we can't reach the translations API.
case 1: // Step 1, direct link or from language chooser.
if ( ! empty( $language ) ) {
$loaded_language = <API key>( $language );
if ( $loaded_language ) {
<API key>( $loaded_language );
$GLOBALS['wp_locale'] = new WP_Locale();
}
}
display_header();
?>
<h1><?php _ex( 'Welcome', 'Howdy' ); ?></h1>
<p><?php _e( 'Welcome to the famous five-minute WordPress installation process! Just fill in the information below and you’ll be on your way to using the most extendable and powerful personal publishing platform in the world.' ); ?></p>
<h1><?php _e( 'Information needed' ); ?></h1>
<p><?php _e( 'Please provide the following information. Don’t worry, you can always change these settings later.' ); ?></p>
<?php
display_setup_form();
break;
case 2:
if ( ! empty( $language ) && <API key>( $language ) ) {
$loaded_language = $language;
$GLOBALS['wp_locale'] = new WP_Locale();
} else {
$loaded_language = 'en_US';
}
if ( ! empty( $wpdb->error ) )
wp_die( $wpdb->error->get_error_message() );
display_header();
// Fill in the data we gathered
$weblog_title = isset( $_POST['weblog_title'] ) ? trim( wp_unslash( $_POST['weblog_title'] ) ) : '';
$user_name = isset($_POST['user_name']) ? trim( wp_unslash( $_POST['user_name'] ) ) : '';
$admin_password = isset($_POST['admin_password']) ? wp_unslash( $_POST['admin_password'] ) : '';
$<API key> = isset($_POST['admin_password2']) ? wp_unslash( $_POST['admin_password2'] ) : '';
$admin_email = isset( $_POST['admin_email'] ) ?trim( wp_unslash( $_POST['admin_email'] ) ) : '';
$public = isset( $_POST['blog_public'] ) ? (int) $_POST['blog_public'] : 0;
// Check e-mail address.
$error = false;
if ( empty( $user_name ) ) {
// TODO: poka-yoke
display_setup_form( __( 'Please provide a valid username.' ) );
$error = true;
} elseif ( $user_name != sanitize_user( $user_name, true ) ) {
display_setup_form( __( 'The username you provided has invalid characters.' ) );
$error = true;
} elseif ( $admin_password != $<API key> ) {
// TODO: poka-yoke
display_setup_form( __( 'Your passwords do not match. Please try again.' ) );
$error = true;
} else if ( empty( $admin_email ) ) {
// TODO: poka-yoke
display_setup_form( __( 'You must provide an email address.' ) );
$error = true;
} elseif ( ! is_email( $admin_email ) ) {
// TODO: poka-yoke
display_setup_form( __( 'Sorry, that isn’t a valid email address. Email addresses look like <code>username@example.com</code>.' ) );
$error = true;
}
if ( $error === false ) {
$wpdb->show_errors();
$result = wp_install( $weblog_title, $user_name, $admin_email, $public, '', wp_slash( $admin_password ), $loaded_language );
?>
<h1><?php _e( 'Success!' ); ?></h1>
<p><?php _e( 'WordPress has been installed. Were you expecting more steps? Sorry to disappoint.' ); ?></p>
<table class="form-table install-success">
<tr>
<th><?php _e( 'Username' ); ?></th>
<td><?php echo esc_html( sanitize_user( $user_name, true ) ); ?></td>
</tr>
<tr>
<th><?php _e( 'Password' ); ?></th>
<td><?php
if ( ! empty( $result['password'] ) && empty( $<API key> ) ): ?>
<code><?php echo esc_html( $result['password'] ) ?></code><br />
<?php endif ?>
<p><?php echo $result['password_message'] ?></p>
</td>
</tr>
</table>
<p class="step"><a href="../wp-login.php" class="button button-large"><?php _e( 'Log In' ); ?></a></p>
<?php
}
break;
}
if ( !wp_is_mobile() ) {
?>
<script type="text/javascript">var t = document.getElementById('weblog_title'); if (t){ t.focus(); }</script>
<?php } ?>
<?php wp_print_scripts( 'user-profile' ); ?>
<?php wp_print_scripts( 'language-chooser' ); ?>
</body>
</html> |
include $(TOPDIR)/rules.mk
PKG_NAME:=shd
PKG_VERSION:=0.1
PKG_RELEASE:=0
PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.bz2
PKG_SOURCE_SUBDIR:=$(PKG_NAME)-$(PKG_VERSION)
PKG_SOURCE_PROTO:=git
PKG_SOURCE_URL:=git@github.com:WhireCrow/shd.git
PKG_SOURCE_VERSION:=master
PKG_FIXUP:=autoreconf
PKG_INSTALL:=1
include $(INCLUDE_DIR)/package.mk
define Package/shd
SECTION:=net
CATEGORY:=Network
TITLE:=SmartHome daemon
URL:=http://sourceforge.net/projects/shd/
endef
define Package/shd/description
This is shd.
endef
#define Package/shd/conffiles
#/etc/shd.conf
#endef
# uses GNU configure
define Package/shd/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/bin/shd $(1)/usr/bin/
endef
$(eval $(call BuildPackage,shd)) |
import os
import sqlalchemy as sa
from sqlalchemy.orm import sessionmaker, relation
from sqlalchemy.ext.declarative import declarative_base
import datetime
# database setup
Base = declarative_base()
# define the tables
class Song(Base):
__tablename__ = 'song'
id = sa.Column(sa.Integer, primary_key=True)
path = sa.Column(sa.Unicode(assert_unicode = False))
title = sa.Column(sa.Unicode(assert_unicode = False))
unknown = sa.Column(sa.Boolean)
track = sa.Column(sa.Integer)
length = sa.Column(sa.Integer)
unknown = sa.Column(sa.Boolean)
mimetype = sa.Column(sa.Text)
album_id = sa.Column(sa.Integer, sa.ForeignKey('album.id'))
artist_id = sa.Column(sa.Integer, sa.ForeignKey('artist.id'))
pattern = sa.Column(sa.Text)
def __init__(self, path, track, title, artist_id, album_id, mimetype, unknown, pattern):
self.path = path
self.track = track
self.title = title
self.artist_id = artist_id
self.album_id = album_id
self.mimetype = mimetype
self.unknown = unknown
self.pattern = pattern
def __repr__(self):
return "<Song %s `%s`>" % (self.id, self.title)
class Artist(Base):
__tablename__ = 'artist'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.Unicode(assert_unicode = False))
unknown = sa.Column(sa.Boolean)
artist_id = relation("Song", backref="song_artist", cascade="all, delete")
album_id = relation("Album", backref="album_artist", cascade="all, delete")
def __init__(self, name, unknown):
self.name = name
self.unknown = unknown
def __repr__(self):
return "<Artist %s>" % self.name
class Album(Base):
__tablename__ = 'album'
id = sa.Column(sa.Integer, primary_key=True)
path = sa.Column(sa.Unicode(assert_unicode = False))
name = sa.Column(sa.Unicode(assert_unicode = False))
art = sa.Column(sa.Boolean)
unknown = sa.Column(sa.Boolean)
sort = sa.Column(sa.Text)
pattern = sa.Column(sa.Text)
artist_id = sa.Column(sa.Integer, sa.ForeignKey('artist.id'))
song_id = relation("Song", backref="song_album", cascade="all, delete")
def __init__(self, path, name, artist_id, unknown, sort, pattern):
self.path = path
self.name = name
self.artist_id = artist_id
self.art = False
self.unknown = unknown
self.sort = sort
self.pattern = pattern
def __repr__(self):
return "<Album %s `%s`>" % (self.id, self.name)
class History(Base):
__tablename__ = 'history'
id = sa.Column(sa.Integer, primary_key=True)
song_id = sa.Column(sa.Integer, sa.ForeignKey('song.id'))
selection_time = sa.Column(sa.DateTime)
user_selected = sa.Column(sa.Boolean)
skipped = sa.Column(sa.Boolean)
song_rel = relation("Song", backref="song_history", cascade="all, delete")
def __init__(self, song_id, user_selected):
self.song_id = song_id
self.user_selected = user_selected
self.selection_time = datetime.datetime.now()
self.skipped = False
def __repr__(self):
return "<History %s %s>" % (self.song_id, self.selection_time)
class Tag(Base):
__tablename__ = 'tag'
id = sa.Column(sa.Integer, primary_key=True)
song_id = sa.Column(sa.Integer, sa.ForeignKey('song.id'))
tag = sa.Column(sa.Text)
value = sa.Column(sa.Text)
song_rel = relation("Song", backref="song_tag", cascade="all, delete")
def __init__(self, song_id, tag, value):
self.song_id = song_id
self.tag = tag
self.value = value
def __repr__(self):
return "<Tag %s %s>" % (self.tag, self.value)
class Scan(Base):
__tablename__ = 'scan'
id = sa.Column(sa.Integer, primary_key=True)
song_id = sa.Column(sa.Integer, sa.ForeignKey('song.id'))
scan = sa.Column(sa.Text)
success = sa.Column(sa.Boolean)
time = sa.Column(sa.DateTime)
song_rel = relation("Song", backref="song_scan", cascade="all, delete")
def __init__(self, song_id, scan, success):
self.song_id = song_id
self.scan = scan
self.success = success
self.time = datetime.datetime.now()
def __repr__(self):
return "<Scan %s %s>" % (self.scan, self.success)
app_path = os.path.dirname(os.path.abspath(__file__))
engine = sa.create_engine('sqlite:///%s' % os.path.join(app_path, 'database.sqlite'))
Base.metadata.create_all(engine)
Session = sessionmaker(bind = engine, autocommit = True) |
# Martin Kolman <mkolman@redhat.com>
# copy, or redistribute it subject to the terms and conditions of the GNU
# implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
# trademarks that are incorporated in the source code or documentation are not
from pykickstart.base import BaseData, KickstartCommand
from pykickstart.errors import KickstartParseError
from pykickstart.options import KSOptionParser
from pykickstart.version import F29
from pykickstart.i18n import _
class F29_ModuleData(BaseData):
removedKeywords = BaseData.removedKeywords
removedAttrs = BaseData.removedAttrs
def __init__(self, *args, **kwargs):
BaseData.__init__(self, *args, **kwargs)
self.name = kwargs.get("name", "")
self.stream = kwargs.get("stream", "")
def __eq__(self, y):
if not y:
return False
return (self.name == y.name and self.stream == y.stream)
def __ne__(self, y):
return not self == y
def __str__(self):
retval = BaseData.__str__(self)
retval += "module --name=%s --stream=%s" % (self.name, self.stream)
return retval.strip() + "\n"
class F29_Module(KickstartCommand):
removedKeywords = KickstartCommand.removedKeywords
removedAttrs = KickstartCommand.removedAttrs
def __init__(self, writePriority=0, *args, **kwargs):
KickstartCommand.__init__(self, writePriority, *args, **kwargs)
self.moduleList = kwargs.get("moduleList", [])
self.op = self._getParser()
def __str__(self):
retval = ""
for module in self.moduleList:
retval += module.__str__()
return retval
def _getParser(self):
op.add_argument("--name", metavar="<module_name>", version=F29, required=True,
help="""
Name of the module to enable.""")
op.add_argument("--stream", metavar="<module_stream_name>", version=F29, required=False,
help="""
Name of the module stream to enable.""")
return op
def parse(self, args):
(ns, extra) = self.op.parse_known_args(args=args, lineno=self.lineno)
if len(extra) > 0:
msg = _("The enable module command does not take position arguments!")
raise KickstartParseError(msg, lineno=self.lineno)
enable_module_data = self.dataClass() # pylint: disable=not-callable
self.set_to_obj(ns, enable_module_data)
enable_module_data.lineno = self.lineno
return enable_module_data
def dataList(self):
return self.moduleList
@property
def dataClass(self):
return self.handler.ModuleData |
cmd_fs/proc/version.o := /pub/CIS520/usr/arm/bin/<API key> -Wp,-MD,fs/proc/.version.o.d -nostdinc -isystem /net/files.cis.ksu.edu/exports/public/CIS520/usr/arm/bin/../lib/gcc/<API key>/4.3.3/include -Iinclude -I/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include -include include/linux/autoconf.h -D__KERNEL__ -mlittle-endian -Iarch/arm/mach-goldfish/include -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs -fno-strict-aliasing -fno-common -<API key> -Os -marm -<API key> -mapcs -mno-sched-prolog -mabi=aapcs-linux -mno-thumb-interwork -D__LINUX_ARM_ARCH__=7 -march=armv7-a -msoft-float -Uarm -fno-stack-protector -<API key> -<API key> -<API key> -Wno-pointer-sign -fwrapv -D"KBUILD_STR(s)=\#s" -D"KBUILD_BASENAME=KBUILD_STR(version)" -D"KBUILD_MODNAME=KBUILD_STR(proc)" -c -o fs/proc/version.o fs/proc/version.c
deps_fs/proc/version.o := \
fs/proc/version.c \
include/linux/fs.h \
$(wildcard include/config/dnotify.h) \
$(wildcard include/config/sysfs.h) \
$(wildcard include/config/smp.h) \
$(wildcard include/config/quota.h) \
$(wildcard include/config/inotify.h) \
$(wildcard include/config/security.h) \
$(wildcard include/config/preempt.h) \
$(wildcard include/config/epoll.h) \
$(wildcard include/config/debug/writecount.h) \
$(wildcard include/config/file/locking.h) \
$(wildcard include/config/auditsyscall.h) \
$(wildcard include/config/block.h) \
$(wildcard include/config/fs/xip.h) \
$(wildcard include/config/migration.h) \
include/linux/limits.h \
include/linux/ioctl.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/ioctl.h \
include/asm-generic/ioctl.h \
include/linux/linkage.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) \
$(wildcard include/config/enable/warn/deprecated.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 \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/linkage.h \
include/linux/wait.h \
$(wildcard include/config/lockdep.h) \
$(wildcard include/config/debug/lock/alloc.h) \
include/linux/list.h \
$(wildcard include/config/debug/list.h) \
include/linux/stddef.h \
include/linux/poison.h \
include/linux/prefetch.h \
include/linux/types.h \
$(wildcard include/config/uid16.h) \
$(wildcard include/config/lbd.h) \
$(wildcard include/config/phys/addr/t/64bit.h) \
$(wildcard include/config/64bit.h) \
include/linux/posix_types.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/posix_types.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/types.h \
include/asm-generic/int-ll64.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/processor.h \
$(wildcard include/config/mmu.h) \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/ptrace.h \
$(wildcard include/config/arm/thumb.h) \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/hwcap.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/cache.h \
$(wildcard include/config/arm/l1/cache/shift.h) \
$(wildcard include/config/aeabi.h) \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/system.h \
$(wildcard include/config/cpu/xsc3.h) \
$(wildcard include/config/cpu/sa1100.h) \
$(wildcard include/config/cpu/sa110.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 \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/irqflags.h \
include/asm-generic/cmpxchg-local.h \
include/asm-generic/cmpxchg.h \
include/linux/spinlock.h \
$(wildcard include/config/debug/spinlock.h) \
$(wildcard include/config/generic/lockbreak.h) \
include/linux/preempt.h \
$(wildcard include/config/debug/preempt.h) \
$(wildcard include/config/preempt/notifiers.h) \
include/linux/thread_info.h \
$(wildcard include/config/compat.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) \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/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 \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/thread_info.h \
$(wildcard include/config/arm/thumbee.h) \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/fpstate.h \
$(wildcard include/config/vfpv3.h) \
$(wildcard include/config/iwmmxt.h) \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/domain.h \
$(wildcard include/config/io/36.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/printk/debug.h) \
$(wildcard include/config/numa.h) \
$(wildcard include/config/ftrace/mcount/record.h) \
/net/files.cis.ksu.edu/exports/public/CIS520/usr/arm/bin/../lib/gcc/<API key>/4.3.3/include/stdarg.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 \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/param.h \
$(wildcard include/config/hz.h) \
include/linux/dynamic_printk.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/byteorder.h \
include/linux/byteorder/little_endian.h \
include/linux/swab.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/swab.h \
include/linux/byteorder/generic.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/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) \
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/lock/stat.h) \
$(wildcard include/config/generic/hardirqs.h) \
include/linux/spinlock_up.h \
include/linux/spinlock_api_up.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/atomic.h \
include/asm-generic/atomic.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/current.h \
include/linux/kdev_t.h \
include/linux/dcache.h \
include/linux/rculist.h \
include/linux/rcupdate.h \
$(wildcard include/config/classic/rcu.h) \
$(wildcard include/config/tree/rcu.h) \
$(wildcard include/config/preempt/rcu.h) \
include/linux/cache.h \
$(wildcard include/config/arch/has/cache/line/size.h) \
include/linux/threads.h \
$(wildcard include/config/nr/cpus.h) \
$(wildcard include/config/base/small.h) \
include/linux/percpu.h \
$(wildcard include/config/modules.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/gfp.h \
$(wildcard include/config/zone/dma.h) \
$(wildcard include/config/zone/dma32.h) \
$(wildcard include/config/highmem.h) \
include/linux/mmzone.h \
$(wildcard include/config/force/max/zoneorder.h) \
$(wildcard include/config/unevictable/lru.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) \
include/linux/numa.h \
$(wildcard include/config/nodes/shift.h) \
include/linux/init.h \
$(wildcard include/config/hotplug.h) \
include/linux/seqlock.h \
include/linux/nodemask.h \
include/linux/bitmap.h \
include/linux/string.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/string.h \
include/linux/pageblock-flags.h \
$(wildcard include/config/hugetlb/page.h) \
$(wildcard include/config/hugetlb/page/size/variable.h) \
include/linux/bounds.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/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/xscale.h) \
$(wildcard include/config/cpu/copy/v6.h) \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/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/ifar.h) \
$(wildcard include/config/cpu/pabrt/noifar.h) \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/memory.h \
$(wildcard include/config/page/offset.h) \
$(wildcard include/config/dram/size.h) \
$(wildcard include/config/dram/base.h) \
include/linux/const.h \
arch/arm/mach-goldfish/include/mach/memory.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/sizes.h \
include/asm-generic/memory_model.h \
$(wildcard include/config/sparsemem/vmemmap.h) \
include/asm-generic/page.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/errno.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/errno.h \
include/asm-generic/errno.h \
include/asm-generic/errno-base.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) \
include/linux/cpumask.h \
$(wildcard include/config/disable/obsolete/cpumask/functions.h) \
$(wildcard include/config/hotplug/cpu.h) \
$(wildcard include/config/cpumask/offstack.h) \
$(wildcard include/config/debug/per/cpu/maps.h) \
include/linux/smp.h \
$(wildcard include/config/use/generic/smp/helpers.h) \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/topology.h \
include/asm-generic/topology.h \
include/linux/slab_def.h \
include/linux/kmalloc_sizes.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/percpu.h \
include/asm-generic/percpu.h \
$(wildcard include/config/have/setup/per/cpu/area.h) \
include/linux/completion.h \
include/linux/rcuclassic.h \
$(wildcard include/config/rcu/cpu/stall/detector.h) \
include/linux/path.h \
include/linux/stat.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/stat.h \
include/linux/time.h \
include/linux/math64.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/div64.h \
include/linux/kobject.h \
include/linux/sysfs.h \
include/linux/kref.h \
include/linux/radix-tree.h \
include/linux/prio_tree.h \
include/linux/pid.h \
include/linux/capability.h \
$(wildcard include/config/security/file/capabilities.h) \
include/linux/semaphore.h \
include/linux/fiemap.h \
include/linux/quota.h \
include/linux/dqblk_xfs.h \
include/linux/dqblk_v1.h \
include/linux/dqblk_v2.h \
include/linux/dqblk_qtree.h \
include/linux/nfs_fs_i.h \
include/linux/nfs.h \
include/linux/sunrpc/msg_prot.h \
include/linux/fcntl.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/fcntl.h \
include/asm-generic/fcntl.h \
include/linux/err.h \
include/linux/proc_fs.h \
$(wildcard include/config/proc/fs.h) \
$(wildcard include/config/proc/devicetree.h) \
$(wildcard include/config/proc/kcore.h) \
include/linux/magic.h \
include/linux/seq_file.h \
include/linux/utsname.h \
$(wildcard include/config/uts/ns.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/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/posix/mqueue.h) \
$(wildcard include/config/keys.h) \
$(wildcard include/config/user/sched.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/cc/stackprotector.h) \
$(wildcard include/config/x86/ptrace/bts.h) \
$(wildcard include/config/sysvipc.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/tracing.h) \
$(wildcard include/config/have/unstable/sched/clock.h) \
$(wildcard include/config/preempt/bkl.h) \
$(wildcard include/config/group/sched.h) \
$(wildcard include/config/mm/owner.h) \
include/linux/timex.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/timex.h \
arch/arm/mach-goldfish/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/mmu/notifier.h) \
include/linux/auxvec.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/auxvec.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/mmu.h \
$(wildcard include/config/cpu/has/asid.h) \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/cputime.h \
include/asm-generic/cputime.h \
include/linux/sem.h \
include/linux/ipc.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/ipcbuf.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/sembuf.h \
include/linux/signal.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/signal.h \
include/asm-generic/signal.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/sigcontext.h \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/arch/arm/include/asm/siginfo.h \
include/asm-generic/siginfo.h \
include/linux/fs_struct.h \
include/linux/proportions.h \
include/linux/percpu_counter.h \
include/linux/seccomp.h \
$(wildcard include/config/seccomp.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 \
/net/files.cis.ksu.edu/exports/home/p/phen/cis520/android/Kernel/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/latencytop.h \
include/linux/cred.h \
include/linux/key.h \
$(wildcard include/config/sysctl.h) \
include/linux/sysctl.h \
include/linux/aio.h \
$(wildcard include/config/aio.h) \
include/linux/workqueue.h \
include/linux/aio_abi.h \
include/linux/uio.h \
include/linux/nsproxy.h \
$(wildcard include/config/cgroup/ns.h) \
fs/proc/version.o: $(deps_fs/proc/version.o)
$(deps_fs/proc/version.o): |
// AEPCommon.hpp : AEP 2.0 client and server base, for the abstract/core AEP
// implementation.
// This file is part of the Intense project.
// Intense is free software; you can redistribute it and/or modify
// (at your option) any later version.
// Intense is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// along with Intense; if not, write to the Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
#ifndef __AEPCOMMON_HPP__
#define __AEPCOMMON_HPP__
namespace intense {
namespace aep {
#define AEP_DEFAULT_PORT 6969
class AEPException
: public std::runtime_error {
io::Log::Priority priority;
public:
AEPException
(const std::string& what, io::Log::Priority priority_ = io::Log::ERROR)
: runtime_error(what)
{}
io::Log::Priority getPriority
()
{
return priority;
}
};
class AEPCommon {
protected:
// A wrapper for participants that associates them with an AEPServer or
// an AEPClient:
class Participant
: virtual public intense::Participant {
friend class AEPCommon;
long id;
protected:
io::Log* log;
io::Log::Priority logLevel;
Participant
(io::Log* log_, io::Log::Priority logLevel_)
: intense::Participant(), id(-1), log(log_), logLevel(logLevel_)
{}
Participant
(long id_, io::Log* log_, io::Log::Priority logLevel_)
: intense::Participant(), id(id_), log(log_), logLevel(logLevel_)
{}
public:
virtual ~Participant
()
{}
long getId
()
{
return id;
}
void setLog
(io::Log* newLog)
{
log = newLog;
}
io::Log* getLog
()
{
return log;
}
void setLogLevel
(io::Log::Priority newLogLevel)
{
logLevel = newLogLevel;
}
io::Log::Priority setLogLevel
()
{
return logLevel;
}
};
class Token
: public io::Serialisable {
public:
virtual bool handle
() = 0;
virtual void aetpPrint
(std::ostream& os) const = 0;
virtual void print
(std::ostream& os, io::Log::Priority logLevel = io::Log::DEBUG)
const = 0;
void print
(io::Log& log, io::Log::Priority logLevel = io::Log::DEBUG) const;
virtual ~Token
()
{}
};
friend class Participant;
std::map<long, Participant*> participants;
long nextParticipantId;
io::Log* log;
io::Log::Priority logLevel;
bool errorTolerant;
pthread_mutexattr_t mutexAttribute;
pthread_mutex_t mutex;
pthread_cond_t condition;
pthread_mutex_t sendMutex;
pthread_mutex_t receptionMutex;
AEPCommon
(io::Log* log_, io::Log::Priority logLevel_, bool errorTolerant_);
virtual ~AEPCommon
();
void setParticipantId
(Participant& participant, long id)
{
participant.id = id;
}
long addParticipant
(Participant& participant);
void <API key>
(Participant& participant, const char* location);
public:
Participant& getParticipant
(long participantId, const char* location);
Participant& getParticipant
(long participantId)
{
return getParticipant(participantId, "AEPCommon::getParticipant");
}
protected:
void removeParticipant
(Participant& participant, const char* location);
void <API key>
(bool deleteParticipants = false);
void sendLock
();
void sendUnlock
();
void wait
(pthread_cond_t* condition_);
void wait
();
virtual void send
(AEPCommon::Token& token) = 0;
virtual bool deletesSentTokens
() = 0;
public:
void lock
();
void unlock
();
void signal
();
void setLogLevel
(io::Log::Priority logLevel_)
{
lock();
logLevel = logLevel_;
unlock();
}
protected:
static const char* modeTypeStrings[];
public:
typedef enum { BINARY, XDR, TEXT } Mode;
static const char* getModeTypeString
(Mode mode)
{
return modeTypeStrings[mode];
}
// Parse AEP URLs of the form aep://some.host.name:port/dim1:dim2:...
// Don't know if this might be useful in AEPServer, one day - it's for
// AEPClient.
static void parseURL
(const char* url, Mode& mode, std::string& host, int& port,
CompoundDimension& dimension);
// Construct an AEP URL, with a possibly-NULL dimension.
static std::string constructURL
(Mode& mode, std::string& host, int port, CompoundDimension* dimension);
};
}
}
#endif // __AEPCOMMON_HPP__ |
<?php
namespace Joomla\Component\Contact\Site\View\Categories;
defined('_JEXEC') or die;
use Joomla\CMS\MVC\View\CategoriesView;
/**
* Content categories view.
*
* @since 1.6
*/
class Html extends CategoriesView
{
/**
* Language key for default page heading
*
* @var string
* @since 3.2
*/
protected $pageHeading = '<API key>';
/**
* @var string The name of the extension for the category
* @since 3.2
*/
protected $extension = 'com_contact';
} |
@extends('layouts.app')
@section('title', '403 ')
@section('content')
<section class="hero is-medium is-warning is-bold">
<div class="hero-body">
<div class="container">
<h1 class="title">403 </h1>
@if(isset($status))
<h2 class="subtitle">
{{ $status }}
</h2>
@endif
</div>
</div>
</section>
@endsection |
#include <catch2/catch.hpp>
#include "gcg.h"
using namespace hume;
TEST_CASE("Parse pragmata", "[gcg]")
{
SECTION("Player")
{
std::string line = "#player1 Jamie James Chew";
gcg::Parser p;
auto result = p.parse_line(line);
auto* pragma = std::get_if<gcg::Pragmata>(&result);
REQUIRE(pragma != nullptr);
CHECK(pragma->keyword == "player1");
CHECK(pragma->arguments.at(0) == "Jamie");
CHECK(pragma->arguments.at(1) == "James");
CHECK(pragma->arguments.at(2) == "Chew");
CHECK(pragma->arguments.size() == 3);
}
SECTION("Title")
{
std::string line = "#title Sample Game";
gcg::Parser p;
auto result = p.parse_line(line);
auto* pragma = std::get_if<gcg::Pragmata>(&result);
REQUIRE(pragma != nullptr);
CHECK(pragma->keyword == "title");
CHECK(pragma->arguments.at(0) == "Sample");
CHECK(pragma->arguments.at(1) == "Game");
CHECK(pragma->arguments.size() == 2);
}
// currently don't fully support this type of pragma because it has
// embedded whitespace
#if 0
SECTION("Comment")
{ |
#include <linux/device.h>
#include <linux/err.h>
#include <linux/i2c.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/mutex.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/pm_runtime.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <media/soc_camera.h>
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-dev.h>
#include <media/videobuf-core.h>
#include <media/soc_mediabus.h>
#include "compat.h"
/* Default to VGA resolution */
#define DEFAULT_WIDTH 640
#define DEFAULT_HEIGHT 480
static LIST_HEAD(hosts);
static LIST_HEAD(devices);
static DEFINE_MUTEX(list_lock); /* Protects the list of hosts */
const struct <API key> *<API key>(
struct soc_camera_device *icd, unsigned int fourcc)
{
unsigned int i;
for (i = 0; i < icd->num_user_formats; i++)
if (icd->user_formats[i].host_fmt->fourcc == fourcc)
return icd->user_formats + i;
return NULL;
}
EXPORT_SYMBOL(<API key>);
/**
* <API key>() - apply platform <API key>* flags
* @icl: camera platform parameters
* @flags: flags to be inverted according to platform configuration
* @return: resulting flags
*/
unsigned long <API key>(struct soc_camera_link *icl,
unsigned long flags)
{
unsigned long f;
/* If only one of the two polarities is supported, switch to the opposite */
if (icl->flags & <API key>) {
f = flags & (<API key> | <API key>);
if (f == <API key> || f == <API key>)
flags ^= <API key> | <API key>;
}
if (icl->flags & <API key>) {
f = flags & (<API key> | <API key>);
if (f == <API key> || f == <API key>)
flags ^= <API key> | <API key>;
}
if (icl->flags & <API key>) {
f = flags & (<API key> | <API key>);
if (f == <API key> || f == <API key>)
flags ^= <API key> | <API key>;
}
return flags;
}
EXPORT_SYMBOL(<API key>);
static int <API key>(struct file *file, void *priv,
struct v4l2_format *f)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
WARN_ON(priv != file->private_data);
/* limit format to hardware capabilities */
return ici->ops->try_fmt(icd, f);
}
static int <API key>(struct file *file, void *priv,
struct v4l2_input *inp)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
int ret = 0;
if (inp->index != 0)
return -EINVAL;
if (icd->ops->enum_input)
ret = icd->ops->enum_input(icd, inp);
else {
/* default is camera */
inp->type = <API key>;
inp->std = V4L2_STD_UNKNOWN;
strcpy(inp->name, "Camera");
}
return ret;
}
static int soc_camera_g_input(struct file *file, void *priv, unsigned int *i)
{
*i = 0;
return 0;
}
static int soc_camera_s_input(struct file *file, void *priv, unsigned int i)
{
if (i > 0)
return -EINVAL;
return 0;
}
static int soc_camera_s_std(struct file *file, void *priv, v4l2_std_id *a)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct v4l2_subdev *sd = <API key>(icd);
return v4l2_subdev_call(sd, core, s_std, *a);
}
static int soc_camera_reqbufs(struct file *file, void *priv,
struct v4l2_requestbuffers *p)
{
int ret;
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
WARN_ON(priv != file->private_data);
ret = videobuf_reqbufs(&icf->vb_vidq, p);
if (ret < 0)
return ret;
return ici->ops->reqbufs(icf, p);
}
static int soc_camera_querybuf(struct file *file, void *priv,
struct v4l2_buffer *p)
{
struct soc_camera_file *icf = file->private_data;
WARN_ON(priv != file->private_data);
return videobuf_querybuf(&icf->vb_vidq, p);
}
static int soc_camera_qbuf(struct file *file, void *priv,
struct v4l2_buffer *p)
{
struct soc_camera_file *icf = file->private_data;
WARN_ON(priv != file->private_data);
return videobuf_qbuf(&icf->vb_vidq, p);
}
static int soc_camera_dqbuf(struct file *file, void *priv,
struct v4l2_buffer *p)
{
struct soc_camera_file *icf = file->private_data;
WARN_ON(priv != file->private_data);
return videobuf_dqbuf(&icf->vb_vidq, p, file->f_flags & O_NONBLOCK);
}
/* Always entered with .video_lock held */
static int <API key>(struct soc_camera_device *icd)
{
struct v4l2_subdev *sd = <API key>(icd);
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
unsigned int i, fmts = 0, raw_fmts = 0;
int ret;
enum v4l2_mbus_pixelcode code;
while (!v4l2_subdev_call(sd, video, enum_mbus_fmt, raw_fmts, &code))
raw_fmts++;
if (!ici->ops->get_formats)
/*
* Fallback mode - the host will have to serve all
* sensor-provided formats one-to-one to the user
*/
fmts = raw_fmts;
else
/*
* First pass - only count formats this host-sensor
* configuration can provide
*/
for (i = 0; i < raw_fmts; i++) {
ret = ici->ops->get_formats(icd, i, NULL);
if (ret < 0)
return ret;
fmts += ret;
}
if (!fmts)
return -ENXIO;
icd->user_formats =
vmalloc(fmts * sizeof(struct <API key>));
if (!icd->user_formats)
return -ENOMEM;
icd->num_user_formats = fmts;
dev_dbg(&icd->dev, "Found %d supported formats.\n", fmts);
/* Second pass - actually fill data formats */
fmts = 0;
for (i = 0; i < raw_fmts; i++)
if (!ici->ops->get_formats) {
v4l2_subdev_call(sd, video, enum_mbus_fmt, i, &code);
icd->user_formats[i].host_fmt =
<API key>(code);
icd->user_formats[i].code = code;
} else {
ret = ici->ops->get_formats(icd, i,
&icd->user_formats[fmts]);
if (ret < 0)
goto egfmt;
fmts += ret;
}
icd->current_fmt = &icd->user_formats[0];
return 0;
egfmt:
icd->num_user_formats = 0;
vfree(icd->user_formats);
return ret;
}
/* Always entered with .video_lock held */
static void <API key>(struct soc_camera_device *icd)
{
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
if (ici->ops->put_formats)
ici->ops->put_formats(icd);
icd->current_fmt = NULL;
icd->num_user_formats = 0;
vfree(icd->user_formats);
icd->user_formats = NULL;
}
#define pixfmtstr(x) (x) & 0xff, ((x) >> 8) & 0xff, ((x) >> 16) & 0xff, \
((x) >> 24) & 0xff
/* Called with .vb_lock held, or from the first open(2), see comment there */
static int soc_camera_set_fmt(struct soc_camera_file *icf,
struct v4l2_format *f)
{
struct soc_camera_device *icd = icf->icd;
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
struct v4l2_pix_format *pix = &f->fmt.pix;
int ret;
dev_dbg(&icd->dev, "S_FMT(%c%c%c%c, %ux%u)\n",
pixfmtstr(pix->pixelformat), pix->width, pix->height);
/* We always call try_fmt() before set_fmt() or set_crop() */
ret = ici->ops->try_fmt(icd, f);
if (ret < 0)
return ret;
ret = ici->ops->set_fmt(icd, f);
if (ret < 0) {
return ret;
} else if (!icd->current_fmt ||
icd->current_fmt->host_fmt->fourcc != pix->pixelformat) {
dev_err(&icd->dev,
"Host driver hasn't set up current format correctly!\n");
return -EINVAL;
}
icd->user_width = pix->width;
icd->user_height = pix->height;
icd->colorspace = pix->colorspace;
icf->vb_vidq.field =
icd->field = pix->field;
if (f->type != <API key>)
dev_warn(&icd->dev, "Attention! Wrong buf-type %d\n",
f->type);
dev_dbg(&icd->dev, "set width: %d height: %d\n",
icd->user_width, icd->user_height);
/* set physical bus parameters */
return ici->ops->set_bus_param(icd, pix->pixelformat);
}
static int soc_camera_open(struct file *file)
{
struct video_device *vdev = video_devdata(file);
struct soc_camera_device *icd = container_of(vdev->parent,
struct soc_camera_device,
dev);
struct soc_camera_link *icl = to_soc_camera_link(icd);
struct soc_camera_host *ici;
struct soc_camera_file *icf;
int ret;
if (!icd->ops)
/* No device driver attached */
return -ENODEV;
ici = to_soc_camera_host(icd->dev.parent);
icf = vmalloc(sizeof(*icf));
if (!icf)
return -ENOMEM;
if (!try_module_get(ici->ops->owner)) {
dev_err(&icd->dev, "Couldn't lock capture bus driver.\n");
ret = -EINVAL;
goto emgi;
}
/*
* Protect against icd->ops->remove() until we module_get() both
* drivers.
*/
mutex_lock(&icd->video_lock);
icf->icd = icd;
icd->use_count++;
/* Now we really have to activate the camera */
if (icd->use_count == 1) {
/* Restore parameters before the last close() per V4L2 API */
struct v4l2_format f = {
.type = <API key>,
.fmt.pix = {
.width = icd->user_width,
.height = icd->user_height,
.field = icd->field,
.colorspace = icd->colorspace,
.pixelformat =
icd->current_fmt->host_fmt->fourcc,
},
};
if (icl->power) {
ret = icl->power(icd->pdev, 1);
if (ret < 0)
goto epower;
}
/* The camera could have been already on, try to reset */
if (icl->reset)
icl->reset(icd->pdev);
ret = ici->ops->add(icd);
if (ret < 0) {
dev_err(&icd->dev, "Couldn't activate the camera: %d\n", ret);
goto eiciadd;
}
pm_runtime_enable(&icd->vdev->dev);
ret = pm_runtime_resume(&icd->vdev->dev);
if (ret < 0 && ret != -ENOSYS)
goto eresume;
/*
* Try to configure with default parameters. Notice: this is the
* very first open, so, we cannot race against other calls,
* apart from someone else calling open() simultaneously, but
* .video_lock is protecting us against it.
*/
ret = soc_camera_set_fmt(icf, &f);
if (ret < 0)
goto esfmt;
}
file->private_data = icf;
dev_dbg(&icd->dev, "camera device open\n");
ici->ops->init_videobuf(&icf->vb_vidq, icd);
mutex_unlock(&icd->video_lock);
return 0;
/*
* First four errors are entered with the .video_lock held
* and use_count == 1
*/
esfmt:
pm_runtime_disable(&icd->vdev->dev);
eresume:
ici->ops->remove(icd);
eiciadd:
if (icl->power)
icl->power(icd->pdev, 0);
epower:
icd->use_count
mutex_unlock(&icd->video_lock);
module_put(ici->ops->owner);
emgi:
vfree(icf);
return ret;
}
static int soc_camera_close(struct file *file)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
mutex_lock(&icd->video_lock);
icd->use_count
if (!icd->use_count) {
struct soc_camera_link *icl = to_soc_camera_link(icd);
pm_runtime_suspend(&icd->vdev->dev);
pm_runtime_disable(&icd->vdev->dev);
ici->ops->remove(icd);
if (icl->power)
icl->power(icd->pdev, 0);
}
mutex_unlock(&icd->video_lock);
module_put(ici->ops->owner);
vfree(icf);
dev_dbg(&icd->dev, "camera device close\n");
return 0;
}
static ssize_t soc_camera_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
int err = -EINVAL;
dev_err(&icd->dev, "camera device read not implemented\n");
return err;
}
static int soc_camera_mmap(struct file *file, struct vm_area_struct *vma)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
int err;
dev_dbg(&icd->dev, "mmap called, vma=0x%08lx\n", (unsigned long)vma);
err = <API key>(&icf->vb_vidq, vma);
dev_dbg(&icd->dev, "vma start=0x%08lx, size=%ld, ret=%d\n",
(unsigned long)vma->vm_start,
(unsigned long)vma->vm_end - (unsigned long)vma->vm_start,
err);
return err;
}
static unsigned int soc_camera_poll(struct file *file, poll_table *pt)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
if (list_empty(&icf->vb_vidq.stream)) {
dev_err(&icd->dev, "Trying to poll with no queued buffers!\n");
return POLLERR;
}
return ici->ops->poll(file, pt);
}
static struct <API key> soc_camera_fops = {
.owner = THIS_MODULE,
.open = soc_camera_open,
.release = soc_camera_close,
.ioctl = video_ioctl2,
.read = soc_camera_read,
.mmap = soc_camera_mmap,
.poll = soc_camera_poll,
};
static int <API key>(struct file *file, void *priv,
struct v4l2_format *f)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
int ret;
WARN_ON(priv != file->private_data);
mutex_lock(&icf->vb_vidq.vb_lock);
if (icf->vb_vidq.bufs[0]) {
dev_err(&icd->dev, "S_FMT denied: queue initialised\n");
ret = -EBUSY;
goto unlock;
}
ret = soc_camera_set_fmt(icf, f);
unlock:
mutex_unlock(&icf->vb_vidq.vb_lock);
return ret;
}
static int <API key>(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
const struct soc_mbus_pixelfmt *format;
WARN_ON(priv != file->private_data);
if (f->index >= icd->num_user_formats)
return -EINVAL;
format = icd->user_formats[f->index].host_fmt;
if (format->name)
strlcpy(f->description, format->name, sizeof(f->description));
f->pixelformat = format->fourcc;
return 0;
}
static int <API key>(struct file *file, void *priv,
struct v4l2_format *f)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct v4l2_pix_format *pix = &f->fmt.pix;
WARN_ON(priv != file->private_data);
pix->width = icd->user_width;
pix->height = icd->user_height;
pix->field = icf->vb_vidq.field;
pix->pixelformat = icd->current_fmt->host_fmt->fourcc;
pix->bytesperline = <API key>(pix->width,
icd->current_fmt->host_fmt);
pix->colorspace = icd->colorspace;
if (pix->bytesperline < 0)
return pix->bytesperline;
pix->sizeimage = pix->height * pix->bytesperline;
dev_dbg(&icd->dev, "current_fmt->fourcc: 0x%08x\n",
icd->current_fmt->host_fmt->fourcc);
return 0;
}
static int soc_camera_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
WARN_ON(priv != file->private_data);
strlcpy(cap->driver, ici->drv_name, sizeof(cap->driver));
return ici->ops->querycap(ici, cap);
}
static int soc_camera_streamon(struct file *file, void *priv,
enum v4l2_buf_type i)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct v4l2_subdev *sd = <API key>(icd);
int ret;
WARN_ON(priv != file->private_data);
if (i != <API key>)
return -EINVAL;
mutex_lock(&icd->video_lock);
v4l2_subdev_call(sd, video, s_stream, 1);
/* This calls buf_queue from host driver's videobuf_queue_ops */
ret = videobuf_streamon(&icf->vb_vidq);
mutex_unlock(&icd->video_lock);
return ret;
}
static int <API key>(struct file *file, void *priv,
enum v4l2_buf_type i)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct v4l2_subdev *sd = <API key>(icd);
WARN_ON(priv != file->private_data);
if (i != <API key>)
return -EINVAL;
mutex_lock(&icd->video_lock);
/*
* This calls buf_release from host driver's videobuf_queue_ops for all
* remaining buffers. When the last buffer is freed, stop capture
*/
videobuf_streamoff(&icf->vb_vidq);
v4l2_subdev_call(sd, video, s_stream, 0);
mutex_unlock(&icd->video_lock);
return 0;
}
static int <API key>(struct file *file, void *priv,
struct v4l2_queryctrl *qc)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
int i;
WARN_ON(priv != file->private_data);
if (!qc->id)
return -EINVAL;
/* First check host controls */
for (i = 0; i < ici->ops->num_controls; i++)
if (qc->id == ici->ops->controls[i].id) {
memcpy(qc, &(ici->ops->controls[i]),
sizeof(*qc));
return 0;
}
/* Then device controls */
for (i = 0; i < icd->ops->num_controls; i++)
if (qc->id == icd->ops->controls[i].id) {
memcpy(qc, &(icd->ops->controls[i]),
sizeof(*qc));
return 0;
}
return -EINVAL;
}
static int soc_camera_g_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
struct v4l2_subdev *sd = <API key>(icd);
int ret;
WARN_ON(priv != file->private_data);
if (ici->ops->get_ctrl) {
ret = ici->ops->get_ctrl(icd, ctrl);
if (ret != -ENOIOCTLCMD)
return ret;
}
return v4l2_subdev_call(sd, core, g_ctrl, ctrl);
}
static int soc_camera_s_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
struct v4l2_subdev *sd = <API key>(icd);
int ret;
WARN_ON(priv != file->private_data);
if (ici->ops->set_ctrl) {
ret = ici->ops->set_ctrl(icd, ctrl);
if (ret != -ENOIOCTLCMD)
return ret;
}
return v4l2_subdev_call(sd, core, s_ctrl, ctrl);
}
static int soc_camera_cropcap(struct file *file, void *fh,
struct v4l2_cropcap *a)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
return ici->ops->cropcap(icd, a);
}
static int soc_camera_g_crop(struct file *file, void *fh,
struct v4l2_crop *a)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
int ret;
mutex_lock(&icf->vb_vidq.vb_lock);
ret = ici->ops->get_crop(icd, a);
mutex_unlock(&icf->vb_vidq.vb_lock);
return ret;
}
/*
* According to the V4L2 API, drivers shall not update the struct v4l2_crop
* argument with the actual geometry, instead, the user shall use G_CROP to
* retrieve it.
*/
static int soc_camera_s_crop(struct file *file, void *fh,
struct v4l2_crop *a)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
struct v4l2_rect *rect = &a->c;
struct v4l2_crop current_crop;
int ret;
if (a->type != <API key>)
return -EINVAL;
dev_dbg(&icd->dev, "S_CROP(%ux%u@%u:%u)\n",
rect->width, rect->height, rect->left, rect->top);
/* Cropping is allowed during a running capture, guard consistency */
mutex_lock(&icf->vb_vidq.vb_lock);
/* If get_crop fails, we'll let host and / or client drivers decide */
ret = ici->ops->get_crop(icd, ¤t_crop);
/* Prohibit window size change with initialised buffers */
if (icf->vb_vidq.bufs[0] && !ret &&
(a->c.width != current_crop.c.width ||
a->c.height != current_crop.c.height)) {
dev_err(&icd->dev,
"S_CROP denied: queue initialised and sizes differ\n");
ret = -EBUSY;
} else {
ret = ici->ops->set_crop(icd, a);
}
mutex_unlock(&icf->vb_vidq.vb_lock);
return ret;
}
static int soc_camera_g_parm(struct file *file, void *fh,
struct v4l2_streamparm *a)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
if (ici->ops->get_parm)
return ici->ops->get_parm(icd, a);
return -ENOIOCTLCMD;
}
static int soc_camera_s_parm(struct file *file, void *fh,
struct v4l2_streamparm *a)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
if (ici->ops->set_parm)
return ici->ops->set_parm(icd, a);
return -ENOIOCTLCMD;
}
static int <API key>(struct file *file, void *fh,
struct v4l2_dbg_chip_ident *id)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct v4l2_subdev *sd = <API key>(icd);
return v4l2_subdev_call(sd, core, g_chip_ident, id);
}
#ifdef <API key>
static int <API key>(struct file *file, void *fh,
struct v4l2_dbg_register *reg)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct v4l2_subdev *sd = <API key>(icd);
return v4l2_subdev_call(sd, core, g_register, reg);
}
static int <API key>(struct file *file, void *fh,
struct v4l2_dbg_register *reg)
{
struct soc_camera_file *icf = file->private_data;
struct soc_camera_device *icd = icf->icd;
struct v4l2_subdev *sd = <API key>(icd);
return v4l2_subdev_call(sd, core, s_register, reg);
}
#endif
/* So far this function cannot fail */
static void scan_add_host(struct soc_camera_host *ici)
{
struct soc_camera_device *icd;
mutex_lock(&list_lock);
list_for_each_entry(icd, &devices, list) {
if (icd->iface == ici->nr) {
int ret;
icd->dev.parent = ici->v4l2_dev.dev;
dev_set_name(&icd->dev, "%u-%u", icd->iface,
icd->devnum);
ret = device_register(&icd->dev);
if (ret < 0) {
icd->dev.parent = NULL;
dev_err(&icd->dev,
"Cannot register device: %d\n", ret);
}
}
}
mutex_unlock(&list_lock);
}
#ifdef <API key>
static int soc_camera_init_i2c(struct soc_camera_device *icd,
struct soc_camera_link *icl)
{
struct i2c_client *client;
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
struct i2c_adapter *adap = i2c_get_adapter(icl->i2c_adapter_id);
struct v4l2_subdev *subdev;
if (!adap) {
dev_err(&icd->dev, "Cannot get I2C adapter #%d. No driver?\n",
icl->i2c_adapter_id);
goto ei2cga;
}
icl->board_info->platform_data = icd;
subdev = <API key>(&ici->v4l2_dev, adap,
icl->module_name, icl->board_info, NULL);
if (!subdev)
goto ei2cnd;
client = subdev->priv;
/* Use to_i2c_client(dev) to recover the i2c client */
dev_set_drvdata(&icd->dev, &client->dev);
return 0;
ei2cnd:
i2c_put_adapter(adap);
ei2cga:
return -ENODEV;
}
static void soc_camera_free_i2c(struct soc_camera_device *icd)
{
struct i2c_client *client =
to_i2c_client(<API key>(icd));
dev_set_drvdata(&icd->dev, NULL);
<API key>(i2c_get_clientdata(client));
<API key>(client);
i2c_put_adapter(client->adapter);
}
#else
#define soc_camera_init_i2c(icd, icl) (-ENODEV)
#define soc_camera_free_i2c(icd) do {} while (0)
#endif
static int <API key>(struct soc_camera_device *icd);
static int video_dev_create(struct soc_camera_device *icd);
/* Called during host-driver probe */
static int soc_camera_probe(struct device *dev)
{
struct soc_camera_device *icd = to_soc_camera_dev(dev);
struct soc_camera_host *ici = to_soc_camera_host(dev->parent);
struct soc_camera_link *icl = to_soc_camera_link(icd);
struct device *control = NULL;
struct v4l2_subdev *sd;
struct v4l2_mbus_framefmt mf;
int ret;
dev_info(dev, "Probing %s\n", dev_name(dev));
if (icl->power) {
ret = icl->power(icd->pdev, 1);
if (ret < 0) {
dev_err(dev,
"Platform failed to power-on the camera.\n");
goto epower;
}
}
/* The camera could have been already on, try to reset */
if (icl->reset)
icl->reset(icd->pdev);
ret = ici->ops->add(icd);
if (ret < 0)
goto eadd;
/* Must have icd->vdev before registering the device */
ret = video_dev_create(icd);
if (ret < 0)
goto evdc;
/* Non-i2c cameras, e.g., soc_camera_platform, have no board_info */
if (icl->board_info) {
ret = soc_camera_init_i2c(icd, icl);
if (ret < 0)
goto eadddev;
} else if (!icl->add_device || !icl->del_device) {
ret = -EINVAL;
goto eadddev;
} else {
if (icl->module_name)
ret = request_module(icl->module_name);
ret = icl->add_device(icl, &icd->dev);
if (ret < 0)
goto eadddev;
/*
* FIXME: this is racy, have to use driver-binding notification,
* when it is available
*/
control = <API key>(icd);
if (!control || !control->driver || !dev_get_drvdata(control) ||
!try_module_get(control->driver->owner)) {
icl->del_device(icl);
goto enodrv;
}
}
/* At this point client .probe() should have run already */
ret = <API key>(icd);
if (ret < 0)
goto eiufmt;
icd->field = V4L2_FIELD_ANY;
/* ..._video_start() will create a device node, so we have to protect */
mutex_lock(&icd->video_lock);
ret = <API key>(icd);
if (ret < 0)
goto evidstart;
/* Try to improve our guess of a reasonable window format */
sd = <API key>(icd);
if (!v4l2_subdev_call(sd, video, g_mbus_fmt, &mf)) {
icd->user_width = mf.width;
icd->user_height = mf.height;
icd->colorspace = mf.colorspace;
icd->field = mf.field;
}
/* Do we have to sysfs_remove_link() before device_unregister()? */
if (sysfs_create_link(&icd->dev.kobj, &<API key>(icd)->kobj,
"control"))
dev_warn(&icd->dev, "Failed creating the control symlink\n");
ici->ops->remove(icd);
if (icl->power)
icl->power(icd->pdev, 0);
mutex_unlock(&icd->video_lock);
return 0;
evidstart:
mutex_unlock(&icd->video_lock);
<API key>(icd);
eiufmt:
if (icl->board_info) {
soc_camera_free_i2c(icd);
} else {
icl->del_device(icl);
module_put(control->driver->owner);
}
enodrv:
eadddev:
<API key>(icd->vdev);
evdc:
ici->ops->remove(icd);
eadd:
if (icl->power)
icl->power(icd->pdev, 0);
epower:
return ret;
}
/*
* This is called on device_unregister, which only means we have to disconnect
* from the host, but not remove ourselves from the device list
*/
static int soc_camera_remove(struct device *dev)
{
struct soc_camera_device *icd = to_soc_camera_dev(dev);
struct soc_camera_link *icl = to_soc_camera_link(icd);
struct video_device *vdev = icd->vdev;
BUG_ON(!dev->parent);
if (vdev) {
mutex_lock(&icd->video_lock);
<API key>(vdev);
icd->vdev = NULL;
mutex_unlock(&icd->video_lock);
}
if (icl->board_info) {
soc_camera_free_i2c(icd);
} else {
struct device_driver *drv = <API key>(icd) ?
<API key>(icd)->driver : NULL;
if (drv) {
icl->del_device(icl);
module_put(drv->owner);
}
}
<API key>(icd);
return 0;
}
static int soc_camera_suspend(struct device *dev, pm_message_t state)
{
struct soc_camera_device *icd = to_soc_camera_dev(dev);
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
int ret = 0;
if (ici->ops->suspend)
ret = ici->ops->suspend(icd, state);
return ret;
}
static int soc_camera_resume(struct device *dev)
{
struct soc_camera_device *icd = to_soc_camera_dev(dev);
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
int ret = 0;
if (ici->ops->resume)
ret = ici->ops->resume(icd);
return ret;
}
static struct bus_type soc_camera_bus_type = {
.name = "soc-camera",
.probe = soc_camera_probe,
.remove = soc_camera_remove,
.suspend = soc_camera_suspend,
.resume = soc_camera_resume,
};
static struct device_driver ic_drv = {
.name = "camera",
.bus = &soc_camera_bus_type,
.owner = THIS_MODULE,
};
static void dummy_release(struct device *dev)
{
}
static int default_cropcap(struct soc_camera_device *icd,
struct v4l2_cropcap *a)
{
struct v4l2_subdev *sd = <API key>(icd);
return v4l2_subdev_call(sd, video, cropcap, a);
}
static int default_g_crop(struct soc_camera_device *icd, struct v4l2_crop *a)
{
struct v4l2_subdev *sd = <API key>(icd);
return v4l2_subdev_call(sd, video, g_crop, a);
}
static int default_s_crop(struct soc_camera_device *icd, struct v4l2_crop *a)
{
struct v4l2_subdev *sd = <API key>(icd);
return v4l2_subdev_call(sd, video, s_crop, a);
}
static void <API key>(struct device *dev, void *pdata)
{
dev->platform_data = pdata;
dev->bus = &soc_camera_bus_type;
dev->release = dummy_release;
}
int <API key>(struct soc_camera_host *ici)
{
struct soc_camera_host *ix;
int ret;
if (!ici || !ici->ops ||
!ici->ops->try_fmt ||
!ici->ops->set_fmt ||
!ici->ops->set_bus_param ||
!ici->ops->querycap ||
!ici->ops->init_videobuf ||
!ici->ops->reqbufs ||
!ici->ops->add ||
!ici->ops->remove ||
!ici->ops->poll ||
!ici->v4l2_dev.dev)
return -EINVAL;
if (!ici->ops->set_crop)
ici->ops->set_crop = default_s_crop;
if (!ici->ops->get_crop)
ici->ops->get_crop = default_g_crop;
if (!ici->ops->cropcap)
ici->ops->cropcap = default_cropcap;
mutex_lock(&list_lock);
list_for_each_entry(ix, &hosts, list) {
if (ix->nr == ici->nr) {
ret = -EBUSY;
goto edevreg;
}
}
ret = <API key>(ici->v4l2_dev.dev, &ici->v4l2_dev);
if (ret < 0)
goto edevreg;
list_add_tail(&ici->list, &hosts);
mutex_unlock(&list_lock);
scan_add_host(ici);
return 0;
edevreg:
mutex_unlock(&list_lock);
return ret;
}
EXPORT_SYMBOL(<API key>);
/* Unregister all clients! */
void <API key>(struct soc_camera_host *ici)
{
struct soc_camera_device *icd;
mutex_lock(&list_lock);
list_del(&ici->list);
list_for_each_entry(icd, &devices, list) {
if (icd->iface == ici->nr) {
void *pdata = icd->dev.platform_data;
/* The bus->remove will be called */
device_unregister(&icd->dev);
/*
* Not before device_unregister(), .remove
* needs parent to call ici->ops->remove().
* If the host module is loaded again, device_register()
* would complain "already initialised," since 2.6.32
* this is also needed to prevent use-after-free of the
* device private data.
*/
memset(&icd->dev, 0, sizeof(icd->dev));
<API key>(&icd->dev, pdata);
}
}
mutex_unlock(&list_lock);
<API key>(&ici->v4l2_dev);
}
EXPORT_SYMBOL(<API key>);
/* Image capture device */
static int <API key>(struct soc_camera_device *icd)
{
struct soc_camera_device *ix;
int num = -1, i;
for (i = 0; i < 256 && num < 0; i++) {
num = i;
/* Check if this index is available on this interface */
list_for_each_entry(ix, &devices, list) {
if (ix->iface == icd->iface && ix->devnum == i) {
num = -1;
break;
}
}
}
if (num < 0)
/*
* ok, we have 256 cameras on this host...
* man, stay reasonable...
*/
return -ENOMEM;
icd->devnum = num;
icd->use_count = 0;
icd->host_priv = NULL;
mutex_init(&icd->video_lock);
list_add_tail(&icd->list, &devices);
return 0;
}
static void <API key>(struct soc_camera_device *icd)
{
list_del(&icd->list);
}
static const struct v4l2_ioctl_ops <API key> = {
.vidioc_querycap = soc_camera_querycap,
.<API key> = <API key>,
.<API key> = <API key>,
.<API key> = <API key>,
.vidioc_enum_input = <API key>,
.vidioc_g_input = soc_camera_g_input,
.vidioc_s_input = soc_camera_s_input,
.vidioc_s_std = soc_camera_s_std,
.vidioc_reqbufs = soc_camera_reqbufs,
.<API key> = <API key>,
.vidioc_querybuf = soc_camera_querybuf,
.vidioc_qbuf = soc_camera_qbuf,
.vidioc_dqbuf = soc_camera_dqbuf,
.vidioc_streamon = soc_camera_streamon,
.vidioc_streamoff = <API key>,
.vidioc_queryctrl = <API key>,
.vidioc_g_ctrl = soc_camera_g_ctrl,
.vidioc_s_ctrl = soc_camera_s_ctrl,
.vidioc_cropcap = soc_camera_cropcap,
.vidioc_g_crop = soc_camera_g_crop,
.vidioc_s_crop = soc_camera_s_crop,
.vidioc_g_parm = soc_camera_g_parm,
.vidioc_s_parm = soc_camera_s_parm,
.vidioc_g_chip_ident = <API key>,
#ifdef <API key>
.vidioc_g_register = <API key>,
.vidioc_s_register = <API key>,
#endif
};
static int video_dev_create(struct soc_camera_device *icd)
{
struct soc_camera_host *ici = to_soc_camera_host(icd->dev.parent);
struct video_device *vdev = video_device_alloc();
if (!vdev)
return -ENOMEM;
strlcpy(vdev->name, ici->drv_name, sizeof(vdev->name));
vdev->parent = &icd->dev;
vdev->current_norm = V4L2_STD_UNKNOWN;
vdev->fops = &soc_camera_fops;
vdev->ioctl_ops = &<API key>;
vdev->release = <API key>;
vdev->tvnorms = V4L2_STD_UNKNOWN;
icd->vdev = vdev;
return 0;
}
/*
* Called from soc_camera_probe() above (with .video_lock held???)
*/
static int <API key>(struct soc_camera_device *icd)
{
struct device_type *type = icd->vdev->dev.type;
int ret;
if (!icd->dev.parent)
return -ENODEV;
if (!icd->ops ||
!icd->ops->query_bus_param ||
!icd->ops->set_bus_param)
return -EINVAL;
ret = <API key>(icd->vdev, VFL_TYPE_GRABBER, -1);
if (ret < 0) {
dev_err(&icd->dev, "<API key> failed: %d\n", ret);
return ret;
}
/* Restore device type, possibly set by the subdevice driver */
icd->vdev->dev.type = type;
return 0;
}
static int __devinit <API key>(struct platform_device *pdev)
{
struct soc_camera_link *icl = pdev->dev.platform_data;
struct soc_camera_device *icd;
int ret;
if (!icl)
return -EINVAL;
icd = kzalloc(sizeof(*icd), GFP_KERNEL);
if (!icd)
return -ENOMEM;
icd->iface = icl->bus_id;
icd->pdev = &pdev->dev;
<API key>(pdev, icd);
ret = <API key>(icd);
if (ret < 0)
goto escdevreg;
<API key>(&icd->dev, icl);
icd->user_width = DEFAULT_WIDTH;
icd->user_height = DEFAULT_HEIGHT;
return 0;
escdevreg:
kfree(icd);
return ret;
}
/*
* Only called on rmmod for each platform device, since they are not
* hot-pluggable. Now we know, that all our users - hosts and devices have
* been unloaded already
*/
static int __devexit <API key>(struct platform_device *pdev)
{
struct soc_camera_device *icd = <API key>(pdev);
if (!icd)
return -EINVAL;
<API key>(icd);
kfree(icd);
return 0;
}
static struct platform_driver __refdata soc_camera_pdrv = {
.remove = __devexit_p(<API key>),
.driver = {
.name = "soc-camera-pdrv",
.owner = THIS_MODULE,
},
};
static int __init soc_camera_init(void)
{
int ret = bus_register(&soc_camera_bus_type);
if (ret)
return ret;
ret = driver_register(&ic_drv);
if (ret)
goto edrvr;
ret = <API key>(&soc_camera_pdrv, <API key>);
if (ret)
goto epdr;
return 0;
epdr:
driver_unregister(&ic_drv);
edrvr:
bus_unregister(&soc_camera_bus_type);
return ret;
}
static void __exit soc_camera_exit(void)
{
<API key>(&soc_camera_pdrv);
driver_unregister(&ic_drv);
bus_unregister(&soc_camera_bus_type);
}
module_init(soc_camera_init);
module_exit(soc_camera_exit);
MODULE_DESCRIPTION("Image capture bus driver");
MODULE_AUTHOR("Guennadi Liakhovetski <kernel@pengutronix.de>");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:soc-camera-pdrv"); |
<?php
// security check - must be included in all scripts
if (!
/**
* Description for $GLOBALS
* @global unknown $GLOBALS['<API key>']
* @name $<API key>
*/
$GLOBALS['<API key>']) {
die("You cannot view this page directly");
}
// end security check
class <API key> extends dbtable
{
/**
* Instance of the altconfig class in the config module.
*
* @access private
* @var object
*/
private $objAltConfig;
/**
* The object property initialiser.
*
* @access public
*/
public function init()
{
$this->objUser = $this->getObject('user', 'security');
$this->userId = $this->objUser->PKId();
$this->facet = $this->getObject('systext_facet', 'systext');
$this->objConfig = $this->getObject('altconfig', 'config');
$this->objModules = $this->getObject('modules', 'modulecatalogue');
}
/**
* The actions to perform after installation of the module.
*
* @access public
* @return void
*
*/
public function postinstall($version)
{
// remove data added with earlier patch method
$types = $this->facet->listSystemTypes();
foreach ($types as $type)
{
$init = stripos($type['id'], 'init_');
if ($init === FALSE)
{
$this->facet->deleteSystemType($type['id']);
$abstracts = $this->facet->listAbstractText($type['id']);
foreach ($abstracts as $abstract)
{
$init = stripos($abstract['id'], 'init');
if ($init === FALSE)
{
$this->facet->deleteAbstractText($abstract['id']);
}
}
}
}
$texts = $this->facet->listTextItems();
foreach ($texts as $text)
{
$init = stripos($text['id'], 'init_');
if ($init === FALSE)
{
$this->facet->deleteTextItem($text['id']);
}
}
switch ($version)
{
case '1.900':
$patchFile = $this->objConfig->getSiteRootPath() . 'core_modules/systext/sql/patch-1.900.xml';
ini_set('max_execution_time','600');
$objXml = simplexml_load_file($patchFile);
foreach ($objXml as $table => $row)
{
$sqlArray = array();
foreach ($row as $field => $value)
{
$sqlArray[$field] = $value;
}
$result = $this->objModules->insert($sqlArray, $table);
}
break;
case '1.910':
$patchFile = $this->objConfig->getSiteRootPath() . 'core_modules/systext/sql/patch-1.910.xml';
ini_set('max_execution_time','600');
$objXml = simplexml_load_file($patchFile);
foreach ($objXml as $table => $row)
{
$sqlArray = array();
foreach ($row as $field => $value)
{
$sqlArray[$field] = $value;
}
$result = $this->objModules->insert($sqlArray, $table);
}
break;
}
}
}
?> |
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <mach/board_lge.h>
#include "../proc_comm.h"
#if 1 //#if defined(<API key>)
unsigned lge_get_pif_info(void)
{
int err;
unsigned pif_value = -1;
unsigned cmd_pif = 8;
err = msm_proc_comm(PCOM_CUSTOMER_CMD2, &pif_value, &cmd_pif);
if (err < 0) {
pr_err("%s: msm_proc_comm(PCOM_CUSTOMER_CMD2) failed\n",
__func__);
return err;
}
return pif_value;
}
EXPORT_SYMBOL(lge_get_pif_info);
unsigned lge_get_lpm_info(void)
{
int err;
unsigned low_power_mode = 0;
unsigned cmd_lpm = 7;
err = msm_proc_comm(PCOM_CUSTOMER_CMD2, &low_power_mode, &cmd_lpm);
if (err < 0) {
pr_err("%s: msm_proc_comm(PCOM_CUSTOMER_CMD2) failed\n",
__func__);
return err;
}
return low_power_mode;
}
EXPORT_SYMBOL(lge_get_lpm_info);
#endif
#ifdef CONFIG_MACH_LGE
unsigned lge_get_batt_volt(void)
{
int err;
unsigned ret = 0;
unsigned cmd = 0x3;
err = msm_proc_comm(PCOM_CUSTOMER_CMD2, &ret, &cmd);
if (err < 0) {
pr_err("%s: msm_proc_comm(PCOM_CUSTOMER_CMD2) failed. cmd(%d)\n",
__func__, cmd);
return err;
}
return ret;
}
EXPORT_SYMBOL(lge_get_batt_volt);
unsigned lge_get_chg_therm(void)
{
int err;
unsigned ret = 0;
unsigned cmd = 0x9;
err = msm_proc_comm(PCOM_CUSTOMER_CMD2, &ret, &cmd);
if (err < 0) {
pr_err("%s: msm_proc_comm(PCOM_CUSTOMER_CMD2) failed. cmd(%d)\n",
__func__, cmd);
return err;
}
return ret;
}
EXPORT_SYMBOL(lge_get_chg_therm);
unsigned lge_get_pcb_version(void)
{
int err;
unsigned ret = 0;
unsigned cmd = 0xA;
err = msm_proc_comm(PCOM_CUSTOMER_CMD2, &ret, &cmd);
if (err < 0) {
pr_err("%s: msm_proc_comm(PCOM_CUSTOMER_CMD2) failed. cmd(%d)\n",
__func__, cmd);
return err;
}
return ret;
}
EXPORT_SYMBOL(lge_get_pcb_version);
unsigned <API key>(void)
{
int err;
unsigned ret = 0;
unsigned cmd = 0xB;
err = msm_proc_comm(PCOM_CUSTOMER_CMD2, &ret, &cmd);
if (err < 0) {
pr_err("%s: msm_proc_comm(PCOM_CUSTOMER_CMD2) failed. cmd(%d)\n",
__func__, cmd);
return err;
}
return ret;
}
EXPORT_SYMBOL(<API key>);
unsigned lge_get_batt_therm(void)
{
int err;
unsigned ret = 0;
unsigned cmd = 0xC;
err = msm_proc_comm(PCOM_CUSTOMER_CMD2, &ret, &cmd);
if (err < 0) {
pr_err("%s: msm_proc_comm(PCOM_CUSTOMER_CMD2) failed. cmd(%d)\n",
__func__, cmd);
return err;
}
return ret;
}
EXPORT_SYMBOL(lge_get_batt_therm);
unsigned <API key>(void)
{
int err;
unsigned ret = 0;
unsigned cmd = 0xD;
err = msm_proc_comm(PCOM_CUSTOMER_CMD2, &ret, &cmd);
if (err < 0) {
pr_err("%s: msm_proc_comm(PCOM_CUSTOMER_CMD2) failed. cmd(%d)\n",
__func__, cmd);
return err;
}
return ret;
}
EXPORT_SYMBOL(<API key>);
#if 1 //#ifdef <API key>
unsigned <API key>(void)
{
int err;
unsigned ret = 0;
unsigned cmd = 0xE;
err = msm_proc_comm(PCOM_CUSTOMER_CMD2, &ret, &cmd);
if (err < 0) {
pr_err("%s: msm_proc_comm(PCOM_CUSTOMER_CMD2) failed. cmd(%d)\n",
__func__, cmd);
return err;
}
return ret;
}
EXPORT_SYMBOL(<API key>);
unsigned lge_get_chg_en_reg(void)
{
int err;
unsigned ret = 0;
unsigned cmd = 0xF;
err = msm_proc_comm(PCOM_CUSTOMER_CMD2, &ret, &cmd);
if (err < 0) {
pr_err("%s: msm_proc_comm(PCOM_CUSTOMER_CMD2) failed. cmd(%d)\n",
__func__, cmd);
return err;
}
return ret;
}
EXPORT_SYMBOL(lge_get_chg_en_reg);
unsigned lge_set_elt_test(void)
{
int err;
unsigned ret = 0;
unsigned cmd = 0x10;
err = msm_proc_comm(PCOM_CUSTOMER_CMD2, &ret, &cmd);
if (err < 0) {
pr_err("%s: msm_proc_comm(PCOM_CUSTOMER_CMD2) failed. cmd(%d)\n",
__func__, cmd);
return err;
}
return ret;
}
EXPORT_SYMBOL(lge_set_elt_test);
unsigned lge_clear_elt_test(void)
{
int err;
unsigned ret = 0;
unsigned cmd = 0x11;
err = msm_proc_comm(PCOM_CUSTOMER_CMD2, &ret, &cmd);
if (err < 0) {
pr_err("%s: msm_proc_comm(PCOM_CUSTOMER_CMD2) failed. cmd(%d)\n",
__func__, cmd);
return err;
}
return ret;
}
EXPORT_SYMBOL(lge_clear_elt_test);
#endif
unsigned lge_get_is_miniOS(void)
{
int err;
unsigned ret = 0;
unsigned cmd = 0x12;
err = msm_proc_comm(PCOM_CUSTOMER_CMD2, &ret, &cmd);
if (err < 0) {
pr_err("%s: msm_proc_comm(PCOM_CUSTOMER_CMD2) failed. cmd(%d)\n",
__func__, cmd);
return err;
}
return ret;
}
EXPORT_SYMBOL(lge_get_is_miniOS);
//LGE_CHANGE_S, [hyo.park@lge.com] , 2011-10-10
unsigned lge_get_batt_id(void)
{
int err;
unsigned ret = 0;
unsigned cmd = 0x4;
err = msm_proc_comm(PCOM_CUSTOMER_CMD2, &ret, &cmd);
if (err < 0) {
pr_err("%s: msm_proc_comm(PCOM_CUSTOMER_CMD2) failed. cmd(%d)\n",
__func__, cmd);
return err;
}
return ret;
}
EXPORT_SYMBOL(lge_get_batt_id);
//LGE_CHANGE_E, [hyo.park@lge.com] , 2011-10-10
//LGE_CHANGE_S, [myunghwan.kim@lge.com], 2011-10-27
unsigned lge_get_cable_info(void)
{
int err;
unsigned ret = 0;
unsigned cmd = 0x13;
err = msm_proc_comm(PCOM_CUSTOMER_CMD2, &ret, &cmd);
if (err < 0) {
pr_err("%s: msm_proc_comm(PCOM_CUSTOMER_CMD2) failed. cmd(%d)\n",
__func__, cmd);
return err;
}
return ret;
}
EXPORT_SYMBOL(lge_get_cable_info);
//LGE_CHANGE_E, [myunghwan.kim@lge.com], 2011-10-27
#endif |
Meteor.startup(function () {
// Hard code for creating a user. Never do this on production
try {
Accounts.createUser({username:'test', password:'test'});
}
catch ( error ) { /* Nothing */ }
}); |
// Cyphesis Online RPG Server and AI Engine
// 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
#ifndef RULESETS_TASK_H
#define RULESETS_TASK_H
#include "common/OperationRouter.h"
#include <Atlas/Message/Element.h>
#include <string>
#include <cassert>
class LocatedEntity;
class Script;
\brief Interface class for handling tasks which take a short while to
complete
class Task {
private:
\brief Count of references held by entities involved in this task
int m_refCount;
protected:
\brief Serial number of the tick due to arrive next at this task.
int m_serialno;
\brief Flag to indicate if this task is obsolete and should be removed
bool m_obsolete;
\brief Progress towards task completion
float m_progress;
\brief Rate of progress towards task completion
float m_rate;
\brief Entity owning the task
This doesn't handle the idea that there might be multiple actors
involved.
LocatedEntity & m_owner;
\brief Additional task attributes
Atlas::Message::MapType m_attr;
\brief Name of task presented to client
std::string m_name;
\brief The language script that will handle this task
Script * m_script;
private:
\brief Private deleted, to make sure slicing is impossible
Task(const Task & t) = delete;
\brief Private deleted, to make sure slicing is impossible
const Task & operator=(const Task &) = delete;
public:
\brief Constructor
explicit Task(LocatedEntity & owner);
~Task();
\brief Flag this task as obsolete
void irrelevant();
\brief Handle the operation that instigates the task
@param op The operation to be processed
@param res The result of the operation is returned here.
void initTask(const Operation & op, OpVector & res);
\brief Handle an operation to perform the task
A Task gets regular ticks which cause whatever actions this
Task involves to be returned.
@param op The operation to be processed
@param res The result of the operation is returned here.
void operation(const Operation & op, OpVector & res);
\brief Create a new tick op for the next iteration of this task
Operation nextTick(double interval);
\brief Increment the reference count on this task
void incRef() {
++m_refCount;
}
\brief Decrement the reference count on this task
void decRef() {
if (--m_refCount < 1) {
assert(m_refCount == 0);
delete this;
}
}
\brief Return the number of entities involved in this task
int count() const {
return m_refCount;
}
\brief Return the number of the next to arrive at this task
int serialno() const {
return m_serialno;
}
\brief Return a new tick serial number.
int newTick() {
return ++m_serialno;
}
\brief Accessor for the script that handles this task
Script * script() const {
return m_script;
}
void setScript(Script * scrpt);
\brief Accessor to determine if this Task is obsolete
const bool obsolete() { return m_obsolete; }
\brief Accessor for character that owns this Task.
LocatedEntity & owner() const { return m_owner; }
\brief Accessor for name of this task
std::string & name() { return m_name; }
\brief Accessor for progress towards completion
float & progress() { return m_progress; }
\brief Accessor for rate of progress towards completion
float & rate() { return m_rate; }
\brief Accessor for additional attributes
int getAttr(const std::string & attr, Atlas::Message::Element & val) const;
\brief Sets additional attribute
void setAttr(const std::string & attr, const Atlas::Message::Element & val);
friend class Tasktest;
};
#endif // RULESETS_TASK_H |
package de.metas.edi.api;
import org.adempiere.util.ISingletonService;
import de.metas.edi.model.<API key>;
public interface IEDIInvoiceCandBL extends ISingletonService
{
void setEdiEnabled(final <API key> candidate);
} |
#!/usr/bin/env perl
# vcf-parallel.pl
# John Davey johnomics@gmail.com
use strict;
use warnings;
use Carp;
use English;
use Getopt::Long;
use Pod::Usage;
use Data::Dumper;
use Parallel::ForkManager;
$OUTPUT_AUTOFLUSH = 1;
my %args;
$args{vcf_filename} = "";
$args{vcf_subs} = "";
$args{threads} = 1;
$args{output_prefix} = "vcf-parallel-output";
$args{lengths_filename} = "";
$args{byscf} = 0;
$args{maxscf} = 0;
$args{uniquescf} = "";
$args{extraargs} = "";
my $options_okay = GetOptions(
'vcf=s' => \$args{vcf_filename},
'script=s' => \$args{vcf_subs},
'threads=i' => \$args{threads},
'output=s' => \$args{output_prefix},
'lengths=s' => \$args{lengths_filename},
'byscaffold' => \$args{byscf},
'maxscf=i' => \$args{maxscf},
'uniquescf=s' => \$args{uniquescf},
'extraargs=s' => \$args{extraargs},
);
croak "Can't process general options: $OS_ERROR\n" if !$options_okay;
croak "No VCF file! Please specify -v $OS_ERROR\n"
if ( $args{vcf_filename} eq "" );
our $setup;
our $process;
our $merge;
our $output;
if ( $args{vcf_subs} eq "" ) {
print STDERR "No script file given with -s, so will count lines in file\n";
$setup = sub {
my $args = shift;
open my $vcf_file, '<', $args->{vcf_filename}
or croak "Can't open VCF file $args->{vcf_filename}! $OS_ERROR\n";
my %samples;
my $vcf_line;
while ( $vcf_line = <$vcf_file> ) {
if ( $vcf_line =~ /^#CHROM/ ) {
last;
}
}
close $vcf_file;
chomp $vcf_line;
my @sample_names = split /\t/, $vcf_line;
map {
$samples{offspring}{lookup}{ $sample_names[$_] } = $_;
push @{ $samples{offspring}{order} }, $sample_names[$_];
} 9 .. $#sample_names;
\%samples;
};
$process = sub {
my ( $scf, $lines, $samples, $scfdata, $userdata ) = @_;
if ( ref($lines) eq "ARRAY" ) {
$scfdata->{lines} += @{$lines};
}
else {
$scfdata->{lines}++;
}
};
$merge = sub {
my ( $part, $all ) = @_;
return if !defined $part;
$all->{lines} += $part->{lines};
};
$output = sub {
my ( $data, $genome, $outfix ) = @_;
print "$data->{lines} lines in VCF file\n";
};
}
else {
require( $args{vcf_subs} );
}
my $genome = load_genome( \%args );
$genome->{scfp} = get_partitions( $genome, $args{threads} );
$args{threads} = keys %{ $genome->{scfp} }; # last thread may not be used;
# each part is always larger than minimum size, so scaffolds for final
# thread may be spread around the other threads
print_partitions( $genome->{scfp}, $genome->{scfl} );
my $userdata = $setup->( \%args );
$output->( parse_vcf( $genome, $userdata, \%args ), $genome, $args{output_prefix}, $userdata );
sub parse_vcf {
my ( $genome, $userdata, $argref ) = @_;
my %data;
# If only one thread specified, do not fork thread
# (This allows code to be profiled)
if ( $argref->{threads} == 1 ) {
my ( $partdata, $scfi ) = run_part( 1, $genome, $userdata, $argref );
print STDERR "1:Done, processed $scfi scaffolds of " . keys( %{ $genome->{scfp}{1} } ) . "\n";
$merge->( $partdata, \%data );
print STDERR "1:Merged\n";
return \%data;
}
my $part_pm = new Parallel::ForkManager( $argref->{threads} );
$part_pm->set_max_procs( $argref->{threads} );
$part_pm->run_on_finish(
sub {
my $pid = shift;
my $exit = shift;
my $part = shift;
my $childdata = pop;
$merge->( $childdata, \%data );
print STDERR "$part:Merged\n";
}
);
foreach my $part ( 1 .. $argref->{threads} ) {
$part_pm->start($part) and next;
my ( $partdata, $scfi ) = run_part( $part, $genome, $userdata, $argref );
print STDERR "$part:Done, processed $scfi scaffolds of " . keys( %{ $genome->{scfp}{$part} } ) . "\n";
$part_pm->finish( 0, $partdata );
}
$part_pm->wait_all_children;
\%data;
}
sub run_part {
my ( $part, $genome, $userdata, $argref ) = @_;
open my $vcf_file, '<', $argref->{vcf_filename}
or croak "Can't open $argref->{vcf_filename} $OS_ERROR!\n";
# Skip header
while (<$vcf_file>) {
last if (/^#CHROM/);
}
my $curscf = "";
my $scfi = 1;
my $foundpart = 0;
my %data;
my @scf_vcf;
my $scf;
my $process_this_scf;
while ( my $vcf_line = <$vcf_file> ) {
last if ( $argref->{maxscf} && $scfi >= $argref->{maxscf} );
$scf = $vcf_line =~ /^(.+?)\t/ ? $1 : "";
$curscf = $scf if $curscf eq ""; # Fill curscf at the start
$process_this_scf = ( $argref->{uniquescf} eq "" or $curscf eq $argref->{uniquescf} ) ? 1 : 0;
if ( defined $genome->{scfp}{$part}{$scf} ) {
$foundpart = 1;
if ( $curscf ne $scf ) {
if ( $argref->{byscf} && @scf_vcf ) {
$process->( $curscf, \@scf_vcf, \%data, $userdata, $genome->{scfl} ) if $process_this_scf;
@scf_vcf = ();
}
print_part_progress( $scfi, $part, $genome->{scfp} )
if ( $scfi % 10 == 0 );
$scfi++;
last if $curscf eq $argref->{uniquescf};
$curscf = $scf;
$process_this_scf = ( $argref->{uniquescf} eq "" or $curscf eq $argref->{uniquescf} ) ? 1 : 0;
}
$argref->{byscf}
? push @scf_vcf, $vcf_line
: $process->( $curscf, $vcf_line, \%data, $userdata, $genome->{scfl} )
if $process_this_scf;
}
else {
if ($foundpart) {
$process->( $curscf, \@scf_vcf, \%data, $userdata, $genome->{scfl} )
if $argref->{byscf}
&& $process_this_scf;
@scf_vcf = ();
$scfi--; # Last iteration will add an extra scaffold to the count,
# so remove it here, after part has been processed
last;
}
}
}
close $vcf_file;
$process->( $curscf, \@scf_vcf, \%data, $userdata, $genome->{scfl} )
if $argref->{byscf}
&& @scf_vcf
&& $process_this_scf;
return ( \%data, $scfi );
}
sub print_part_progress {
my ( $scfi, $part, $scfpref ) = @_;
printf STDERR "%3d:%4d scaffolds processed, %4d remaining\n", $part, $scfi, keys( %{ $scfpref->{$part} } ) - $scfi;
}
sub print_partitions {
my ( $scfpref, $scflref ) = @_;
my $genscf = 0;
my $genpartl = 0;
print STDERR "Part\tScaffolds\tLength\n";
foreach my $part ( sort { $a <=> $b } keys %{$scfpref} ) {
my $partl = 0;
my $numscf = keys %{ $scfpref->{$part} };
foreach my $scf ( keys %{ $scfpref->{$part} } ) {
$partl += $scflref->{$scf};
}
print STDERR "$part\t$numscf\t$partl\n";
$genscf += $numscf;
$genpartl += $partl;
}
print STDERR "Genome\t$genscf\t$genpartl\n";
return;
}
sub get_partitions {
my ( $genome, $threads ) = @_;
my %scfp;
my $part = 1;
my $threshold = $genome->{length} / $threads;
my $part_size = 0;
for my $scf ( @{ $genome->{scf} } ) {
$scfp{$part}{$scf}++;
$part_size += $genome->{scfl}{$scf};
if ( $part_size > $threshold ) {
$part_size = 0;
$part++;
}
}
\%scfp;
}
sub load_genome {
my $argref = shift;
my @scflines =
parse_vcf_header( $argref->{vcf_filename} )
or load_lengths( $argref->{lengths_filename} )
or croak "No scaffold lengths in VCF header or scaffold lengths file (-l)\n";
return load_scflen(@scflines);
}
sub load_scflen {
my @scflines = @_;
my %scfl;
my @scf;
my $genl = 0;
foreach my $scfline (@scflines) {
my ( $scf, $len ) = split /\t/, $scfline;
$scfl{$scf} = $len;
push @scf, $scf;
$genl += $len;
}
{ scfl => \%scfl, scf => \@scf, length => $genl };
}
sub parse_vcf_header {
my $vcf_filename = shift;
open my $vcf_file, '<', $vcf_filename
or croak "Can't open VCF file $vcf_filename! $OS_ERROR\n";
my @scflines;
my $vcf_line = <$vcf_file>;
while ( $vcf_line !~ /^#CHROM/ ) {
if ( $vcf_line =~ /^##contig=<ID=(.+),length=(\d+)>$/ ) {
push @scflines, "$1\t$2";
}
$vcf_line = <$vcf_file>;
}
close $vcf_file;
@scflines;
}
sub load_lengths {
my $lengths_filename = shift;
my @scflines;
return @scflines if ( $lengths_filename eq "" );
open my $lengths_file, "<", $lengths_filename
or croak "Can't open scaffold lengths file $lengths_filename! $OS_ERROR\n";
while ( my $scf_line = <$lengths_file> ) {
if ( $scf_line =~ /^(.+)\t(.+)$/ ) {
push @scflines, "$1\t$2";
}
}
close $lengths_file;
@scflines;
} |
#ifndef <API key>
#define <API key>
gd_region *dbfilopn (gd_region *reg);
void dbsecspc(gd_region *reg, sgmnt_data_ptr_t csd);
void db_init(gd_region *reg, sgmnt_data_ptr_t tsd);
void db_auto_upgrade(gd_region *reg);
#endif |
\hypertarget{<API key>}{}\section{x\+Task\+Create\+Restricted}
\label{<API key>}\index{x\+Task\+Create\+Restricted@{x\+Task\+Create\+Restricted}}
task. h
\begin{DoxyPre}
BaseType\_t <API key>( TaskParameters\_t *pxTaskDefinition, TaskHandle\_t *pxCreatedTask );\end{DoxyPre}
x\+Task\+Create\+Restricted() should only be used in systems that include an M\+PU implementation.
Create a new task and add it to the list of tasks that are ready to run. The function parameters define the memory regions and associated access permissions allocated to the task.
\begin{DoxyParams}{Parameters}
{\em px\+Task\+Definition} & Pointer to a structure that contains a member for each of the normal x\+Task\+Create() parameters (see the x\+Task\+Create() A\+PI documentation) plus an optional stack buffer and the memory region definitions.\\
\hline
{\em px\+Created\+Task} & Used to pass back a handle by which the created task can be referenced.\\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{Returns}
pd\+P\+A\+SS if the task was successfully created and added to a ready list, otherwise an error code defined in the file \hyperlink{projdefs_8h}{projdefs.\+h}
\end{DoxyReturn}
Example usage\+:
\begin{DoxyPre}
// Create an TaskParameters\_t structure that defines the task to be created.
static const TaskParameters\_t <API key> =
\{
vATask, // pvTaskCode - the function that implements the task.
"ATask", // pcName - just a text name for the task to assist debugging.
100, // usStackDepth - the stack size DEFINED IN WORDS.
NULL, // pvParameters - passed into the task function as the function parameters.
( 1UL | portPRIVILEGE\_BIT ),// uxPriority - task priority, set the portPRIVILEGE\_BIT if the task should run in a privileged state.
cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack.\end{DoxyPre}
\begin{DoxyPre} // xRegions - Allocate up to three separate memory regions for access by
// different memory alignment requirements - refer to the FreeRTOS documentation
// for full information.
\{
// Base address Length Parameters
\{ cReadWriteArray, 32, portMPU\_REGION\_READ\_WRITE \},
\{ cReadOnlyArray, 32, portMPU\_REGION\_READ\_ONLY \},
\{ <API key>, 128, portMPU\_REGION\_PRIVILEGED\_READ\_WRITE \}
\}
\};\end{DoxyPre}
\begin{DoxyPre}int \hyperlink{<API key>}{main( void )}
\{
TaskHandle\_t xHandle;
\begin{DoxyVerb}// Create a task from the const structure defined above. The task handle
// is requested (the second parameter is not NULL) but in this case just for
// demonstration purposes as its not actually used.
<API key>( &xRegTest1Parameters, &xHandle );
// Start the scheduler.
vTaskStartScheduler();
// Will only get here if there was insufficient memory to create the idle
// and/or timer task.
for( ;; );
\end{DoxyVerb}
\}
\end{DoxyPre}
task. h
\begin{DoxyPre}
void \hyperlink{<API key>}{<API key>( TaskHandle\_t xTask, const MemoryRegion\_t * const pxRegions )};\end{DoxyPre}
Memory regions are assigned to a restricted task when the task is created by a call to x\+Task\+Create\+Restricted(). These regions can be redefined using \hyperlink{<API key>}{v\+Task\+Allocate\+M\+P\+U\+Regions()}.
\begin{DoxyParams}{Parameters}
{\em x\+Task} & The handle of the task being updated.\\
\hline
{\em x\+Regions} & A pointer to an Memory\+Region\+\_\+t structure that contains the new memory region definitions.\\
\hline
\end{DoxyParams}
Example usage\+:
\begin{DoxyPre}
// Define an array of MemoryRegion\_t structures that configures an MPU region
// allowing read/write access for 1024 bytes starting at the beginning of the
// ucOneKByte array. The other two of the maximum 3 definable regions are
// unused so set to zero.
static const MemoryRegion\_t xAltRegions[ portNUM\_CONFIGURABLE\_REGIONS ] =
\{
// Base address Length Parameters
\{ ucOneKByte, 1024, portMPU\_REGION\_READ\_WRITE \},
\{ 0, 0, 0 \},
\{ 0, 0, 0 \}
\};\end{DoxyPre}
\begin{DoxyPre}void vATask( void *pvParameters )
\{
// This task was created such that it has access to certain regions of
// memory as defined by the MPU configuration. At some point it is
// desired that these MPU regions are replaced with that defined in the
// xAltRegions const struct above. Use a call to \hyperlink{<API key>}{<API key>()}
// for this purpose. NULL is used as the task handle to indicate that this
// function should modify the MPU regions of the calling task.
<API key>( NULL, xAltRegions );\end{DoxyPre}
\begin{DoxyPre} // Now the task can continue its function, but from this point on can only
// access its stack and the ucOneKByte array (unless any other statically
// defined or shared regions have been declared elsewhere).
\}
\end{DoxyPre} |
#include <linux/if.h>
#include <linux/module.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/if_ether.h>
#include <linux/ieee80211.h>
#include <linux/nl80211.h>
#include <linux/rtnetlink.h>
#include <linux/netlink.h>
#include <linux/etherdevice.h>
#include <net/net_namespace.h>
#include <net/genetlink.h>
#include <net/cfg80211.h>
#include <net/sock.h>
#include "core.h"
#include "nl80211.h"
#include "reg.h"
static bool <API key>(enum nl80211_auth_type auth_type);
static int <API key>(struct <API key> *rdev,
struct genl_info *info,
struct <API key> *settings,
int cipher_limit);
static int nl80211_pre_doit(struct genl_ops *ops, struct sk_buff *skb,
struct genl_info *info);
static void nl80211_post_doit(struct genl_ops *ops, struct sk_buff *skb,
struct genl_info *info);
/* the netlink family */
static struct genl_family nl80211_fam = {
.id = GENL_ID_GENERATE, /* don't bother with a hardcoded ID */
.name = "nl80211", /* have users key off the name instead */
.hdrsize = 0, /* no private header */
.version = 1, /* no particular meaning now */
.maxattr = NL80211_ATTR_MAX,
.netnsok = true,
.pre_doit = nl80211_pre_doit,
.post_doit = nl80211_post_doit,
};
/* internal helper: get rdev and dev */
static int <API key>(struct net *netns, struct nlattr **attrs,
struct <API key> **rdev,
struct net_device **dev)
{
int ifindex;
if (!attrs[<API key>])
return -EINVAL;
ifindex = nla_get_u32(attrs[<API key>]);
*dev = dev_get_by_index(netns, ifindex);
if (!*dev)
return -ENODEV;
*rdev = <API key>(netns, ifindex);
if (IS_ERR(*rdev)) {
dev_put(*dev);
return PTR_ERR(*rdev);
}
return 0;
}
/* policy for the attributes */
static const struct nla_policy nl80211_policy[NL80211_ATTR_MAX+1] = {
[NL80211_ATTR_WIPHY] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_NUL_STRING,
.len = 20-1 },
[<API key>] = { .type = NLA_NESTED },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U8 },
[NL80211_ATTR_IFTYPE] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U32 },
[NL80211_ATTR_IFNAME] = { .type = NLA_NUL_STRING, .len = IFNAMSIZ-1 },
[NL80211_ATTR_MAC] = { .len = ETH_ALEN },
[<API key>] = { .len = ETH_ALEN },
[NL80211_ATTR_KEY] = { .type = NLA_NESTED, },
[<API key>] = { .type = NLA_BINARY,
.len = WLAN_MAX_KEY_LEN },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_BINARY, .len = 16 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_BINARY,
.len = <API key> },
[<API key>] = { .type = NLA_BINARY,
.len = <API key> },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_NESTED },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_BINARY,
.len = <API key> },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { /* NLA_NESTED can't be empty */ },
[<API key>] = { .type = NLA_BINARY,
.len = <API key> },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_STRING, .len = 2 },
[<API key>] = { .type = NLA_NESTED },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_BINARY,
.len = <API key> },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_NESTED },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .len = <API key> },
[<API key>] = { .type = NLA_U8 },
[NL80211_ATTR_IE] = { .type = NLA_BINARY,
.len = <API key> },
[<API key>] = { .type = NLA_NESTED },
[<API key>] = { .type = NLA_NESTED },
[NL80211_ATTR_SSID] = { .type = NLA_BINARY,
.len = <API key> },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_U32 },
[<API key>] = {
.len = sizeof(struct <API key>),
},
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U32 },
[NL80211_ATTR_PID] = { .type = NLA_U32 },
[NL80211_ATTR_4ADDR] = { .type = NLA_U8 },
[NL80211_ATTR_PMKID] = { .type = NLA_BINARY,
.len = WLAN_PMKID_LEN },
[<API key>] = { .type = NLA_U32 },
[NL80211_ATTR_COOKIE] = { .type = NLA_U64 },
[<API key>] = { .type = NLA_NESTED },
[NL80211_ATTR_FRAME] = { .type = NLA_BINARY,
.len = <API key> },
[<API key>] = { .type = NLA_BINARY, },
[<API key>] = { .type = NLA_U32 },
[NL80211_ATTR_CQM] = { .type = NLA_NESTED, },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_NESTED },
[<API key>] = { .type = NLA_NESTED },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_NESTED },
[<API key>] = { .type = NLA_NESTED },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_BINARY,
.len = <API key> },
[<API key>] = { .type = NLA_BINARY,
.len = <API key> },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_NESTED },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_BINARY,
.len = <API key> },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = {
.len = <API key>
},
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_U16 },
[NL80211_ATTR_WDEV] = { .type = NLA_U64 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_BINARY, },
[<API key>] = { .len = <API key> },
[<API key>] = {. type = NLA_U32 },
[<API key>] = { .type = NLA_NESTED },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_BINARY, },
[<API key>] = { .type = NLA_FLAG, },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = {
.len = <API key>,
},
[NL80211_ATTR_MDID] = { .type = NLA_U16 },
[NL80211_ATTR_IE_RIC] = { .type = NLA_BINARY,
.len = <API key> },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_BINARY },
[<API key>] = { .type = NLA_BINARY },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_NESTED },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_BINARY },
[<API key>] = { .type = NLA_BINARY },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_BINARY },
[<API key>] = { .type = NLA_BINARY,
.len = <API key> },
[<API key>] = { .len = ETH_ALEN },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U32 },
};
/* policy for the key attributes */
static const struct nla_policy nl80211_key_policy[NL80211_KEY_MAX + 1] = {
[NL80211_KEY_DATA] = { .type = NLA_BINARY, .len = WLAN_MAX_KEY_LEN },
[NL80211_KEY_IDX] = { .type = NLA_U8 },
[NL80211_KEY_CIPHER] = { .type = NLA_U32 },
[NL80211_KEY_SEQ] = { .type = NLA_BINARY, .len = 16 },
[NL80211_KEY_DEFAULT] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
[NL80211_KEY_TYPE] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_NESTED },
};
/* policy for the key default flags */
static const struct nla_policy
<API key>[<API key>] = {
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
};
/* policy for WoWLAN attributes */
static const struct nla_policy
<API key>[<API key>] = {
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_NESTED },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
};
/* policy for GTK rekey offload attributes */
static const struct nla_policy
<API key>[<API key>] = {
[<API key>] = { .len = NL80211_KEK_LEN },
[<API key>] = { .len = NL80211_KCK_LEN },
[<API key>] = { .len = <API key> },
};
static const struct nla_policy
<API key>[<API key> + 1] = {
[<API key>] = { .type = NLA_BINARY,
.len = <API key> },
};
/* ifidx get helper */
static int nl80211_get_ifidx(struct netlink_callback *cb)
{
int res;
res = nlmsg_parse(cb->nlh, GENL_HDRLEN + nl80211_fam.hdrsize,
nl80211_fam.attrbuf, nl80211_fam.maxattr,
nl80211_policy);
if (res)
return res;
if (!nl80211_fam.attrbuf[<API key>])
return -EINVAL;
res = nla_get_u32(nl80211_fam.attrbuf[<API key>]);
if (!res)
return -EINVAL;
return res;
}
static int <API key>(struct sk_buff *skb,
struct netlink_callback *cb,
struct <API key> **rdev,
struct net_device **dev)
{
int ifidx = cb->args[0];
int err;
if (!ifidx)
ifidx = nl80211_get_ifidx(cb);
if (ifidx < 0)
return ifidx;
cb->args[0] = ifidx;
rtnl_lock();
*dev = __dev_get_by_index(sock_net(skb->sk), ifidx);
if (!*dev) {
err = -ENODEV;
goto out_rtnl;
}
*rdev = <API key>(sock_net(skb->sk), ifidx);
if (IS_ERR(*rdev)) {
err = PTR_ERR(*rdev);
goto out_rtnl;
}
return 0;
out_rtnl:
rtnl_unlock();
return err;
}
static void <API key>(struct <API key> *rdev)
{
<API key>(rdev);
rtnl_unlock();
}
/* IE validation */
static bool is_valid_ie_attr(const struct nlattr *attr)
{
const u8 *pos;
int len;
if (!attr)
return true;
pos = nla_data(attr);
len = nla_len(attr);
while (len) {
u8 elemlen;
if (len < 2)
return false;
len -= 2;
elemlen = pos[1];
if (elemlen > len)
return false;
len -= elemlen;
pos += 2 + elemlen;
}
return true;
}
/* message building helper */
static inline void *nl80211hdr_put(struct sk_buff *skb, u32 pid, u32 seq,
int flags, u8 cmd)
{
/* since there is no private header just add the generic one */
return genlmsg_put(skb, pid, seq, &nl80211_fam, flags, cmd);
}
static int <API key>(struct sk_buff *msg,
struct ieee80211_channel *chan)
{
NLA_PUT_U32(msg, <API key>,
chan->center_freq);
if (chan->flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
if (chan->flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
if (chan->flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
if (chan->flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
NLA_PUT_U32(msg, <API key>,
DBM_TO_MBM(chan->max_power));
return 0;
nla_put_failure:
return -ENOBUFS;
}
/* netlink command implementations */
struct key_parse {
struct key_params p;
int idx;
int type;
bool def, defmgmt;
bool def_uni, def_multi;
};
static int <API key>(struct nlattr *key, struct key_parse *k)
{
struct nlattr *tb[NL80211_KEY_MAX + 1];
int err = nla_parse_nested(tb, NL80211_KEY_MAX, key,
nl80211_key_policy);
if (err)
return err;
k->def = !!tb[NL80211_KEY_DEFAULT];
k->defmgmt = !!tb[<API key>];
if (k->def) {
k->def_uni = true;
k->def_multi = true;
}
if (k->defmgmt)
k->def_multi = true;
if (tb[NL80211_KEY_IDX])
k->idx = nla_get_u8(tb[NL80211_KEY_IDX]);
if (tb[NL80211_KEY_DATA]) {
k->p.key = nla_data(tb[NL80211_KEY_DATA]);
k->p.key_len = nla_len(tb[NL80211_KEY_DATA]);
}
if (tb[NL80211_KEY_SEQ]) {
k->p.seq = nla_data(tb[NL80211_KEY_SEQ]);
k->p.seq_len = nla_len(tb[NL80211_KEY_SEQ]);
}
if (tb[NL80211_KEY_CIPHER])
k->p.cipher = nla_get_u32(tb[NL80211_KEY_CIPHER]);
if (tb[NL80211_KEY_TYPE]) {
k->type = nla_get_u32(tb[NL80211_KEY_TYPE]);
if (k->type < 0 || k->type >= <API key>)
return -EINVAL;
}
if (tb[<API key>]) {
struct nlattr *kdt[<API key>];
err = nla_parse_nested(kdt, <API key> - 1,
tb[<API key>],
<API key>);
if (err)
return err;
k->def_uni = kdt[<API key>];
k->def_multi = kdt[<API key>];
}
return 0;
}
static int <API key>(struct genl_info *info, struct key_parse *k)
{
if (info->attrs[<API key>]) {
k->p.key = nla_data(info->attrs[<API key>]);
k->p.key_len = nla_len(info->attrs[<API key>]);
}
if (info->attrs[<API key>]) {
k->p.seq = nla_data(info->attrs[<API key>]);
k->p.seq_len = nla_len(info->attrs[<API key>]);
}
if (info->attrs[<API key>])
k->idx = nla_get_u8(info->attrs[<API key>]);
if (info->attrs[<API key>])
k->p.cipher = nla_get_u32(info->attrs[<API key>]);
k->def = !!info->attrs[<API key>];
k->defmgmt = !!info->attrs[<API key>];
if (k->def) {
k->def_uni = true;
k->def_multi = true;
}
if (k->defmgmt)
k->def_multi = true;
if (info->attrs[<API key>]) {
k->type = nla_get_u32(info->attrs[<API key>]);
if (k->type < 0 || k->type >= <API key>)
return -EINVAL;
}
if (info->attrs[<API key>]) {
struct nlattr *kdt[<API key>];
int err = nla_parse_nested(
kdt, <API key> - 1,
info->attrs[<API key>],
<API key>);
if (err)
return err;
k->def_uni = kdt[<API key>];
k->def_multi = kdt[<API key>];
}
return 0;
}
static int nl80211_parse_key(struct genl_info *info, struct key_parse *k)
{
int err;
memset(k, 0, sizeof(*k));
k->idx = -1;
k->type = -1;
if (info->attrs[NL80211_ATTR_KEY])
err = <API key>(info->attrs[NL80211_ATTR_KEY], k);
else
err = <API key>(info, k);
if (err)
return err;
if (k->def && k->defmgmt)
return -EINVAL;
if (k->defmgmt) {
if (k->def_uni || !k->def_multi)
return -EINVAL;
}
if (k->idx != -1) {
if (k->defmgmt) {
if (k->idx < 4 || k->idx > 5)
return -EINVAL;
} else if (k->def) {
if (k->idx < 0 || k->idx > 3)
return -EINVAL;
} else {
if (k->idx < 0 || k->idx > 5)
return -EINVAL;
}
}
return 0;
}
static struct <API key> *
<API key>(struct <API key> *rdev,
struct nlattr *keys)
{
struct key_parse parse;
struct nlattr *key;
struct <API key> *result;
int rem, err, def = 0;
result = kzalloc(sizeof(*result), GFP_KERNEL);
if (!result)
return ERR_PTR(-ENOMEM);
result->def = -1;
result->defmgmt = -1;
nla_for_each_nested(key, keys, rem) {
memset(&parse, 0, sizeof(parse));
parse.idx = -1;
err = <API key>(key, &parse);
if (err)
goto error;
err = -EINVAL;
if (!parse.p.key)
goto error;
if (parse.idx < 0 || parse.idx > 4)
goto error;
if (parse.def) {
if (def)
goto error;
def = 1;
result->def = parse.idx;
if (!parse.def_uni || !parse.def_multi)
goto error;
} else if (parse.defmgmt)
goto error;
err = <API key>(rdev, &parse.p,
parse.idx, false, NULL);
if (err)
goto error;
result->params[parse.idx].cipher = parse.p.cipher;
result->params[parse.idx].key_len = parse.p.key_len;
result->params[parse.idx].key = result->data[parse.idx];
memcpy(result->data[parse.idx], parse.p.key, parse.p.key_len);
}
return result;
error:
kfree(result);
return ERR_PTR(err);
}
static int nl80211_key_allowed(struct wireless_dev *wdev)
{
ASSERT_WDEV_LOCK(wdev);
switch (wdev->iftype) {
case NL80211_IFTYPE_AP:
case <API key>:
case <API key>:
case <API key>:
break;
case <API key>:
if (!wdev->current_bss)
return -ENOLINK;
break;
case <API key>:
case <API key>:
if (wdev->sme_state != <API key>)
return -ENOLINK;
break;
default:
return -EINVAL;
}
return 0;
}
static int nl80211_put_iftypes(struct sk_buff *msg, u32 attr, u16 ifmodes)
{
struct nlattr *nl_modes = nla_nest_start(msg, attr);
int i;
if (!nl_modes)
goto nla_put_failure;
i = 0;
while (ifmodes) {
if (ifmodes & 1)
NLA_PUT_FLAG(msg, i);
ifmodes >>= 1;
i++;
}
nla_nest_end(msg, nl_modes);
return 0;
nla_put_failure:
return -ENOBUFS;
}
static int <API key>(struct wiphy *wiphy,
struct sk_buff *msg)
{
struct nlattr *nl_combis;
int i, j;
nl_combis = nla_nest_start(msg,
<API key>);
if (!nl_combis)
goto nla_put_failure;
for (i = 0; i < wiphy-><API key>; i++) {
const struct <API key> *c;
struct nlattr *nl_combi, *nl_limits;
c = &wiphy->iface_combinations[i];
nl_combi = nla_nest_start(msg, i + 1);
if (!nl_combi)
goto nla_put_failure;
nl_limits = nla_nest_start(msg, <API key>);
if (!nl_limits)
goto nla_put_failure;
for (j = 0; j < c->n_limits; j++) {
struct nlattr *nl_limit;
nl_limit = nla_nest_start(msg, j + 1);
if (!nl_limit)
goto nla_put_failure;
NLA_PUT_U32(msg, <API key>,
c->limits[j].max);
if (nl80211_put_iftypes(msg, <API key>,
c->limits[j].types))
goto nla_put_failure;
nla_nest_end(msg, nl_limit);
}
nla_nest_end(msg, nl_limits);
if (c-><API key>)
NLA_PUT_FLAG(msg,
<API key>);
NLA_PUT_U32(msg, <API key>,
c-><API key>);
NLA_PUT_U32(msg, <API key>,
c->max_interfaces);
nla_nest_end(msg, nl_combi);
}
nla_nest_end(msg, nl_combis);
return 0;
nla_put_failure:
return -ENOBUFS;
}
static int nl80211_send_wiphy(struct sk_buff *msg, u32 pid, u32 seq, int flags,
struct <API key> *dev)
{
void *hdr;
struct nlattr *nl_bands, *nl_band;
struct nlattr *nl_freqs, *nl_freq;
struct nlattr *nl_rates, *nl_rate;
struct nlattr *nl_cmds;
enum ieee80211_band band;
struct ieee80211_channel *chan;
struct ieee80211_rate *rate;
int i;
const struct <API key> *mgmt_stypes =
dev->wiphy.mgmt_stypes;
hdr = nl80211hdr_put(msg, pid, seq, flags, <API key>);
if (!hdr)
return -1;
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, dev->wiphy_idx);
NLA_PUT_STRING(msg, <API key>, wiphy_name(&dev->wiphy));
NLA_PUT_U32(msg, <API key>,
<API key>);
NLA_PUT_U8(msg, <API key>,
dev->wiphy.retry_short);
NLA_PUT_U8(msg, <API key>,
dev->wiphy.retry_long);
NLA_PUT_U32(msg, <API key>,
dev->wiphy.frag_threshold);
NLA_PUT_U32(msg, <API key>,
dev->wiphy.rts_threshold);
NLA_PUT_U8(msg, <API key>,
dev->wiphy.coverage_class);
NLA_PUT_U8(msg, <API key>,
dev->wiphy.max_scan_ssids);
NLA_PUT_U8(msg, <API key>,
dev->wiphy.<API key>);
NLA_PUT_U16(msg, <API key>,
dev->wiphy.max_scan_ie_len);
NLA_PUT_U16(msg, <API key>,
dev->wiphy.<API key>);
NLA_PUT_U8(msg, <API key>,
dev->wiphy.max_match_sets);
if (dev->wiphy.flags & WIPHY_FLAG_IBSS_RSN)
NLA_PUT_FLAG(msg, <API key>);
if (dev->wiphy.flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
if (dev->wiphy.flags & WIPHY_FLAG_AP_UAPSD)
NLA_PUT_FLAG(msg, <API key>);
if (dev->wiphy.flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
if (dev->wiphy.flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
if (dev->wiphy.flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
NLA_PUT(msg, <API key>,
sizeof(u32) * dev->wiphy.n_cipher_suites,
dev->wiphy.cipher_suites);
NLA_PUT_U8(msg, <API key>,
dev->wiphy.max_num_pmkids);
if (dev->wiphy.flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
NLA_PUT_U32(msg, <API key>,
dev->wiphy.<API key>);
NLA_PUT_U32(msg, <API key>,
dev->wiphy.<API key>);
if (dev->wiphy.flags & <API key>)
NLA_PUT_U32(msg, <API key>,
dev->wiphy.probe_resp_offload);
if ((dev->wiphy.<API key> ||
dev->wiphy.<API key>) && dev->ops->get_antenna) {
u32 tx_ant = 0, rx_ant = 0;
int res;
res = dev->ops->get_antenna(&dev->wiphy, &tx_ant, &rx_ant);
if (!res) {
NLA_PUT_U32(msg, <API key>, tx_ant);
NLA_PUT_U32(msg, <API key>, rx_ant);
}
}
if (nl80211_put_iftypes(msg, <API key>,
dev->wiphy.interface_modes))
goto nla_put_failure;
nl_bands = nla_nest_start(msg, <API key>);
if (!nl_bands)
goto nla_put_failure;
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
if (!dev->wiphy.bands[band])
continue;
nl_band = nla_nest_start(msg, band);
if (!nl_band)
goto nla_put_failure;
/* add HT info */
if (dev->wiphy.bands[band]->ht_cap.ht_supported) {
NLA_PUT(msg, <API key>,
sizeof(dev->wiphy.bands[band]->ht_cap.mcs),
&dev->wiphy.bands[band]->ht_cap.mcs);
NLA_PUT_U16(msg, <API key>,
dev->wiphy.bands[band]->ht_cap.cap);
NLA_PUT_U8(msg, <API key>,
dev->wiphy.bands[band]->ht_cap.ampdu_factor);
NLA_PUT_U8(msg, <API key>,
dev->wiphy.bands[band]->ht_cap.ampdu_density);
}
/* add VHT info */
if (dev->wiphy.bands[band]->vht_cap.vht_supported &&
(nla_put(msg, <API key>,
sizeof(dev->wiphy.bands[band]->vht_cap.vht_mcs),
&dev->wiphy.bands[band]->vht_cap.vht_mcs) ||
nla_put_u32(msg, <API key>,
dev->wiphy.bands[band]->vht_cap.cap)))
goto nla_put_failure;
/* add frequencies */
nl_freqs = nla_nest_start(msg, <API key>);
if (!nl_freqs)
goto nla_put_failure;
for (i = 0; i < dev->wiphy.bands[band]->n_channels; i++) {
nl_freq = nla_nest_start(msg, i);
if (!nl_freq)
goto nla_put_failure;
chan = &dev->wiphy.bands[band]->channels[i];
if (<API key>(msg, chan))
goto nla_put_failure;
nla_nest_end(msg, nl_freq);
}
nla_nest_end(msg, nl_freqs);
/* add bitrates */
nl_rates = nla_nest_start(msg, <API key>);
if (!nl_rates)
goto nla_put_failure;
for (i = 0; i < dev->wiphy.bands[band]->n_bitrates; i++) {
nl_rate = nla_nest_start(msg, i);
if (!nl_rate)
goto nla_put_failure;
rate = &dev->wiphy.bands[band]->bitrates[i];
NLA_PUT_U32(msg, <API key>,
rate->bitrate);
if (rate->flags & <API key>)
NLA_PUT_FLAG(msg,
<API key>);
nla_nest_end(msg, nl_rate);
}
nla_nest_end(msg, nl_rates);
nla_nest_end(msg, nl_band);
}
nla_nest_end(msg, nl_bands);
nl_cmds = nla_nest_start(msg, <API key>);
if (!nl_cmds)
goto nla_put_failure;
i = 0;
#define CMD(op, n) \
do { \
if (dev->ops->op) { \
i++; \
NLA_PUT_U32(msg, i, NL80211_CMD_
} \
} while (0)
CMD(add_virtual_intf, NEW_INTERFACE);
CMD(change_virtual_intf, SET_INTERFACE);
CMD(add_key, NEW_KEY);
CMD(start_ap, START_AP);
CMD(add_station, NEW_STATION);
CMD(add_mpath, NEW_MPATH);
CMD(update_mesh_config, SET_MESH_CONFIG);
CMD(change_bss, SET_BSS);
CMD(auth, AUTHENTICATE);
CMD(assoc, ASSOCIATE);
CMD(deauth, DEAUTHENTICATE);
CMD(disassoc, DISASSOCIATE);
CMD(join_ibss, JOIN_IBSS);
CMD(join_mesh, JOIN_MESH);
CMD(set_pmksa, SET_PMKSA);
CMD(del_pmksa, DEL_PMKSA);
CMD(flush_pmksa, FLUSH_PMKSA);
if (dev->wiphy.flags & <API key>)
CMD(remain_on_channel, REMAIN_ON_CHANNEL);
CMD(set_bitrate_mask, SET_TX_BITRATE_MASK);
CMD(mgmt_tx, FRAME);
CMD(mgmt_tx_cancel_wait, FRAME_WAIT_CANCEL);
if (dev->wiphy.flags & WIPHY_FLAG_NETNS_OK) {
i++;
NLA_PUT_U32(msg, i, <API key>);
}
CMD(set_channel, SET_CHANNEL);
CMD(set_wds_peer, SET_WDS_PEER);
if (dev->wiphy.flags & <API key>) {
CMD(tdls_mgmt, TDLS_MGMT);
CMD(tdls_oper, TDLS_OPER);
}
if (dev->wiphy.flags & <API key>)
CMD(sched_scan_start, START_SCHED_SCAN);
CMD(probe_client, PROBE_CLIENT);
CMD(set_noack_map, SET_NOACK_MAP);
if (dev->wiphy.flags & <API key>) {
i++;
NLA_PUT_U32(msg, i, <API key>);
}
CMD(set_qos_map, SET_QOS_MAP);
#ifdef <API key>
CMD(testmode_cmd, TESTMODE);
#endif
#undef CMD
if (dev->ops->connect || dev->ops->auth) {
i++;
NLA_PUT_U32(msg, i, NL80211_CMD_CONNECT);
}
if (dev->ops->disconnect || dev->ops->deauth) {
i++;
NLA_PUT_U32(msg, i, <API key>);
}
nla_nest_end(msg, nl_cmds);
if (dev->ops->remain_on_channel &&
dev->wiphy.flags & <API key>)
NLA_PUT_U32(msg, <API key>,
dev->wiphy.<API key>);
if (dev->wiphy.flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
if (mgmt_stypes) {
u16 stypes;
struct nlattr *nl_ftypes, *nl_ifs;
enum nl80211_iftype ift;
nl_ifs = nla_nest_start(msg, <API key>);
if (!nl_ifs)
goto nla_put_failure;
for (ift = 0; ift < NUM_NL80211_IFTYPES; ift++) {
nl_ftypes = nla_nest_start(msg, ift);
if (!nl_ftypes)
goto nla_put_failure;
i = 0;
stypes = mgmt_stypes[ift].tx;
while (stypes) {
if (stypes & 1)
NLA_PUT_U16(msg, <API key>,
(i << 4) | <API key>);
stypes >>= 1;
i++;
}
nla_nest_end(msg, nl_ftypes);
}
nla_nest_end(msg, nl_ifs);
nl_ifs = nla_nest_start(msg, <API key>);
if (!nl_ifs)
goto nla_put_failure;
for (ift = 0; ift < NUM_NL80211_IFTYPES; ift++) {
nl_ftypes = nla_nest_start(msg, ift);
if (!nl_ftypes)
goto nla_put_failure;
i = 0;
stypes = mgmt_stypes[ift].rx;
while (stypes) {
if (stypes & 1)
NLA_PUT_U16(msg, <API key>,
(i << 4) | <API key>);
stypes >>= 1;
i++;
}
nla_nest_end(msg, nl_ftypes);
}
nla_nest_end(msg, nl_ifs);
}
if (dev->wiphy.wowlan.flags || dev->wiphy.wowlan.n_patterns) {
struct nlattr *nl_wowlan;
nl_wowlan = nla_nest_start(msg,
<API key>);
if (!nl_wowlan)
goto nla_put_failure;
if (dev->wiphy.wowlan.flags & WIPHY_WOWLAN_ANY)
NLA_PUT_FLAG(msg, <API key>);
if (dev->wiphy.wowlan.flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
if (dev->wiphy.wowlan.flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
if (dev->wiphy.wowlan.flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
if (dev->wiphy.wowlan.flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
if (dev->wiphy.wowlan.flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
if (dev->wiphy.wowlan.flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
if (dev->wiphy.wowlan.flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
if (dev->wiphy.wowlan.n_patterns) {
struct <API key> pat = {
.max_patterns = dev->wiphy.wowlan.n_patterns,
.min_pattern_len =
dev->wiphy.wowlan.pattern_min_len,
.max_pattern_len =
dev->wiphy.wowlan.pattern_max_len,
};
NLA_PUT(msg, <API key>,
sizeof(pat), &pat);
}
nla_nest_end(msg, nl_wowlan);
}
if (nl80211_put_iftypes(msg, <API key>,
dev->wiphy.software_iftypes))
goto nla_put_failure;
if (<API key>(&dev->wiphy, msg))
goto nla_put_failure;
if (dev->wiphy.flags & <API key>)
NLA_PUT_U32(msg, <API key>,
dev->wiphy.ap_sme_capa);
NLA_PUT_U32(msg, <API key>, dev->wiphy.features);
if (dev->wiphy.ht_capa_mod_mask)
NLA_PUT(msg, <API key>,
sizeof(*dev->wiphy.ht_capa_mod_mask),
dev->wiphy.ht_capa_mod_mask);
if (dev->wiphy.flags & <API key> &&
dev->wiphy.max_acl_mac_addrs)
NLA_PUT_U32(msg, <API key>,
dev->wiphy.max_acl_mac_addrs);
if (dev->wiphy.max_ap_assoc_sta &&
nla_put_u32(msg, <API key>,
dev->wiphy.max_ap_assoc_sta))
goto nla_put_failure;
if (dev->wiphy.n_vendor_commands) {
const struct <API key> *info;
struct nlattr *nested;
nested = nla_nest_start(msg, <API key>);
if (!nested)
goto nla_put_failure;
for (i = 0; i < dev->wiphy.n_vendor_commands; i++) {
info = &dev->wiphy.vendor_commands[i].info;
if (nla_put(msg, i + 1, sizeof(*info), info))
goto nla_put_failure;
}
nla_nest_end(msg, nested);
}
if (dev->wiphy.n_vendor_events) {
const struct <API key> *info;
struct nlattr *nested;
nested = nla_nest_start(msg,
<API key>);
if (!nested)
goto nla_put_failure;
for (i = 0; i < dev->wiphy.n_vendor_events; i++) {
info = &dev->wiphy.vendor_events[i];
if (nla_put(msg, i + 1, sizeof(*info), info))
goto nla_put_failure;
}
nla_nest_end(msg, nested);
}
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nl80211_dump_wiphy(struct sk_buff *skb, struct netlink_callback *cb)
{
int idx = 0;
int start = cb->args[0];
struct <API key> *dev;
mutex_lock(&cfg80211_mutex);
list_for_each_entry(dev, &cfg80211_rdev_list, list) {
if (!net_eq(wiphy_net(&dev->wiphy), sock_net(skb->sk)))
continue;
if (++idx <= start)
continue;
if (nl80211_send_wiphy(skb, NETLINK_CB(cb->skb).pid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
dev) < 0) {
idx
break;
}
}
mutex_unlock(&cfg80211_mutex);
cb->args[0] = idx;
return skb->len;
}
static int nl80211_get_wiphy(struct sk_buff *skb, struct genl_info *info)
{
struct sk_buff *msg;
struct <API key> *dev = info->user_ptr[0];
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
if (nl80211_send_wiphy(msg, info->snd_pid, info->snd_seq, 0, dev) < 0) {
nlmsg_free(msg);
return -ENOBUFS;
}
return genlmsg_reply(msg, info);
}
static const struct nla_policy txq_params_policy[<API key> + 1] = {
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_U8 },
};
static int parse_txq_params(struct nlattr *tb[],
struct <API key> *txq_params)
{
if (!tb[<API key>] || !tb[<API key>] ||
!tb[<API key>] || !tb[<API key>] ||
!tb[<API key>])
return -EINVAL;
txq_params->queue = nla_get_u8(tb[<API key>]);
txq_params->txop = nla_get_u16(tb[<API key>]);
txq_params->cwmin = nla_get_u16(tb[<API key>]);
txq_params->cwmax = nla_get_u16(tb[<API key>]);
txq_params->aifs = nla_get_u8(tb[<API key>]);
return 0;
}
static bool <API key>(struct wireless_dev *wdev)
{
/*
* You can only set the channel explicitly for AP, mesh
* and WDS type interfaces; all others have their channel
* managed via their respective "establish a connection"
* command (connect, join, ...)
*
* Monitors are special as they are normally slaved to
* whatever else is going on, so they behave as though
* you tried setting the wiphy channel itself.
*/
return !wdev ||
wdev->iftype == NL80211_IFTYPE_AP ||
wdev->iftype == NL80211_IFTYPE_WDS ||
wdev->iftype == <API key> ||
wdev->iftype == <API key> ||
wdev->iftype == <API key>;
}
static int <API key>(struct <API key> *rdev,
struct wireless_dev *wdev,
struct genl_info *info)
{
enum <API key> channel_type = NL80211_CHAN_NO_HT;
u32 freq;
int result;
if (!info->attrs[<API key>])
return -EINVAL;
if (!<API key>(wdev))
return -EOPNOTSUPP;
if (info->attrs[<API key>]) {
channel_type = nla_get_u32(info->attrs[
<API key>]);
if (channel_type != NL80211_CHAN_NO_HT &&
channel_type != NL80211_CHAN_HT20 &&
channel_type != <API key> &&
channel_type != <API key>)
return -EINVAL;
}
freq = nla_get_u32(info->attrs[<API key>]);
mutex_lock(&rdev->devlist_mtx);
if (wdev) {
wdev_lock(wdev);
result = cfg80211_set_freq(rdev, wdev, freq, channel_type);
wdev_unlock(wdev);
} else {
result = cfg80211_set_freq(rdev, NULL, freq, channel_type);
}
mutex_unlock(&rdev->devlist_mtx);
return result;
}
static int nl80211_set_channel(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *netdev = info->user_ptr[1];
return <API key>(rdev, netdev->ieee80211_ptr, info);
}
static int <API key>(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
const u8 *bssid;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (netif_running(dev))
return -EBUSY;
if (!rdev->ops->set_wds_peer)
return -EOPNOTSUPP;
if (wdev->iftype != NL80211_IFTYPE_WDS)
return -EOPNOTSUPP;
bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
return rdev->ops->set_wds_peer(wdev->wiphy, dev, bssid);
}
static int nl80211_set_wiphy(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev;
struct net_device *netdev = NULL;
struct wireless_dev *wdev;
int result = 0, rem_txq_params = 0;
struct nlattr *nl_txq_params;
u32 changed;
u8 retry_short = 0, retry_long = 0;
u32 frag_threshold = 0, rts_threshold = 0;
u8 coverage_class = 0;
/*
* Try to find the wiphy and netdev. Normally this
* function shouldn't need the netdev, but this is
* done for backward compatibility -- previously
* setting the channel was done per wiphy, but now
* it is per netdev. Previous userland like hostapd
* also passed a netdev to set_wiphy, so that it is
* possible to let that go to the right netdev!
*/
mutex_lock(&cfg80211_mutex);
if (info->attrs[<API key>]) {
int ifindex = nla_get_u32(info->attrs[<API key>]);
netdev = dev_get_by_index(genl_info_net(info), ifindex);
if (netdev && netdev->ieee80211_ptr) {
rdev = wiphy_to_dev(netdev->ieee80211_ptr->wiphy);
mutex_lock(&rdev->mtx);
} else
netdev = NULL;
}
if (!netdev) {
rdev = <API key>(info);
if (IS_ERR(rdev)) {
mutex_unlock(&cfg80211_mutex);
return PTR_ERR(rdev);
}
wdev = NULL;
netdev = NULL;
result = 0;
mutex_lock(&rdev->mtx);
} else if (netif_running(netdev) &&
<API key>(netdev->ieee80211_ptr))
wdev = netdev->ieee80211_ptr;
else
wdev = NULL;
/*
* end workaround code, by now the rdev is available
* and locked, and wdev may or may not be NULL.
*/
if (info->attrs[<API key>])
result = cfg80211_dev_rename(
rdev, nla_data(info->attrs[<API key>]));
mutex_unlock(&cfg80211_mutex);
if (result)
goto bad_res;
if (info->attrs[<API key>]) {
struct <API key> txq_params;
struct nlattr *tb[<API key> + 1];
if (!rdev->ops->set_txq_params) {
result = -EOPNOTSUPP;
goto bad_res;
}
if (!netdev) {
result = -EINVAL;
goto bad_res;
}
if (netdev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
netdev->ieee80211_ptr->iftype != <API key>) {
result = -EINVAL;
goto bad_res;
}
if (!netif_running(netdev)) {
result = -ENETDOWN;
goto bad_res;
}
nla_for_each_nested(nl_txq_params,
info->attrs[<API key>],
rem_txq_params) {
nla_parse(tb, <API key>,
nla_data(nl_txq_params),
nla_len(nl_txq_params),
txq_params_policy);
result = parse_txq_params(tb, &txq_params);
if (result)
goto bad_res;
result = rdev->ops->set_txq_params(&rdev->wiphy,
netdev,
&txq_params);
if (result)
goto bad_res;
}
}
if (info->attrs[<API key>]) {
result = <API key>(rdev, wdev, info);
if (result)
goto bad_res;
}
if (info->attrs[<API key>]) {
enum <API key> type;
int idx, mbm = 0;
if (!rdev->ops->set_tx_power) {
result = -EOPNOTSUPP;
goto bad_res;
}
idx = <API key>;
type = nla_get_u32(info->attrs[idx]);
if (!info->attrs[<API key>] &&
(type != <API key>)) {
result = -EINVAL;
goto bad_res;
}
if (type != <API key>) {
idx = <API key>;
mbm = nla_get_u32(info->attrs[idx]);
}
result = rdev->ops->set_tx_power(&rdev->wiphy, type, mbm);
if (result)
goto bad_res;
}
if (info->attrs[<API key>] &&
info->attrs[<API key>]) {
u32 tx_ant, rx_ant;
if ((!rdev->wiphy.<API key> &&
!rdev->wiphy.<API key>) ||
!rdev->ops->set_antenna) {
result = -EOPNOTSUPP;
goto bad_res;
}
tx_ant = nla_get_u32(info->attrs[<API key>]);
rx_ant = nla_get_u32(info->attrs[<API key>]);
/* reject antenna configurations which don't match the
* available antenna masks, except for the "all" mask */
if ((~tx_ant && (tx_ant & ~rdev->wiphy.<API key>)) ||
(~rx_ant && (rx_ant & ~rdev->wiphy.<API key>))) {
result = -EINVAL;
goto bad_res;
}
tx_ant = tx_ant & rdev->wiphy.<API key>;
rx_ant = rx_ant & rdev->wiphy.<API key>;
result = rdev->ops->set_antenna(&rdev->wiphy, tx_ant, rx_ant);
if (result)
goto bad_res;
}
changed = 0;
if (info->attrs[<API key>]) {
retry_short = nla_get_u8(
info->attrs[<API key>]);
if (retry_short == 0) {
result = -EINVAL;
goto bad_res;
}
changed |= <API key>;
}
if (info->attrs[<API key>]) {
retry_long = nla_get_u8(
info->attrs[<API key>]);
if (retry_long == 0) {
result = -EINVAL;
goto bad_res;
}
changed |= <API key>;
}
if (info->attrs[<API key>]) {
frag_threshold = nla_get_u32(
info->attrs[<API key>]);
if (frag_threshold < 256) {
result = -EINVAL;
goto bad_res;
}
if (frag_threshold != (u32) -1) {
/*
* Fragments (apart from the last one) are required to
* have even length. Make the fragmentation code
* simpler by stripping LSB should someone try to use
* odd threshold value.
*/
frag_threshold &= ~0x1;
}
changed |= <API key>;
}
if (info->attrs[<API key>]) {
rts_threshold = nla_get_u32(
info->attrs[<API key>]);
changed |= <API key>;
}
if (info->attrs[<API key>]) {
coverage_class = nla_get_u8(
info->attrs[<API key>]);
changed |= <API key>;
}
if (changed) {
u8 old_retry_short, old_retry_long;
u32 old_frag_threshold, old_rts_threshold;
u8 old_coverage_class;
if (!rdev->ops->set_wiphy_params) {
result = -EOPNOTSUPP;
goto bad_res;
}
old_retry_short = rdev->wiphy.retry_short;
old_retry_long = rdev->wiphy.retry_long;
old_frag_threshold = rdev->wiphy.frag_threshold;
old_rts_threshold = rdev->wiphy.rts_threshold;
old_coverage_class = rdev->wiphy.coverage_class;
if (changed & <API key>)
rdev->wiphy.retry_short = retry_short;
if (changed & <API key>)
rdev->wiphy.retry_long = retry_long;
if (changed & <API key>)
rdev->wiphy.frag_threshold = frag_threshold;
if (changed & <API key>)
rdev->wiphy.rts_threshold = rts_threshold;
if (changed & <API key>)
rdev->wiphy.coverage_class = coverage_class;
result = rdev->ops->set_wiphy_params(&rdev->wiphy, changed);
if (result) {
rdev->wiphy.retry_short = old_retry_short;
rdev->wiphy.retry_long = old_retry_long;
rdev->wiphy.frag_threshold = old_frag_threshold;
rdev->wiphy.rts_threshold = old_rts_threshold;
rdev->wiphy.coverage_class = old_coverage_class;
}
}
bad_res:
mutex_unlock(&rdev->mtx);
if (netdev)
dev_put(netdev);
return result;
}
static int nl80211_send_iface(struct sk_buff *msg, u32 pid, u32 seq, int flags,
struct <API key> *rdev,
struct net_device *dev)
{
void *hdr;
hdr = nl80211hdr_put(msg, pid, seq, flags, <API key>);
if (!hdr)
return -1;
NLA_PUT_U32(msg, <API key>, dev->ifindex);
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, dev->name);
NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, dev->ieee80211_ptr->iftype);
NLA_PUT_U32(msg, <API key>,
rdev->devlist_generation ^
(<API key> << 2));
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int <API key>(struct sk_buff *skb, struct netlink_callback *cb)
{
int wp_idx = 0;
int if_idx = 0;
int wp_start = cb->args[0];
int if_start = cb->args[1];
struct <API key> *rdev;
struct wireless_dev *wdev;
mutex_lock(&cfg80211_mutex);
list_for_each_entry(rdev, &cfg80211_rdev_list, list) {
if (!net_eq(wiphy_net(&rdev->wiphy), sock_net(skb->sk)))
continue;
if (wp_idx < wp_start) {
wp_idx++;
continue;
}
if_idx = 0;
mutex_lock(&rdev->devlist_mtx);
list_for_each_entry(wdev, &rdev->netdev_list, list) {
if (if_idx < if_start) {
if_idx++;
continue;
}
if (nl80211_send_iface(skb, NETLINK_CB(cb->skb).pid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
rdev, wdev->netdev) < 0) {
mutex_unlock(&rdev->devlist_mtx);
goto out;
}
if_idx++;
}
mutex_unlock(&rdev->devlist_mtx);
wp_idx++;
}
out:
mutex_unlock(&cfg80211_mutex);
cb->args[0] = wp_idx;
cb->args[1] = if_idx;
return skb->len;
}
static int <API key>(struct sk_buff *skb, struct genl_info *info)
{
struct sk_buff *msg;
struct <API key> *dev = info->user_ptr[0];
struct net_device *netdev = info->user_ptr[1];
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
if (nl80211_send_iface(msg, info->snd_pid, info->snd_seq, 0,
dev, netdev) < 0) {
nlmsg_free(msg);
return -ENOBUFS;
}
return genlmsg_reply(msg, info);
}
static const struct nla_policy mntr_flags_policy[<API key> + 1] = {
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
};
static int parse_monitor_flags(struct nlattr *nla, u32 *mntrflags)
{
struct nlattr *flags[<API key> + 1];
int flag;
*mntrflags = 0;
if (!nla)
return -EINVAL;
if (nla_parse_nested(flags, <API key>,
nla, mntr_flags_policy))
return -EINVAL;
for (flag = 1; flag <= <API key>; flag++)
if (flags[flag])
*mntrflags |= (1<<flag);
return 0;
}
static int nl80211_valid_4addr(struct <API key> *rdev,
struct net_device *netdev, u8 use_4addr,
enum nl80211_iftype iftype)
{
if (!use_4addr) {
if (netdev && (netdev->priv_flags & IFF_BRIDGE_PORT))
return -EBUSY;
return 0;
}
switch (iftype) {
case <API key>:
if (rdev->wiphy.flags & WIPHY_FLAG_4ADDR_AP)
return 0;
break;
case <API key>:
if (rdev->wiphy.flags & <API key>)
return 0;
break;
default:
break;
}
return -EOPNOTSUPP;
}
static int <API key>(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct vif_params params;
int err;
enum nl80211_iftype otype, ntype;
struct net_device *dev = info->user_ptr[1];
u32 _flags, *flags = NULL;
bool change = false;
memset(¶ms, 0, sizeof(params));
otype = ntype = dev->ieee80211_ptr->iftype;
if (info->attrs[NL80211_ATTR_IFTYPE]) {
ntype = nla_get_u32(info->attrs[NL80211_ATTR_IFTYPE]);
if (otype != ntype)
change = true;
if (ntype > NL80211_IFTYPE_MAX)
return -EINVAL;
}
if (info->attrs[<API key>]) {
struct wireless_dev *wdev = dev->ieee80211_ptr;
if (ntype != <API key>)
return -EINVAL;
if (netif_running(dev))
return -EBUSY;
wdev_lock(wdev);
BUILD_BUG_ON(<API key> !=
<API key>);
wdev->mesh_id_up_len =
nla_len(info->attrs[<API key>]);
memcpy(wdev->ssid, nla_data(info->attrs[<API key>]),
wdev->mesh_id_up_len);
wdev_unlock(wdev);
}
if (info->attrs[NL80211_ATTR_4ADDR]) {
params.use_4addr = !!nla_get_u8(info->attrs[NL80211_ATTR_4ADDR]);
change = true;
err = nl80211_valid_4addr(rdev, dev, params.use_4addr, ntype);
if (err)
return err;
} else {
params.use_4addr = -1;
}
if (info->attrs[<API key>]) {
if (ntype != <API key>)
return -EINVAL;
err = parse_monitor_flags(info->attrs[<API key>],
&_flags);
if (err)
return err;
flags = &_flags;
change = true;
}
if (change)
err = <API key>(rdev, dev, ntype, flags, ¶ms);
else
err = 0;
if (!err && params.use_4addr != -1)
dev->ieee80211_ptr->use_4addr = params.use_4addr;
return err;
}
static int <API key>(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct vif_params params;
struct net_device *dev;
int err;
enum nl80211_iftype type = <API key>;
u32 flags;
memset(¶ms, 0, sizeof(params));
if (!info->attrs[NL80211_ATTR_IFNAME])
return -EINVAL;
if (info->attrs[NL80211_ATTR_IFTYPE]) {
type = nla_get_u32(info->attrs[NL80211_ATTR_IFTYPE]);
if (type > NL80211_IFTYPE_MAX)
return -EINVAL;
}
if (!rdev->ops->add_virtual_intf ||
!(rdev->wiphy.interface_modes & (1 << type)))
return -EOPNOTSUPP;
if (info->attrs[NL80211_ATTR_4ADDR]) {
params.use_4addr = !!nla_get_u8(info->attrs[NL80211_ATTR_4ADDR]);
err = nl80211_valid_4addr(rdev, NULL, params.use_4addr, type);
if (err)
return err;
}
err = parse_monitor_flags(type == <API key> ?
info->attrs[<API key>] : NULL,
&flags);
dev = rdev->ops->add_virtual_intf(&rdev->wiphy,
nla_data(info->attrs[NL80211_ATTR_IFNAME]),
type, err ? NULL : &flags, ¶ms);
if (IS_ERR(dev))
return PTR_ERR(dev);
if (type == <API key> &&
info->attrs[<API key>]) {
struct wireless_dev *wdev = dev->ieee80211_ptr;
wdev_lock(wdev);
BUILD_BUG_ON(<API key> !=
<API key>);
wdev->mesh_id_up_len =
nla_len(info->attrs[<API key>]);
memcpy(wdev->ssid, nla_data(info->attrs[<API key>]),
wdev->mesh_id_up_len);
wdev_unlock(wdev);
}
return 0;
}
static int <API key>(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
if (!rdev->ops->del_virtual_intf)
return -EOPNOTSUPP;
return rdev->ops->del_virtual_intf(&rdev->wiphy, dev);
}
static int <API key>(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u16 noack_map;
if (!info->attrs[<API key>])
return -EINVAL;
if (!rdev->ops->set_noack_map)
return -EOPNOTSUPP;
noack_map = nla_get_u16(info->attrs[<API key>]);
return rdev->ops->set_noack_map(&rdev->wiphy, dev, noack_map);
}
struct get_key_cookie {
struct sk_buff *msg;
int error;
int idx;
};
static void get_key_callback(void *c, struct key_params *params)
{
struct nlattr *key;
struct get_key_cookie *cookie = c;
if (params->key)
NLA_PUT(cookie->msg, <API key>,
params->key_len, params->key);
if (params->seq)
NLA_PUT(cookie->msg, <API key>,
params->seq_len, params->seq);
if (params->cipher)
NLA_PUT_U32(cookie->msg, <API key>,
params->cipher);
key = nla_nest_start(cookie->msg, NL80211_ATTR_KEY);
if (!key)
goto nla_put_failure;
if (params->key)
NLA_PUT(cookie->msg, NL80211_KEY_DATA,
params->key_len, params->key);
if (params->seq)
NLA_PUT(cookie->msg, NL80211_KEY_SEQ,
params->seq_len, params->seq);
if (params->cipher)
NLA_PUT_U32(cookie->msg, NL80211_KEY_CIPHER,
params->cipher);
NLA_PUT_U8(cookie->msg, <API key>, cookie->idx);
nla_nest_end(cookie->msg, key);
return;
nla_put_failure:
cookie->error = 1;
}
static int nl80211_get_key(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
int err;
struct net_device *dev = info->user_ptr[1];
u8 key_idx = 0;
const u8 *mac_addr = NULL;
bool pairwise;
struct get_key_cookie cookie = {
.error = 0,
};
void *hdr;
struct sk_buff *msg;
if (info->attrs[<API key>])
key_idx = nla_get_u8(info->attrs[<API key>]);
if (key_idx > 5)
return -EINVAL;
if (info->attrs[NL80211_ATTR_MAC])
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
pairwise = !!mac_addr;
if (info->attrs[<API key>]) {
u32 kt = nla_get_u32(info->attrs[<API key>]);
if (kt >= <API key>)
return -EINVAL;
if (kt != <API key> &&
kt != <API key>)
return -EINVAL;
pairwise = kt == <API key>;
}
if (!rdev->ops->get_key)
return -EOPNOTSUPP;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_pid, info->snd_seq, 0,
NL80211_CMD_NEW_KEY);
if (!hdr)
goto nla_put_failure;
cookie.msg = msg;
cookie.idx = key_idx;
NLA_PUT_U32(msg, <API key>, dev->ifindex);
NLA_PUT_U8(msg, <API key>, key_idx);
if (mac_addr)
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, mac_addr);
if (pairwise && mac_addr &&
!(rdev->wiphy.flags & WIPHY_FLAG_IBSS_RSN))
return -ENOENT;
err = rdev->ops->get_key(&rdev->wiphy, dev, key_idx, pairwise,
mac_addr, &cookie, get_key_callback);
if (err)
goto free_msg;
if (cookie.error)
goto nla_put_failure;
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
err = -ENOBUFS;
free_msg:
nlmsg_free(msg);
return err;
}
static int nl80211_set_key(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct key_parse key;
int err;
struct net_device *dev = info->user_ptr[1];
err = nl80211_parse_key(info, &key);
if (err)
return err;
if (key.idx < 0)
return -EINVAL;
/* only support setting default key */
if (!key.def && !key.defmgmt)
return -EINVAL;
wdev_lock(dev->ieee80211_ptr);
if (key.def) {
if (!rdev->ops->set_default_key) {
err = -EOPNOTSUPP;
goto out;
}
err = nl80211_key_allowed(dev->ieee80211_ptr);
if (err)
goto out;
err = rdev->ops->set_default_key(&rdev->wiphy, dev, key.idx,
key.def_uni, key.def_multi);
if (err)
goto out;
#ifdef <API key>
dev->ieee80211_ptr->wext.default_key = key.idx;
#endif
} else {
if (key.def_uni || !key.def_multi) {
err = -EINVAL;
goto out;
}
if (!rdev->ops-><API key>) {
err = -EOPNOTSUPP;
goto out;
}
err = nl80211_key_allowed(dev->ieee80211_ptr);
if (err)
goto out;
err = rdev->ops-><API key>(&rdev->wiphy,
dev, key.idx);
if (err)
goto out;
#ifdef <API key>
dev->ieee80211_ptr->wext.default_mgmt_key = key.idx;
#endif
}
out:
wdev_unlock(dev->ieee80211_ptr);
return err;
}
static int nl80211_new_key(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
int err;
struct net_device *dev = info->user_ptr[1];
struct key_parse key;
const u8 *mac_addr = NULL;
err = nl80211_parse_key(info, &key);
if (err)
return err;
if (!key.p.key)
return -EINVAL;
if (info->attrs[NL80211_ATTR_MAC])
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (key.type == -1) {
if (mac_addr)
key.type = <API key>;
else
key.type = <API key>;
}
/* for now */
if (key.type != <API key> &&
key.type != <API key>)
return -EINVAL;
if (!rdev->ops->add_key)
return -EOPNOTSUPP;
if (<API key>(rdev, &key.p, key.idx,
key.type == <API key>,
mac_addr))
return -EINVAL;
wdev_lock(dev->ieee80211_ptr);
err = nl80211_key_allowed(dev->ieee80211_ptr);
if (!err)
err = rdev->ops->add_key(&rdev->wiphy, dev, key.idx,
key.type == <API key>,
mac_addr, &key.p);
wdev_unlock(dev->ieee80211_ptr);
return err;
}
static int nl80211_del_key(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
int err;
struct net_device *dev = info->user_ptr[1];
u8 *mac_addr = NULL;
struct key_parse key;
err = nl80211_parse_key(info, &key);
if (err)
return err;
if (info->attrs[NL80211_ATTR_MAC])
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (key.type == -1) {
if (mac_addr)
key.type = <API key>;
else
key.type = <API key>;
}
/* for now */
if (key.type != <API key> &&
key.type != <API key>)
return -EINVAL;
if (!rdev->ops->del_key)
return -EOPNOTSUPP;
wdev_lock(dev->ieee80211_ptr);
err = nl80211_key_allowed(dev->ieee80211_ptr);
if (key.type == <API key> && mac_addr &&
!(rdev->wiphy.flags & WIPHY_FLAG_IBSS_RSN))
err = -ENOENT;
if (!err)
err = rdev->ops->del_key(&rdev->wiphy, dev, key.idx,
key.type == <API key>,
mac_addr);
#ifdef <API key>
if (!err) {
if (key.idx == dev->ieee80211_ptr->wext.default_key)
dev->ieee80211_ptr->wext.default_key = -1;
else if (key.idx == dev->ieee80211_ptr->wext.default_mgmt_key)
dev->ieee80211_ptr->wext.default_mgmt_key = -1;
}
#endif
wdev_unlock(dev->ieee80211_ptr);
return err;
}
/* This function returns an error or the number of nested attributes */
static int <API key>(struct nlattr *nl_attr)
{
struct nlattr *attr;
int n_entries = 0, tmp;
nla_for_each_nested(attr, nl_attr, tmp) {
if (nla_len(attr) != ETH_ALEN)
return -EINVAL;
n_entries++;
}
return n_entries;
}
/*
* This function parses ACL information and allocates memory for ACL data.
* On successful return, the calling function is responsible to free the
* ACL buffer returned by this function.
*/
static struct cfg80211_acl_data *parse_acl_data(struct wiphy *wiphy,
struct genl_info *info)
{
enum nl80211_acl_policy acl_policy;
struct nlattr *attr;
struct cfg80211_acl_data *acl;
int i = 0, n_entries, tmp;
if (!wiphy->max_acl_mac_addrs)
return ERR_PTR(-EOPNOTSUPP);
if (!info->attrs[<API key>])
return ERR_PTR(-EINVAL);
acl_policy = nla_get_u32(info->attrs[<API key>]);
if (acl_policy != <API key> &&
acl_policy != <API key>)
return ERR_PTR(-EINVAL);
if (!info->attrs[<API key>])
return ERR_PTR(-EINVAL);
n_entries = <API key>(info->attrs[<API key>]);
if (n_entries < 0)
return ERR_PTR(n_entries);
if (n_entries > wiphy->max_acl_mac_addrs)
return ERR_PTR(-ENOTSUPP);
acl = kzalloc(sizeof(*acl) + (sizeof(struct mac_address) * n_entries),
GFP_KERNEL);
if (!acl)
return ERR_PTR(-ENOMEM);
nla_for_each_nested(attr, info->attrs[<API key>], tmp) {
memcpy(acl->mac_addrs[i].addr, nla_data(attr), ETH_ALEN);
i++;
}
acl->n_acl_entries = n_entries;
acl->acl_policy = acl_policy;
return acl;
}
static int nl80211_set_mac_acl(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct cfg80211_acl_data *acl;
int err;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
if (!dev->ieee80211_ptr->beacon_interval)
return -EINVAL;
acl = parse_acl_data(&rdev->wiphy, info);
if (IS_ERR(acl))
return PTR_ERR(acl);
err = rdev->ops->set_mac_acl(&rdev->wiphy, dev, acl);
kfree(acl);
return err;
}
static int <API key>(struct genl_info *info,
struct <API key> *bcn)
{
bool haveinfo = false;
if (!is_valid_ie_attr(info->attrs[<API key>]) ||
!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]) ||
!is_valid_ie_attr(info->attrs[<API key>]) ||
!is_valid_ie_attr(info->attrs[<API key>]))
return -EINVAL;
memset(bcn, 0, sizeof(*bcn));
if (info->attrs[<API key>]) {
bcn->head = nla_data(info->attrs[<API key>]);
bcn->head_len = nla_len(info->attrs[<API key>]);
if (!bcn->head_len)
return -EINVAL;
haveinfo = true;
}
if (info->attrs[<API key>]) {
bcn->tail = nla_data(info->attrs[<API key>]);
bcn->tail_len =
nla_len(info->attrs[<API key>]);
haveinfo = true;
}
if (!haveinfo)
return -EINVAL;
if (info->attrs[NL80211_ATTR_IE]) {
bcn->beacon_ies = nla_data(info->attrs[NL80211_ATTR_IE]);
bcn->beacon_ies_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
if (info->attrs[<API key>]) {
bcn->proberesp_ies =
nla_data(info->attrs[<API key>]);
bcn->proberesp_ies_len =
nla_len(info->attrs[<API key>]);
}
if (info->attrs[<API key>]) {
bcn->assocresp_ies =
nla_data(info->attrs[<API key>]);
bcn->assocresp_ies_len =
nla_len(info->attrs[<API key>]);
}
if (info->attrs[<API key>]) {
bcn->probe_resp =
nla_data(info->attrs[<API key>]);
bcn->probe_resp_len =
nla_len(info->attrs[<API key>]);
}
return 0;
}
static int nl80211_start_ap(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> params;
int err;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
if (!rdev->ops->start_ap)
return -EOPNOTSUPP;
if (wdev->beacon_interval)
return -EALREADY;
memset(¶ms, 0, sizeof(params));
/* these are required for START_AP */
if (!info->attrs[<API key>] ||
!info->attrs[<API key>] ||
!info->attrs[<API key>])
return -EINVAL;
err = <API key>(info, ¶ms.beacon);
if (err)
return err;
params.beacon_interval =
nla_get_u32(info->attrs[<API key>]);
params.dtim_period =
nla_get_u32(info->attrs[<API key>]);
err = <API key>(rdev, params.beacon_interval);
if (err)
return err;
/*
* In theory, some of these attributes should be required here
* but since they were not used when the command was originally
* added, keep them optional for old user space programs to let
* them continue to work with drivers that do not need the
* additional information -- drivers must check!
*/
if (info->attrs[NL80211_ATTR_SSID]) {
params.ssid = nla_data(info->attrs[NL80211_ATTR_SSID]);
params.ssid_len =
nla_len(info->attrs[NL80211_ATTR_SSID]);
if (params.ssid_len == 0 ||
params.ssid_len > <API key>)
return -EINVAL;
}
if (info->attrs[<API key>]) {
params.hidden_ssid = nla_get_u32(
info->attrs[<API key>]);
if (params.hidden_ssid != <API key> &&
params.hidden_ssid != <API key> &&
params.hidden_ssid != <API key>)
return -EINVAL;
}
params.privacy = !!info->attrs[<API key>];
if (info->attrs[<API key>]) {
params.auth_type = nla_get_u32(
info->attrs[<API key>]);
if (!<API key>(params.auth_type))
return -EINVAL;
} else
params.auth_type = <API key>;
err = <API key>(rdev, info, ¶ms.crypto,
<API key>);
if (err)
return err;
if (info->attrs[<API key>]) {
if (!(rdev->wiphy.features & <API key>))
return -EOPNOTSUPP;
params.inactivity_timeout = nla_get_u16(
info->attrs[<API key>]);
}
if (info->attrs[<API key>]) {
params.acl = parse_acl_data(&rdev->wiphy, info);
if (IS_ERR(params.acl))
return PTR_ERR(params.acl);
}
err = rdev->ops->start_ap(&rdev->wiphy, dev, ¶ms);
if (!err)
wdev->beacon_interval = params.beacon_interval;
kfree(params.acl);
return err;
}
static int nl80211_set_beacon(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> params;
int err;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
if (!rdev->ops->change_beacon)
return -EOPNOTSUPP;
if (!wdev->beacon_interval)
return -EINVAL;
err = <API key>(info, ¶ms);
if (err)
return err;
return rdev->ops->change_beacon(&rdev->wiphy, dev, ¶ms);
}
static int nl80211_stop_ap(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
int err;
if (!rdev->ops->stop_ap)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
if (!wdev->beacon_interval)
return -ENOENT;
err = rdev->ops->stop_ap(&rdev->wiphy, dev);
wdev->beacon_interval = 0;
return err;
}
static const struct nla_policy sta_flags_policy[<API key> + 1] = {
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_FLAG },
};
static int parse_station_flags(struct genl_info *info,
enum nl80211_iftype iftype,
struct station_parameters *params)
{
struct nlattr *flags[<API key> + 1];
struct nlattr *nla;
int flag;
/*
* Try parsing the new attribute first so userspace
* can specify both for older kernels.
*/
nla = info->attrs[<API key>];
if (nla) {
struct <API key> *sta_flags;
sta_flags = nla_data(nla);
params->sta_flags_mask = sta_flags->mask;
params->sta_flags_set = sta_flags->set;
if ((params->sta_flags_mask |
params->sta_flags_set) & BIT(<API key>))
return -EINVAL;
return 0;
}
/* if present, parse the old attribute */
nla = info->attrs[<API key>];
if (!nla)
return 0;
if (nla_parse_nested(flags, <API key>,
nla, sta_flags_policy))
return -EINVAL;
/*
* Only allow certain flags for interface types so that
* other attributes are silently ignored. Remember that
* this is backward compatibility code with old userspace
* and shouldn't be hit in other cases anyway.
*/
switch (iftype) {
case NL80211_IFTYPE_AP:
case <API key>:
case <API key>:
params->sta_flags_mask = BIT(<API key>) |
BIT(<API key>) |
BIT(<API key>) |
BIT(<API key>);
break;
case <API key>:
case <API key>:
params->sta_flags_mask = BIT(<API key>) |
BIT(<API key>);
break;
case <API key>:
params->sta_flags_mask = BIT(<API key>) |
BIT(<API key>) |
BIT(<API key>);
default:
return -EINVAL;
}
for (flag = 1; flag <= <API key>; flag++)
if (flags[flag])
params->sta_flags_set |= (1<<flag);
return 0;
}
static bool <API key>(struct sk_buff *msg, struct rate_info *info,
int attr)
{
struct nlattr *rate;
u16 bitrate;
rate = nla_nest_start(msg, attr);
if (!rate)
return false;
/* <API key> will return 0 for mcs >= 32 */
bitrate = <API key>(info);
if (bitrate > 0)
nla_put_u16(msg, <API key>, bitrate);
if (info->flags & RATE_INFO_FLAGS_MCS) {
if (nla_put_u8(msg, <API key>, info->mcs))
return false;
if (info->flags & <API key> &&
nla_put_flag(msg, <API key>))
return false;
if (info->flags & <API key> &&
nla_put_flag(msg, <API key>))
return false;
} else if (info->flags & <API key>) {
if (nla_put_u8(msg, <API key>, info->mcs))
return false;
if (nla_put_u8(msg, <API key>, info->nss))
return false;
if (info->flags & <API key> &&
nla_put_flag(msg, <API key>))
return false;
if (info->flags & <API key> &&
nla_put_flag(msg, <API key>))
return false;
if (info->flags & <API key> &&
nla_put_flag(msg, <API key>))
return false;
if (info->flags & <API key> &&
nla_put_flag(msg, <API key>))
return false;
if (info->flags & <API key> &&
nla_put_flag(msg, <API key>))
return false;
}
nla_nest_end(msg, rate);
return true;
}
static int <API key>(struct sk_buff *msg, u32 pid, u32 seq,
int flags,
struct <API key> *rdev,
struct net_device *dev,
const u8 *mac_addr, struct station_info *sinfo)
{
void *hdr;
struct nlattr *sinfoattr, *bss_param;
hdr = nl80211hdr_put(msg, pid, seq, flags, <API key>);
if (!hdr)
return -1;
NLA_PUT_U32(msg, <API key>, dev->ifindex);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, mac_addr);
NLA_PUT_U32(msg, <API key>, sinfo->generation);
sinfoattr = nla_nest_start(msg, <API key>);
if (!sinfoattr)
goto nla_put_failure;
if (sinfo->filled & <API key>)
NLA_PUT_U32(msg, <API key>,
sinfo->connected_time);
if (sinfo->filled & <API key>)
NLA_PUT_U32(msg, <API key>,
sinfo->inactive_time);
if (sinfo->filled & <API key>)
NLA_PUT_U32(msg, <API key>,
sinfo->rx_bytes);
if (sinfo->filled & <API key>)
NLA_PUT_U32(msg, <API key>,
sinfo->tx_bytes);
if (sinfo->filled & STATION_INFO_LLID)
NLA_PUT_U16(msg, <API key>,
sinfo->llid);
if (sinfo->filled & STATION_INFO_PLID)
NLA_PUT_U16(msg, <API key>,
sinfo->plid);
if (sinfo->filled & <API key>)
NLA_PUT_U8(msg, <API key>,
sinfo->plink_state);
switch (rdev->wiphy.signal_type) {
case <API key>:
if (sinfo->filled & STATION_INFO_SIGNAL)
NLA_PUT_U8(msg, <API key>,
sinfo->signal);
if (sinfo->filled & <API key>)
NLA_PUT_U8(msg, <API key>,
sinfo->signal_avg);
break;
default:
break;
}
if (sinfo->filled & <API key>) {
if (!<API key>(msg, &sinfo->txrate,
<API key>))
goto nla_put_failure;
}
if (sinfo->filled & <API key>) {
if (!<API key>(msg, &sinfo->rxrate,
<API key>))
goto nla_put_failure;
}
if (sinfo->filled & <API key>)
NLA_PUT_U32(msg, <API key>,
sinfo->rx_packets);
if (sinfo->filled & <API key>)
NLA_PUT_U32(msg, <API key>,
sinfo->tx_packets);
if (sinfo->filled & <API key>)
NLA_PUT_U32(msg, <API key>,
sinfo->tx_retries);
if (sinfo->filled & <API key>)
NLA_PUT_U32(msg, <API key>,
sinfo->tx_failed);
if (sinfo->filled & <API key>)
NLA_PUT_U32(msg, <API key>,
sinfo->beacon_loss_count);
if (sinfo->filled & <API key>) {
bss_param = nla_nest_start(msg, <API key>);
if (!bss_param)
goto nla_put_failure;
if (sinfo->bss_param.flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
if (sinfo->bss_param.flags & <API key>)
NLA_PUT_FLAG(msg, <API key>);
if (sinfo->bss_param.flags & <API key>)
NLA_PUT_FLAG(msg,
<API key>);
NLA_PUT_U8(msg, <API key>,
sinfo->bss_param.dtim_period);
NLA_PUT_U16(msg, <API key>,
sinfo->bss_param.beacon_interval);
nla_nest_end(msg, bss_param);
}
if (sinfo->filled & <API key>)
NLA_PUT(msg, <API key>,
sizeof(struct <API key>),
&sinfo->sta_flags);
nla_nest_end(msg, sinfoattr);
if (sinfo->filled & <API key>)
NLA_PUT(msg, NL80211_ATTR_IE, sinfo->assoc_req_ies_len,
sinfo->assoc_req_ies);
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int <API key>(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct station_info sinfo;
struct <API key> *dev;
struct net_device *netdev;
u8 mac_addr[ETH_ALEN];
int sta_idx = cb->args[1];
int err;
err = <API key>(skb, cb, &dev, &netdev);
if (err)
return err;
if (!dev->ops->dump_station) {
err = -EOPNOTSUPP;
goto out_err;
}
while (1) {
memset(&sinfo, 0, sizeof(sinfo));
err = dev->ops->dump_station(&dev->wiphy, netdev, sta_idx,
mac_addr, &sinfo);
if (err == -ENOENT)
break;
if (err)
goto out_err;
if (<API key>(skb,
NETLINK_CB(cb->skb).pid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
dev, netdev, mac_addr,
&sinfo) < 0)
goto out;
sta_idx++;
}
out:
cb->args[1] = sta_idx;
err = skb->len;
out_err:
<API key>(dev);
return err;
}
static int nl80211_get_station(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct station_info sinfo;
struct sk_buff *msg;
u8 *mac_addr = NULL;
int err;
memset(&sinfo, 0, sizeof(sinfo));
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (!rdev->ops->get_station)
return -EOPNOTSUPP;
err = rdev->ops->get_station(&rdev->wiphy, dev, mac_addr, &sinfo);
if (err)
return err;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
if (<API key>(msg, info->snd_pid, info->snd_seq, 0,
rdev, dev, mac_addr, &sinfo) < 0) {
nlmsg_free(msg);
return -ENOBUFS;
}
return genlmsg_reply(msg, info);
}
/*
* Get vlan interface making sure it is running and on the right wiphy.
*/
static struct net_device *get_vlan(struct genl_info *info,
struct <API key> *rdev)
{
struct nlattr *vlanattr = info->attrs[<API key>];
struct net_device *v;
int ret;
if (!vlanattr)
return NULL;
v = dev_get_by_index(genl_info_net(info), nla_get_u32(vlanattr));
if (!v)
return ERR_PTR(-ENODEV);
if (!v->ieee80211_ptr || v->ieee80211_ptr->wiphy != &rdev->wiphy) {
ret = -EINVAL;
goto error;
}
if (!netif_running(v)) {
ret = -ENETDOWN;
goto error;
}
return v;
error:
dev_put(v);
return ERR_PTR(ret);
}
static int <API key>(struct genl_info *info,
struct station_parameters *params)
{
if (info->attrs[<API key>]) {
params->supported_channels =
nla_data(info->attrs[<API key>]);
params-><API key> =
nla_len(info->attrs[<API key>]);
/*
* Need to include at least one (first channel, number of
* channels) tuple for each subband, and must have proper
* tuples for the rest of the data as well.
*/
if (params-><API key> < 2)
return -EINVAL;
if (params-><API key> % 2)
return -EINVAL;
}
if (info->attrs[<API key>]) {
params-><API key> =
nla_data(info->attrs[<API key>]);
params-><API key> =
nla_len(info->attrs[<API key>]);
/*
* The value of the Length field of the Supported Operating
* Classes element is between 2 and 253.
*/
if (params-><API key> < 2 ||
params-><API key> > 253)
return -EINVAL;
}
return 0;
}
static struct nla_policy
<API key>[NL80211_STA_WME_MAX + 1] __read_mostly = {
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U8 },
};
static int <API key>(struct genl_info *info,
struct station_parameters *params)
{
struct nlattr *tb[NL80211_STA_WME_MAX + 1];
struct nlattr *nla;
int err;
/* Dummy STA entry gets updated once the peer capabilities are known */
if (info->attrs[<API key>])
params->aid = nla_get_u16(info->attrs[<API key>]);
if (info->attrs[<API key>])
params->ht_capa =
nla_data(info->attrs[<API key>]);
if (info->attrs[<API key>])
params->vht_capa =
nla_data(info->attrs[<API key>]);
err = <API key>(info, params);
if (err)
return err;
/* parse WME attributes if present */
if (!info->attrs[<API key>])
return 0;
nla = info->attrs[<API key>];
err = nla_parse_nested(tb, NL80211_STA_WME_MAX, nla,
<API key>);
if (err)
return err;
if (tb[<API key>])
params->uapsd_queues = nla_get_u8(
tb[<API key>]);
if (params->uapsd_queues & ~<API key>)
return -EINVAL;
if (tb[<API key>])
params->max_sp = nla_get_u8(tb[<API key>]);
if (params->max_sp & ~<API key>)
return -EINVAL;
params->sta_modify_mask |= <API key>;
return 0;
}
static int <API key>(struct genl_info *info,
struct station_parameters *params)
{
/* Dummy STA entry gets updated once the peer capabilities are known */
if (info->attrs[<API key>])
params->ht_capa =
nla_data(info->attrs[<API key>]);
if (info->attrs[<API key>])
params->vht_capa =
nla_data(info->attrs[<API key>]);
return <API key>(info, params);
}
static int nl80211_set_station(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
int err;
struct net_device *dev = info->user_ptr[1];
struct station_parameters params;
u8 *mac_addr = NULL;
memset(¶ms, 0, sizeof(params));
params.listen_interval = -1;
params.plink_state = -1;
if (info->attrs[<API key>])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (info->attrs[<API key>]) {
params.supported_rates =
nla_data(info->attrs[<API key>]);
params.supported_rates_len =
nla_len(info->attrs[<API key>]);
}
if (info->attrs[<API key>]) {
params.capability =
nla_get_u16(info->attrs[<API key>]);
params.sta_modify_mask |= <API key>;
}
if (info->attrs[<API key>]) {
params.ext_capab =
nla_data(info->attrs[<API key>]);
params.ext_capab_len =
nla_len(info->attrs[<API key>]);
}
if (info->attrs[<API key>])
params.listen_interval =
nla_get_u16(info->attrs[<API key>]);
if (info->attrs[<API key>])
params.ht_capa =
nla_data(info->attrs[<API key>]);
if (!rdev->ops->change_station)
return -EOPNOTSUPP;
if (parse_station_flags(info, dev->ieee80211_ptr->iftype, ¶ms))
return -EINVAL;
if (info->attrs[<API key>])
params.plink_action =
nla_get_u8(info->attrs[<API key>]);
if (info->attrs[<API key>])
params.plink_state =
nla_get_u8(info->attrs[<API key>]);
switch (dev->ieee80211_ptr->iftype) {
case NL80211_IFTYPE_AP:
case <API key>:
case <API key>:
/* disallow mesh-specific things */
if (params.plink_action)
return -EINVAL;
/* TDLS can't be set, ... */
if (params.sta_flags_set & BIT(<API key>))
return -EINVAL;
/*
* ... but don't bother the driver with it. This works around
* a hostapd/wpa_supplicant issue -- it always includes the
* TLDS_PEER flag in the mask even for AP mode.
*/
params.sta_flags_mask &= ~BIT(<API key>);
/* accept only the listed bits */
if (params.sta_flags_mask &
~(BIT(<API key>) |
BIT(<API key>) |
BIT(<API key>) |
BIT(<API key>)))
return -EINVAL;
if (info->attrs[<API key>])
return -EINVAL;
if (info->attrs[<API key>])
return -EINVAL;
if (info->attrs[<API key>] ||
info->attrs[<API key>])
return -EINVAL;
/* must be last in here for error handling */
params.vlan = get_vlan(info, rdev);
if (IS_ERR(params.vlan))
return PTR_ERR(params.vlan);
break;
case <API key>:
case <API key>:
/*
* Don't allow userspace to change the TDLS_PEER flag,
* but silently ignore attempts to change it since we
* don't have state here to verify that it doesn't try
* to change the flag.
*/
params.sta_flags_mask &= ~BIT(<API key>);
/* Include parameters for TDLS peer (driver will check) */
err = <API key>(info, ¶ms);
if (err)
return err;
/* disallow things sta doesn't support */
if (params.plink_action)
return -EINVAL;
if (params.sta_flags_mask & ~(BIT(<API key>) |
BIT(<API key>)))
return -EINVAL;
break;
case <API key>:
/* disallow things sta doesn't support */
if (params.plink_action)
return -EINVAL;
if (params.ht_capa)
return -EINVAL;
if (params.listen_interval >= 0)
return -EINVAL;
if (info->attrs[<API key>] ||
info->attrs[<API key>])
return -EINVAL;
/* reject any changes other than AUTHORIZED */
if (params.sta_flags_mask & ~BIT(<API key>))
return -EINVAL;
break;
case <API key>:
/* disallow things mesh doesn't support */
if (params.vlan)
return -EINVAL;
if (params.ht_capa)
return -EINVAL;
if (params.listen_interval >= 0)
return -EINVAL;
if (info->attrs[<API key>])
return -EINVAL;
if (info->attrs[<API key>])
return -EINVAL;
if (info->attrs[<API key>] ||
info->attrs[<API key>])
return -EINVAL;
/*
* No special handling for TDLS here -- the userspace
* mesh code doesn't have this bug.
*/
if (params.sta_flags_mask &
~(BIT(<API key>) |
BIT(<API key>) |
BIT(<API key>)))
return -EINVAL;
break;
default:
return -EOPNOTSUPP;
}
/* be aware of params.vlan when changing code here */
err = rdev->ops->change_station(&rdev->wiphy, dev, mac_addr, ¶ms);
if (params.vlan)
dev_put(params.vlan);
return err;
}
static int nl80211_new_station(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
int err;
struct net_device *dev = info->user_ptr[1];
struct station_parameters params;
u8 *mac_addr = NULL;
memset(¶ms, 0, sizeof(params));
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[<API key>])
return -EINVAL;
if (!info->attrs[<API key>])
return -EINVAL;
if (!info->attrs[<API key>] &&
!info->attrs[<API key>])
return -EINVAL;
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
params.supported_rates =
nla_data(info->attrs[<API key>]);
params.supported_rates_len =
nla_len(info->attrs[<API key>]);
params.listen_interval =
nla_get_u16(info->attrs[<API key>]);
if (info->attrs[<API key>])
params.aid = nla_get_u16(info->attrs[<API key>]);
else
params.aid = nla_get_u16(info->attrs[<API key>]);
if (!params.aid || params.aid > IEEE80211_MAX_AID)
return -EINVAL;
if (info->attrs[<API key>]) {
params.capability =
nla_get_u16(info->attrs[<API key>]);
params.sta_modify_mask |= <API key>;
}
if (info->attrs[<API key>]) {
params.ext_capab =
nla_data(info->attrs[<API key>]);
params.ext_capab_len =
nla_len(info->attrs[<API key>]);
}
if (info->attrs[<API key>])
params.ht_capa =
nla_data(info->attrs[<API key>]);
if (info->attrs[<API key>])
params.vht_capa =
nla_data(info->attrs[<API key>]);
if (info->attrs[<API key>])
params.plink_action =
nla_get_u8(info->attrs[<API key>]);
err = <API key>(info, ¶ms);
if (err)
return err;
if (!rdev->ops->add_station)
return -EOPNOTSUPP;
if (parse_station_flags(info, dev->ieee80211_ptr->iftype, ¶ms))
return -EINVAL;
switch (dev->ieee80211_ptr->iftype) {
case NL80211_IFTYPE_AP:
case <API key>:
case <API key>:
/* parse WME attributes if sta is WME capable */
if ((rdev->wiphy.flags & WIPHY_FLAG_AP_UAPSD) &&
(params.sta_flags_set & BIT(<API key>)) &&
info->attrs[<API key>]) {
struct nlattr *tb[NL80211_STA_WME_MAX + 1];
struct nlattr *nla;
nla = info->attrs[<API key>];
err = nla_parse_nested(tb, NL80211_STA_WME_MAX, nla,
<API key>);
if (err)
return err;
if (tb[<API key>])
params.uapsd_queues =
nla_get_u8(tb[<API key>]);
if (params.uapsd_queues &
~<API key>)
return -EINVAL;
if (tb[<API key>])
params.max_sp =
nla_get_u8(tb[<API key>]);
if (params.max_sp &
~<API key>)
return -EINVAL;
params.sta_modify_mask |= <API key>;
}
/* TDLS peers cannot be added */
if ((params.sta_flags_set & BIT(<API key>)) ||
info->attrs[<API key>])
return -EINVAL;
/* but don't bother the driver with it */
params.sta_flags_mask &= ~BIT(<API key>);
/* must be last in here for error handling */
params.vlan = get_vlan(info, rdev);
if (IS_ERR(params.vlan))
return PTR_ERR(params.vlan);
break;
case <API key>:
/* TDLS peers cannot be added */
if ((params.sta_flags_set & BIT(<API key>)) ||
info->attrs[<API key>])
return -EINVAL;
break;
case <API key>:
case <API key>:
/* Only TDLS peers can be added */
if (!(params.sta_flags_set & BIT(<API key>)))
return -EINVAL;
/* Can only add if TDLS ... */
if (!(rdev->wiphy.flags & <API key>))
return -EOPNOTSUPP;
/* ... with external setup is supported */
if (!(rdev->wiphy.flags & <API key>))
return -EOPNOTSUPP;
break;
default:
return -EOPNOTSUPP;
}
/* be aware of params.vlan when changing code here */
err = rdev->ops->add_station(&rdev->wiphy, dev, mac_addr, ¶ms);
if (params.vlan)
dev_put(params.vlan);
return err;
}
static int nl80211_del_station(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u8 *mac_addr = NULL;
if (info->attrs[NL80211_ATTR_MAC])
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key>)
return -EINVAL;
if (!rdev->ops->del_station)
return -EOPNOTSUPP;
return rdev->ops->del_station(&rdev->wiphy, dev, mac_addr);
}
static int nl80211_send_mpath(struct sk_buff *msg, u32 pid, u32 seq,
int flags, struct net_device *dev,
u8 *dst, u8 *next_hop,
struct mpath_info *pinfo)
{
void *hdr;
struct nlattr *pinfoattr;
hdr = nl80211hdr_put(msg, pid, seq, flags, <API key>);
if (!hdr)
return -1;
NLA_PUT_U32(msg, <API key>, dev->ifindex);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, dst);
NLA_PUT(msg, <API key>, ETH_ALEN, next_hop);
NLA_PUT_U32(msg, <API key>, pinfo->generation);
pinfoattr = nla_nest_start(msg, <API key>);
if (!pinfoattr)
goto nla_put_failure;
if (pinfo->filled & <API key>)
NLA_PUT_U32(msg, <API key>,
pinfo->frame_qlen);
if (pinfo->filled & MPATH_INFO_SN)
NLA_PUT_U32(msg, <API key>,
pinfo->sn);
if (pinfo->filled & MPATH_INFO_METRIC)
NLA_PUT_U32(msg, <API key>,
pinfo->metric);
if (pinfo->filled & MPATH_INFO_EXPTIME)
NLA_PUT_U32(msg, <API key>,
pinfo->exptime);
if (pinfo->filled & MPATH_INFO_FLAGS)
NLA_PUT_U8(msg, <API key>,
pinfo->flags);
if (pinfo->filled & <API key>)
NLA_PUT_U32(msg, <API key>,
pinfo->discovery_timeout);
if (pinfo->filled & <API key>)
NLA_PUT_U8(msg, <API key>,
pinfo->discovery_retries);
nla_nest_end(msg, pinfoattr);
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nl80211_dump_mpath(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct mpath_info pinfo;
struct <API key> *dev;
struct net_device *netdev;
u8 dst[ETH_ALEN];
u8 next_hop[ETH_ALEN];
int path_idx = cb->args[1];
int err;
err = <API key>(skb, cb, &dev, &netdev);
if (err)
return err;
if (!dev->ops->dump_mpath) {
err = -EOPNOTSUPP;
goto out_err;
}
if (netdev->ieee80211_ptr->iftype != <API key>) {
err = -EOPNOTSUPP;
goto out_err;
}
while (1) {
err = dev->ops->dump_mpath(&dev->wiphy, netdev, path_idx,
dst, next_hop, &pinfo);
if (err == -ENOENT)
break;
if (err)
goto out_err;
if (nl80211_send_mpath(skb, NETLINK_CB(cb->skb).pid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
netdev, dst, next_hop,
&pinfo) < 0)
goto out;
path_idx++;
}
out:
cb->args[1] = path_idx;
err = skb->len;
out_err:
<API key>(dev);
return err;
}
static int nl80211_get_mpath(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
int err;
struct net_device *dev = info->user_ptr[1];
struct mpath_info pinfo;
struct sk_buff *msg;
u8 *dst = NULL;
u8 next_hop[ETH_ALEN];
memset(&pinfo, 0, sizeof(pinfo));
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
dst = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (!rdev->ops->get_mpath)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
err = rdev->ops->get_mpath(&rdev->wiphy, dev, dst, next_hop, &pinfo);
if (err)
return err;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
if (nl80211_send_mpath(msg, info->snd_pid, info->snd_seq, 0,
dev, dst, next_hop, &pinfo) < 0) {
nlmsg_free(msg);
return -ENOBUFS;
}
return genlmsg_reply(msg, info);
}
static int nl80211_set_mpath(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u8 *dst = NULL;
u8 *next_hop = NULL;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[<API key>])
return -EINVAL;
dst = nla_data(info->attrs[NL80211_ATTR_MAC]);
next_hop = nla_data(info->attrs[<API key>]);
if (!rdev->ops->change_mpath)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
return rdev->ops->change_mpath(&rdev->wiphy, dev, dst, next_hop);
}
static int nl80211_new_mpath(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u8 *dst = NULL;
u8 *next_hop = NULL;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[<API key>])
return -EINVAL;
dst = nla_data(info->attrs[NL80211_ATTR_MAC]);
next_hop = nla_data(info->attrs[<API key>]);
if (!rdev->ops->add_mpath)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
return rdev->ops->add_mpath(&rdev->wiphy, dev, dst, next_hop);
}
static int nl80211_del_mpath(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u8 *dst = NULL;
if (info->attrs[NL80211_ATTR_MAC])
dst = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (!rdev->ops->del_mpath)
return -EOPNOTSUPP;
return rdev->ops->del_mpath(&rdev->wiphy, dev, dst);
}
static int nl80211_set_bss(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct bss_parameters params;
memset(¶ms, 0, sizeof(params));
/* default to not changing parameters */
params.use_cts_prot = -1;
params.use_short_preamble = -1;
params.use_short_slot_time = -1;
params.ap_isolate = -1;
params.ht_opmode = -1;
if (info->attrs[<API key>])
params.use_cts_prot =
nla_get_u8(info->attrs[<API key>]);
if (info->attrs[<API key>])
params.use_short_preamble =
nla_get_u8(info->attrs[<API key>]);
if (info->attrs[<API key>])
params.use_short_slot_time =
nla_get_u8(info->attrs[<API key>]);
if (info->attrs[<API key>]) {
params.basic_rates =
nla_data(info->attrs[<API key>]);
params.basic_rates_len =
nla_len(info->attrs[<API key>]);
}
if (info->attrs[<API key>])
params.ap_isolate = !!nla_get_u8(info->attrs[<API key>]);
if (info->attrs[<API key>])
params.ht_opmode =
nla_get_u16(info->attrs[<API key>]);
if (!rdev->ops->change_bss)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
return rdev->ops->change_bss(&rdev->wiphy, dev, ¶ms);
}
static const struct nla_policy reg_rule_policy[<API key> + 1] = {
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U32 },
};
static int parse_reg_rule(struct nlattr *tb[],
struct ieee80211_reg_rule *reg_rule)
{
struct <API key> *freq_range = ®_rule->freq_range;
struct <API key> *power_rule = ®_rule->power_rule;
if (!tb[<API key>])
return -EINVAL;
if (!tb[<API key>])
return -EINVAL;
if (!tb[<API key>])
return -EINVAL;
if (!tb[<API key>])
return -EINVAL;
if (!tb[<API key>])
return -EINVAL;
reg_rule->flags = nla_get_u32(tb[<API key>]);
freq_range->start_freq_khz =
nla_get_u32(tb[<API key>]);
freq_range->end_freq_khz =
nla_get_u32(tb[<API key>]);
freq_range->max_bandwidth_khz =
nla_get_u32(tb[<API key>]);
power_rule->max_eirp =
nla_get_u32(tb[<API key>]);
if (tb[<API key>])
power_rule->max_antenna_gain =
nla_get_u32(tb[<API key>]);
return 0;
}
static int nl80211_req_set_reg(struct sk_buff *skb, struct genl_info *info)
{
int r;
char *data = NULL;
/*
* You should only get this when cfg80211 hasn't yet initialized
* completely when built-in to the kernel right between the time
* window between nl80211_init() and regulatory_init(), if that is
* even possible.
*/
mutex_lock(&cfg80211_mutex);
if (unlikely(!cfg80211_regdomain)) {
mutex_unlock(&cfg80211_mutex);
return -EINPROGRESS;
}
mutex_unlock(&cfg80211_mutex);
if (!info->attrs[<API key>])
return -EINVAL;
data = nla_data(info->attrs[<API key>]);
r = <API key>(data);
return r;
}
static int <API key>(struct sk_buff *skb,
struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct mesh_config cur_params;
int err = 0;
void *hdr;
struct nlattr *pinfoattr;
struct sk_buff *msg;
if (wdev->iftype != <API key>)
return -EOPNOTSUPP;
if (!rdev->ops->get_mesh_config)
return -EOPNOTSUPP;
wdev_lock(wdev);
/* If not connected, get default parameters */
if (!wdev->mesh_id_len)
memcpy(&cur_params, &default_mesh_config, sizeof(cur_params));
else
err = rdev->ops->get_mesh_config(&rdev->wiphy, dev,
&cur_params);
wdev_unlock(wdev);
if (err)
return err;
/* Draw up a netlink message to send back */
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_pid, info->snd_seq, 0,
<API key>);
if (!hdr)
goto out;
pinfoattr = nla_nest_start(msg, <API key>);
if (!pinfoattr)
goto nla_put_failure;
NLA_PUT_U32(msg, <API key>, dev->ifindex);
NLA_PUT_U16(msg, <API key>,
cur_params.<API key>);
NLA_PUT_U16(msg, <API key>,
cur_params.<API key>);
NLA_PUT_U16(msg, <API key>,
cur_params.<API key>);
NLA_PUT_U16(msg, <API key>,
cur_params.<API key>);
NLA_PUT_U8(msg, <API key>,
cur_params.dot11MeshMaxRetries);
NLA_PUT_U8(msg, <API key>,
cur_params.dot11MeshTTL);
NLA_PUT_U8(msg, <API key>,
cur_params.element_ttl);
NLA_PUT_U8(msg, <API key>,
cur_params.auto_open_plinks);
NLA_PUT_U8(msg, <API key>,
cur_params.<API key>);
NLA_PUT_U32(msg, <API key>,
cur_params.path_refresh_time);
NLA_PUT_U16(msg, <API key>,
cur_params.<API key>);
NLA_PUT_U32(msg, <API key>,
cur_params.<API key>);
NLA_PUT_U16(msg, <API key>,
cur_params.<API key>);
NLA_PUT_U16(msg, <API key>,
cur_params.<API key>);
NLA_PUT_U16(msg, <API key>,
cur_params.<API key>);
NLA_PUT_U8(msg, <API key>,
cur_params.<API key>);
NLA_PUT_U16(msg, <API key>,
cur_params.<API key>);
NLA_PUT_U8(msg, <API key>,
cur_params.<API key>);
NLA_PUT_U8(msg, <API key>,
cur_params.dot11MeshForwarding);
NLA_PUT_U32(msg, <API key>,
cur_params.rssi_threshold);
nla_nest_end(msg, pinfoattr);
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
genlmsg_cancel(msg, hdr);
out:
nlmsg_free(msg);
return -ENOBUFS;
}
static const struct nla_policy <API key>[<API key>+1] = {
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U16 },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U32},
};
static const struct nla_policy
<API key>[<API key>+1] = {
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_U8 },
[<API key>] = { .type = NLA_FLAG },
[<API key>] = { .type = NLA_BINARY,
.len = <API key> },
[<API key>] = { .type = NLA_FLAG },
};
static int <API key>(struct genl_info *info,
struct mesh_config *cfg,
u32 *mask_out)
{
struct nlattr *tb[<API key> + 1];
u32 mask = 0;
#define <API key>(table, cfg, param, mask, attr_num, nla_fn) \
do {\
if (table[attr_num]) {\
cfg->param = nla_fn(table[attr_num]); \
mask |= (1 << (attr_num - 1)); \
} \
} while (0);\
if (!info->attrs[<API key>])
return -EINVAL;
if (nla_parse_nested(tb, <API key>,
info->attrs[<API key>],
<API key>))
return -EINVAL;
/* This makes sure that there aren't more than 32 mesh config
* parameters (otherwise our bitfield scheme would not work.) */
BUILD_BUG_ON(<API key> > 32);
/* Fill in the params struct */
<API key>(tb, cfg, <API key>,
mask, <API key>, nla_get_u16);
<API key>(tb, cfg, <API key>,
mask, <API key>, nla_get_u16);
<API key>(tb, cfg, <API key>,
mask, <API key>, nla_get_u16);
<API key>(tb, cfg, <API key>,
mask, <API key>, nla_get_u16);
<API key>(tb, cfg, dot11MeshMaxRetries,
mask, <API key>, nla_get_u8);
<API key>(tb, cfg, dot11MeshTTL,
mask, <API key>, nla_get_u8);
<API key>(tb, cfg, element_ttl,
mask, <API key>, nla_get_u8);
<API key>(tb, cfg, auto_open_plinks,
mask, <API key>, nla_get_u8);
<API key>(tb, cfg, <API key>,
mask, <API key>,
nla_get_u8);
<API key>(tb, cfg, path_refresh_time,
mask, <API key>, nla_get_u32);
<API key>(tb, cfg, <API key>,
mask, <API key>,
nla_get_u16);
<API key>(tb, cfg, <API key>,
mask, <API key>,
nla_get_u32);
<API key>(tb, cfg, <API key>,
mask, <API key>,
nla_get_u16);
<API key>(tb, cfg, <API key>,
mask, <API key>,
nla_get_u16);
<API key>(tb, cfg,
<API key>,
mask, <API key>,
nla_get_u16);
<API key>(tb, cfg,
<API key>, mask,
<API key>,
nla_get_u8);
<API key>(tb, cfg,
<API key>, mask,
<API key>,
nla_get_u16);
<API key>(tb, cfg,
<API key>, mask,
<API key>,
nla_get_u8);
<API key>(tb, cfg, dot11MeshForwarding,
mask, <API key>, nla_get_u8);
<API key>(tb, cfg, rssi_threshold,
mask, <API key>, nla_get_u32);
if (mask_out)
*mask_out = mask;
return 0;
#undef <API key>
}
static int <API key>(struct genl_info *info,
struct mesh_setup *setup)
{
struct nlattr *tb[<API key> + 1];
if (!info->attrs[<API key>])
return -EINVAL;
if (nla_parse_nested(tb, <API key>,
info->attrs[<API key>],
<API key>))
return -EINVAL;
if (tb[<API key>])
setup->path_sel_proto =
(nla_get_u8(tb[<API key>])) ?
<API key> :
<API key>;
if (tb[<API key>])
setup->path_metric =
(nla_get_u8(tb[<API key>])) ?
<API key> :
<API key>;
if (tb[<API key>]) {
struct nlattr *ieattr =
tb[<API key>];
if (!is_valid_ie_attr(ieattr))
return -EINVAL;
setup->ie = nla_data(ieattr);
setup->ie_len = nla_len(ieattr);
}
setup->is_authenticated = nla_get_flag(tb[<API key>]);
setup->is_secure = nla_get_flag(tb[<API key>]);
return 0;
}
static int <API key>(struct sk_buff *skb,
struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct mesh_config cfg;
u32 mask;
int err;
if (wdev->iftype != <API key>)
return -EOPNOTSUPP;
if (!rdev->ops->update_mesh_config)
return -EOPNOTSUPP;
err = <API key>(info, &cfg, &mask);
if (err)
return err;
wdev_lock(wdev);
if (!wdev->mesh_id_len)
err = -ENOLINK;
if (!err)
err = rdev->ops->update_mesh_config(&rdev->wiphy, dev,
mask, &cfg);
wdev_unlock(wdev);
return err;
}
static int nl80211_get_reg(struct sk_buff *skb, struct genl_info *info)
{
struct sk_buff *msg;
void *hdr = NULL;
struct nlattr *nl_reg_rules;
unsigned int i;
int err = -EINVAL;
mutex_lock(&cfg80211_mutex);
if (!cfg80211_regdomain)
goto out;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg) {
err = -ENOBUFS;
goto out;
}
hdr = nl80211hdr_put(msg, info->snd_pid, info->snd_seq, 0,
NL80211_CMD_GET_REG);
if (!hdr)
goto put_failure;
NLA_PUT_STRING(msg, <API key>,
cfg80211_regdomain->alpha2);
if (cfg80211_regdomain->dfs_region)
NLA_PUT_U8(msg, <API key>,
cfg80211_regdomain->dfs_region);
nl_reg_rules = nla_nest_start(msg, <API key>);
if (!nl_reg_rules)
goto nla_put_failure;
for (i = 0; i < cfg80211_regdomain->n_reg_rules; i++) {
struct nlattr *nl_reg_rule;
const struct ieee80211_reg_rule *reg_rule;
const struct <API key> *freq_range;
const struct <API key> *power_rule;
reg_rule = &cfg80211_regdomain->reg_rules[i];
freq_range = ®_rule->freq_range;
power_rule = ®_rule->power_rule;
nl_reg_rule = nla_nest_start(msg, i);
if (!nl_reg_rule)
goto nla_put_failure;
NLA_PUT_U32(msg, <API key>,
reg_rule->flags);
NLA_PUT_U32(msg, <API key>,
freq_range->start_freq_khz);
NLA_PUT_U32(msg, <API key>,
freq_range->end_freq_khz);
NLA_PUT_U32(msg, <API key>,
freq_range->max_bandwidth_khz);
NLA_PUT_U32(msg, <API key>,
power_rule->max_antenna_gain);
NLA_PUT_U32(msg, <API key>,
power_rule->max_eirp);
nla_nest_end(msg, nl_reg_rule);
}
nla_nest_end(msg, nl_reg_rules);
genlmsg_end(msg, hdr);
err = genlmsg_reply(msg, info);
goto out;
nla_put_failure:
genlmsg_cancel(msg, hdr);
put_failure:
nlmsg_free(msg);
err = -EMSGSIZE;
out:
mutex_unlock(&cfg80211_mutex);
return err;
}
static int nl80211_set_reg(struct sk_buff *skb, struct genl_info *info)
{
struct nlattr *tb[<API key> + 1];
struct nlattr *nl_reg_rule;
char *alpha2 = NULL;
int rem_reg_rules = 0, r = 0;
u32 num_rules = 0, rule_idx = 0, size_of_regd;
u8 dfs_region = 0;
struct ieee80211_regdomain *rd = NULL;
if (!info->attrs[<API key>])
return -EINVAL;
if (!info->attrs[<API key>])
return -EINVAL;
alpha2 = nla_data(info->attrs[<API key>]);
if (info->attrs[<API key>])
dfs_region = nla_get_u8(info->attrs[<API key>]);
nla_for_each_nested(nl_reg_rule, info->attrs[<API key>],
rem_reg_rules) {
num_rules++;
if (num_rules > <API key>)
return -EINVAL;
}
mutex_lock(&cfg80211_mutex);
if (!<API key>(alpha2)) {
r = -EINVAL;
goto bad_reg;
}
size_of_regd = sizeof(struct ieee80211_regdomain) +
(num_rules * sizeof(struct ieee80211_reg_rule));
rd = kzalloc(size_of_regd, GFP_KERNEL);
if (!rd) {
r = -ENOMEM;
goto bad_reg;
}
rd->n_reg_rules = num_rules;
rd->alpha2[0] = alpha2[0];
rd->alpha2[1] = alpha2[1];
/*
* Disable DFS master mode if the DFS region was
* not supported or known on this kernel.
*/
if (<API key>(dfs_region))
rd->dfs_region = dfs_region;
nla_for_each_nested(nl_reg_rule, info->attrs[<API key>],
rem_reg_rules) {
nla_parse(tb, <API key>,
nla_data(nl_reg_rule), nla_len(nl_reg_rule),
reg_rule_policy);
r = parse_reg_rule(tb, &rd->reg_rules[rule_idx]);
if (r)
goto bad_reg;
rule_idx++;
if (rule_idx > <API key>) {
r = -EINVAL;
goto bad_reg;
}
}
BUG_ON(rule_idx != num_rules);
r = set_regdom(rd);
mutex_unlock(&cfg80211_mutex);
return r;
bad_reg:
mutex_unlock(&cfg80211_mutex);
kfree(rd);
return r;
}
static int validate_scan_freqs(struct nlattr *freqs)
{
struct nlattr *attr1, *attr2;
int n_channels = 0, tmp1, tmp2;
nla_for_each_nested(attr1, freqs, tmp1) {
n_channels++;
/*
* Some hardware has a limited channel list for
* scanning, and it is pretty much nonsensical
* to scan for a channel twice, so disallow that
* and don't require drivers to check that the
* channel list they get isn't longer than what
* they can scan, as long as they can scan all
* the channels they registered at once.
*/
nla_for_each_nested(attr2, freqs, tmp2)
if (attr1 != attr2 &&
nla_get_u32(attr1) == nla_get_u32(attr2))
return 0;
}
return n_channels;
}
static int <API key>(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct <API key> *request;
struct nlattr *attr;
struct wiphy *wiphy;
int err, tmp, n_ssids = 0, n_channels, i;
size_t ie_len;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
wiphy = &rdev->wiphy;
if (!rdev->ops->scan)
return -EOPNOTSUPP;
if (rdev->scan_req)
return -EBUSY;
if (info->attrs[<API key>]) {
n_channels = validate_scan_freqs(
info->attrs[<API key>]);
if (!n_channels)
return -EINVAL;
} else {
enum ieee80211_band band;
n_channels = 0;
for (band = 0; band < IEEE80211_NUM_BANDS; band++)
if (wiphy->bands[band])
n_channels += wiphy->bands[band]->n_channels;
}
if (info->attrs[<API key>])
nla_for_each_nested(attr, info->attrs[<API key>], tmp)
n_ssids++;
if (n_ssids > wiphy->max_scan_ssids)
return -EINVAL;
if (info->attrs[NL80211_ATTR_IE])
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
else
ie_len = 0;
if (ie_len > wiphy->max_scan_ie_len)
return -EINVAL;
request = kzalloc(sizeof(*request)
+ sizeof(*request->ssids) * n_ssids
+ sizeof(*request->channels) * n_channels
+ ie_len, GFP_KERNEL);
if (!request)
return -ENOMEM;
if (n_ssids)
request->ssids = (void *)&request->channels[n_channels];
request->n_ssids = n_ssids;
if (ie_len) {
if (request->ssids)
request->ie = (void *)(request->ssids + n_ssids);
else
request->ie = (void *)(request->channels + n_channels);
}
i = 0;
if (info->attrs[<API key>]) {
/* user specified, bail out if channel not found */
nla_for_each_nested(attr, info->attrs[<API key>], tmp) {
struct ieee80211_channel *chan;
chan = <API key>(wiphy, nla_get_u32(attr));
if (!chan) {
err = -EINVAL;
goto out_free;
}
/* ignore disabled channels */
if (chan->flags & <API key>)
continue;
request->channels[i] = chan;
i++;
}
} else {
enum ieee80211_band band;
/* all channels */
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
int j;
if (!wiphy->bands[band])
continue;
for (j = 0; j < wiphy->bands[band]->n_channels; j++) {
struct ieee80211_channel *chan;
chan = &wiphy->bands[band]->channels[j];
if (chan->flags & <API key>)
continue;
request->channels[i] = chan;
i++;
}
}
}
if (!i) {
err = -EINVAL;
goto out_free;
}
request->n_channels = i;
i = 0;
if (info->attrs[<API key>]) {
nla_for_each_nested(attr, info->attrs[<API key>], tmp) {
if (nla_len(attr) > <API key>) {
err = -EINVAL;
goto out_free;
}
request->ssids[i].ssid_len = nla_len(attr);
memcpy(request->ssids[i].ssid, nla_data(attr), nla_len(attr));
i++;
}
}
if (info->attrs[NL80211_ATTR_IE]) {
request->ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
memcpy((void *)request->ie,
nla_data(info->attrs[NL80211_ATTR_IE]),
request->ie_len);
}
for (i = 0; i < IEEE80211_NUM_BANDS; i++)
if (wiphy->bands[i])
request->rates[i] =
(1 << wiphy->bands[i]->n_bitrates) - 1;
if (info->attrs[<API key>]) {
nla_for_each_nested(attr,
info->attrs[<API key>],
tmp) {
enum ieee80211_band band = nla_type(attr);
if (band < 0 || band >= IEEE80211_NUM_BANDS) {
err = -EINVAL;
goto out_free;
}
err = <API key>(wiphy->bands[band],
nla_data(attr),
nla_len(attr),
&request->rates[band]);
if (err)
goto out_free;
}
}
for (i = 0; i < IEEE80211_NUM_BANDS; i++)
if (wiphy->bands[i])
request->rates[i] =
(1 << wiphy->bands[i]->n_bitrates) - 1;
if (info->attrs[<API key>]) {
nla_for_each_nested(attr,
info->attrs[<API key>],
tmp) {
enum ieee80211_band band = nla_type(attr);
if (band < 0 || band >= IEEE80211_NUM_BANDS) {
err = -EINVAL;
goto out_free;
}
if (!wiphy->bands[band])
continue;
err = <API key>(wiphy->bands[band],
nla_data(attr),
nla_len(attr),
&request->rates[band]);
if (err)
goto out_free;
}
}
request->no_cck =
nla_get_flag(info->attrs[<API key>]);
request->dev = dev;
request->wiphy = &rdev->wiphy;
request->no_cck =
nla_get_flag(info->attrs[<API key>]);
rdev->scan_req = request;
err = rdev->ops->scan(&rdev->wiphy, dev, request);
if (!err) {
<API key>(rdev, dev);
dev_hold(dev);
} else {
out_free:
rdev->scan_req = NULL;
kfree(request);
}
return err;
}
static int <API key>(struct sk_buff *skb,
struct genl_info *info)
{
struct <API key> *request;
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct nlattr *attr;
struct wiphy *wiphy;
int err, tmp, n_ssids = 0, n_match_sets = 0, n_channels, i;
u32 interval;
enum ieee80211_band band;
size_t ie_len;
struct nlattr *tb[<API key> + 1];
if (!(rdev->wiphy.flags & <API key>) ||
!rdev->ops->sched_scan_start)
return -EOPNOTSUPP;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[<API key>])
return -EINVAL;
interval = nla_get_u32(info->attrs[<API key>]);
if (interval == 0)
return -EINVAL;
wiphy = &rdev->wiphy;
if (info->attrs[<API key>]) {
n_channels = validate_scan_freqs(
info->attrs[<API key>]);
if (!n_channels)
return -EINVAL;
} else {
n_channels = 0;
for (band = 0; band < IEEE80211_NUM_BANDS; band++)
if (wiphy->bands[band])
n_channels += wiphy->bands[band]->n_channels;
}
if (info->attrs[<API key>])
nla_for_each_nested(attr, info->attrs[<API key>],
tmp)
n_ssids++;
if (n_ssids > wiphy-><API key>)
return -EINVAL;
if (info->attrs[<API key>])
nla_for_each_nested(attr,
info->attrs[<API key>],
tmp)
n_match_sets++;
if (n_match_sets > wiphy->max_match_sets)
return -EINVAL;
if (info->attrs[NL80211_ATTR_IE])
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
else
ie_len = 0;
if (ie_len > wiphy-><API key>)
return -EINVAL;
mutex_lock(&rdev->sched_scan_mtx);
if (rdev->sched_scan_req) {
err = -EINPROGRESS;
goto out;
}
request = kzalloc(sizeof(*request)
+ sizeof(*request->ssids) * n_ssids
+ sizeof(*request->match_sets) * n_match_sets
+ sizeof(*request->channels) * n_channels
+ ie_len, GFP_KERNEL);
if (!request) {
err = -ENOMEM;
goto out;
}
if (n_ssids)
request->ssids = (void *)&request->channels[n_channels];
request->n_ssids = n_ssids;
if (ie_len) {
if (request->ssids)
request->ie = (void *)(request->ssids + n_ssids);
else
request->ie = (void *)(request->channels + n_channels);
}
if (n_match_sets) {
if (request->ie)
request->match_sets = (void *)(request->ie + ie_len);
else if (request->ssids)
request->match_sets =
(void *)(request->ssids + n_ssids);
else
request->match_sets =
(void *)(request->channels + n_channels);
}
request->n_match_sets = n_match_sets;
i = 0;
if (info->attrs[<API key>]) {
/* user specified, bail out if channel not found */
nla_for_each_nested(attr,
info->attrs[<API key>],
tmp) {
struct ieee80211_channel *chan;
chan = <API key>(wiphy, nla_get_u32(attr));
if (!chan) {
err = -EINVAL;
goto out_free;
}
/* ignore disabled channels */
if (chan->flags & <API key>)
continue;
request->channels[i] = chan;
i++;
}
} else {
/* all channels */
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
int j;
if (!wiphy->bands[band])
continue;
for (j = 0; j < wiphy->bands[band]->n_channels; j++) {
struct ieee80211_channel *chan;
chan = &wiphy->bands[band]->channels[j];
if (chan->flags & <API key>)
continue;
request->channels[i] = chan;
i++;
}
}
}
if (!i) {
err = -EINVAL;
goto out_free;
}
request->n_channels = i;
i = 0;
if (info->attrs[<API key>]) {
nla_for_each_nested(attr, info->attrs[<API key>],
tmp) {
if (nla_len(attr) > <API key>) {
err = -EINVAL;
goto out_free;
}
request->ssids[i].ssid_len = nla_len(attr);
memcpy(request->ssids[i].ssid, nla_data(attr),
nla_len(attr));
i++;
}
}
i = 0;
if (info->attrs[<API key>]) {
nla_for_each_nested(attr,
info->attrs[<API key>],
tmp) {
struct nlattr *ssid;
nla_parse(tb, <API key>,
nla_data(attr), nla_len(attr),
<API key>);
ssid = tb[<API key>];
if (ssid) {
if (nla_len(ssid) > <API key>) {
err = -EINVAL;
goto out_free;
}
memcpy(request->match_sets[i].ssid.ssid,
nla_data(ssid), nla_len(ssid));
request->match_sets[i].ssid.ssid_len =
nla_len(ssid);
}
i++;
}
}
if (info->attrs[NL80211_ATTR_IE]) {
request->ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
memcpy((void *)request->ie,
nla_data(info->attrs[NL80211_ATTR_IE]),
request->ie_len);
}
request->dev = dev;
request->wiphy = &rdev->wiphy;
request->interval = interval;
err = rdev->ops->sched_scan_start(&rdev->wiphy, dev, request);
if (!err) {
rdev->sched_scan_req = request;
<API key>(rdev, dev,
<API key>);
goto out;
}
out_free:
kfree(request);
out:
mutex_unlock(&rdev->sched_scan_mtx);
return err;
}
static int <API key>(struct sk_buff *skb,
struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
int err;
if (!(rdev->wiphy.flags & <API key>) ||
!rdev->ops->sched_scan_stop)
return -EOPNOTSUPP;
mutex_lock(&rdev->sched_scan_mtx);
err = <API key>(rdev, false);
mutex_unlock(&rdev->sched_scan_mtx);
return err;
}
static int nl80211_send_bss(struct sk_buff *msg, struct netlink_callback *cb,
u32 seq, int flags,
struct <API key> *rdev,
struct wireless_dev *wdev,
struct <API key> *intbss)
{
struct cfg80211_bss *res = &intbss->pub;
void *hdr;
struct nlattr *bss;
ASSERT_WDEV_LOCK(wdev);
hdr = nl80211hdr_put(msg, NETLINK_CB(cb->skb).pid, seq, flags,
<API key>);
if (!hdr)
return -1;
<API key>(cb, hdr, &nl80211_fam);
NLA_PUT_U32(msg, <API key>, rdev->bss_generation);
NLA_PUT_U32(msg, <API key>, wdev->netdev->ifindex);
bss = nla_nest_start(msg, NL80211_ATTR_BSS);
if (!bss)
goto nla_put_failure;
if (!is_zero_ether_addr(res->bssid))
NLA_PUT(msg, NL80211_BSS_BSSID, ETH_ALEN, res->bssid);
if (res-><API key> && res-><API key>)
NLA_PUT(msg, <API key>,
res-><API key>,
res-><API key>);
if (res->beacon_ies && res->len_beacon_ies &&
res->beacon_ies != res-><API key>)
NLA_PUT(msg, <API key>,
res->len_beacon_ies, res->beacon_ies);
if (res->tsf)
NLA_PUT_U64(msg, NL80211_BSS_TSF, res->tsf);
if (res->beacon_interval)
NLA_PUT_U16(msg, <API key>, res->beacon_interval);
NLA_PUT_U16(msg, <API key>, res->capability);
NLA_PUT_U32(msg, <API key>, res->channel->center_freq);
NLA_PUT_U32(msg, <API key>,
jiffies_to_msecs(jiffies - intbss->ts));
switch (rdev->wiphy.signal_type) {
case <API key>:
NLA_PUT_U32(msg, <API key>, res->signal);
break;
case <API key>:
NLA_PUT_U8(msg, <API key>, res->signal);
break;
default:
break;
}
switch (wdev->iftype) {
case <API key>:
case <API key>:
if (intbss == wdev->current_bss)
NLA_PUT_U32(msg, NL80211_BSS_STATUS,
<API key>);
break;
case <API key>:
if (intbss == wdev->current_bss)
NLA_PUT_U32(msg, NL80211_BSS_STATUS,
<API key>);
break;
default:
break;
}
nla_nest_end(msg, bss);
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nl80211_dump_scan(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct <API key> *rdev;
struct net_device *dev;
struct <API key> *scan;
struct wireless_dev *wdev;
int start = cb->args[1], idx = 0;
int err;
err = <API key>(skb, cb, &rdev, &dev);
if (err)
return err;
wdev = dev->ieee80211_ptr;
wdev_lock(wdev);
spin_lock_bh(&rdev->bss_lock);
cfg80211_bss_expire(rdev);
cb->seq = rdev->bss_generation;
list_for_each_entry(scan, &rdev->bss_list, list) {
if (++idx <= start)
continue;
if (nl80211_send_bss(skb, cb,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
rdev, wdev, scan) < 0) {
idx
break;
}
}
spin_unlock_bh(&rdev->bss_lock);
wdev_unlock(wdev);
cb->args[1] = idx;
<API key>(rdev);
return skb->len;
}
static int nl80211_send_survey(struct sk_buff *msg, u32 pid, u32 seq,
int flags, struct net_device *dev,
struct survey_info *survey)
{
void *hdr;
struct nlattr *infoattr;
hdr = nl80211hdr_put(msg, pid, seq, flags,
<API key>);
if (!hdr)
return -ENOMEM;
NLA_PUT_U32(msg, <API key>, dev->ifindex);
infoattr = nla_nest_start(msg, <API key>);
if (!infoattr)
goto nla_put_failure;
NLA_PUT_U32(msg, <API key>,
survey->channel->center_freq);
if (survey->filled & <API key>)
NLA_PUT_U8(msg, <API key>,
survey->noise);
if (survey->filled & SURVEY_INFO_IN_USE)
NLA_PUT_FLAG(msg, <API key>);
if (survey->filled & <API key>)
NLA_PUT_U64(msg, <API key>,
survey->channel_time);
if (survey->filled & <API key>)
NLA_PUT_U64(msg, <API key>,
survey->channel_time_busy);
if (survey->filled & <API key>)
NLA_PUT_U64(msg, <API key>,
survey-><API key>);
if (survey->filled & <API key>)
NLA_PUT_U64(msg, <API key>,
survey->channel_time_rx);
if (survey->filled & <API key>)
NLA_PUT_U64(msg, <API key>,
survey->channel_time_tx);
nla_nest_end(msg, infoattr);
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nl80211_dump_survey(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct survey_info survey;
struct <API key> *dev;
struct net_device *netdev;
int survey_idx = cb->args[1];
int res;
res = <API key>(skb, cb, &dev, &netdev);
if (res)
return res;
if (!dev->ops->dump_survey) {
res = -EOPNOTSUPP;
goto out_err;
}
while (1) {
struct ieee80211_channel *chan;
res = dev->ops->dump_survey(&dev->wiphy, netdev, survey_idx,
&survey);
if (res == -ENOENT)
break;
if (res)
goto out_err;
/* Survey without a channel doesn't make sense */
if (!survey.channel) {
res = -EINVAL;
goto out;
}
chan = <API key>(&dev->wiphy,
survey.channel->center_freq);
if (!chan || chan->flags & <API key>) {
survey_idx++;
continue;
}
if (nl80211_send_survey(skb,
NETLINK_CB(cb->skb).pid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
netdev,
&survey) < 0)
goto out;
survey_idx++;
}
out:
cb->args[1] = survey_idx;
res = skb->len;
out_err:
<API key>(dev);
return res;
}
static bool <API key>(enum nl80211_auth_type auth_type)
{
return auth_type <= <API key>;
}
static bool <API key>(u32 wpa_versions)
{
return !(wpa_versions & ~(<API key> |
<API key>));
}
static int <API key>(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct ieee80211_channel *chan;
const u8 *bssid, *ssid, *ie = NULL;
int err, ssid_len, ie_len = 0;
enum nl80211_auth_type auth_type;
struct key_parse key;
bool local_state_change;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[<API key>])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_SSID])
return -EINVAL;
if (!info->attrs[<API key>])
return -EINVAL;
err = nl80211_parse_key(info, &key);
if (err)
return err;
if (key.idx >= 0) {
if (key.type != -1 && key.type != <API key>)
return -EINVAL;
if (!key.p.key || !key.p.key_len)
return -EINVAL;
if ((key.p.cipher != <API key> ||
key.p.key_len != WLAN_KEY_LEN_WEP40) &&
(key.p.cipher != <API key> ||
key.p.key_len != WLAN_KEY_LEN_WEP104))
return -EINVAL;
if (key.idx > 4)
return -EINVAL;
} else {
key.p.key_len = 0;
key.p.key = NULL;
}
if (key.idx >= 0) {
int i;
bool ok = false;
for (i = 0; i < rdev->wiphy.n_cipher_suites; i++) {
if (key.p.cipher == rdev->wiphy.cipher_suites[i]) {
ok = true;
break;
}
}
if (!ok)
return -EINVAL;
}
if (!rdev->ops->auth)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
chan = <API key>(&rdev->wiphy,
nla_get_u32(info->attrs[<API key>]));
if (!chan || (chan->flags & <API key>))
return -EINVAL;
ssid = nla_data(info->attrs[NL80211_ATTR_SSID]);
ssid_len = nla_len(info->attrs[NL80211_ATTR_SSID]);
if (info->attrs[NL80211_ATTR_IE]) {
ie = nla_data(info->attrs[NL80211_ATTR_IE]);
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
auth_type = nla_get_u32(info->attrs[<API key>]);
if (!<API key>(auth_type))
return -EINVAL;
local_state_change = !!info->attrs[<API key>];
/*
* Since we no longer track auth state, ignore
* requests to only change local state.
*/
if (local_state_change)
return 0;
return cfg80211_mlme_auth(rdev, dev, chan, auth_type, bssid,
ssid, ssid_len, ie, ie_len,
key.p.key, key.p.key_len, key.idx);
}
static int <API key>(struct <API key> *rdev,
struct genl_info *info,
struct <API key> *settings,
int cipher_limit)
{
memset(settings, 0, sizeof(*settings));
settings->control_port = info->attrs[<API key>];
if (info->attrs[<API key>]) {
u16 proto;
proto = nla_get_u16(
info->attrs[<API key>]);
settings-><API key> = cpu_to_be16(proto);
if (!(rdev->wiphy.flags & <API key>) &&
proto != ETH_P_PAE)
return -EINVAL;
if (info->attrs[<API key>])
settings-><API key> = true;
} else
settings-><API key> = cpu_to_be16(ETH_P_PAE);
if (info->attrs[<API key>]) {
void *data;
int len, i;
data = nla_data(info->attrs[<API key>]);
len = nla_len(info->attrs[<API key>]);
settings->n_ciphers_pairwise = len / sizeof(u32);
if (len % sizeof(u32))
return -EINVAL;
if (settings->n_ciphers_pairwise > cipher_limit)
return -EINVAL;
memcpy(settings->ciphers_pairwise, data, len);
for (i = 0; i < settings->n_ciphers_pairwise; i++)
if (!<API key>(
&rdev->wiphy,
settings->ciphers_pairwise[i]))
return -EINVAL;
}
if (info->attrs[<API key>]) {
settings->cipher_group =
nla_get_u32(info->attrs[<API key>]);
if (!<API key>(&rdev->wiphy,
settings->cipher_group))
return -EINVAL;
}
if (info->attrs[<API key>]) {
settings->wpa_versions =
nla_get_u32(info->attrs[<API key>]);
if (!<API key>(settings->wpa_versions))
return -EINVAL;
}
if (info->attrs[<API key>]) {
void *data;
int len;
data = nla_data(info->attrs[<API key>]);
len = nla_len(info->attrs[<API key>]);
settings->n_akm_suites = len / sizeof(u32);
if (len % sizeof(u32))
return -EINVAL;
if (settings->n_akm_suites > <API key>)
return -EINVAL;
memcpy(settings->akm_suites, data, len);
}
return 0;
}
static int nl80211_associate(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct <API key> crypto;
struct ieee80211_channel *chan;
const u8 *bssid, *ssid, *ie = NULL, *prev_bssid = NULL;
int err, ssid_len, ie_len = 0;
bool use_mfp = false;
u32 flags = 0;
struct ieee80211_ht_cap *ht_capa = NULL;
struct ieee80211_ht_cap *ht_capa_mask = NULL;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MAC] ||
!info->attrs[NL80211_ATTR_SSID] ||
!info->attrs[<API key>])
return -EINVAL;
if (!rdev->ops->assoc)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
chan = <API key>(&rdev->wiphy,
nla_get_u32(info->attrs[<API key>]));
if (!chan || (chan->flags & <API key>))
return -EINVAL;
ssid = nla_data(info->attrs[NL80211_ATTR_SSID]);
ssid_len = nla_len(info->attrs[NL80211_ATTR_SSID]);
if (info->attrs[NL80211_ATTR_IE]) {
ie = nla_data(info->attrs[NL80211_ATTR_IE]);
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
if (info->attrs[<API key>]) {
enum nl80211_mfp mfp =
nla_get_u32(info->attrs[<API key>]);
if (mfp == <API key>)
use_mfp = true;
else if (mfp != NL80211_MFP_NO)
return -EINVAL;
}
if (info->attrs[<API key>])
prev_bssid = nla_data(info->attrs[<API key>]);
if (nla_get_flag(info->attrs[<API key>]))
flags |= <API key>;
if (info->attrs[<API key>])
ht_capa_mask =
nla_data(info->attrs[<API key>]);
if (info->attrs[<API key>]) {
if (!ht_capa_mask)
return -EINVAL;
ht_capa = nla_data(info->attrs[<API key>]);
}
err = <API key>(rdev, info, &crypto, 1);
if (!err)
err = cfg80211_mlme_assoc(rdev, dev, chan, bssid, prev_bssid,
ssid, ssid_len, ie, ie_len, use_mfp,
&crypto, flags, ht_capa,
ht_capa_mask);
return err;
}
static int <API key>(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
const u8 *ie = NULL, *bssid;
int ie_len = 0;
u16 reason_code;
bool local_state_change;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[<API key>])
return -EINVAL;
if (!rdev->ops->deauth)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
reason_code = nla_get_u16(info->attrs[<API key>]);
if (reason_code == 0) {
/* Reason Code 0 is reserved */
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_IE]) {
ie = nla_data(info->attrs[NL80211_ATTR_IE]);
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
local_state_change = !!info->attrs[<API key>];
return <API key>(rdev, dev, bssid, ie, ie_len, reason_code,
local_state_change);
}
static int <API key>(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
const u8 *ie = NULL, *bssid;
int ie_len = 0;
u16 reason_code;
bool local_state_change;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[<API key>])
return -EINVAL;
if (!rdev->ops->disassoc)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
reason_code = nla_get_u16(info->attrs[<API key>]);
if (reason_code == 0) {
/* Reason Code 0 is reserved */
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_IE]) {
ie = nla_data(info->attrs[NL80211_ATTR_IE]);
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
local_state_change = !!info->attrs[<API key>];
return <API key>(rdev, dev, bssid, ie, ie_len, reason_code,
local_state_change);
}
static bool
<API key>(struct <API key> *rdev,
int mcast_rate[IEEE80211_NUM_BANDS],
int rateval)
{
struct wiphy *wiphy = &rdev->wiphy;
bool found = false;
int band, i;
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
struct <API key> *sband;
sband = wiphy->bands[band];
if (!sband)
continue;
for (i = 0; i < sband->n_bitrates; i++) {
if (sband->bitrates[i].bitrate == rateval) {
mcast_rate[band] = i + 1;
found = true;
break;
}
}
}
return found;
}
static int nl80211_join_ibss(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct <API key> ibss;
struct wiphy *wiphy;
struct <API key> *connkeys = NULL;
int err;
memset(&ibss, 0, sizeof(ibss));
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[<API key>] ||
!info->attrs[NL80211_ATTR_SSID] ||
!nla_len(info->attrs[NL80211_ATTR_SSID]))
return -EINVAL;
ibss.beacon_interval = 100;
if (info->attrs[<API key>]) {
ibss.beacon_interval =
nla_get_u32(info->attrs[<API key>]);
if (ibss.beacon_interval < 1 || ibss.beacon_interval > 10000)
return -EINVAL;
}
if (!rdev->ops->join_ibss)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
wiphy = &rdev->wiphy;
if (info->attrs[NL80211_ATTR_MAC]) {
ibss.bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (!is_valid_ether_addr(ibss.bssid))
return -EINVAL;
}
ibss.ssid = nla_data(info->attrs[NL80211_ATTR_SSID]);
ibss.ssid_len = nla_len(info->attrs[NL80211_ATTR_SSID]);
if (info->attrs[NL80211_ATTR_IE]) {
ibss.ie = nla_data(info->attrs[NL80211_ATTR_IE]);
ibss.ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
if (info->attrs[<API key>]) {
enum <API key> channel_type;
channel_type = nla_get_u32(
info->attrs[<API key>]);
if (channel_type != NL80211_CHAN_NO_HT &&
channel_type != NL80211_CHAN_HT20 &&
channel_type != <API key> &&
channel_type != <API key>)
return -EINVAL;
if (channel_type != NL80211_CHAN_NO_HT &&
!(wiphy->features & <API key>))
return -EINVAL;
ibss.channel_type = channel_type;
} else {
ibss.channel_type = NL80211_CHAN_NO_HT;
}
ibss.channel = rdev_freq_to_chan(rdev,
nla_get_u32(info->attrs[<API key>]),
ibss.channel_type);
if (!ibss.channel ||
ibss.channel->flags & <API key> ||
ibss.channel->flags & <API key>)
return -EINVAL;
/* Both channels should be able to initiate communication */
if ((ibss.channel_type == <API key> ||
ibss.channel_type == <API key>) &&
!<API key>(&rdev->wiphy, ibss.channel,
ibss.channel_type))
return -EINVAL;
ibss.channel_fixed = !!info->attrs[<API key>];
ibss.privacy = !!info->attrs[<API key>];
if (info->attrs[<API key>]) {
u8 *rates =
nla_data(info->attrs[<API key>]);
int n_rates =
nla_len(info->attrs[<API key>]);
struct <API key> *sband =
wiphy->bands[ibss.channel->band];
err = <API key>(sband, rates, n_rates,
&ibss.basic_rates);
if (err)
return err;
}
if (info->attrs[<API key>] &&
!<API key>(rdev, ibss.mcast_rate,
nla_get_u32(info->attrs[<API key>])))
return -EINVAL;
if (ibss.privacy && info->attrs[NL80211_ATTR_KEYS]) {
connkeys = <API key>(rdev,
info->attrs[NL80211_ATTR_KEYS]);
if (IS_ERR(connkeys))
return PTR_ERR(connkeys);
}
ibss.control_port =
nla_get_flag(info->attrs[<API key>]);
err = cfg80211_join_ibss(rdev, dev, &ibss, connkeys);
if (err)
kfree(connkeys);
return err;
}
static int nl80211_leave_ibss(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
if (!rdev->ops->leave_ibss)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
return cfg80211_leave_ibss(rdev, dev, false);
}
static struct sk_buff *
<API key>(struct <API key> *rdev,
int approxlen, u32 portid, u32 seq,
enum nl80211_commands cmd,
enum nl80211_attrs attr,
const struct <API key> *info,
gfp_t gfp)
{
struct sk_buff *skb;
void *hdr;
struct nlattr *data;
skb = nlmsg_new(approxlen + 100, gfp);
if (!skb)
return NULL;
hdr = nl80211hdr_put(skb, portid, seq, 0, cmd);
if (!hdr) {
kfree_skb(skb);
return NULL;
}
if (nla_put_u32(skb, NL80211_ATTR_WIPHY, rdev->wiphy_idx))
goto nla_put_failure;
if (info) {
if (nla_put_u32(skb, <API key>,
info->vendor_id))
goto nla_put_failure;
if (nla_put_u32(skb, <API key>,
info->subcmd))
goto nla_put_failure;
}
data = nla_nest_start(skb, attr);
((void **)skb->cb)[0] = rdev;
((void **)skb->cb)[1] = hdr;
((void **)skb->cb)[2] = data;
return skb;
nla_put_failure:
kfree_skb(skb);
return NULL;
}
static struct <API key> <API key> = {
.name = "vendor",
};
#ifdef <API key>
static struct <API key> <API key> = {
.name = "testmode",
};
static int nl80211_testmode_do(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
int err;
if (!info->attrs[<API key>])
return -EINVAL;
err = -EOPNOTSUPP;
if (rdev->ops->testmode_cmd) {
rdev->cur_cmd_info = info;
err = rdev->ops->testmode_cmd(&rdev->wiphy,
nla_data(info->attrs[<API key>]),
nla_len(info->attrs[<API key>]));
rdev->cur_cmd_info = NULL;
}
return err;
}
static int <API key>(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct <API key> *rdev;
int err;
long phy_idx;
void *data = NULL;
int data_len = 0;
if (cb->args[0]) {
/*
* 0 is a valid index, but not valid for args[0],
* so we need to offset by 1.
*/
phy_idx = cb->args[0] - 1;
} else {
err = nlmsg_parse(cb->nlh, GENL_HDRLEN + nl80211_fam.hdrsize,
nl80211_fam.attrbuf, nl80211_fam.maxattr,
nl80211_policy);
if (err)
return err;
if (nl80211_fam.attrbuf[NL80211_ATTR_WIPHY]) {
phy_idx = nla_get_u32(
nl80211_fam.attrbuf[NL80211_ATTR_WIPHY]);
} else {
struct net_device *netdev;
err = <API key>(sock_net(skb->sk),
nl80211_fam.attrbuf,
&rdev, &netdev);
if (err)
return err;
dev_put(netdev);
phy_idx = rdev->wiphy_idx;
<API key>(rdev);
}
if (nl80211_fam.attrbuf[<API key>])
cb->args[1] =
(long)nl80211_fam.attrbuf[<API key>];
}
if (cb->args[1]) {
data = nla_data((void *)cb->args[1]);
data_len = nla_len((void *)cb->args[1]);
}
mutex_lock(&cfg80211_mutex);
rdev = <API key>(phy_idx);
if (!rdev) {
mutex_unlock(&cfg80211_mutex);
return -ENOENT;
}
cfg80211_lock_rdev(rdev);
mutex_unlock(&cfg80211_mutex);
if (!rdev->ops->testmode_dump) {
err = -EOPNOTSUPP;
goto out_err;
}
while (1) {
void *hdr = nl80211hdr_put(skb, NETLINK_CB(cb->skb).pid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
<API key>);
struct nlattr *tmdata;
if (!hdr)
break;
if (nla_put_u32(skb, NL80211_ATTR_WIPHY, phy_idx) < 0) {
genlmsg_cancel(skb, hdr);
break;
}
tmdata = nla_nest_start(skb, <API key>);
if (!tmdata) {
genlmsg_cancel(skb, hdr);
break;
}
err = rdev->ops->testmode_dump(&rdev->wiphy, skb, cb,
data, data_len);
nla_nest_end(skb, tmdata);
if (err == -ENOBUFS || err == -ENOENT) {
genlmsg_cancel(skb, hdr);
break;
} else if (err) {
genlmsg_cancel(skb, hdr);
goto out_err;
}
genlmsg_end(skb, hdr);
}
err = skb->len;
/* see above */
cb->args[0] = phy_idx + 1;
out_err:
<API key>(rdev);
return err;
}
#endif
struct sk_buff *<API key>(struct wiphy *wiphy,
enum nl80211_commands cmd,
enum nl80211_attrs attr,
int vendor_event_idx,
int approxlen, gfp_t gfp)
{
struct <API key> *rdev = wiphy_to_dev(wiphy);
const struct <API key> *info;
switch (cmd) {
case <API key>:
if (WARN_ON(vendor_event_idx != -1))
return NULL;
info = NULL;
break;
case NL80211_CMD_VENDOR:
if (WARN_ON(vendor_event_idx < 0 ||
vendor_event_idx >= wiphy->n_vendor_events))
return NULL;
info = &wiphy->vendor_events[vendor_event_idx];
break;
default:
WARN_ON(1);
return NULL;
}
return <API key>(rdev, approxlen, 0, 0,
cmd, attr, info, gfp);
}
EXPORT_SYMBOL(<API key>);
void <API key>(struct sk_buff *skb, gfp_t gfp)
{
struct <API key> *rdev = ((void **)skb->cb)[0];
void *hdr = ((void **)skb->cb)[1];
struct nlattr *data = ((void **)skb->cb)[2];
nla_nest_end(skb, data);
genlmsg_end(skb, hdr);
if (data->nla_type == <API key>)
<API key>(wiphy_net(&rdev->wiphy), skb, 0,
<API key>.id, gfp);
else
<API key>(wiphy_net(&rdev->wiphy), skb, 0,
<API key>.id, gfp);
}
EXPORT_SYMBOL(<API key>);
static int nl80211_connect(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct <API key> connect;
struct wiphy *wiphy;
struct <API key> *connkeys = NULL;
int err;
memset(&connect, 0, sizeof(connect));
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[NL80211_ATTR_SSID] ||
!nla_len(info->attrs[NL80211_ATTR_SSID]))
return -EINVAL;
if (info->attrs[<API key>]) {
connect.auth_type =
nla_get_u32(info->attrs[<API key>]);
if (!<API key>(connect.auth_type))
return -EINVAL;
} else
connect.auth_type = <API key>;
connect.privacy = info->attrs[<API key>];
err = <API key>(rdev, info, &connect.crypto,
<API key>);
if (err)
return err;
if (dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
wiphy = &rdev->wiphy;
connect.bg_scan_period = -1;
if (info->attrs[<API key>] &&
(wiphy->flags & <API key>)) {
connect.bg_scan_period =
nla_get_u16(info->attrs[<API key>]);
}
if (info->attrs[NL80211_ATTR_MAC])
connect.bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
else if (info->attrs[<API key>])
connect.bssid_hint =
nla_data(info->attrs[<API key>]);
connect.ssid = nla_data(info->attrs[NL80211_ATTR_SSID]);
connect.ssid_len = nla_len(info->attrs[NL80211_ATTR_SSID]);
if (info->attrs[NL80211_ATTR_IE]) {
connect.ie = nla_data(info->attrs[NL80211_ATTR_IE]);
connect.ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
if (info->attrs[<API key>]) {
connect.mfp = nla_get_u32(info->attrs[<API key>]);
if (connect.mfp != <API key> &&
connect.mfp != NL80211_MFP_NO)
return -EINVAL;
} else {
connect.mfp = NL80211_MFP_NO;
}
if (info->attrs[<API key>]) {
connect.channel =
<API key>(wiphy,
nla_get_u32(info->attrs[<API key>]));
if (!connect.channel ||
connect.channel->flags & <API key>)
return -EINVAL;
} else if (info->attrs[<API key>]) {
connect.channel_hint =
<API key>(wiphy,
nla_get_u32(
info->attrs[<API key>]));
if (!connect.channel_hint ||
connect.channel_hint->flags & <API key>)
return -EINVAL;
}
if (connect.privacy && info->attrs[NL80211_ATTR_KEYS]) {
connkeys = <API key>(rdev,
info->attrs[NL80211_ATTR_KEYS]);
if (IS_ERR(connkeys))
return PTR_ERR(connkeys);
}
if (nla_get_flag(info->attrs[<API key>]))
connect.flags |= <API key>;
if (info->attrs[<API key>])
memcpy(&connect.ht_capa_mask,
nla_data(info->attrs[<API key>]),
sizeof(connect.ht_capa_mask));
if (info->attrs[<API key>]) {
if (!info->attrs[<API key>])
return -EINVAL;
memcpy(&connect.ht_capa,
nla_data(info->attrs[<API key>]),
sizeof(connect.ht_capa));
}
err = cfg80211_connect(rdev, dev, &connect, connkeys);
if (err)
kfree(connkeys);
return err;
}
static int nl80211_disconnect(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u16 reason;
if (!info->attrs[<API key>])
reason = <API key>;
else
reason = nla_get_u16(info->attrs[<API key>]);
if (reason == 0)
return -EINVAL;
if (dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
return cfg80211_disconnect(rdev, dev, reason, true);
}
static int nl80211_wiphy_netns(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net *net;
int err;
u32 pid;
if (!info->attrs[NL80211_ATTR_PID])
return -EINVAL;
pid = nla_get_u32(info->attrs[NL80211_ATTR_PID]);
net = get_net_ns_by_pid(pid);
if (IS_ERR(net))
return PTR_ERR(net);
err = 0;
/* check if anything to do */
if (!net_eq(wiphy_net(&rdev->wiphy), net))
err = <API key>(rdev, net);
put_net(net);
return err;
}
static int <API key>(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
int (*rdev_ops)(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_pmksa *pmksa) = NULL;
struct net_device *dev = info->user_ptr[1];
struct cfg80211_pmksa pmksa;
memset(&pmksa, 0, sizeof(struct cfg80211_pmksa));
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_PMKID])
return -EINVAL;
pmksa.pmkid = nla_data(info->attrs[NL80211_ATTR_PMKID]);
pmksa.bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
switch (info->genlhdr->cmd) {
case <API key>:
rdev_ops = rdev->ops->set_pmksa;
break;
case <API key>:
rdev_ops = rdev->ops->del_pmksa;
break;
default:
WARN_ON(1);
break;
}
if (!rdev_ops)
return -EOPNOTSUPP;
return rdev_ops(&rdev->wiphy, dev, &pmksa);
}
static int nl80211_flush_pmksa(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
if (dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
if (!rdev->ops->flush_pmksa)
return -EOPNOTSUPP;
return rdev->ops->flush_pmksa(&rdev->wiphy, dev);
}
static int nl80211_tdls_mgmt(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u8 action_code, dialog_token;
u32 peer_capability = 0;
u16 status_code;
u8 *peer;
if (!(rdev->wiphy.flags & <API key>) ||
!rdev->ops->tdls_mgmt)
return -EOPNOTSUPP;
if (!info->attrs[<API key>] ||
!info->attrs[<API key>] ||
!info->attrs[<API key>] ||
!info->attrs[NL80211_ATTR_IE] ||
!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
peer = nla_data(info->attrs[NL80211_ATTR_MAC]);
action_code = nla_get_u8(info->attrs[<API key>]);
status_code = nla_get_u16(info->attrs[<API key>]);
dialog_token = nla_get_u8(info->attrs[<API key>]);
if (info->attrs[<API key>])
peer_capability =
nla_get_u32(info->attrs[<API key>]);
return rdev->ops->tdls_mgmt(&rdev->wiphy, dev, peer, action_code,
dialog_token, status_code, peer_capability,
nla_data(info->attrs[NL80211_ATTR_IE]),
nla_len(info->attrs[NL80211_ATTR_IE]));
}
static int nl80211_tdls_oper(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
enum <API key> operation;
u8 *peer;
if (!(rdev->wiphy.flags & <API key>) ||
!rdev->ops->tdls_oper)
return -EOPNOTSUPP;
if (!info->attrs[<API key>] ||
!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
operation = nla_get_u8(info->attrs[<API key>]);
peer = nla_data(info->attrs[NL80211_ATTR_MAC]);
return rdev->ops->tdls_oper(&rdev->wiphy, dev, peer, operation);
}
static int <API key>(struct sk_buff *skb,
struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct ieee80211_channel *chan;
struct sk_buff *msg;
void *hdr;
u64 cookie;
enum <API key> channel_type = NL80211_CHAN_NO_HT;
u32 freq, duration;
int err;
if (!info->attrs[<API key>] ||
!info->attrs[<API key>])
return -EINVAL;
duration = nla_get_u32(info->attrs[<API key>]);
/*
* We should be on that channel for at least one jiffie,
* and more than 5 seconds seems excessive.
*/
if (!duration || !msecs_to_jiffies(duration) ||
duration > rdev->wiphy.<API key>)
return -EINVAL;
if (!rdev->ops->remain_on_channel ||
!(rdev->wiphy.flags & <API key>))
return -EOPNOTSUPP;
if (info->attrs[<API key>]) {
channel_type = nla_get_u32(
info->attrs[<API key>]);
if (channel_type != NL80211_CHAN_NO_HT &&
channel_type != NL80211_CHAN_HT20 &&
channel_type != <API key> &&
channel_type != <API key>)
return -EINVAL;
}
freq = nla_get_u32(info->attrs[<API key>]);
chan = rdev_freq_to_chan(rdev, freq, channel_type);
if (chan == NULL)
return -EINVAL;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_pid, info->snd_seq, 0,
<API key>);
if (!hdr) {
err = -ENOBUFS;
goto free_msg;
}
err = rdev->ops->remain_on_channel(&rdev->wiphy, dev, chan,
channel_type, duration, &cookie);
if (err)
goto free_msg;
NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, cookie);
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
err = -ENOBUFS;
free_msg:
nlmsg_free(msg);
return err;
}
static int <API key>(struct sk_buff *skb,
struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u64 cookie;
if (!info->attrs[NL80211_ATTR_COOKIE])
return -EINVAL;
if (!rdev->ops-><API key>)
return -EOPNOTSUPP;
cookie = nla_get_u64(info->attrs[NL80211_ATTR_COOKIE]);
return rdev->ops-><API key>(&rdev->wiphy, dev, cookie);
}
static u32 rateset_to_mask(struct <API key> *sband,
u8 *rates, u8 rates_len)
{
u8 i;
u32 mask = 0;
for (i = 0; i < rates_len; i++) {
int rate = (rates[i] & 0x7f) * 5;
int ridx;
for (ridx = 0; ridx < sband->n_bitrates; ridx++) {
struct ieee80211_rate *srate =
&sband->bitrates[ridx];
if (rate == srate->bitrate) {
mask |= 1 << ridx;
break;
}
}
if (ridx == sband->n_bitrates)
return 0; /* rate not found */
}
return mask;
}
static bool ht_rateset_to_mask(struct <API key> *sband,
u8 *rates, u8 rates_len,
u8 mcs[<API key>])
{
u8 i;
memset(mcs, 0, <API key>);
for (i = 0; i < rates_len; i++) {
int ridx, rbit;
ridx = rates[i] / 8;
rbit = BIT(rates[i] % 8);
/* check validity */
if ((ridx < 0) || (ridx >= <API key>))
return false;
/* check availability */
if (sband->ht_cap.mcs.rx_mask[ridx] & rbit)
mcs[ridx] |= rbit;
else
return false;
}
return true;
}
static const struct nla_policy <API key>[NL80211_TXRATE_MAX + 1] = {
[<API key>] = { .type = NLA_BINARY,
.len = <API key> },
[NL80211_TXRATE_MCS] = { .type = NLA_BINARY,
.len = <API key> },
};
static int <API key>(struct sk_buff *skb,
struct genl_info *info)
{
struct nlattr *tb[NL80211_TXRATE_MAX + 1];
struct <API key> *rdev = info->user_ptr[0];
struct <API key> mask;
int rem, i;
struct net_device *dev = info->user_ptr[1];
struct nlattr *tx_rates;
struct <API key> *sband;
if (info->attrs[<API key>] == NULL)
return -EINVAL;
if (!rdev->ops->set_bitrate_mask)
return -EOPNOTSUPP;
memset(&mask, 0, sizeof(mask));
/* Default to all rates enabled */
for (i = 0; i < IEEE80211_NUM_BANDS; i++) {
sband = rdev->wiphy.bands[i];
mask.control[i].legacy =
sband ? (1 << sband->n_bitrates) - 1 : 0;
if (sband)
memcpy(mask.control[i].mcs,
sband->ht_cap.mcs.rx_mask,
sizeof(mask.control[i].mcs));
else
memset(mask.control[i].mcs, 0,
sizeof(mask.control[i].mcs));
}
/*
* The nested attribute uses enum nl80211_band as the index. This maps
* directly to the enum ieee80211_band values used in cfg80211.
*/
BUILD_BUG_ON(<API key> > <API key> * 8);
nla_for_each_nested(tx_rates, info->attrs[<API key>], rem)
{
enum ieee80211_band band = nla_type(tx_rates);
if (band < 0 || band >= IEEE80211_NUM_BANDS)
return -EINVAL;
sband = rdev->wiphy.bands[band];
if (sband == NULL)
return -EINVAL;
nla_parse(tb, NL80211_TXRATE_MAX, nla_data(tx_rates),
nla_len(tx_rates), <API key>);
if (tb[<API key>]) {
mask.control[band].legacy = rateset_to_mask(
sband,
nla_data(tb[<API key>]),
nla_len(tb[<API key>]));
}
if (tb[NL80211_TXRATE_MCS]) {
if (!ht_rateset_to_mask(
sband,
nla_data(tb[NL80211_TXRATE_MCS]),
nla_len(tb[NL80211_TXRATE_MCS]),
mask.control[band].mcs))
return -EINVAL;
}
if (mask.control[band].legacy == 0) {
/* don't allow empty legacy rates if HT
* is not even supported. */
if (!rdev->wiphy.bands[band]->ht_cap.ht_supported)
return -EINVAL;
for (i = 0; i < <API key>; i++)
if (mask.control[band].mcs[i])
break;
/* legacy and mcs rates may not be both empty */
if (i == <API key>)
return -EINVAL;
}
}
return rdev->ops->set_bitrate_mask(&rdev->wiphy, dev, NULL, &mask);
}
static int <API key>(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u16 frame_type = <API key> | <API key>;
if (!info->attrs[<API key>])
return -EINVAL;
if (info->attrs[<API key>])
frame_type = nla_get_u16(info->attrs[<API key>]);
if (dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
/* not much point in registering if we can't reply */
if (!rdev->ops->mgmt_tx)
return -EOPNOTSUPP;
return <API key>(dev->ieee80211_ptr, info->snd_pid,
frame_type,
nla_data(info->attrs[<API key>]),
nla_len(info->attrs[<API key>]));
}
static int nl80211_tx_mgmt(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct ieee80211_channel *chan;
enum <API key> channel_type = NL80211_CHAN_NO_HT;
bool channel_type_valid = false;
u32 freq;
int err;
void *hdr = NULL;
u64 cookie;
struct sk_buff *msg = NULL;
unsigned int wait = 0;
bool offchan, no_cck, dont_wait_for_ack;
dont_wait_for_ack = info->attrs[<API key>];
if (!info->attrs[NL80211_ATTR_FRAME] ||
!info->attrs[<API key>])
return -EINVAL;
if (!rdev->ops->mgmt_tx)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
if (info->attrs[<API key>]) {
if (!(rdev->wiphy.flags & <API key>))
return -EINVAL;
wait = nla_get_u32(info->attrs[<API key>]);
}
if (info->attrs[<API key>]) {
channel_type = nla_get_u32(
info->attrs[<API key>]);
if (channel_type != NL80211_CHAN_NO_HT &&
channel_type != NL80211_CHAN_HT20 &&
channel_type != <API key> &&
channel_type != <API key>)
return -EINVAL;
channel_type_valid = true;
}
offchan = info->attrs[<API key>];
if (offchan && !(rdev->wiphy.flags & <API key>))
return -EINVAL;
no_cck = nla_get_flag(info->attrs[<API key>]);
freq = nla_get_u32(info->attrs[<API key>]);
chan = rdev_freq_to_chan(rdev, freq, channel_type);
if (chan == NULL)
return -EINVAL;
if (!dont_wait_for_ack) {
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_pid, info->snd_seq, 0,
NL80211_CMD_FRAME);
if (!hdr) {
err = -ENOBUFS;
goto free_msg;
}
}
err = <API key>(rdev, dev, chan, offchan, channel_type,
channel_type_valid, wait,
nla_data(info->attrs[NL80211_ATTR_FRAME]),
nla_len(info->attrs[NL80211_ATTR_FRAME]),
no_cck, dont_wait_for_ack, &cookie);
if (err)
goto free_msg;
if (msg) {
NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, cookie);
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
}
return 0;
nla_put_failure:
err = -ENOBUFS;
free_msg:
nlmsg_free(msg);
return err;
}
static int <API key>(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u64 cookie;
if (!info->attrs[NL80211_ATTR_COOKIE])
return -EINVAL;
if (!rdev->ops->mgmt_tx_cancel_wait)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != <API key> &&
dev->ieee80211_ptr->iftype != <API key>)
return -EOPNOTSUPP;
cookie = nla_get_u64(info->attrs[NL80211_ATTR_COOKIE]);
return rdev->ops->mgmt_tx_cancel_wait(&rdev->wiphy, dev, cookie);
}
static int <API key>(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct wireless_dev *wdev;
struct net_device *dev = info->user_ptr[1];
u8 ps_state;
bool state;
int err;
if (!info->attrs[<API key>])
return -EINVAL;
ps_state = nla_get_u32(info->attrs[<API key>]);
if (ps_state != NL80211_PS_DISABLED && ps_state != NL80211_PS_ENABLED)
return -EINVAL;
wdev = dev->ieee80211_ptr;
if (!rdev->ops->set_power_mgmt)
return -EOPNOTSUPP;
state = (ps_state == NL80211_PS_ENABLED) ? true : false;
if (state == wdev->ps)
return 0;
err = rdev->ops->set_power_mgmt(wdev->wiphy, dev, state,
wdev->ps_timeout);
if (!err)
wdev->ps = state;
return err;
}
static int <API key>(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
enum nl80211_ps_state ps_state;
struct wireless_dev *wdev;
struct net_device *dev = info->user_ptr[1];
struct sk_buff *msg;
void *hdr;
int err;
wdev = dev->ieee80211_ptr;
if (!rdev->ops->set_power_mgmt)
return -EOPNOTSUPP;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_pid, info->snd_seq, 0,
<API key>);
if (!hdr) {
err = -ENOBUFS;
goto free_msg;
}
if (wdev->ps)
ps_state = NL80211_PS_ENABLED;
else
ps_state = NL80211_PS_DISABLED;
NLA_PUT_U32(msg, <API key>, ps_state);
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
err = -ENOBUFS;
free_msg:
nlmsg_free(msg);
return err;
}
static struct nla_policy
<API key>[<API key> + 1] __read_mostly = {
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U32 },
[<API key>] = { .type = NLA_U32 },
};
static int <API key>(struct genl_info *info,
s32 threshold, u32 hysteresis)
{
struct <API key> *rdev = info->user_ptr[0];
struct wireless_dev *wdev;
struct net_device *dev = info->user_ptr[1];
if (threshold > 0)
return -EINVAL;
wdev = dev->ieee80211_ptr;
if (!rdev->ops->set_cqm_rssi_config)
return -EOPNOTSUPP;
if (wdev->iftype != <API key> &&
wdev->iftype != <API key>)
return -EOPNOTSUPP;
return rdev->ops->set_cqm_rssi_config(wdev->wiphy, dev,
threshold, hysteresis);
}
static int nl80211_set_cqm(struct sk_buff *skb, struct genl_info *info)
{
struct nlattr *attrs[<API key> + 1];
struct nlattr *cqm;
int err;
cqm = info->attrs[NL80211_ATTR_CQM];
if (!cqm) {
err = -EINVAL;
goto out;
}
err = nla_parse_nested(attrs, <API key>, cqm,
<API key>);
if (err)
goto out;
if (attrs[<API key>] &&
attrs[<API key>]) {
s32 threshold;
u32 hysteresis;
threshold = nla_get_u32(attrs[<API key>]);
hysteresis = nla_get_u32(attrs[<API key>]);
err = <API key>(info, threshold, hysteresis);
} else
err = -EINVAL;
out:
return err;
}
static int nl80211_join_mesh(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct mesh_config cfg;
struct mesh_setup setup;
int err;
/* start with default */
memcpy(&cfg, &default_mesh_config, sizeof(cfg));
memcpy(&setup, &default_mesh_setup, sizeof(setup));
if (info->attrs[<API key>]) {
/* and parse parameters if given */
err = <API key>(info, &cfg, NULL);
if (err)
return err;
}
if (!info->attrs[<API key>] ||
!nla_len(info->attrs[<API key>]))
return -EINVAL;
setup.mesh_id = nla_data(info->attrs[<API key>]);
setup.mesh_id_len = nla_len(info->attrs[<API key>]);
if (info->attrs[<API key>] &&
!<API key>(rdev, setup.mcast_rate,
nla_get_u32(info->attrs[<API key>])))
return -EINVAL;
if (info->attrs[<API key>]) {
/* parse additional setup parameters if given */
err = <API key>(info, &setup);
if (err)
return err;
}
return cfg80211_join_mesh(rdev, dev, &setup, &cfg);
}
static int nl80211_leave_mesh(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
return cfg80211_leave_mesh(rdev, dev);
}
static int nl80211_get_wowlan(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct sk_buff *msg;
void *hdr;
if (!rdev->wiphy.wowlan.flags && !rdev->wiphy.wowlan.n_patterns)
return -EOPNOTSUPP;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_pid, info->snd_seq, 0,
<API key>);
if (!hdr)
goto nla_put_failure;
if (rdev->wowlan) {
struct nlattr *nl_wowlan;
nl_wowlan = nla_nest_start(msg, <API key>);
if (!nl_wowlan)
goto nla_put_failure;
if (rdev->wowlan->any)
NLA_PUT_FLAG(msg, <API key>);
if (rdev->wowlan->disconnect)
NLA_PUT_FLAG(msg, <API key>);
if (rdev->wowlan->magic_pkt)
NLA_PUT_FLAG(msg, <API key>);
if (rdev->wowlan->gtk_rekey_failure)
NLA_PUT_FLAG(msg, <API key>);
if (rdev->wowlan->eap_identity_req)
NLA_PUT_FLAG(msg, <API key>);
if (rdev->wowlan->four_way_handshake)
NLA_PUT_FLAG(msg, <API key>);
if (rdev->wowlan->rfkill_release)
NLA_PUT_FLAG(msg, <API key>);
if (rdev->wowlan->n_patterns) {
struct nlattr *nl_pats, *nl_pat;
int i, pat_len;
nl_pats = nla_nest_start(msg,
<API key>);
if (!nl_pats)
goto nla_put_failure;
for (i = 0; i < rdev->wowlan->n_patterns; i++) {
nl_pat = nla_nest_start(msg, i + 1);
if (!nl_pat)
goto nla_put_failure;
pat_len = rdev->wowlan->patterns[i].pattern_len;
NLA_PUT(msg, <API key>,
DIV_ROUND_UP(pat_len, 8),
rdev->wowlan->patterns[i].mask);
NLA_PUT(msg, <API key>,
pat_len,
rdev->wowlan->patterns[i].pattern);
nla_nest_end(msg, nl_pat);
}
nla_nest_end(msg, nl_pats);
}
nla_nest_end(msg, nl_wowlan);
}
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
nlmsg_free(msg);
return -ENOBUFS;
}
static int nl80211_set_wowlan(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct nlattr *tb[<API key>];
struct cfg80211_wowlan no_triggers = {};
struct cfg80211_wowlan new_triggers = {};
struct <API key> *wowlan = &rdev->wiphy.wowlan;
int err, i;
if (!rdev->wiphy.wowlan.flags && !rdev->wiphy.wowlan.n_patterns)
return -EOPNOTSUPP;
if (!info->attrs[<API key>])
goto no_triggers;
err = nla_parse(tb, <API key>,
nla_data(info->attrs[<API key>]),
nla_len(info->attrs[<API key>]),
<API key>);
if (err)
return err;
if (tb[<API key>]) {
if (!(wowlan->flags & WIPHY_WOWLAN_ANY))
return -EINVAL;
new_triggers.any = true;
}
if (tb[<API key>]) {
if (!(wowlan->flags & <API key>))
return -EINVAL;
new_triggers.disconnect = true;
}
if (tb[<API key>]) {
if (!(wowlan->flags & <API key>))
return -EINVAL;
new_triggers.magic_pkt = true;
}
if (tb[<API key>])
return -EINVAL;
if (tb[<API key>]) {
if (!(wowlan->flags & <API key>))
return -EINVAL;
new_triggers.gtk_rekey_failure = true;
}
if (tb[<API key>]) {
if (!(wowlan->flags & <API key>))
return -EINVAL;
new_triggers.eap_identity_req = true;
}
if (tb[<API key>]) {
if (!(wowlan->flags & <API key>))
return -EINVAL;
new_triggers.four_way_handshake = true;
}
if (tb[<API key>]) {
if (!(wowlan->flags & <API key>))
return -EINVAL;
new_triggers.rfkill_release = true;
}
if (tb[<API key>]) {
struct nlattr *pat;
int n_patterns = 0;
int rem, pat_len, mask_len;
struct nlattr *pat_tb[<API key>];
nla_for_each_nested(pat, tb[<API key>],
rem)
n_patterns++;
if (n_patterns > wowlan->n_patterns)
return -EINVAL;
new_triggers.patterns = kcalloc(n_patterns,
sizeof(new_triggers.patterns[0]),
GFP_KERNEL);
if (!new_triggers.patterns)
return -ENOMEM;
new_triggers.n_patterns = n_patterns;
i = 0;
nla_for_each_nested(pat, tb[<API key>],
rem) {
nla_parse(pat_tb, <API key>,
nla_data(pat), nla_len(pat), NULL);
err = -EINVAL;
if (!pat_tb[<API key>] ||
!pat_tb[<API key>])
goto error;
pat_len = nla_len(pat_tb[<API key>]);
mask_len = DIV_ROUND_UP(pat_len, 8);
if (nla_len(pat_tb[<API key>]) !=
mask_len)
goto error;
if (pat_len > wowlan->pattern_max_len ||
pat_len < wowlan->pattern_min_len)
goto error;
new_triggers.patterns[i].mask =
kmalloc(mask_len + pat_len, GFP_KERNEL);
if (!new_triggers.patterns[i].mask) {
err = -ENOMEM;
goto error;
}
new_triggers.patterns[i].pattern =
new_triggers.patterns[i].mask + mask_len;
memcpy(new_triggers.patterns[i].mask,
nla_data(pat_tb[<API key>]),
mask_len);
new_triggers.patterns[i].pattern_len = pat_len;
memcpy(new_triggers.patterns[i].pattern,
nla_data(pat_tb[<API key>]),
pat_len);
i++;
}
}
if (memcmp(&new_triggers, &no_triggers, sizeof(new_triggers))) {
struct cfg80211_wowlan *ntrig;
ntrig = kmemdup(&new_triggers, sizeof(new_triggers),
GFP_KERNEL);
if (!ntrig) {
err = -ENOMEM;
goto error;
}
<API key>(rdev);
rdev->wowlan = ntrig;
} else {
no_triggers:
<API key>(rdev);
rdev->wowlan = NULL;
}
return 0;
error:
for (i = 0; i < new_triggers.n_patterns; i++)
kfree(new_triggers.patterns[i].mask);
kfree(new_triggers.patterns);
return err;
}
static int <API key>(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct nlattr *tb[<API key>];
struct <API key> rekey_data;
int err;
if (!info->attrs[<API key>])
return -EINVAL;
err = nla_parse(tb, <API key>,
nla_data(info->attrs[<API key>]),
nla_len(info->attrs[<API key>]),
<API key>);
if (err)
return err;
if (nla_len(tb[<API key>]) != <API key>)
return -ERANGE;
if (nla_len(tb[<API key>]) != NL80211_KEK_LEN)
return -ERANGE;
if (nla_len(tb[<API key>]) != NL80211_KCK_LEN)
return -ERANGE;
memcpy(rekey_data.kek, nla_data(tb[<API key>]),
NL80211_KEK_LEN);
memcpy(rekey_data.kck, nla_data(tb[<API key>]),
NL80211_KCK_LEN);
memcpy(rekey_data.replay_ctr,
nla_data(tb[<API key>]),
<API key>);
wdev_lock(wdev);
if (!wdev->current_bss) {
err = -ENOTCONN;
goto out;
}
if (!rdev->ops->set_rekey_data) {
err = -EOPNOTSUPP;
goto out;
}
err = rdev->ops->set_rekey_data(&rdev->wiphy, dev, &rekey_data);
out:
wdev_unlock(wdev);
return err;
}
static int <API key>(struct sk_buff *skb,
struct genl_info *info)
{
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
if (wdev->iftype != NL80211_IFTYPE_AP &&
wdev->iftype != <API key>)
return -EINVAL;
if (wdev->ap_unexpected_nlpid)
return -EBUSY;
wdev->ap_unexpected_nlpid = info->snd_pid;
return 0;
}
static int <API key>(struct sk_buff *skb,
struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct sk_buff *msg;
void *hdr;
const u8 *addr;
u64 cookie;
int err;
if (wdev->iftype != NL80211_IFTYPE_AP &&
wdev->iftype != <API key>)
return -EOPNOTSUPP;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!rdev->ops->probe_client)
return -EOPNOTSUPP;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_pid, info->snd_seq, 0,
<API key>);
if (!hdr) {
err = -ENOBUFS;
goto free_msg;
}
addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
err = rdev->ops->probe_client(&rdev->wiphy, dev, addr, &cookie);
if (err)
goto free_msg;
NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, cookie);
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
err = -ENOBUFS;
free_msg:
nlmsg_free(msg);
return err;
}
static int <API key>(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
if (!(rdev->wiphy.flags & <API key>))
return -EOPNOTSUPP;
if (rdev->ap_beacons_nlpid)
return -EBUSY;
rdev->ap_beacons_nlpid = info->snd_pid;
return 0;
}
static int <API key>(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct <API key> ft_params;
struct net_device *dev = info->user_ptr[1];
if (!rdev->ops->update_ft_ies)
return -EOPNOTSUPP;
if (!info->attrs[NL80211_ATTR_MDID] ||
!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
memset(&ft_params, 0, sizeof(ft_params));
ft_params.md = nla_get_u16(info->attrs[NL80211_ATTR_MDID]);
ft_params.ie = nla_data(info->attrs[NL80211_ATTR_IE]);
ft_params.ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
return rdev->ops->update_ft_ies(&rdev->wiphy, dev, &ft_params);
}
static int nl80211_vendor_cmd(struct sk_buff *skb, struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
int i, err;
u32 vid, subcmd;
if (!rdev->wiphy.vendor_commands)
return -EOPNOTSUPP;
if (IS_ERR(wdev)) {
err = PTR_ERR(wdev);
if (err != -EINVAL)
return err;
wdev = NULL;
} else if (wdev->wiphy != &rdev->wiphy) {
return -EINVAL;
}
if (!info->attrs[<API key>] ||
!info->attrs[<API key>])
return -EINVAL;
vid = nla_get_u32(info->attrs[<API key>]);
subcmd = nla_get_u32(info->attrs[<API key>]);
for (i = 0; i < rdev->wiphy.n_vendor_commands; i++) {
const struct <API key> *vcmd;
void *data = NULL;
int len = 0;
vcmd = &rdev->wiphy.vendor_commands[i];
if (vcmd->info.vendor_id != vid || vcmd->info.subcmd != subcmd)
continue;
if (vcmd->flags & (<API key> |
<API key>)) {
if (!wdev)
return -EINVAL;
if (vcmd->flags & <API key> &&
!wdev->netdev)
return -EINVAL;
if (vcmd->flags & <API key>) {
if (wdev->netdev &&
!netif_running(wdev->netdev))
return -ENETDOWN;
}
} else {
wdev = NULL;
}
if (info->attrs[<API key>]) {
data = nla_data(info->attrs[<API key>]);
len = nla_len(info->attrs[<API key>]);
}
rdev->cur_cmd_info = info;
err = rdev->wiphy.vendor_commands[i].doit(&rdev->wiphy, wdev,
data, len);
rdev->cur_cmd_info = NULL;
return err;
}
return -EOPNOTSUPP;
}
struct sk_buff *<API key>(struct wiphy *wiphy,
enum nl80211_commands cmd,
enum nl80211_attrs attr,
int approxlen)
{
struct <API key> *rdev = wiphy_to_dev(wiphy);
if (WARN_ON(!rdev->cur_cmd_info))
return NULL;
return <API key>(rdev, approxlen,
0,
0,
cmd, attr, NULL, GFP_KERNEL);
}
EXPORT_SYMBOL(<API key>);
int <API key>(struct sk_buff *skb)
{
struct <API key> *rdev = ((void **)skb->cb)[0];
void *hdr = ((void **)skb->cb)[1];
struct nlattr *data = ((void **)skb->cb)[2];
if (WARN_ON(!rdev->cur_cmd_info)) {
kfree_skb(skb);
return -EINVAL;
}
nla_nest_end(skb, data);
genlmsg_end(skb, hdr);
return genlmsg_reply(skb, rdev->cur_cmd_info);
}
EXPORT_SYMBOL(<API key>);
static int nl80211_set_qos_map(struct sk_buff *skb,
struct genl_info *info)
{
struct <API key> *rdev = info->user_ptr[0];
struct cfg80211_qos_map *qos_map = NULL;
struct net_device *dev = info->user_ptr[1];
u8 *pos, len, num_des, des_len, des;
int ret;
if (!rdev->ops->set_qos_map)
return -EOPNOTSUPP;
if (info->attrs[<API key>]) {
pos = nla_data(info->attrs[<API key>]);
len = nla_len(info->attrs[<API key>]);
if (len % 2 || len < <API key> ||
len > <API key>)
return -EINVAL;
qos_map = kzalloc(sizeof(struct cfg80211_qos_map), GFP_KERNEL);
if (!qos_map)
return -ENOMEM;
num_des = (len - <API key>) >> 1;
if (num_des) {
des_len = num_des *
sizeof(struct <API key>);
memcpy(qos_map->dscp_exception, pos, des_len);
qos_map->num_des = num_des;
for (des = 0; des < num_des; des++) {
if (qos_map->dscp_exception[des].up > 7) {
kfree(qos_map);
return -EINVAL;
}
}
pos += des_len;
}
memcpy(qos_map->up, pos, <API key>);
}
wdev_lock(dev->ieee80211_ptr);
ret = nl80211_key_allowed(dev->ieee80211_ptr);
if (!ret)
ret = rdev->ops->set_qos_map(&rdev->wiphy, dev, qos_map);
wdev_unlock(dev->ieee80211_ptr);
kfree(qos_map);
return ret;
}
#define <API key> 0x01
#define <API key> 0x02
#define <API key> 0x04
#define <API key> 0x08
#define <API key> (<API key> |\
<API key>)
static int nl80211_pre_doit(struct genl_ops *ops, struct sk_buff *skb,
struct genl_info *info)
{
struct <API key> *rdev;
struct net_device *dev;
int err;
bool rtnl = ops->internal_flags & <API key>;
if (rtnl)
rtnl_lock();
if (ops->internal_flags & <API key>) {
rdev = <API key>(info);
if (IS_ERR(rdev)) {
if (rtnl)
rtnl_unlock();
return PTR_ERR(rdev);
}
info->user_ptr[0] = rdev;
} else if (ops->internal_flags & <API key>) {
err = <API key>(genl_info_net(info), info->attrs,
&rdev, &dev);
if (err) {
if (rtnl)
rtnl_unlock();
return err;
}
if (ops->internal_flags & <API key> &&
!netif_running(dev)) {
<API key>(rdev);
dev_put(dev);
if (rtnl)
rtnl_unlock();
return -ENETDOWN;
}
info->user_ptr[0] = rdev;
info->user_ptr[1] = dev;
}
return 0;
}
static void nl80211_post_doit(struct genl_ops *ops, struct sk_buff *skb,
struct genl_info *info)
{
if (info->user_ptr[0])
<API key>(info->user_ptr[0]);
if (info->user_ptr[1])
dev_put(info->user_ptr[1]);
if (ops->internal_flags & <API key>)
rtnl_unlock();
}
static struct genl_ops nl80211_ops[] = {
{
.cmd = <API key>,
.doit = nl80211_get_wiphy,
.dumpit = nl80211_dump_wiphy,
.policy = nl80211_policy,
/* can be retrieved by unprivileged users */
.internal_flags = <API key>,
},
{
.cmd = <API key>,
.doit = nl80211_set_wiphy,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.dumpit = <API key>,
.policy = nl80211_policy,
/* can be retrieved by unprivileged users */
.internal_flags = <API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = NL80211_CMD_GET_KEY,
.doit = nl80211_get_key,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = NL80211_CMD_SET_KEY,
.doit = nl80211_set_key,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = NL80211_CMD_NEW_KEY,
.doit = nl80211_new_key,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = NL80211_CMD_DEL_KEY,
.doit = nl80211_del_key,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.doit = nl80211_set_beacon,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.doit = nl80211_start_ap,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = NL80211_CMD_STOP_AP,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.doit = nl80211_stop_ap,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_get_station,
.dumpit = <API key>,
.policy = nl80211_policy,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_set_station,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_new_station,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_del_station,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_get_mpath,
.dumpit = nl80211_dump_mpath,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_set_mpath,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_new_mpath,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_del_mpath,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = NL80211_CMD_SET_BSS,
.doit = nl80211_set_bss,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = NL80211_CMD_GET_REG,
.doit = nl80211_get_reg,
.policy = nl80211_policy,
/* can be retrieved by unprivileged users */
},
{
.cmd = NL80211_CMD_SET_REG,
.doit = nl80211_set_reg,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
},
{
.cmd = <API key>,
.doit = nl80211_req_set_reg,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
/* can be retrieved by unprivileged users */
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.policy = nl80211_policy,
.dumpit = nl80211_dump_scan,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_associate,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_join_ibss,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_leave_ibss,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
#ifdef <API key>
{
.cmd = <API key>,
.doit = nl80211_testmode_do,
.dumpit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
#endif
{
.cmd = NL80211_CMD_CONNECT,
.doit = nl80211_connect,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_disconnect,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_wiphy_netns,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.policy = nl80211_policy,
.dumpit = nl80211_dump_survey,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_flush_pmksa,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = NL80211_CMD_FRAME,
.doit = nl80211_tx_mgmt,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
/* can be retrieved by unprivileged users */
.internal_flags = <API key> |
<API key>,
},
{
.cmd = NL80211_CMD_SET_CQM,
.doit = nl80211_set_cqm,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_set_channel,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_join_mesh,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_leave_mesh,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_get_wowlan,
.policy = nl80211_policy,
/* can be retrieved by unprivileged users */
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_set_wowlan,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_tdls_mgmt,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_tdls_oper,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_set_mac_acl,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = <API key>,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = NL80211_CMD_VENDOR,
.doit = nl80211_vendor_cmd,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
{
.cmd = <API key>,
.doit = nl80211_set_qos_map,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = <API key> |
<API key>,
},
};
static struct <API key> nl80211_mlme_mcgrp = {
.name = "mlme",
};
/* multicast groups */
static struct <API key> <API key> = {
.name = "config",
};
static struct <API key> nl80211_scan_mcgrp = {
.name = "scan",
};
static struct <API key> <API key> = {
.name = "regulatory",
};
/* notification functions */
void <API key>(struct <API key> *rdev)
{
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
if (nl80211_send_wiphy(msg, 0, 0, 0, rdev) < 0) {
nlmsg_free(msg);
return;
}
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
<API key>.id, GFP_KERNEL);
}
static int <API key>(struct sk_buff *msg,
struct <API key> *rdev)
{
struct <API key> *req = rdev->scan_req;
struct nlattr *nest;
int i;
ASSERT_RDEV_LOCK(rdev);
if (WARN_ON(!req))
return 0;
nest = nla_nest_start(msg, <API key>);
if (!nest)
goto nla_put_failure;
for (i = 0; i < req->n_ssids; i++)
NLA_PUT(msg, i, req->ssids[i].ssid_len, req->ssids[i].ssid);
nla_nest_end(msg, nest);
nest = nla_nest_start(msg, <API key>);
if (!nest)
goto nla_put_failure;
for (i = 0; i < req->n_channels; i++)
NLA_PUT_U32(msg, i, req->channels[i]->center_freq);
nla_nest_end(msg, nest);
if (req->ie)
NLA_PUT(msg, NL80211_ATTR_IE, req->ie_len, req->ie);
return 0;
nla_put_failure:
return -ENOBUFS;
}
static int <API key>(struct sk_buff *msg,
struct <API key> *rdev,
struct net_device *netdev,
u32 pid, u32 seq, int flags,
u32 cmd)
{
void *hdr;
hdr = nl80211hdr_put(msg, pid, seq, flags, cmd);
if (!hdr)
return -1;
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, netdev->ifindex);
/* ignore errors and send incomplete event anyway */
<API key>(msg, rdev);
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int
<API key>(struct sk_buff *msg,
struct <API key> *rdev,
struct net_device *netdev,
u32 pid, u32 seq, int flags, u32 cmd)
{
void *hdr;
hdr = nl80211hdr_put(msg, pid, seq, flags, cmd);
if (!hdr)
return -1;
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, netdev->ifindex);
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev)
{
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
if (!msg)
return;
if (<API key>(msg, rdev, netdev, 0, 0, 0,
<API key>) < 0) {
nlmsg_free(msg);
return;
}
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_scan_mcgrp.id, GFP_KERNEL);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev)
{
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
if (<API key>(msg, rdev, netdev, 0, 0, 0,
<API key>) < 0) {
nlmsg_free(msg);
return;
}
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_scan_mcgrp.id, GFP_KERNEL);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev)
{
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
if (<API key>(msg, rdev, netdev, 0, 0, 0,
<API key>) < 0) {
nlmsg_free(msg);
return;
}
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_scan_mcgrp.id, GFP_KERNEL);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev)
{
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
if (<API key>(msg, rdev, netdev, 0, 0, 0,
<API key>) < 0) {
nlmsg_free(msg);
return;
}
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_scan_mcgrp.id, GFP_KERNEL);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev, u32 cmd)
{
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
if (!msg)
return;
if (<API key>(msg, rdev, netdev, 0, 0, 0, cmd) < 0) {
nlmsg_free(msg);
return;
}
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_scan_mcgrp.id, GFP_KERNEL);
}
/*
* This can happen on global regulatory changes or device specific settings
* based on custom world regulatory domains.
*/
void <API key>(struct regulatory_request *request)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, <API key>);
if (!hdr) {
nlmsg_free(msg);
return;
}
/* Userspace can always count this one always being set */
NLA_PUT_U8(msg, <API key>, request->initiator);
if (request->alpha2[0] == '0' && request->alpha2[1] == '0')
NLA_PUT_U8(msg, <API key>,
<API key>);
else if (request->alpha2[0] == '9' && request->alpha2[1] == '9')
NLA_PUT_U8(msg, <API key>,
<API key>);
else if ((request->alpha2[0] == '9' && request->alpha2[1] == '8') ||
request->intersect)
NLA_PUT_U8(msg, <API key>,
<API key>);
else {
NLA_PUT_U8(msg, <API key>,
<API key>);
NLA_PUT_STRING(msg, <API key>, request->alpha2);
}
if (wiphy_idx_valid(request->wiphy_idx))
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, request->wiphy_idx);
genlmsg_end(msg, hdr);
rcu_read_lock();
<API key>(msg, 0, <API key>.id,
GFP_ATOMIC);
rcu_read_unlock();
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
static void <API key>(struct <API key> *rdev,
struct net_device *netdev,
const u8 *buf, size_t len,
enum nl80211_commands cmd, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, cmd);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, netdev->ifindex);
NLA_PUT(msg, NL80211_ATTR_FRAME, len, buf);
genlmsg_end(msg, hdr);
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev, const u8 *buf,
size_t len, gfp_t gfp)
{
<API key>(rdev, netdev, buf, len,
<API key>, gfp);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev, const u8 *buf,
size_t len, gfp_t gfp)
{
<API key>(rdev, netdev, buf, len,
<API key>, gfp);
}
void nl80211_send_deauth(struct <API key> *rdev,
struct net_device *netdev, const u8 *buf,
size_t len, gfp_t gfp)
{
<API key>(rdev, netdev, buf, len,
<API key>, gfp);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev, const u8 *buf,
size_t len, gfp_t gfp)
{
<API key>(rdev, netdev, buf, len,
<API key>, gfp);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev, const u8 *buf,
size_t len, gfp_t gfp)
{
<API key>(rdev, netdev, buf, len,
<API key>, gfp);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev, const u8 *buf,
size_t len, gfp_t gfp)
{
<API key>(rdev, netdev, buf, len,
<API key>, gfp);
}
static void <API key>(struct <API key> *rdev,
struct net_device *netdev, int cmd,
const u8 *addr, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, cmd);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, netdev->ifindex);
NLA_PUT_FLAG(msg, <API key>);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
genlmsg_end(msg, hdr);
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev, const u8 *addr,
gfp_t gfp)
{
<API key>(rdev, netdev, <API key>,
addr, gfp);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev, const u8 *addr,
gfp_t gfp)
{
<API key>(rdev, netdev, <API key>,
addr, gfp);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev, const u8 *bssid,
const u8 *req_ie, size_t req_ie_len,
const u8 *resp_ie, size_t resp_ie_len,
u16 status, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_GOODSIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_CONNECT);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, netdev->ifindex);
if (bssid)
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid);
NLA_PUT_U16(msg, <API key>, status);
if (req_ie)
NLA_PUT(msg, NL80211_ATTR_REQ_IE, req_ie_len, req_ie);
if (resp_ie)
NLA_PUT(msg, <API key>, resp_ie_len, resp_ie);
genlmsg_end(msg, hdr);
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void nl80211_send_roamed(struct <API key> *rdev,
struct net_device *netdev, const u8 *bssid,
const u8 *req_ie, size_t req_ie_len,
const u8 *resp_ie, size_t resp_ie_len, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_GOODSIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_ROAM);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, netdev->ifindex);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid);
if (req_ie)
NLA_PUT(msg, NL80211_ATTR_REQ_IE, req_ie_len, req_ie);
if (resp_ie)
NLA_PUT(msg, <API key>, resp_ie_len, resp_ie);
genlmsg_end(msg, hdr);
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev, u16 reason,
const u8 *ie, size_t ie_len, bool from_ap)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, <API key>);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, netdev->ifindex);
if (from_ap && reason)
NLA_PUT_U16(msg, <API key>, reason);
if (from_ap)
NLA_PUT_FLAG(msg, <API key>);
if (ie)
NLA_PUT(msg, NL80211_ATTR_IE, ie_len, ie);
genlmsg_end(msg, hdr);
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, GFP_KERNEL);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev, const u8 *bssid,
gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, <API key>);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, netdev->ifindex);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid);
genlmsg_end(msg, hdr);
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev,
const u8 *macaddr, const u8* ie, u8 ie_len,
gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, <API key>);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, netdev->ifindex);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, macaddr);
if (ie_len && ie)
NLA_PUT(msg, NL80211_ATTR_IE, ie_len , ie);
genlmsg_end(msg, hdr);
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev, const u8 *addr,
enum nl80211_key_type key_type, int key_id,
const u8 *tsc, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, <API key>);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, netdev->ifindex);
if (addr)
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
NLA_PUT_U32(msg, <API key>, key_type);
if (key_id != -1)
NLA_PUT_U8(msg, <API key>, key_id);
if (tsc)
NLA_PUT(msg, <API key>, 6, tsc);
genlmsg_end(msg, hdr);
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void <API key>(struct wiphy *wiphy,
struct ieee80211_channel *channel_before,
struct ieee80211_channel *channel_after)
{
struct sk_buff *msg;
void *hdr;
struct nlattr *nl_freq;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, <API key>);
if (!hdr) {
nlmsg_free(msg);
return;
}
/*
* Since we are applying the beacon hint to a wiphy we know its
* wiphy_idx is valid
*/
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, get_wiphy_idx(wiphy));
/* Before */
nl_freq = nla_nest_start(msg, <API key>);
if (!nl_freq)
goto nla_put_failure;
if (<API key>(msg, channel_before))
goto nla_put_failure;
nla_nest_end(msg, nl_freq);
/* After */
nl_freq = nla_nest_start(msg, <API key>);
if (!nl_freq)
goto nla_put_failure;
if (<API key>(msg, channel_after))
goto nla_put_failure;
nla_nest_end(msg, nl_freq);
genlmsg_end(msg, hdr);
rcu_read_lock();
<API key>(msg, 0, <API key>.id,
GFP_ATOMIC);
rcu_read_unlock();
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
static void <API key>(
int cmd, struct <API key> *rdev,
struct net_device *netdev, u64 cookie,
struct ieee80211_channel *chan,
enum <API key> channel_type,
unsigned int duration, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, cmd);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, netdev->ifindex);
NLA_PUT_U32(msg, <API key>, chan->center_freq);
NLA_PUT_U32(msg, <API key>, channel_type);
NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, cookie);
if (cmd == <API key>)
NLA_PUT_U32(msg, <API key>, duration);
genlmsg_end(msg, hdr);
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev, u64 cookie,
struct ieee80211_channel *chan,
enum <API key> channel_type,
unsigned int duration, gfp_t gfp)
{
<API key>(<API key>,
rdev, netdev, cookie, chan,
channel_type, duration, gfp);
}
void <API key>(
struct <API key> *rdev, struct net_device *netdev,
u64 cookie, struct ieee80211_channel *chan,
enum <API key> channel_type, gfp_t gfp)
{
<API key>(<API key>,
rdev, netdev, cookie, chan,
channel_type, 0, gfp);
}
void <API key>(struct <API key> *rdev,
struct net_device *dev, const u8 *mac_addr,
struct station_info *sinfo, gfp_t gfp)
{
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_GOODSIZE, gfp);
if (!msg)
return;
if (<API key>(msg, 0, 0, 0,
rdev, dev, mac_addr, sinfo) < 0) {
nlmsg_free(msg);
return;
}
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
}
void <API key>(struct <API key> *rdev,
struct net_device *dev, const u8 *mac_addr,
gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_GOODSIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, <API key>);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, <API key>, dev->ifindex);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, mac_addr);
genlmsg_end(msg, hdr);
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
static bool <API key>(struct net_device *dev, u8 cmd,
const u8 *addr, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
struct sk_buff *msg;
void *hdr;
int err;
u32 nlpid = ACCESS_ONCE(wdev->ap_unexpected_nlpid);
if (!nlpid)
return false;
msg = nlmsg_new(100, gfp);
if (!msg)
return true;
hdr = nl80211hdr_put(msg, 0, 0, 0, cmd);
if (!hdr) {
nlmsg_free(msg);
return true;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, dev->ifindex);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
err = genlmsg_end(msg, hdr);
if (err < 0) {
nlmsg_free(msg);
return true;
}
genlmsg_unicast(wiphy_net(&rdev->wiphy), msg, nlpid);
return true;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
return true;
}
bool <API key>(struct net_device *dev, const u8 *addr, gfp_t gfp)
{
return <API key>(dev, <API key>,
addr, gfp);
}
bool <API key>(struct net_device *dev,
const u8 *addr, gfp_t gfp)
{
return <API key>(dev,
<API key>,
addr, gfp);
}
int nl80211_send_mgmt(struct <API key> *rdev,
struct net_device *netdev, u32 nlpid,
int freq, int sig_dbm,
const u8 *buf, size_t len, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_FRAME);
if (!hdr) {
nlmsg_free(msg);
return -ENOMEM;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, netdev->ifindex);
NLA_PUT_U32(msg, <API key>, freq);
if (sig_dbm)
NLA_PUT_U32(msg, <API key>, sig_dbm);
NLA_PUT(msg, NL80211_ATTR_FRAME, len, buf);
genlmsg_end(msg, hdr);
return genlmsg_unicast(wiphy_net(&rdev->wiphy), msg, nlpid);
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
return -ENOBUFS;
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev, u64 cookie,
const u8 *buf, size_t len, bool ack,
gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, <API key>);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, netdev->ifindex);
NLA_PUT(msg, NL80211_ATTR_FRAME, len, buf);
NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, cookie);
if (ack)
NLA_PUT_FLAG(msg, NL80211_ATTR_ACK);
genlmsg_end(msg, hdr);
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void
<API key>(struct <API key> *rdev,
struct net_device *netdev,
enum <API key> rssi_event,
gfp_t gfp)
{
struct sk_buff *msg;
struct nlattr *pinfoattr;
void *hdr;
msg = nlmsg_new(NLMSG_GOODSIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, <API key>);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, netdev->ifindex);
pinfoattr = nla_nest_start(msg, NL80211_ATTR_CQM);
if (!pinfoattr)
goto nla_put_failure;
NLA_PUT_U32(msg, <API key>,
rssi_event);
nla_nest_end(msg, pinfoattr);
genlmsg_end(msg, hdr);
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev, const u8 *bssid,
const u8 *replay_ctr, gfp_t gfp)
{
struct sk_buff *msg;
struct nlattr *rekey_attr;
void *hdr;
msg = nlmsg_new(NLMSG_GOODSIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, <API key>);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, netdev->ifindex);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid);
rekey_attr = nla_nest_start(msg, <API key>);
if (!rekey_attr)
goto nla_put_failure;
NLA_PUT(msg, <API key>,
<API key>, replay_ctr);
nla_nest_end(msg, rekey_attr);
genlmsg_end(msg, hdr);
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void <API key>(struct <API key> *rdev,
struct net_device *netdev, int index,
const u8 *bssid, bool preauth, gfp_t gfp)
{
struct sk_buff *msg;
struct nlattr *attr;
void *hdr;
msg = nlmsg_new(NLMSG_GOODSIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, <API key>);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, netdev->ifindex);
attr = nla_nest_start(msg, <API key>);
if (!attr)
goto nla_put_failure;
NLA_PUT_U32(msg, <API key>, index);
NLA_PUT(msg, <API key>, ETH_ALEN, bssid);
if (preauth)
NLA_PUT_FLAG(msg, <API key>);
nla_nest_end(msg, attr);
genlmsg_end(msg, hdr);
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void
<API key>(struct <API key> *rdev,
struct net_device *netdev, const u8 *peer,
u32 num_packets, gfp_t gfp)
{
struct sk_buff *msg;
struct nlattr *pinfoattr;
void *hdr;
msg = nlmsg_new(NLMSG_GOODSIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, <API key>);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, netdev->ifindex);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, peer);
pinfoattr = nla_nest_start(msg, NL80211_ATTR_CQM);
if (!pinfoattr)
goto nla_put_failure;
NLA_PUT_U32(msg, <API key>, num_packets);
nla_nest_end(msg, pinfoattr);
genlmsg_end(msg, hdr);
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void <API key>(struct net_device *dev, const u8 *addr,
u64 cookie, bool acked, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
struct sk_buff *msg;
void *hdr;
int err;
msg = nlmsg_new(NLMSG_GOODSIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, <API key>);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
NLA_PUT_U32(msg, <API key>, dev->ifindex);
NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, cookie);
if (acked)
NLA_PUT_FLAG(msg, NL80211_ATTR_ACK);
err = genlmsg_end(msg, hdr);
if (err < 0) {
nlmsg_free(msg);
return;
}
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
EXPORT_SYMBOL(<API key>);
void <API key>(struct wiphy *wiphy,
const u8 *frame, size_t len,
int freq, int sig_dbm, gfp_t gfp)
{
struct <API key> *rdev = wiphy_to_dev(wiphy);
struct sk_buff *msg;
void *hdr;
u32 nlpid = ACCESS_ONCE(rdev->ap_beacons_nlpid);
if (!nlpid)
return;
msg = nlmsg_new(len + 100, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_FRAME);
if (!hdr) {
nlmsg_free(msg);
return;
}
NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
if (freq)
NLA_PUT_U32(msg, <API key>, freq);
if (sig_dbm)
NLA_PUT_U32(msg, <API key>, sig_dbm);
NLA_PUT(msg, NL80211_ATTR_FRAME, len, frame);
genlmsg_end(msg, hdr);
genlmsg_unicast(wiphy_net(&rdev->wiphy), msg, nlpid);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
EXPORT_SYMBOL(<API key>);
void <API key>(struct net_device *dev, const u8 *peer,
enum <API key> oper,
u16 reason_code, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
struct sk_buff *msg;
void *hdr;
int err;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, <API key>);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, <API key>, dev->ifindex) ||
nla_put_u8(msg, <API key>, oper) ||
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, peer) ||
(reason_code > 0 &&
nla_put_u16(msg, <API key>, reason_code)))
goto nla_put_failure;
err = genlmsg_end(msg, hdr);
if (err < 0) {
nlmsg_free(msg);
return;
}
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
EXPORT_SYMBOL(<API key>);
static int <API key>(struct notifier_block * nb,
unsigned long state,
void *_notify)
{
struct netlink_notify *notify = _notify;
struct <API key> *rdev;
struct wireless_dev *wdev;
if (state != NETLINK_URELEASE)
return NOTIFY_DONE;
rcu_read_lock();
<API key>(rdev, &cfg80211_rdev_list, list) {
<API key>(wdev, &rdev->netdev_list, list)
<API key>(wdev, notify->pid);
if (rdev->ap_beacons_nlpid == notify->pid)
rdev->ap_beacons_nlpid = 0;
}
rcu_read_unlock();
return NOTIFY_DONE;
}
static struct notifier_block <API key> = {
.notifier_call = <API key>,
};
void cfg80211_ft_event(struct net_device *netdev,
struct <API key> *ft_event)
{
struct wiphy *wiphy = netdev->ieee80211_ptr->wiphy;
struct <API key> *rdev = wiphy_to_dev(wiphy);
struct sk_buff *msg;
void *hdr;
int err;
if (!ft_event->target_ap)
return;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, <API key>);
if (!hdr) {
nlmsg_free(msg);
return;
}
nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx);
nla_put_u32(msg, <API key>, netdev->ifindex);
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, ft_event->target_ap);
if (ft_event->ies)
nla_put(msg, NL80211_ATTR_IE, ft_event->ies_len, ft_event->ies);
if (ft_event->ric_ies)
nla_put(msg, NL80211_ATTR_IE_RIC, ft_event->ric_ies_len,
ft_event->ric_ies);
err = genlmsg_end(msg, hdr);
if (err < 0) {
nlmsg_free(msg);
return;
}
<API key>(wiphy_net(&rdev->wiphy), msg, 0,
nl80211_mlme_mcgrp.id, GFP_KERNEL);
}
EXPORT_SYMBOL(cfg80211_ft_event);
void cfg80211_ap_stopped(struct net_device *netdev, gfp_t gfp)
{
struct wireless_dev *wdev = netdev->ieee80211_ptr;
struct <API key> *rdev = wiphy_to_dev(wdev->wiphy);
<API key>(rdev, netdev, NULL, 0,
NL80211_CMD_STOP_AP, gfp);
}
EXPORT_SYMBOL(cfg80211_ap_stopped);
/* initialisation/exit functions */
int nl80211_init(void)
{
int err;
err = <API key>(&nl80211_fam,
nl80211_ops, ARRAY_SIZE(nl80211_ops));
if (err)
return err;
err = <API key>(&nl80211_fam, &<API key>);
if (err)
goto err_out;
err = <API key>(&nl80211_fam, &nl80211_scan_mcgrp);
if (err)
goto err_out;
err = <API key>(&nl80211_fam, &<API key>);
if (err)
goto err_out;
err = <API key>(&nl80211_fam, &nl80211_mlme_mcgrp);
if (err)
goto err_out;
#ifdef <API key>
err = <API key>(&nl80211_fam, &<API key>);
if (err)
goto err_out;
#endif
err = <API key>(&nl80211_fam, &<API key>);
if (err)
goto err_out;
err = <API key>(&<API key>);
if (err)
goto err_out;
return 0;
err_out:
<API key>(&nl80211_fam);
return err;
}
void nl80211_exit(void)
{
<API key>(&<API key>);
<API key>(&nl80211_fam);
} |
#!/usr/bin/python
# Author = Andrej Frank, IT-Designers GmbH, STZ Softwaretechnik
# Version = 0.0.1 Alpha
# what we do:
# - read configuration(user,pass,what to save, where to save)
# - get the config from switchs
# - log in ssh, get the configs/files/dirs
# - store it on git( clone if not exists, commit, push)
# at moment is it alpha and the error handling is very bad (like my english ;)
import git
import subprocess
import sys, os
import shutil
import paramiko
import tarfile
from optparse import OptionParser
import ssl
import ssh
import readConfig
import pc6248
import ap541
ENV={}
C_GIT='git-configs'
C_SSH='ssh-server'
debug=True
def log(ok=True, msg='', exit=False):
'''simple log if the debug is true. '''
if debug:
if ok:
print "[+] %s"%msg
else:
print "[-] %s"%msg
if exit:
sys.exit(-1)
def get_copy(host):
'''copy a remote file to local file'''
log(ok=True, msg="start to copy...")
hostip = ENV[host]['ipaddress']
name = ENV[host]['username']
passwd = ENV[host]['password']
paths = ENV[host]['file']
repo = ENV[C_GIT]['repopath']
log(ok=True, msg="connect to %s user %s"%(hostip, name))
print "%s %s %s"%(hostip, name, passwd)
client = ssh.open(hostip, name, passwd)
ssh.scp(client, paths, repo)
client.close()
log(ok=True, msg="copy ok")
def get_copy_remote(host):
'''copy a remote file to local file, which was copied from pc6248 to remote file.
we must delete the remote file'''
log(ok=True, msg="start to copy...")
hostip = ENV[C_SSH]['ipaddress']
name = ENV[C_SSH]['username']
passwd = ENV[C_SSH]['password']
paths = ENV[host]['pc6428']
repo = ENV[C_GIT]['repopath']
# TODO: it is better if we have temporaer local files
log(ok=True, msg="connect to %s user %s"%(hostip, name))
client = ssh.open(hostip, name, passwd)
ssh.scp(client, paths, repo)
for x in paths:
ssh.remove(client, x['remotepath'])
client.close()
log(ok=True, msg="copy ok")
def get_directory(host):
''' get the remote diretory with ssh, tar and untar. '''
log(ok=True, msg="start to copy a directory...")
hostip = ENV[host]['ipaddress']
name = ENV[host]['username']
passwd = ENV[host]['password']
paths = ENV[host]['dirs']
repo = ENV[C_GIT]['repopath']
log(ok=True, msg="connect to %s user %s"%(hostip, name))
client = ssh.open(hostip, name, passwd)
ftp = client.open_sftp()
for x in paths:
remote = x['remotepath']
local = x['localpath']
log(ok=True, msg="copy dirs %s:/%s to local %s/%s"%(host,remote,repo,local))
tokens = remote.split('/')
if tokens[-1] == '':
name = tokens[-2]
directory = '/'.join(tokens[:-2])
else:
name = tokens[-1]
directory = '/'.join(tokens[:-1])
# print "client: %s name: %s dir: %s"%(client, name, directory)
err, lines = ssh.tar_c(client, name, directory)
if not err: # move to the repo
tarname='/tmp/%s.tgz'%name
log(ok=True, msg="untar %s"%tarname)
ssh.scp_file(ftp, tarname, tarname)
ssh.remove(client, tarname)
tar = tarfile.open(tarname)
tar.extractall(path=repo+'/'+local)
tar.close()
os.remove(tarname)
else:
log(ok=False, msg="something is wrong on ssh tar: %s"%lines)
sys.exit(-1)
client.close()
def open_repo():
''' open the repo if exists and pull it'''
log(ok=True, msg="open repo...")
repopath=ENV[C_GIT]['repopath']
# try open the repo, if none, then clone
try:
repo=git.Repo(repopath)
log(ok=True, msg="get the repo %s"%repopath)
origin = repo.remotes.origin
# pull
origin.pull()
log(ok=True, msg="pulled")
return repo
except git.exc.NoSuchPathError:
print "error you must clone the repo first,"
print "execute following commands:\n"
t=repopath.split('/')
print " cd %s"%('/'.join(t[:-1]))
print " git clone %s"%(ENV[C_GIT]['remote'])
print
print "and you must set the username:password in .git/config url"
print "we dont handle username:password yet\n"
sys.exit(-1)
def add2git(repo, msg):
''' add a file/dir to git'''
log(ok=True, msg="start to add...")
repopath=ENV[C_GIT]['repopath']
# commit the file if modified or new
gitCommit(msg, repopath)
log(ok=True, msg="commited (%s)"%msg)
def push2git(repo):
'''push to remote git'''
log(ok=True, msg="start to push...")
origin = repo.remotes.origin
origin.push()
log(ok=True, msg="pushed")
def gitCommit(message, repoDir):
''' we use "git commit -a -m message", because the python git has not work correct.
or we have not use it correct.'''
cmd = ['git', 'add', '.']
p = subprocess.Popen(cmd, cwd=repoDir)
p.wait()
cmd = ['git', 'commit', '-a', '-m', message]
p = subprocess.Popen(cmd, cwd=repoDir)
p.wait()
def getPC6248(host):
''' get the configuration of the PowerConnect 6248 Switch.'''
log(ok=True, msg="start to get from Switch pc6248 %s..."%host)
if 'ssh-server' in ENV.keys():
sshenv = ENV['ssh-server']
else:
log(ok=False, msg="ERROR, no ssh-server config found", exit=True)
hostenv=ENV[host]
cl = pc6248.PC6248(host, hostenv, sshenv)
r, msg = cl.login()
log(ok=True, msg="Login ok: %d, %s"%(r, msg))
if r==200:
r=cl.get_config()
if r:
log(ok=True, msg="OK, get the files")
else:
log(ok=False, msg="Error on getting files from pc6428 %s"%host)
else:
log(ok=False, msg="Error on getting files from pc6428 %s"%host)
def getAP541(host):
''' get the configuration of the Access Point AP541.'''
log(ok=True, msg="start to get from Access Point ap541 %s..."%host)
hostenv=ENV[host]
cl = ap541.AP541(host, hostenv)
r, msg = cl.login()
log(ok=True, msg="Login ok: %d %s"%(r, msg))
if r==200:
r=cl.get_config()
if r:
log(ok=True, msg="OK, get the files")
else:
log(ok=False, msg="Error on getting files from ap541 %s"%host)
else:
log(ok=False, msg="Error on getting files from ap541 %s"%host)
def move_local(host, how, nr):
''' move a local file. '''
log(ok=True, msg="move local file...")
repo = ENV[C_GIT]['repopath']
fromfile = ENV[host][how][nr]['remotepath']
tofile = repo+"/"+ENV[host][how][nr]['localpath']
log(ok=True, msg="move local file from %s to %s ..."%(fromfile, tofile))
shutil.move(fromfile, tofile)
if __name__ == '__main__':
ssl.<API key> = ssl.<API key>
parser = OptionParser()
parser.add_option("-c", "--config", dest="config",
help="get the config file", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
(options, args) = parser.parse_args()
configfile=''
if options.config==None:
sys.stderr.write('ERROR: please give a configuration file (see -h)\n')
sys.exit(-1)
else:
configfile=options.config
if not os.path.isfile(configfile):
sys.stderr.write('ERROR: can\'t open the file\n')
sys.exit(-1)
if not options.verbose:
debug=True
log(ok=True, msg="read configuration...")
ENV = readConfig.read(configpath=configfile)
#readConfig.printOut(ENV)
repo=open_repo()
for host in ENV.keys():
if host != C_GIT:
log(ok=True, msg="work on host: %s"%host)
if 'file' in ENV[host].keys():
get_copy(host)
add2git(repo, "added config host %s"%host)
if 'pc6428' in ENV[host].keys():
getPC6248(host)
get_copy_remote(host)
add2git(repo, "added pc6248 config from host %s"%host)
if 'ap541' in ENV[host].keys():
getAP541(host)
move_local(host, 'ap541', 0)
add2git(repo, "added AP541 config.xml from host %s"%host)
if 'dirs' in ENV[host].keys():
get_directory(host)
add2git(repo, "added direcotory from host %s"%host)
push2git(repo)
log(ok=True, msg="all done") |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="ast">
<context>
<name>AboutDialog</name>
<message>
<location filename="../src/core/ui/about.cpp" line="34"/>
<source>using Qt </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="41"/>
<source>About</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="42"/>
<source>Thanks</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="43"/>
<source>Help us</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="100"/>
<source>is a crossplatform application for fast creating screenshots of your desktop.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="102"/>
<source>It is a light and powerful application, written in Qt.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="105"/>
<source>Website</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="109"/>
<source>Licensed under the </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="113"/>
<source>Copyright &copy; 2009-2013, Artem 'DOOMer' Galichkin</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="120"/>
<source>You can join us and help us if you want. This is an invitation if you like this application.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="123"/>
<source>What you can do?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="126"/>
<source>Translate ScreenGrab to other languages</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="127"/>
<source>Make suggestions for next releases</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="128"/>
<source>Report bugs and issues</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="131"/>
<source>Bug tracker</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="141"/>
<source>Translate:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="143"/>
<source> Brazilian Portuguese translation</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="144"/>
<source>Marcio Moraes</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="146"/>
<source> Ukrainian translation</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="147"/>
<source>Gennadi Motsyo</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="149"/>
<source> Spanish translation</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="150"/>
<source>Burjans L García D</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="152"/>
<source> Italian translation</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="156"/>
<source>Testing:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="158"/>
<source>Dual monitor support and other in Linux</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="159"/>
<source>Dual monitor support in Linux</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="160"/>
<source>win32-build [Windows XP and 7]</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="161"/>
<source>old win32-build [Windows Vista]</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/about.cpp" line="162"/>
<source>win32-build [Windows 7]</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>ConfigDialog</name>
<message>
<location filename="../src/core/ui/configwidget.cpp" line="192"/>
<source>Directory %1 does not exist. Do you want to create it?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.cpp" line="193"/>
<location filename="../src/core/ui/configwidget.cpp" line="294"/>
<source>Warning</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.cpp" line="282"/>
<source>Select directory</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.cpp" line="293"/>
<source>Do you want to reset the settings to the defaults?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.cpp" line="351"/>
<source>Example: </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.cpp" line="406"/>
<source>This key is already used in ScreenGrab! Please select another.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.cpp" line="424"/>
<source>This key is not supported on your system!</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.cpp" line="444"/>
<source>Error</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Core</name>
<message>
<location filename="../src/core/core.cpp" line="58"/>
<source>is a crossplatform application for fast creating screenshots of your desktop.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/core.cpp" line="62"/>
<source>Take a fullscreen screenshot</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/core.cpp" line="66"/>
<source>Take a screenshot of the active window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/core.cpp" line="70"/>
<source>Take a screenshot of a selection of the screen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/core.cpp" line="74"/>
<source>Run the application with a hidden main window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/core.cpp" line="431"/>
<source>Saved</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/core.cpp" line="431"/>
<source>Saved to </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/core.cpp" line="453"/>
<source>Name of saved file is copied to the clipboard</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/core.cpp" line="459"/>
<source>Path to saved file is copied to the clipboard</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/core.cpp" line="481"/>
<source>Copied</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/core.cpp" line="481"/>
<source>Screenshot is copied to clipboard</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../src/core/ui/mainwindow.ui" line="14"/>
<source>ScreenGrab</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.ui" line="79"/>
<source>Type:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.ui" line="89"/>
<source>Type of screenshot</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.ui" line="96"/>
<source>Full screen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.ui" line="101"/>
<source>Window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.ui" line="106"/>
<source>Screen area</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.ui" line="111"/>
<source>Last selected area</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.ui" line="141"/>
<source>Delay:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.ui" line="154"/>
<source>Delay in seconds before taking screenshot</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.ui" line="157"/>
<source>None</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.ui" line="160"/>
<source> sec</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.ui" line="203"/>
<source>Zoom area around mouse</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.ui" line="210"/>
<source>No window decoration</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.ui" line="217"/>
<source>Include mouse pointer</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.ui" line="246"/>
<source>toolBar</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.cpp" line="45"/>
<source>New</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.cpp" line="46"/>
<source>Save</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.cpp" line="47"/>
<source>Copy</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.cpp" line="48"/>
<source>Options</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.cpp" line="49"/>
<location filename="../src/core/ui/mainwindow.cpp" line="73"/>
<source>Help</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.cpp" line="50"/>
<source>About</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.cpp" line="51"/>
<source>Quit</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.cpp" line="341"/>
<source>Screenshot </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.cpp" line="345"/>
<source>Double click to open screenshot in external default image viewer</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.cpp" line="354"/>
<location filename="../src/core/ui/mainwindow.cpp" line="485"/>
<source>Hide</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.cpp" line="492"/>
<source>Show</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.cpp" line="545"/>
<source>%1 Files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/mainwindow.cpp" line="567"/>
<source>Save As...</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>QApplication</name>
<message>
<location filename="../src/core/regionselect.cpp" line="170"/>
<source>Click and drag to draw a rectangle,
right click to fit to edges,
double click or press Enter
to take a screenshot.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/regionselect.cpp" line="202"/>
<source>%1 x %2 pixels </source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<location filename="../src/modules/extedit/moduleextedit.cpp" line="35"/>
<source>External edit</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/modules/extedit/moduleextedit.cpp" line="46"/>
<source>Edit in...</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>aboutWidget</name>
<message>
<location filename="../src/core/ui/aboutwidget.ui" line="128"/>
<source>About Qt</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/aboutwidget.ui" line="154"/>
<source>Close</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>configwidget</name>
<message>
<location filename="../src/core/ui/configwidget.ui" line="26"/>
<location filename="../src/core/ui/configwidget.ui" line="628"/>
<source>Options</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="77"/>
<source>Main</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="82"/>
<source>Advanced</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="87"/>
<source>System tray</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="92"/>
<source>Shortcuts</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="116"/>
<source>Default save directory</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="122"/>
<source>Path to default selection dir for saving</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="135"/>
<source>Browse filesystem</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="138"/>
<source>Browse</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="148"/>
<source>Default file</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="161"/>
<source>Name:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="168"/>
<source>Default filename</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="179"/>
<source>Format</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="192"/>
<source>Default saving image format</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="211"/>
<source>Copy file name to the clipboard when saving</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="225"/>
<source>Do not copy</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="230"/>
<source>Copy file name only</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="235"/>
<source>Copy full file path</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="245"/>
<source>Image quality</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="251"/>
<source>Image quality (1 - small file, 100 - high quality)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="316"/>
<source>Inserting current date time into saved filename</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="319"/>
<source>Insert current date and time in file name</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="328"/>
<source>Template: </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="353"/>
<source>Example: </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="363"/>
<source>Automatically saving screenshots in grabbing process</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="366"/>
<source>Autosave screenshot</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="378"/>
<source>Save first screenshot</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="387"/>
<source>Allow run multiplies copy of ScreenGrab</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="390"/>
<source>Allow multiple instances of ScreenGrab</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="397"/>
<source>Open in external viewer on double click</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="400"/>
<source>Enable external viewer</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="407"/>
<source>If this is unchecked, the selected area
might become larger to fit to outer edges</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="411"/>
<source>Fit to edges inside selected area by right clicking</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="449"/>
<source>Show ScreenGrab in the system tray</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="458"/>
<source>Tray messages:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="471"/>
<source>Tray messages display mode</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="475"/>
<source>Never</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="480"/>
<source>Tray mode</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="485"/>
<source>Always</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="497"/>
<source>Time of display tray messages</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="513"/>
<source>Time to display tray messages</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="516"/>
<source> sec</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="534"/>
<source>Minimize to tray on click close button</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="537"/>
<source>Minimize to tray when closing</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="576"/>
<source>Action</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="581"/>
<source>Shortcut</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="586"/>
<source>Global shortcuts</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="593"/>
<source>Full screen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="598"/>
<source>Active window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="603"/>
<source>Area select</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="609"/>
<source>Local shortcuts</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="613"/>
<source>New screen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="618"/>
<source>Save screen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="623"/>
<source>Copy screen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="633"/>
<source>Help</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="638"/>
<source>Quit</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="649"/>
<source>Selected shortcut:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../src/core/ui/configwidget.ui" line="656"/>
<source>Not defined</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS> |
#!/bin/bash
# <API key>.sh - parse installer-specific options
. /lib/anaconda-lib.sh
. /lib/url-lib.sh
# create the repodir and isodir that anaconda will look for
mkdir -p "$repodir" "$isodir"
# add some modules
modprobe -q edd
# get some info from .buildstamp
buildstamp=/run/initramfs/.buildstamp
[ -f /.buildstamp ] && buildstamp=/.buildstamp
if [ ! -f $buildstamp ]; then
warn ".buildstamp missing"
else
product=$(config_get Main Product < $buildstamp)
version=$(config_get Main Version < $buildstamp)
# TODO: this is silly. There should be an "Arch" item in there..
uuid=$(config_get Main UUID < $buildstamp)
strstr "$uuid" "." && arch=${uuid
fi
[ -z "$arch" ] && arch=$(uname -m)
echo Loading "$product" "$version" "$arch" installer...
# set HTTP headers so server(s) will recognize us
set_http_header "<API key>" "$arch"
set_http_header "<API key>" "$product"
# convenience function to warn the user about old argument names.
warn_renamed_arg() {
local arg=""
arg="$(getarg "$1")" && warn_critical "'$1=$arg'" && \
warn_critical "$1 has been deprecated and will be removed. Please use $2 instead."
}
# check for deprecated arg, warn user, and write new arg to /etc/cmdline
check_depr_arg() {
local arg="" quiet="" newval=""
if [ "$1" == "--quiet" ]; then quiet=1; shift; fi
arg="$(getarg "$1")"
[ "$arg" ] || return 1
# shellcheck disable=SC2059 # yes, $2 *is* the format string
newval=$(printf "$2" "$arg")
[ "$quiet" ] || warn_critical "'$1' is deprecated. Using '$newval' instead."
echo "$newval" >> /etc/cmdline.d/75-anaconda-options.conf
}
check_depr_args() {
local q=""
for i in $(getargs "$1"); do check_depr_arg "$q" "$i" "$2" && q="--quiet"; done
}
check_removed_arg() {
local arg="$1"; shift
if getarg "$arg" > /dev/null; then
warn_critical "'$arg' is deprecated and has been removed."
[ -n "$*" ] && warn_critical "$*"
fi
}
<API key>() {
local removed_arg="$1" new_arg="$2"
check_removed_arg "$removed_arg" "All usage of Anaconda boot arguments without 'inst.' prefix \
was removed. Please use $new_arg instead."
}
# ssh
<API key> "sshd" "inst.sshd"
# serial was never supposed to be used for anything!
check_removed_arg serial "To change the console use 'console=' instead."
# USB is built-in and can't be disabled anymore. DEAL WITH IT.
check_removed_arg nousb "USB drivers can't be disabled."
# ethtool is gone. Who forces their devices to single-duplex anymore?
check_removed_arg ethtool
# interactive junk in initramfs
# (maybe we'll bring it back someday?)
check_removed_arg askmethod "Use an appropriate 'inst.repo=' argument instead."
check_removed_arg asknetwork "Use an appropriate 'ip=' argument instead."
# lang & keymap
<API key> "lang" "inst.lang"
<API key> "keymap" "inst.keymap"
# repo
check_depr_arg "method=" "repo=%s"
<API key> "repo" "inst.repo"
# stage2
<API key> "stage2" "inst.stage2"
# kickstart
<API key> "ks" "inst.ks"
<API key> "ksdevice" "inst.ks.device"
<API key> "kssendmac" "inst.ks.sendmac"
<API key> "kssendsn" "inst.ks.sendsn"
# mpath
check_removed_arg "inst.nompath"
# Ignore self-signed SSL certs
<API key> "noverifyssl" "inst.noverifyssl"
if getargbool 0 inst.noverifyssl; then
# Tell dracut to use curl --insecure
echo "rd.noverifyssl" >> /etc/cmdline.d/75-anaconda-options.conf
fi
# updates
<API key> "updates" "inst.updates"
if updates=$(getarg inst.updates); then
if [ -n "$updates" ]; then
export anac_updates=$updates
case $updates in
http*|ftp*|nfs*)
echo "live.updates=$updates" \
>> /etc/cmdline.d/75-anaconda-options.conf ;;
esac
else
warn "'updates' requires a location for the updates disk"
fi
fi
# for vnc bring network up in initramfs so that cmdline configuration is used
<API key> "vnc" "inst.vnc"
getargbool 0 inst.vnc && warn "anaconda requiring network for vnc" && set_neednet
# Driver Update Disk
<API key> "dd" "inst.dd"
# re-read the commandline args
unset CMDLINE |
package uk.me.parabola.imgfmt.app;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import uk.me.parabola.imgfmt.MapFailedException;
import uk.me.parabola.imgfmt.Sized;
import uk.me.parabola.imgfmt.fs.ImgChannel;
import uk.me.parabola.imgfmt.sys.FileLink;
import uk.me.parabola.log.Logger;
/**
* A straight forward implementation that just keeps all the data in a buffer
* until the file needs to be written to disk.
*
* @author Steve Ratcliffe
*/
public class <API key> implements ImgFileWriter, Sized {
private static final Logger log = Logger.getLogger(<API key>.class);
private static final int KBYTE = 1024;
private static final int INIT_SIZE = 16 * KBYTE;
private static final int GROW_SIZE = 128 * KBYTE;
private static final int GUARD_SIZE = KBYTE;
private final ImgChannel chan;
private ByteBuffer buf = ByteBuffer.allocate(INIT_SIZE);
private int bufferSize = INIT_SIZE;
// The size of the file. Note that for this to be set properly, the
// position must be set to a low value after the full file is written. This
// always happens because we go back and write the header after all is
// written.
// Always use getSize() which takes care of things.
private int maxSize;
// The maximum allowed file size.
private long maxAllowedSize = 0xffffff;
public <API key>(ImgChannel chan) {
this.chan = chan;
buf.order(ByteOrder.LITTLE_ENDIAN);
if (chan instanceof FileLink) {
((FileLink) chan).link(this, this);
}
}
/**
* Called to write out any saved buffers. The strategy may write
* directly to the file in which case this would have nothing or
* little to do.
*/
public void sync() throws IOException {
buf.limit((int) getSize());
buf.position(0);
log.debug("syncing to pos", chan.position(), ", size", buf.limit());
chan.write(buf);
}
/**
* Get the position. Needed because may not be reflected in the underlying
* file if being buffered.
*
* @return The logical position within the file.
*/
public int position() {
return buf.position();
}
/**
* Set the position of the file.
*
* @param pos The new position in the file.
*/
public void position(long pos) {
int cur = position();
if (cur > maxSize)
maxSize = cur;
buf.position((int) pos);
}
/**
* Called when the stream is closed.
*/
public void close() throws IOException {
sync();
}
/**
* Write out a single byte.
* Should not be used for writing numbers, use put1s/u instead.
*
* @param b The byte to write.
*/
public void put(byte b) {
ensureSize(1);
buf.put(b);
}
/**
* Write out int in range -128..127 as single byte.
* @param val The byte to write.
*/
public void put1s(int val) {
assert val >= -128 && val <= 127 : val;
ensureSize(1);
buf.put((byte)val);
}
/**
* Write out int in range -32768..32767 as two bytes in little endian byte order.
* @param val The value to write.
*/
public void put2s(int val) {
assert val >= -32768 && val <= 32767 : val;
ensureSize(2);
buf.putShort((short)val);
}
/**
* Write out int in range -0x800000..0x7fffff in little endian byte order.
* @param val The value to write.
*/
public void put3s(int val) {
assert val >= -0x800000 && val <= 0x7fffff : val;
ensureSize(3);
buf.put((byte)val);
buf.putShort((short)(val >> 8));
}
/**
* Write out int in range 0..255 as single byte.
* @param val The value to write.
*/
public void put1u(int val) {
assert val >= 0 && val <= 255 : val;
ensureSize(1);
buf.put((byte)val);
}
/**
* Write out int in range 0..65535 as two bytes in little endian byte order.
* @param val The value to write.
*/
public void put2u(int val) {
assert val >= 0 && val <= 65535 : val;
ensureSize(2);
buf.putChar((char)val);
}
/**
* Write out int in range 0..0xffffff as three bytes in little endian byte order.
* @param val The value to write.
*/
public void put3u(int val) {
assert val >= 0 && val <= 0xffffff : val;
ensureSize(3);
buf.put((byte)val);
buf.putChar((char)(val >> 8));
}
/**
* Write out int as 1-4 bytes in little endian byte order.
*
* @param nBytes The number of bytes to write.
* @param val The value to write. Unsigned
*/
public void putNu(int nBytes, int val) {
ensureSize(nBytes);
switch (nBytes) {
case 1:
assert val >= 0 && val <= 255 : val;
put((byte)val);
break;
case 2:
assert val >= 0 && val <= 65535 : val;
buf.putShort((short)val);
break;
case 3:
assert val >= 0 && val <= 0xffffff : val;
buf.put((byte)val);
buf.putShort((short)(val >> 8));
break;
case 4:
buf.putInt(val);
break;
default:
assert false : nBytes;
}
}
/**
* Write out int (signed or unsigned) as 4 bytes.
*
* @param val The value to write.
*/
public void put4(int val) {
ensureSize(4);
buf.putInt(val);
}
/**
* Write out an arbitrary length sequence of bytes.
*
* @param val The values to write.
*/
public void put(byte[] val) {
ensureSize(val.length);
buf.put(val);
}
/**
* Write out part of a byte array.
*
* @param src The array to take bytes from.
* @param start The start position.
* @param length The number of bytes to write.
*/
public void put(byte[] src, int start, int length) {
ensureSize(length);
buf.put(src, start, length);
}
public void put(ByteBuffer src) {
ensureSize(src.limit());
buf.put(src);
}
/**
* Get the size of the file as written.
*
* NOTE: that calling this is only valid at certain times.
*
* @return The size of the file, if it is available.
*/
public long getSize() {
return Math.max(maxSize, position());
}
public ByteBuffer getBuffer() {
return buf;
}
/**
* Make sure there is enough room for the data we are about to write.
*
* @param length The amount of data.
*/
private void ensureSize(int length) {
int needed = buf.position() + length;
if (needed > (bufferSize - GUARD_SIZE)) {
while(needed > (bufferSize - GUARD_SIZE))
bufferSize += GROW_SIZE;
if (bufferSize > maxAllowedSize) {
// Previous message was confusing people, although it is difficult to come
// up with something that is strictly true in all situations.
throw new MapFailedException(
"There is not enough room in a single garmin map for all the input data." +
" The .osm file should be split into smaller pieces first.");
}
ByteBuffer newb = ByteBuffer.allocate(bufferSize);
newb.order(ByteOrder.LITTLE_ENDIAN);
buf.flip();
newb.put(buf);
buf = newb;
}
}
public void setMaxSize(long maxSize) {
this.maxAllowedSize = maxSize;
}
} |
from django.db import connections
from django.db.models.manager import Manager as DJManager
from django.db.utils import DatabaseError
from bson.objectid import ObjectId
import re
from .utils import dict_keys_to_str
try:
from django.core.exceptions import <API key>, ObjectDoesNotExist
except ImportError:
class ObjectDoesNotExist(Exception):
pass
class <API key>(Exception):
pass
DoesNotExist = ObjectDoesNotExist
__all__ = ['queryset_manager', 'Q', 'InvalidQueryError',
'<API key>']
# The maximum number of items to display in a QuerySet.__repr__
REPR_OUTPUT_SIZE = 20
class InvalidQueryError(Exception):
pass
class OperationError(Exception):
pass
class <API key>(Exception):
pass
RE_TYPE = type(re.compile(''))
class InternalMetadata:
def __init__(self, meta):
self.object_name = meta["object_name"]
class InternalModel:
"""
An internal queryset model to be embedded in a query set for django compatibility.
"""
def __init__(self, document):
self.document = document
self._meta = InternalMetadata(document._meta)
self.DoesNotExist = ObjectDoesNotExist
class QuerySet(object):
"""
A set of results returned from a query. Wraps a ES cursor,
providing :class:`~mongoengine.Document` objects as the results.
"""
def __init__(self, document, collection):
self._document = document
self._collection_obj = collection
self.<API key> = False
self._query = {}
self._where_clause = None
self._loaded_fields = []
self._ordering = []
self.transform = None
# If inheritance is allowed, only return instances and instances of
# subclasses of the class being used
# if document._meta.get('allow_inheritance'):
# self._query = {'_types': self._document._class_name}
self._cursor_obj = None
self._limit = None
self._skip = None
# required for compatibility with django
# self.model = InternalModel(document)
def __call__(self, q_obj=None, **query):
"""Filter the selected documents by calling the
:class:`~mongoengine.queryset.QuerySet` with a query.
:param q_obj: a :class:`~mongoengine.queryset.Q` object to be used in
the query; the :class:`~mongoengine.queryset.QuerySet` is filtered
multiple times with different :class:`~mongoengine.queryset.Q`
objects, only the last one will be used
:param query: Django-style query keyword arguments
"""
if q_obj:
self._where_clause = q_obj.as_js(self._document)
query = QuerySet._transform_query(_doc_cls=self._document, **query)
self._query.update(query)
return self
def filter(self, *q_objs, **query):
"""An alias of :meth:`~mongoengine.queryset.QuerySet.__call__`
"""
return self.__call__(*q_objs, **query)
def find(self, query):
self._query.update(self.transform.transform_incoming(query, self._collection))
return self
def exclude(self, *q_objs, **query):
"""An alias of :meth:`~mongoengine.queryset.QuerySet.__call__`
"""
query["not"] = True
return self.__call__(*q_objs, **query)
def all(self):
"""An alias of :meth:`~mongoengine.queryset.QuerySet.__call__`
"""
return self.__call__()
def distinct(self, *args, **kwargs):
"""
Distinct method
"""
return self._cursor.distinct(*args, **kwargs)
@property
def _collection(self):
"""Property that returns the collection object. This allows us to
perform operations only if the collection is accessed.
"""
return self._collection_obj
def values(self, *args):
return (args and [dict(zip(args, [getattr(doc, key) for key in args])) for doc in self]) or [obj for obj in
self._cursor.clone()]
def values_list(self, *args, **kwargs):
flat = kwargs.pop("flat", False)
if flat and len(args) != 1:
raise Exception("args len must be 1 when flat=True")
return (flat and self.distinct(args[0] if not args[0] in ["id", "pk"] else "_id")) or zip(
*[self.distinct(field if field not in ["id", "pk"] else "_id") for field in args])
@property
def _cursor(self):
if self._cursor_obj is None:
cursor_args = {}
if self._loaded_fields:
cursor_args = {'fields': self._loaded_fields}
self._cursor_obj = self._collection.find(self._query,
**cursor_args)
# Apply where clauses to cursor
if self._where_clause:
self._cursor_obj.where(self._where_clause)
# apply default ordering
# if self._document._meta['ordering']:
# self.order_by(*self._document._meta['ordering'])
return self._cursor_obj.clone()
@classmethod
def _lookup_field(cls, document, fields):
"""
Looks for "field" in "document"
"""
if isinstance(fields, (tuple, list)):
return [document._meta.get_field_by_name((field == "pk" and "id") or field)[0] for field in fields]
return document._meta.get_field_by_name((fields == "pk" and "id") or fields)[0]
@classmethod
def <API key>(cls, doc_cls, field, sep='.'):
"""Translate a field attribute name to a database field name.
"""
parts = field.split(sep)
parts = [f.attname for f in QuerySet._lookup_field(doc_cls, parts)]
return '.'.join(parts)
@classmethod
def _transform_query(self, _doc_cls=None, **parameters):
"""
Converts parameters to elasticsearch queries.
"""
spec = {}
operators = ['ne', 'gt', 'gte', 'lt', 'lte', 'in', 'nin', 'mod', 'all', 'size', 'exists']
match_operators = ['contains', 'icontains', 'startswith', 'istartswith', 'endswith', 'iendswith', 'exact',
'iexact']
exclude = parameters.pop("not", False)
for key, value in parameters.items():
parts = key.split("__")
lookup_type = (len(parts) >= 2) and ( parts[-1] in operators + match_operators and parts.pop()) or ""
# Let's get the right field and be sure that it exists
parts[0] = QuerySet._lookup_field(_doc_cls, parts[0]).attname
if not lookup_type and len(parts) == 1:
if exclude:
value = {"$ne": value}
spec.update({parts[0]: value})
continue
if parts[0] == "id":
parts[0] = "_id"
value = [isinstance(par, basestring) or par for par in value]
if lookup_type in ['contains', 'icontains',
'startswith', 'istartswith',
'endswith', 'iendswith',
'exact', 'iexact']:
flags = 0
if lookup_type.startswith('i'):
flags = re.IGNORECASE
lookup_type = lookup_type.lstrip('i')
regex = r'%s'
if lookup_type == 'startswith':
regex = r'^%s'
elif lookup_type == 'endswith':
regex = r'%s$'
elif lookup_type == 'exact':
regex = r'^%s$'
value = re.compile(regex % value, flags)
elif lookup_type in operators:
value = {"$" + lookup_type: value}
elif lookup_type and len(parts) == 1:
raise DatabaseError("Unsupported lookup type: %r" % lookup_type)
key = '.'.join(parts)
if exclude:
value = {"$ne": value}
spec.update({key: value})
return spec
def get(self, *q_objs, **query):
"""Retrieve the the matching object raising id django is available
:class:`~django.core.exceptions.<API key>` or
:class:`~django.core.exceptions.ObjectDoesNotExist` exceptions if multiple or
no results are found.
If django is not available:
:class:`~mongoengine.queryset.<API key>` or
`DocumentName.<API key>` exception if multiple results and
:class:`~mongoengine.queryset.DoesNotExist` or `DocumentName.DoesNotExist`
if no results are found.
.. versionadded:: 0.3
"""
self.__call__(*q_objs, **query)
count = self.count()
if count == 1:
return self[0]
elif count > 1:
message = u'%d items returned, instead of 1' % count
raise self._document.<API key>(message)
else:
raise self._document.DoesNotExist("%s matching query does not exist."
% self._document._meta.object_name)
def get_or_create(self, *q_objs, **query):
"""Retrieve unique object or create, if it doesn't exist. Returns a tuple of
``(object, created)``, where ``object`` is the retrieved or created object
and ``created`` is a boolean specifying whether a new object was created. Raises
:class:`~mongoengine.queryset.<API key>` or
`DocumentName.<API key>` if multiple results are found.
A new document will be created if the document doesn't exists; a
dictionary of default values for the new document may be provided as a
keyword argument called :attr:`defaults`.
.. versionadded:: 0.3
"""
defaults = query.get('defaults', {})
if 'defaults' in query:
del query['defaults']
self.__call__(*q_objs, **query)
count = self.count()
if count == 0:
query.update(defaults)
doc = self._document(**query)
doc.save()
return doc, True
elif count == 1:
return self.first(), False
else:
message = u'%d items returned, instead of 1' % count
raise self._document.<API key>(message)
def first(self):
"""Retrieve the first object matching the query.
"""
try:
result = self[0]
except IndexError:
result = None
return result
def with_id(self, object_id):
"""Retrieve the object matching the id provided.
:param object_id: the value for the id of the document to look up
"""
id_field = self._document._meta['id_field']
object_id = self._document._fields[id_field].to_mongo(object_id)
result = self._collection.find_one(
{'_id': (not isinstance(object_id, ObjectId) and ObjectId(object_id)) or object_id})
if result is not None:
result = self._document(**dict_keys_to_str(result))
return result
def in_bulk(self, object_ids):
"""Retrieve a set of documents by their ids.
:param object_ids: a list or tuple of id's
:rtype: dict of ids as keys and collection-specific
Document subclasses as values.
.. versionadded:: 0.3
"""
doc_map = {}
docs = self._collection.find(
{'_id': {'$in': [(not isinstance(id, ObjectId) and ObjectId(id)) or id for id in object_ids]}})
for doc in docs:
doc_map[str(doc['id'])] = self._document(**dict_keys_to_str(doc))
return doc_map
def count(self):
"""Count the selected elements in the query.
"""
if self._limit == 0:
return 0
return self._cursor.count(with_limit_and_skip=False)
def __len__(self):
return self.count()
def limit(self, n):
"""Limit the number of returned documents to `n`. This may also be
achieved using array-slicing syntax (e.g. ``User.objects[:5]``).
:param n: the maximum number of objects to return
"""
if n == 0:
self._cursor.limit(1)
else:
self._cursor.limit(n)
self._limit = n
# Return self to allow chaining
return self
def skip(self, n):
"""Skip `n` documents before returning the results. This may also be
achieved using array-slicing syntax (e.g. ``User.objects[5:]``).
:param n: the number of objects to skip before returning results
"""
self._cursor.skip(n)
self._skip = n
return self
def __getitem__(self, key):
"""Support skip and limit using getitem and slicing syntax.
"""
# Slice provided
if isinstance(key, slice):
try:
self._cursor_obj = self._cursor[key]
self._skip, self._limit = key.start, key.stop
except IndexError, err:
# PyMongo raises an error if key.start == key.stop, catch it,
# bin it, kill it.
start = key.start or 0
if start >= 0 and key.stop >= 0 and key.step is None:
if start == key.stop:
self.limit(0)
self._skip, self._limit = key.start, key.stop - start
return self
raise err
# Allow further QuerySet modifications to be performed
return self
# Integer index provided
elif isinstance(key, int):
return self._document(**dict_keys_to_str(self._cursor[key]))
def only(self, *fields):
"""Load only a subset of this document's fields. ::
post = BlogPost.objects(...).only("title")
:param fields: fields to include
.. versionadded:: 0.3
"""
self._loaded_fields = []
for field in fields:
if '.' in field:
raise InvalidQueryError('Subfields cannot be used as '
'arguments to QuerySet.only')
# Translate field name
field = QuerySet._lookup_field(self._document, field)[-1].db_field
self._loaded_fields.append(field)
# _cls is needed for polymorphism
if self._document._meta.get('allow_inheritance'):
self._loaded_fields += ['_cls']
return self
def order_by(self, *args):
"""
Order the :class:`~mongoengine.queryset.QuerySet` by the keys. The
order may be specified by prepending each of the keys by a + or a -.
Ascending order is assumed.
:param keys: fields to order the query results by; keys may be
prefixed with **+** or **-** to determine the ordering direction
"""
self._ordering = []
for col in args:
self._ordering.append(((col.startswith("-") and col[1:]) or col, (col.startswith("-") and -1) or 1))
self._cursor.sort(self._ordering)
return self
def explain(self, format=False):
"""Return an explain plan record for the
:class:`~mongoengine.queryset.QuerySet`\ 's cursor.
:param format: format the plan before returning it
"""
plan = self._cursor.explain()
if format:
import pprint
plan = pprint.pformat(plan)
return plan
def delete(self, safe=False):
"""Delete the documents matched by the query.
:param safe: check if the operation succeeded before returning
"""
self._collection.remove(self._query, safe=safe)
@classmethod
def _transform_update(cls, _doc_cls=None, **update):
"""Transform an update spec from Django-style format to Mongo format.
"""
operators = ['set', 'unset', 'inc', 'dec', 'push', 'push_all', 'pull',
'pull_all']
mongo_update = {}
for key, value in update.items():
parts = key.split('__')
# Check for an operator and transform to mongo-style if there is
op = None
if parts[0] in operators:
op = parts.pop(0)
# Convert Pythonic names to Mongo equivalents
if op in ('push_all', 'pull_all'):
op = op.replace('_all', 'All')
elif op == 'dec':
# Support decrement by flipping a positive value's sign
# and using 'inc'
op = 'inc'
if value > 0:
value = -value
if _doc_cls:
# Switch field names to proper names [set in Field(name='foo')]
fields = QuerySet._lookup_field(_doc_cls, parts)
parts = [field.db_field for field in fields]
# Convert value to proper value
field = fields[-1]
if op in (None, 'set', 'unset', 'push', 'pull'):
value = field.prepare_query_value(op, value)
elif op in ('pushAll', 'pullAll'):
value = [field.prepare_query_value(op, v) for v in value]
key = '.'.join(parts)
if op:
value = {key: value}
key = '$' + op
if op is None or key not in mongo_update:
mongo_update[key] = value
elif key in mongo_update and isinstance(mongo_update[key], dict):
mongo_update[key].update(value)
return mongo_update
def update(self, safe_update=True, upsert=False, **update):
pass
def update_one(self, safe_update=True, upsert=False, **update):
pass
def __iter__(self, *args, **kwargs):
for obj in self._cursor:
data = dict_keys_to_str(obj)
if '_id' in data:
data['id'] = data.pop('_id')
yield self._document(**data)
def _sub_js_fields(self, code):
"""When fields are specified with [~fieldname] syntax, where
*fieldname* is the Python name of a field, *fieldname* will be
substituted for the MongoDB name of the field (specified using the
:attr:`name` keyword argument in a field's constructor).
"""
def field_sub(match):
# Extract just the field name, and look up the field objects
field_name = match.group(1).split('.')
fields = QuerySet._lookup_field(self._document, field_name)
# Substitute the correct name for the field into the javascript
return u'["%s"]' % fields[-1].db_field
return re.sub(u'\[\s*~([A-z_][A-z_0-9.]+?)\s*\]', field_sub, code)
def __repr__(self):
limit = REPR_OUTPUT_SIZE + 1
if self._limit is not None and self._limit < limit:
limit = self._limit
data = list(self[self._skip:limit])
if len(data) > REPR_OUTPUT_SIZE:
data[-1] = "...(remaining elements truncated)..."
return repr(data)
def _clone(self):
return self
class Manager(DJManager):
def __init__(self, manager_func=None):
super(Manager, self).__init__()
self._manager_func = manager_func
self._collection = None
def contribute_to_class(self, model, name):
# TODO: Use weakref because of possible memory leak / circular reference.
self.model = model
# setattr(model, name, ManagerDescriptor(self))
if model._meta.abstract or (self._inherited and not self.model._meta.proxy):
model._meta.abstract_managers.append((self.creation_counter, name,
self))
else:
model._meta.concrete_managers.append((self.creation_counter, name,
self))
def __get__(self, instance, owner):
"""
Descriptor for instantiating a new QuerySet object when
Document.objects is accessed.
"""
self.model = owner # We need to set the model to get the db
if instance is not None:
# Document class being used rather than a document object
return self
if self._collection is None:
self._collection = connections[self.db].db_connection[owner._meta.db_table]
# owner is the document that contains the QuerySetManager
queryset = QuerySet(owner, self._collection)
if self._manager_func:
if self._manager_func.func_code.co_argcount == 1:
queryset = self._manager_func(queryset)
else:
queryset = self._manager_func(owner, queryset)
return queryset |
import PropTypes from 'prop-types';
import { Component } from 'react';
const SVG_SIZE = 30;
class <API key> extends Component {
static propTypes = {
description: PropTypes.string,
name: PropTypes.string.isRequired,
};
render() {
const { description, name } = this.props;
return (
<div className="<API key>">
<div className="<API key>">
<svg
className="<API key>"
viewBox={ `0 0 ${ SVG_SIZE } ${ SVG_SIZE }` }
>
<circle
className="<API key>"
cx={ SVG_SIZE / 2 }
cy={ SVG_SIZE / 2 }
r={ SVG_SIZE / 2 }
/>
</svg>
<div className={ '<API key>' }>{ name }</div>
</div>
<div className="<API key>">
<div className={ '<API key>' }>{ '100 (100%)' }</div>
{ description && (
<div className={ '<API key>' }>{ description }</div>
) }
</div>
</div>
);
}
}
export default <API key>; |
<?php
/**
* Checks whether the chosen layout is the 'grid-landscape' layout.
*
* @since 1.0.0
* @access public
* @return bool
*/
function extant_is_landscape() {
return hybrid_is_layout( 'grid-landscape' );
}
/**
* Checks whether the chosen layout is the 'grid-portrait' layout.
*
* @since 1.0.0
* @access public
* @return bool
*/
function extant_is_portrait() {
return hybrid_is_layout( 'grid-portrait' );
}
/**
* Checks whether the chosen layout type is 'full'.
*
* @since 1.0.0
* @access public
* @return bool
*/
function <API key>() {
return 'full' === <API key>();
}
/**
* Checks whether the chosen layout type is 'boxed'.
*
* @since 1.0.0
* @access public
* @return bool
*/
function extant_is_boxed() {
return 'boxed' === <API key>();
}
/**
* Returns the layout type.
*
* @since 1.0.0
* @access public
* @return bool
*/
function <API key>() {
return <API key>( 'layout_type', 'full' );
}
/**
* Returns the header icon theme mod.
*
* @since 1.0.0
* @access public
* @return string
*/
function <API key>() {
return <API key>( 'header_icon', 'fa-home' );
}
/**
* Returns the primary icon theme mod.
*
* @since 1.0.0
* @access public
* @return string
*/
function <API key>() {
return <API key>( 'menu_primary_icon', 'fa-bars' );
}
/**
* Returns the secondary menu icon theme mod.
*
* @since 1.0.0
* @access public
* @return string
*/
function <API key>() {
return <API key>( 'menu_secondary_icon', 'fa-circle-o' );
}
/**
* Returns the search menu icon theme mod.
*
* @since 1.0.0
* @access public
* @return string
*/
function <API key>() {
return <API key>( 'menu_search_icon', 'fa-search' );
}
/**
* Conditional tag to check if the header icon should be shown. Note that it always
* appears on mobile devices (<= 480px).
*
* @since 1.0.0
* @access public
* @return bool
*/
function <API key>() {
return <API key>( 'show_header_icon', false );
}
/**
* Conditional tag to check whether the user is running the pro version.
*
* @since 1.0.0
* @access public
* @return bool
*/
function extant_is_pro() {
return apply_filters( 'extant_is_pro', false );
} |
// Written by qingfeng.wang, some source code form snort,nginx.
// Thanks to China Standard software Co.,Ltd ;
#ifndef <API key>
#define <API key>
#include "sk_config.h"
#include "sk_core.h"
void <API key>(sk_cycle_t *cycle);
#endif |
// Created 2015/04/10 honda
package jobnet
import (
"fmt"
"net/url"
"strings"
"time"
"github.com/unirita/cuto/console"
"github.com/unirita/cuto/db"
"github.com/unirita/cuto/db/tx"
"github.com/unirita/cuto/log"
"github.com/unirita/cuto/master/config"
"github.com/unirita/cuto/master/remote"
"github.com/unirita/cuto/message"
"github.com/unirita/cuto/util"
)
type sendFunc func(string, int, string, chan<- string) (string, error)
type Job struct {
id string
Name string
Node string
Port int
FilePath string
Param string
Env string
Workspace string
WrnRC int
WrnPtn string
ErrRC int
ErrPtn string
Timeout int
SecondaryNode string
SecondaryPort int
Next Element
Instance *Network
sendRequest sendFunc
IsRerunJob bool
}
// Job
// param ; id ID
// param : name
// param : nwk
// return :
// return :
func NewJob(id string, name string, nwk *Network) (*Job, error) {
if util.<API key>(name) {
return nil, fmt.Errorf("Job name[%s] includes forbidden character.", name)
}
job := new(Job)
job.id = id
job.Name = name
job.Instance = nwk
job.sendRequest = remote.SendRequest
return job, nil
}
// return : ID.
func (j *Job) ID() string {
return j.id
}
// return :
func (j *Job) Type() elementType {
return ELM_JOB
}
// param :
func (j *Job) AddNext(e Element) error {
if j.Next != nil {
return fmt.Errorf("ServiceTask cannot connect with over 1 element.")
}
j.Next = e
return nil
}
// return : true
func (j *Job) HasNext() bool {
return j.Next != nil
}
func (j *Job) SetDefaultEx() {
if j.Node == "" {
j.Node = config.Job.DefaultNode
}
if j.Port == 0 {
j.Port = config.Job.DefaultPort
}
if j.FilePath == "" {
j.FilePath = j.Name
}
if j.Timeout < 0 {
j.Timeout = config.Job.DefaultTimeoutMin * 60
}
}
// servant
// return :
// return :
func (j *Job) Execute() (Element, error) {
if j.IsRerunJob {
jobres, _ := j.Instance.Result.GetJobResults(j.id)
if jobres.Status == db.NORMAL || jobres.Status == db.WARN {
j.resumeJobValue()
return j.Next, nil
} else {
j.Node = jobres.Node
j.Port = jobres.Port
result, err := j.<API key>()
if err != nil {
return nil, j.abnormalEnd(err)
}
switch result.Stat {
case db.RUNNING:
return nil, fmt.Errorf("Job ID [%s] still running.", j.id)
case db.NORMAL:
fallthrough
case db.WARN:
j.<API key>(result)
return j.Next, nil
default:
j.changeStatusRunning()
}
}
}
res, err := j.executeRequest()
if err != nil {
return nil, j.abnormalEnd(err)
}
defer j.end(res)
if isAbnormalEnd(res) {
joblogFile := res.JoblogFile
if len(joblogFile) == 0 {
j.<API key>(res)
}
console.Display("CTM026I", joblogFile, j.Node)
return nil, fmt.Errorf("")
}
return j.Next, nil
}
func (j *Job) executeRequest() (*message.Response, error) {
if !j.IsRerunJob {
j.start()
}
console.Display("CTM023I", j.Name, j.Node, j.Instance.ID, j.id)
resMsg, err := j.<API key>()
if j.isNecessaryToRetry(err) && j.SecondaryNode != "" {
j.useSecondaryNode()
console.Display("CTM028W", j.Name, j.SecondaryNode)
resMsg, err = j.<API key>()
}
if err != nil {
return nil, err
}
res := new(message.Response)
err = res.ParseJSON(resMsg)
if err != nil {
return nil, err
}
return res, nil
}
func (j *Job) <API key>() (string, error) {
req := j.createRequest()
err := req.ExpandMasterVars()
if err != nil {
return "", err
}
reqMsg, err := req.GenerateJSON()
if err != nil {
return "", err
}
timerEndCh := make(chan struct{}, 1)
go j.startTimer(timerEndCh)
defer close(timerEndCh)
stCh := make(chan string, 1)
defer close(stCh)
go j.<API key>(stCh)
return j.<API key>(reqMsg, stCh)
}
func (j *Job) <API key>() (*message.JobResult, error) {
chk := new(message.JobCheck)
chk.NID = j.Instance.ID
chk.JID = j.ID()
chkMsg, err := chk.GenerateJSON()
if err != nil {
return nil, err
}
resultMsg, err := j.<API key>(chkMsg)
if err != nil {
return nil, err
}
result := new(message.JobResult)
err = result.ParseJSON(resultMsg)
if err != nil {
return nil, err
}
return result, nil
}
func (j *Job) <API key>(reqMsg string, stCh chan<- string) (string, error) {
limit := config.Job.AttemptLimit
var resMsg string
var err error
for i := 0; i < limit; i++ {
if i != 0 {
console.Display("CTM027W", j.Name, i, limit-1)
}
host, _, _ := explodeNodeString(j.Node)
resMsg, err = j.sendRequest(host, j.Port, reqMsg, stCh)
if !j.isNecessaryToRetry(err) {
break
}
}
return resMsg, err
}
func (j *Job) <API key>(chkMsg string) (string, error) {
stCh := make(chan string, 1)
defer close(stCh)
limit := config.Job.AttemptLimit
var resultMsg string
var err error
for i := 0; i < limit; i++ {
if i != 0 {
console.Display("CTM027W", j.Name, i, limit-1)
}
host, _, _ := explodeNodeString(j.Node)
resultMsg, err = j.sendRequest(host, j.Port, chkMsg, stCh)
if err == nil {
break
}
}
return resultMsg, err
}
func (j *Job) isNecessaryToRetry(err error) bool {
if err != nil {
jobres, exist := j.Instance.Result.GetJobResults(j.id)
if !exist {
return true
} else if jobres.StartDate == "" {
return true
}
}
return false
}
// responsertrue
// false
func isAbnormalEnd(r *message.Response) bool {
if r.Stat == db.ABNORMAL {
return true
}
return false
}
func (j *Job) start() {
jobres := db.NewJobResult(int(j.Instance.ID))
jobres.JobId = j.ID()
jobres.JobName = j.Name
jobres.Node = j.Node
jobres.Port = j.Port
jobres.Status = db.RUNNING
j.Instance.Result.AddJobResults(j.id, jobres)
tx.InsertJob(j.Instance.Result.GetConnection(), jobres, &j.Instance.localMutex)
}
func (j *Job) useSecondaryNode() {
j.Node = j.SecondaryNode
j.Port = j.SecondaryPort
jobres, exist := j.Instance.Result.GetJobResults(j.id)
if !exist {
log.Error(fmt.Errorf("Job result[id = %s] is unregisted.", j.id))
return
}
jobres.Node = j.SecondaryNode
jobres.Port = j.SecondaryPort
tx.UpdateJob(j.Instance.Result.GetConnection(), jobres, &j.Instance.localMutex)
j.SecondaryNode = ""
j.SecondaryPort = 0
}
func (j *Job) <API key>(stCh <-chan string) {
st := <-stCh
if len(st) == 0 {
return
}
log.Debug(fmt.Sprintf("JOB[%s] StartDate[%s]", j.Name, st))
jobres, exist := j.Instance.Result.GetJobResults(j.id)
if !exist {
log.Error(fmt.Errorf("Job result[id = %s] is unregisted.", j.id))
return
}
jobres.StartDate = st
tx.UpdateJob(j.Instance.Result.GetConnection(), jobres, &j.Instance.localMutex)
}
func (j *Job) end(res *message.Response) {
var jobres *db.JobResult
var exist bool
if jobres, exist = j.Instance.Result.GetJobResults(j.id); !exist {
log.Error(fmt.Errorf("Job result[id = %s] is unregisted.", j.id))
return
}
jobres.StartDate = res.St
jobres.EndDate = res.Et
jobres.Status = res.Stat
jobres.Rc = res.RC
jobres.Detail = res.Detail
jobres.Variable = res.Var
message.AddJobValue(j.Name, res)
tx.UpdateJob(j.Instance.Result.GetConnection(), jobres, &j.Instance.localMutex)
var st string
switch jobres.Status {
case db.NORMAL:
st = db.ST_NORMAL
case db.WARN:
st = db.ST_WARN
default:
st = db.ST_ABNORMAL
}
if jobres.Status != db.ABNORMAL {
console.Display("CTM024I", j.Name, j.Node, j.Instance.ID, j.id, st)
} else {
console.Display("CTM025W", j.Name, j.Node, j.Instance.ID, j.id, st, jobres.Detail)
}
}
func (j *Job) abnormalEnd(err error) error {
jobres, exist := j.Instance.Result.GetJobResults(j.id)
if !exist {
return fmt.Errorf("Job result[id = %s] is unregisted.", j.id)
}
jobres.Status = db.ABNORMAL
jobres.Detail = err.Error()
tx.UpdateJob(j.Instance.Result.GetConnection(), jobres, &j.Instance.localMutex)
console.Display("CTM025W", j.Name, j.Node, j.Instance.ID, j.id, jobres.Status, jobres.Detail)
return err
}
func (j *Job) resumeJobValue() {
jobres, _ := j.Instance.Result.GetJobResults(j.id)
res := new(message.Response)
res.JID = j.id
res.RC = jobres.Rc
res.St = jobres.StartDate
res.Et = jobres.EndDate
res.Var = jobres.Variable
message.AddJobValue(j.Name, res)
}
func (j *Job) <API key>(result *message.JobResult) {
jobres, exists := j.Instance.Result.GetJobResults(j.id)
if !exists {
log.Error(fmt.Errorf("Job result[id = %s] is unregisted.", j.id))
return
}
jobres.Status = result.Stat
jobres.Rc = result.RC
jobres.StartDate = result.St
jobres.EndDate = result.Et
jobres.Detail = ""
jobres.Variable = result.Var
tx.UpdateJob(j.Instance.Result.GetConnection(), jobres, &j.Instance.localMutex)
j.resumeJobValue()
}
func (j *Job) changeStatusRunning() {
jobres, exists := j.Instance.Result.GetJobResults(j.id)
if !exists {
log.Error(fmt.Errorf("Job result[id = %s] is unregisted.", j.id))
return
}
jobres.Status = db.RUNNING
tx.UpdateJob(j.Instance.Result.GetConnection(), jobres, &j.Instance.localMutex)
}
func (j *Job) startTimer(endCh chan struct{}) {
span := config.Job.TimeTrackingSpanMin
if span == 0 {
return
}
rapTime := 0
for {
select {
case <-time.After(time.Duration(span) * time.Minute):
rapTime += span
console.Display("CTM022I", j.Name, rapTime)
case <-endCh:
return
}
}
}
func (j *Job) <API key>(r *message.Response) string {
job := j.FilePath
if strings.LastIndex(job, "\\") != -1 {
tokens := strings.Split(job, "\\")
job = tokens[len(tokens)-1]
} else if strings.LastIndex(job, "/") != -1 {
tokens := strings.Split(job, "/")
job = tokens[len(tokens)-1]
}
if extpos := strings.LastIndex(job, "."); extpos != -1 {
job = job[:extpos]
}
timestamp := r.St
timestamp = strings.Replace(timestamp, "-", "", -1)
timestamp = strings.Replace(timestamp, " ", "", -1)
timestamp = strings.Replace(timestamp, ":", "", -1)
return fmt.Sprintf("%v.%v.%v.%v.log", j.Instance.ID, job, j.ID(), timestamp)
}
func (j *Job) createRequest() *message.Request {
req := new(message.Request)
req.NID = j.Instance.ID
req.JID = j.ID()
req.Path = j.FilePath
req.Param = j.Param
req.Env = j.Env
req.Workspace = j.Workspace
req.WarnRC = j.WrnRC
req.WarnStr = j.WrnPtn
req.ErrRC = j.ErrRC
req.ErrStr = j.ErrPtn
req.Timeout = j.Timeout
_, cntHost, cntName := explodeNodeString(j.Node)
if cntName != "" {
req.Path = message.DockerTag
req.Param = fmt.Sprintf("exec %s %s %s", cntName, j.FilePath, j.Param)
if cntHost != "" {
req.Param = fmt.Sprintf("-H=%s %s", cntHost, req.Param)
}
}
return req
}
func explodeNodeString(node string) (string, string, string) {
hostAndContainer := strings.SplitN(node, ">", 2)
if len(hostAndContainer) == 1 {
return node, "", ""
}
host := hostAndContainer[0]
container := hostAndContainer[1]
containerURL, err := url.Parse(container)
if err != nil || !containerURL.IsAbs() {
return host, "", container
}
containerHost := fmt.Sprintf("%s://%s", containerURL.Scheme, containerURL.Host)
containerName := strings.TrimLeft(containerURL.Path, "/")
return host, containerHost, containerName
} |
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <asm/io.h>
#include <asm/byteorder.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/mtd/map.h>
#include <linux/mtd/cfi.h>
#include <linux/mtd/compatmac.h>
// debugging, turns off buffer write mode #define FORCE_WORD_WRITE
static int cfi_intelext_read (struct mtd_info *, loff_t, size_t, size_t *, u_char *);
static int <API key> (struct mtd_info *, loff_t, size_t, size_t *, u_char *);
static int <API key> (struct mtd_info *, loff_t, size_t, size_t *, u_char *);
static int <API key>(struct mtd_info *, loff_t, size_t, size_t *, const u_char *);
static int <API key>(struct mtd_info *, loff_t, size_t, size_t *, const u_char *);
static int <API key>(struct mtd_info *, struct erase_info *);
static void cfi_intelext_sync (struct mtd_info *);
static int cfi_intelext_lock(struct mtd_info *mtd, loff_t ofs, size_t len);
static int cfi_intelext_unlock(struct mtd_info *mtd, loff_t ofs, size_t len);
static int <API key> (struct mtd_info *);
static void cfi_intelext_resume (struct mtd_info *);
static void <API key>(struct mtd_info *);
struct mtd_info *cfi_cmdset_0001(struct map_info *, int);
static struct mtd_info *cfi_intelext_setup (struct map_info *);
static int do_point (struct mtd_info *mtd, loff_t from, size_t len,
size_t *retlen, u_char **mtdbuf);
static void do_unpoint (struct mtd_info *mtd, u_char *addr, loff_t from,
size_t len);
static struct mtd_chip_driver <API key> = {
probe: NULL, /* Not usable directly */
destroy: <API key>,
name: "cfi_cmdset_0001",
module: THIS_MODULE
};
/* #define DEBUG_LOCK_BITS */
/* #define DEBUG_CFI_FEATURES */
#ifdef DEBUG_CFI_FEATURES
static void cfi_tell_features(struct cfi_pri_intelext *extp)
{
int i;
printk(" Feature/Command Support: %4.4X\n", extp->FeatureSupport);
printk(" - Chip Erase: %s\n", extp->FeatureSupport&1?"supported":"unsupported");
printk(" - Suspend Erase: %s\n", extp->FeatureSupport&2?"supported":"unsupported");
printk(" - Suspend Program: %s\n", extp->FeatureSupport&4?"supported":"unsupported");
printk(" - Legacy Lock/Unlock: %s\n", extp->FeatureSupport&8?"supported":"unsupported");
printk(" - Queued Erase: %s\n", extp->FeatureSupport&16?"supported":"unsupported");
printk(" - Instant block lock: %s\n", extp->FeatureSupport&32?"supported":"unsupported");
printk(" - Protection Bits: %s\n", extp->FeatureSupport&64?"supported":"unsupported");
printk(" - Page-mode read: %s\n", extp->FeatureSupport&128?"supported":"unsupported");
printk(" - Synchronous read: %s\n", extp->FeatureSupport&256?"supported":"unsupported");
for (i=9; i<32; i++) {
if (extp->FeatureSupport & (1<<i))
printk(" - Unknown Bit %X: supported\n", i);
}
printk(" Supported functions after Suspend: %2.2X\n", extp->SuspendCmdSupport);
printk(" - Program after Erase Suspend: %s\n", extp->SuspendCmdSupport&1?"supported":"unsupported");
for (i=1; i<8; i++) {
if (extp->SuspendCmdSupport & (1<<i))
printk(" - Unknown Bit %X: supported\n", i);
}
printk(" Block Status Register Mask: %4.4X\n", extp->BlkStatusRegMask);
printk(" - Lock Bit Active: %s\n", extp->BlkStatusRegMask&1?"yes":"no");
printk(" - Valid Bit Active: %s\n", extp->BlkStatusRegMask&2?"yes":"no");
for (i=2; i<16; i++) {
if (extp->BlkStatusRegMask & (1<<i))
printk(" - Unknown Bit %X Active: yes\n",i);
}
printk(" Vcc Logic Supply Optimum Program/Erase Voltage: %d.%d V\n",
extp->VccOptimal >> 8, extp->VccOptimal & 0xf);
if (extp->VppOptimal)
printk(" Vpp Programming Supply Optimum Program/Erase Voltage: %d.%d V\n",
extp->VppOptimal >> 8, extp->VppOptimal & 0xf);
}
#endif
/* This routine is made available to other mtd code via
* <API key>. It must only be accessed through
* inter_module_get which will bump the use count of this module. The
* addresses passed back in cfi are valid as long as the use count of
* this module is non-zero, i.e. between inter_module_get and
* inter_module_put. Keith Owens <kaos@ocs.com.au> 29 Oct 2000.
*/
struct mtd_info *cfi_cmdset_0001(struct map_info *map, int primary)
{
struct cfi_private *cfi = map->fldrv_priv;
int i;
__u32 base = cfi->chips[0].start;
if (cfi->cfi_mode == CFI_MODE_CFI) {
/*
* It's a real CFI chip, not one for which the probe
* routine faked a CFI structure. So we read the feature
* table from it.
*/
__u16 adr = primary?cfi->cfiq->P_ADR:cfi->cfiq->A_ADR;
struct cfi_pri_intelext *extp;
int ofs_factor = cfi->interleave * cfi->device_type;
//printk(" Intel/Sharp Extended Query Table at 0x%4.4X\n", adr);
if (!adr)
return NULL;
/* Switch it into Query Mode */
cfi_send_gen_cmd(0x98, 0x55, base, map, cfi, cfi->device_type, NULL);
extp = kmalloc(sizeof(*extp), GFP_KERNEL);
if (!extp) {
printk(KERN_ERR "Failed to allocate memory\n");
return NULL;
}
/* Read in the Extended Query Table */
for (i=0; i<sizeof(*extp); i++) {
((unsigned char *)extp)[i] =
cfi_read_query(map, (base+((adr+i)*ofs_factor)));
}
if (extp->MajorVersion != '1' ||
(extp->MinorVersion < '0' || extp->MinorVersion > '3')) {
printk(KERN_WARNING " Unknown IntelExt Extended Query "
"version %c.%c.\n", extp->MajorVersion,
extp->MinorVersion);
kfree(extp);
return NULL;
}
/* Do some byteswapping if necessary */
extp->FeatureSupport = le32_to_cpu(extp->FeatureSupport);
extp->BlkStatusRegMask = le16_to_cpu(extp->BlkStatusRegMask);
extp->ProtRegAddr = le16_to_cpu(extp->ProtRegAddr);
#ifdef DEBUG_CFI_FEATURES
/* Tell the user about it in lots of lovely detail */
cfi_tell_features(extp);
#endif
if(extp->SuspendCmdSupport & 1) {
//#define <API key>
#ifdef <API key>
/* Some Intel Strata Flash prior to FPO revision C has bugs in this area */
printk(KERN_WARNING "cfi_cmdset_0001: Suspend "
"erase on write disabled.\n");
extp->SuspendCmdSupport &= ~1;
#else
printk(KERN_NOTICE "cfi_cmdset_0001: Erase suspend on write enabled\n");
#endif
}
/* Install our own private info structure */
cfi->cmdset_priv = extp;
}
for (i=0; i< cfi->numchips; i++) {
cfi->chips[i].word_write_time = 1<<cfi->cfiq->WordWriteTimeoutTyp;
cfi->chips[i].buffer_write_time = 1<<cfi->cfiq->BufWriteTimeoutTyp;
cfi->chips[i].erase_time = 1<<cfi->cfiq-><API key>;
cfi->chips[i].ref_point_counter = 0;
}
map->fldrv = &<API key>;
/* Make sure it's in read mode */
cfi_send_gen_cmd(0xff, 0x55, base, map, cfi, cfi->device_type, NULL);
return cfi_intelext_setup(map);
}
static struct mtd_info *cfi_intelext_setup(struct map_info *map)
{
struct cfi_private *cfi = map->fldrv_priv;
struct mtd_info *mtd;
unsigned long offset = 0;
int i,j;
unsigned long devsize = (1<<cfi->cfiq->DevSize) * cfi->interleave;
mtd = kmalloc(sizeof(*mtd), GFP_KERNEL);
//printk(KERN_DEBUG "number of CFI chips: %d\n", cfi->numchips);
if (!mtd) {
printk(KERN_ERR "Failed to allocate memory for MTD device\n");
goto setup_err;
}
memset(mtd, 0, sizeof(*mtd));
mtd->priv = map;
mtd->type = MTD_NORFLASH;
mtd->size = devsize * cfi->numchips;
mtd->numeraseregions = cfi->cfiq->NumEraseRegions * cfi->numchips;
mtd->eraseregions = kmalloc(sizeof(struct <API key>)
* mtd->numeraseregions, GFP_KERNEL);
if (!mtd->eraseregions) {
printk(KERN_ERR "Failed to allocate memory for MTD erase region info\n");
goto setup_err;
}
for (i=0; i<cfi->cfiq->NumEraseRegions; i++) {
unsigned long ernum, ersize;
ersize = ((cfi->cfiq->EraseRegionInfo[i] >> 8) & ~0xff) * cfi->interleave;
ernum = (cfi->cfiq->EraseRegionInfo[i] & 0xffff) + 1;
if (mtd->erasesize < ersize) {
mtd->erasesize = ersize;
}
for (j=0; j<cfi->numchips; j++) {
mtd->eraseregions[(j*cfi->cfiq->NumEraseRegions)+i].offset = (j*devsize)+offset;
mtd->eraseregions[(j*cfi->cfiq->NumEraseRegions)+i].erasesize = ersize;
mtd->eraseregions[(j*cfi->cfiq->NumEraseRegions)+i].numblocks = ernum;
}
offset += (ersize * ernum);
}
if (offset != devsize) {
/* Argh */
printk(KERN_WARNING "Sum of regions (%lx) != total size of set of interleaved chips (%lx)\n", offset, devsize);
goto setup_err;
}
for (i=0; i<mtd->numeraseregions;i++){
printk(KERN_DEBUG "%d: offset=0x%x,size=0x%x,blocks=%d\n",
i,mtd->eraseregions[i].offset,
mtd->eraseregions[i].erasesize,
mtd->eraseregions[i].numblocks);
}
/* Also select the correct geometry setup too */
mtd->erase = <API key>;
mtd->read = cfi_intelext_read;
if(map->point && map->unpoint){
mtd->point = do_point;
mtd->unpoint = do_unpoint;
}
#ifndef FORCE_WORD_WRITE
if ( cfi->cfiq->BufWriteTimeoutTyp ) {
printk("Using buffer write method\n" );
mtd->write = <API key>;
} else {
#else
{
#endif
printk("Using word write method\n" );
mtd->write = <API key>;
}
mtd->read_user_prot_reg = <API key>;
mtd->read_fact_prot_reg = <API key>;
mtd->sync = cfi_intelext_sync;
mtd->lock = cfi_intelext_lock;
mtd->unlock = cfi_intelext_unlock;
mtd->suspend = <API key>;
mtd->resume = cfi_intelext_resume;
mtd->flags = MTD_CAP_NORFLASH;
map->fldrv = &<API key>;
MOD_INC_USE_COUNT;
mtd->name = map->name;
return mtd;
setup_err:
if(mtd) {
if(mtd->eraseregions)
kfree(mtd->eraseregions);
kfree(mtd);
}
kfree(cfi->cmdset_priv);
kfree(cfi->cfiq);
return NULL;
}
static int do_point_onechip (struct map_info *map, struct flchip *chip, loff_t adr, size_t len)
{
cfi_word status, status_OK;
unsigned long timeo;
DECLARE_WAITQUEUE(wait, current);
unsigned long cmd_addr;
struct cfi_private *cfi = map->fldrv_priv;
adr += chip->start;
/* Ensure cmd read/writes are aligned. */
cmd_addr = adr & ~(CFIDEV_BUSWIDTH-1);
/* Let's determine this according to the interleave only once */
status_OK = CMD(0x80);
timeo = jiffies + HZ;
retry:
spin_lock(chip->mutex);
/* Check that the chip's ready to talk to us.
* If it's in FL_ERASING state, suspend it and make it talk now.
*/
switch (chip->state) {
case FL_READY:
case FL_POINT:
break;
case FL_CFI_QUERY:
case FL_JEDEC_QUERY:
cfi_write(map, CMD(0x70), cmd_addr);
chip->state = FL_STATUS;
case FL_STATUS:
status = cfi_read(map, cmd_addr);
if ((status & status_OK) == status_OK) {
cfi_write(map, CMD(0xff), cmd_addr);
chip->state = FL_READY;
break;
}
/* Urgh. Chip not yet ready to talk to us. */
if (time_after(jiffies, timeo)) {
spin_unlock(chip->mutex);
printk(KERN_ERR "waiting for chip to be ready timed out in read. WSM status = %llx\n", (__u64)status);
return -EIO;
}
/* Latency issues. Drop the lock, wait a while and retry */
spin_unlock(chip->mutex);
cfi_udelay(1);
goto retry;
default:
/* Stick ourselves on a wait queue to be woken when
someone changes the status */
set_current_state(<API key>);
add_wait_queue(&chip->wq, &wait);
spin_unlock(chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
timeo = jiffies + HZ;
goto retry;
}
chip->state = FL_POINT;
chip->ref_point_counter++;
spin_unlock(chip->mutex);
return 0;
}
static int do_point (struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen, u_char **mtdbuf)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
unsigned long ofs;
int chipnum;
int ret = 0;
if (from + len > mtd->size)
return -EINVAL;
*mtdbuf = map->point(map, from, len);
if(*mtdbuf == NULL)
return -EINVAL; /* can not point this region */
*retlen = 0;
/* Now lock the chip(s) to POINT state */
/* ofs: offset within the first chip that the first read should start */
chipnum = (from >> cfi->chipshift);
ofs = from - (chipnum << cfi->chipshift);
while (len) {
unsigned long thislen;
if (chipnum >= cfi->numchips)
break;
if ((len + ofs -1) >> cfi->chipshift)
thislen = (1<<cfi->chipshift) - ofs;
else
thislen = len;
ret = do_point_onechip(map, &cfi->chips[chipnum], ofs, thislen);
if (ret)
break;
*retlen += thislen;
len -= thislen;
ofs = 0;
chipnum++;
}
return 0;
}
static void do_unpoint (struct mtd_info *mtd, u_char *addr, loff_t from, size_t len)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
unsigned long ofs;
int chipnum;
map->unpoint(map, addr, from, len);
/* Now unlock the chip(s) POINT state */
/* ofs: offset within the first chip that the first read should start */
chipnum = (from >> cfi->chipshift);
ofs = from - (chipnum << cfi->chipshift);
while (len) {
unsigned long thislen;
struct flchip *chip;
chip = &cfi->chips[chipnum];
if (chipnum >= cfi->numchips)
break;
if ((len + ofs -1) >> cfi->chipshift)
thislen = (1<<cfi->chipshift) - ofs;
else
thislen = len;
spin_lock(chip->mutex);
if(chip->state == FL_POINT){
chip->ref_point_counter
if(chip->ref_point_counter == 0)
chip->state = FL_READY;
} else
printk("Warning: unpoint called on non pointed region\n"); /* Should this give an error? */
wake_up(&chip->wq);
spin_unlock(chip->mutex);
len -= thislen;
ofs = 0;
chipnum++;
}
}
static inline int do_read_onechip(struct map_info *map, struct flchip *chip, loff_t adr, size_t len, u_char *buf)
{
cfi_word status, status_OK;
unsigned long timeo;
DECLARE_WAITQUEUE(wait, current);
int suspended = 0;
unsigned long cmd_addr;
struct cfi_private *cfi = map->fldrv_priv;
adr += chip->start;
/* Ensure cmd read/writes are aligned. */
cmd_addr = adr & ~(CFIDEV_BUSWIDTH-1);
/* Let's determine this according to the interleave only once */
status_OK = CMD(0x80);
timeo = jiffies + HZ;
retry:
spin_lock(chip->mutex);
/* Check that the chip's ready to talk to us.
* If it's in FL_ERASING state, suspend it and make it talk now.
*/
switch (chip->state) {
case FL_ERASING:
if (!cfi->cmdset_priv ||
!(((struct cfi_pri_intelext *)cfi->cmdset_priv)->FeatureSupport & 2))
goto sleep; /* We don't support erase suspend */
cfi_write (map, CMD(0xb0), cmd_addr);
/* If the flash has finished erasing, then 'erase suspend'
* appears to make some (28F320) flash devices switch to
* 'read' mode. Make sure that we switch to 'read status'
* mode so we get the right data. --rmk
*/
cfi_write(map, CMD(0x70), cmd_addr);
chip->oldstate = FL_ERASING;
chip->state = FL_ERASE_SUSPENDING;
// printk("Erase suspending at 0x%lx\n", cmd_addr);
for (;;) {
status = cfi_read(map, cmd_addr);
if ((status & status_OK) == status_OK)
break;
if (time_after(jiffies, timeo)) {
/* Urgh */
cfi_write(map, CMD(0xd0), cmd_addr);
/* make sure we're in 'read status' mode */
cfi_write(map, CMD(0x70), cmd_addr);
chip->state = FL_ERASING;
spin_unlock(chip->mutex);
printk(KERN_ERR "Chip not ready after erase "
"suspended: status = 0x%llx\n", (__u64)status);
return -EIO;
}
spin_unlock(chip->mutex);
cfi_udelay(1);
spin_lock(chip->mutex);
}
suspended = 1;
cfi_write(map, CMD(0xff), cmd_addr);
chip->state = FL_READY;
break;
#if 0
case FL_WRITING:
/* Not quite yet */
#endif
case FL_READY:
case FL_POINT:
break;
case FL_CFI_QUERY:
case FL_JEDEC_QUERY:
cfi_write(map, CMD(0x70), cmd_addr);
chip->state = FL_STATUS;
case FL_STATUS:
status = cfi_read(map, cmd_addr);
if ((status & status_OK) == status_OK) {
cfi_write(map, CMD(0xff), cmd_addr);
chip->state = FL_READY;
break;
}
/* Urgh. Chip not yet ready to talk to us. */
if (time_after(jiffies, timeo)) {
spin_unlock(chip->mutex);
printk(KERN_ERR "waiting for chip to be ready timed out in read. WSM status = %llx\n", (__u64)status);
return -EIO;
}
/* Latency issues. Drop the lock, wait a while and retry */
spin_unlock(chip->mutex);
cfi_udelay(1);
goto retry;
default:
sleep:
/* Stick ourselves on a wait queue to be woken when
someone changes the status */
set_current_state(<API key>);
add_wait_queue(&chip->wq, &wait);
spin_unlock(chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
timeo = jiffies + HZ;
goto retry;
}
map->copy_from(map, buf, adr, len);
if (suspended) {
chip->state = chip->oldstate;
/* What if one interleaved chip has finished and the
other hasn't? The old code would leave the finished
one in READY mode. That's bad, and caused -EROFS
errors to be returned from do_erase_oneblock because
that's the only bit it checked for at the time.
As the state machine appears to explicitly allow
sending the 0x70 (Read Status) command to an erasing
chip and expecting it to be ignored, that's what we
do. */
cfi_write(map, CMD(0xd0), cmd_addr);
cfi_write(map, CMD(0x70), cmd_addr);
}
wake_up(&chip->wq);
spin_unlock(chip->mutex);
return 0;
}
static int cfi_intelext_read (struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen, u_char *buf)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
unsigned long ofs;
int chipnum;
int ret = 0;
/* ofs: offset within the first chip that the first read should start */
chipnum = (from >> cfi->chipshift);
ofs = from - (chipnum << cfi->chipshift);
*retlen = 0;
while (len) {
unsigned long thislen;
if (chipnum >= cfi->numchips)
break;
if ((len + ofs -1) >> cfi->chipshift)
thislen = (1<<cfi->chipshift) - ofs;
else
thislen = len;
ret = do_read_onechip(map, &cfi->chips[chipnum], ofs, thislen, buf);
if (ret)
break;
*retlen += thislen;
len -= thislen;
buf += thislen;
ofs = 0;
chipnum++;
}
return ret;
}
static int <API key> (struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen, u_char *buf, int base_offst, int reg_sz)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
struct cfi_pri_intelext *extp=cfi->cmdset_priv;
int ofs_factor = cfi->interleave * cfi->device_type;
int count=len;
struct flchip *chip;
int chip_num,offst;
unsigned long timeo;
DECLARE_WAITQUEUE(wait, current);
chip=0;
/* Calculate which chip & protection register offset we need */
chip_num=((unsigned int)from/reg_sz);
offst=from-(reg_sz*chip_num)+base_offst;
while(count){
if(chip_num>=cfi->numchips)
goto out;
/* Make sure that the chip is in the right state */
timeo = jiffies + HZ;
chip=&cfi->chips[chip_num];
retry:
spin_lock(chip->mutex);
switch (chip->state) {
case FL_READY:
case FL_STATUS:
case FL_CFI_QUERY:
case FL_JEDEC_QUERY:
break;
default:
/* Stick ourselves on a wait queue to be woken when
someone changes the status */
set_current_state(<API key>);
add_wait_queue(&chip->wq, &wait);
spin_unlock(chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
timeo = jiffies + HZ;
goto retry;
}
/* Now read the data required from this flash */
cfi_send_gen_cmd(0x90, 0x55,chip->start, map, cfi, cfi->device_type, NULL);
while(count && ((offst-base_offst)<reg_sz)){
*buf=map->read8(map,(chip->start+((extp->ProtRegAddr+1)*ofs_factor)+offst));
buf++;
offst++;
count
}
chip->state=FL_CFI_QUERY;
spin_unlock(chip->mutex);
/* Move on to the next chip */
chip_num++;
offst=base_offst;
}
out:
wake_up(&chip->wq);
return len-count;
}
static int <API key> (struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen, u_char *buf)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
struct cfi_pri_intelext *extp=cfi->cmdset_priv;
int base_offst,reg_sz;
/* Check that we actually have some protection registers */
if(!(extp->FeatureSupport&64)){
printk(KERN_WARNING "%s: This flash device has no protection data to read!\n",map->name);
return 0;
}
base_offst=(1<<extp->FactProtRegSize);
reg_sz=(1<<extp->UserProtRegSize);
return <API key>(mtd, from, len, retlen, buf, base_offst, reg_sz);
}
static int <API key> (struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen, u_char *buf)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
struct cfi_pri_intelext *extp=cfi->cmdset_priv;
int base_offst,reg_sz;
/* Check that we actually have some protection registers */
if(!(extp->FeatureSupport&64)){
printk(KERN_WARNING "%s: This flash device has no protection data to read!\n",map->name);
return 0;
}
base_offst=0;
reg_sz=(1<<extp->FactProtRegSize);
return <API key>(mtd, from, len, retlen, buf, base_offst, reg_sz);
}
static int do_write_oneword(struct map_info *map, struct flchip *chip, unsigned long adr, cfi_word datum)
{
struct cfi_private *cfi = map->fldrv_priv;
struct cfi_pri_intelext *extp = cfi->cmdset_priv;
cfi_word status, status_OK;
unsigned long timeo;
DECLARE_WAITQUEUE(wait, current);
int z, suspended=0, ret=0;
adr += chip->start;
/* Let's determine this according to the interleave only once */
status_OK = CMD(0x80);
timeo = jiffies + HZ;
retry:
spin_lock(chip->mutex);
/* Check that the chip's ready to talk to us.
* Later, we can actually think about interrupting it
* if it's in FL_ERASING state.
* Not just yet, though.
*/
switch (chip->state) {
case FL_READY:
break;
case FL_CFI_QUERY:
case FL_JEDEC_QUERY:
cfi_write(map, CMD(0x70), adr);
chip->state = FL_STATUS;
case FL_STATUS:
status = cfi_read(map, adr);
if ((status & status_OK) == status_OK)
break;
/* Urgh. Chip not yet ready to talk to us. */
if (time_after(jiffies, timeo)) {
spin_unlock(chip->mutex);
printk(KERN_ERR "waiting for chip to be ready timed out in read\n");
return -EIO;
}
/* Latency issues. Drop the lock, wait a while and retry */
spin_unlock(chip->mutex);
cfi_udelay(1);
goto retry;
case FL_ERASING:
if (!extp ||
!((extp->FeatureSupport & 2) && (extp->SuspendCmdSupport & 1)))
goto sleep; /* We don't support erase suspend */
cfi_write (map, CMD(0xb0), adr);
/* If the flash has finished erasing, then 'erase suspend'
* appears to make some (28F320) flash devices switch to
* 'read' mode. Make sure that we switch to 'read status'
* mode so we get the right data. --rmk
*/
cfi_write(map, CMD(0x70), adr);
chip->oldstate = FL_ERASING;
chip->state = FL_ERASE_SUSPENDING;
for (;;) {
status = cfi_read(map, adr);
if ((status & status_OK) == status_OK)
break;
if (time_after(jiffies, timeo)) {
/* Urgh */
cfi_write(map, CMD(0xd0), adr);
/* make sure we're in 'read status' mode */
cfi_write(map, CMD(0x70), adr);
chip->state = FL_ERASING;
spin_unlock(chip->mutex);
printk(KERN_ERR "Chip not ready after erase "
"suspended: status = 0x%x\n", status);
return -EIO;
}
spin_unlock(chip->mutex);
cfi_udelay(1);
spin_lock(chip->mutex);
}
suspended = 1;
chip->state = FL_STATUS;
break;
default:
sleep:
/* Stick ourselves on a wait queue to be woken when
someone changes the status */
set_current_state(<API key>);
add_wait_queue(&chip->wq, &wait);
spin_unlock(chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
timeo = jiffies + HZ;
goto retry;
}
ENABLE_VPP(map);
cfi_write(map, CMD(0x40), adr);
cfi_write(map, datum, adr);
chip->state = FL_WRITING;
spin_unlock(chip->mutex);
cfi_udelay(chip->word_write_time);
spin_lock(chip->mutex);
timeo = jiffies + (HZ/2);
z = 0;
for (;;) {
if (chip->state != FL_WRITING) {
/* Someone's suspended the write. Sleep */
set_current_state(<API key>);
add_wait_queue(&chip->wq, &wait);
spin_unlock(chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
timeo = jiffies + (HZ / 2); /* FIXME */
spin_lock(chip->mutex);
continue;
}
status = cfi_read(map, adr);
if ((status & status_OK) == status_OK)
break;
/* OK Still waiting */
if (time_after(jiffies, timeo)) {
chip->state = FL_STATUS;
DISABLE_VPP(map);
printk(KERN_ERR "waiting for chip to be ready timed out in word write\n");
ret = -EIO;
goto out;
}
/* Latency issues. Drop the lock, wait a while and retry */
spin_unlock(chip->mutex);
z++;
cfi_udelay(1);
spin_lock(chip->mutex);
}
if (!z) {
chip->word_write_time
if (!chip->word_write_time)
chip->word_write_time++;
}
if (z > 1)
chip->word_write_time++;
/* Done and happy. */
chip->state = FL_STATUS;
/* check for lock bit */
if (status & CMD(0x02)) {
/* clear status */
cfi_write(map, CMD(0x50), adr);
/* put back into read status register mode */
cfi_write(map, CMD(0x70), adr);
ret = -EROFS;
goto out;
}
out:
if (suspended) {
chip->state = chip->oldstate;
/* What if one interleaved chip has finished and the
other hasn't? The old code would leave the finished
one in READY mode. That's bad, and caused -EROFS
errors to be returned from do_erase_oneblock because
that's the only bit it checked for at the time.
As the state machine appears to explicitly allow
sending the 0x70 (Read Status) command to an erasing
chip and expecting it to be ignored, that's what we
do. */
cfi_write(map, CMD(0xd0), adr);
cfi_write(map, CMD(0x70), adr);
} else
DISABLE_VPP(map); /* must not clear the VPP if there is a suspended erase to be resumed */
wake_up(&chip->wq);
spin_unlock(chip->mutex);
return ret;
}
static int <API key> (struct mtd_info *mtd, loff_t to , size_t len, size_t *retlen, const u_char *buf)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
int ret = 0;
int chipnum;
unsigned long ofs;
*retlen = 0;
if (!len)
return 0;
chipnum = to >> cfi->chipshift;
ofs = to - (chipnum << cfi->chipshift);
/* If it's not bus-aligned, do the first byte write */
if (ofs & (CFIDEV_BUSWIDTH-1)) {
unsigned long bus_ofs = ofs & ~(CFIDEV_BUSWIDTH-1);
int gap = ofs - bus_ofs;
int i = 0, n = 0;
u_char tmp_buf[8];
cfi_word datum;
while (gap
tmp_buf[i++] = 0xff;
while (len && i < CFIDEV_BUSWIDTH)
tmp_buf[i++] = buf[n++], len
while (i < CFIDEV_BUSWIDTH)
tmp_buf[i++] = 0xff;
if (cfi_buswidth_is_2()) {
datum = *(__u16*)tmp_buf;
} else if (cfi_buswidth_is_4()) {
datum = *(__u32*)tmp_buf;
} else if (cfi_buswidth_is_8()) {
datum = *(__u64*)tmp_buf;
} else {
return -EINVAL; /* should never happen, but be safe */
}
ret = do_write_oneword(map, &cfi->chips[chipnum],
bus_ofs, datum);
if (ret)
return ret;
ofs += n;
buf += n;
(*retlen) += n;
if (ofs >> cfi->chipshift) {
chipnum ++;
ofs = 0;
if (chipnum == cfi->numchips)
return 0;
}
}
while(len >= CFIDEV_BUSWIDTH) {
cfi_word datum;
if (cfi_buswidth_is_1()) {
datum = *(__u8*)buf;
} else if (cfi_buswidth_is_2()) {
datum = *(__u16*)buf;
} else if (cfi_buswidth_is_4()) {
datum = *(__u32*)buf;
} else if (cfi_buswidth_is_8()) {
datum = *(__u64*)buf;
} else {
return -EINVAL;
}
ret = do_write_oneword(map, &cfi->chips[chipnum],
ofs, datum);
if (ret)
return ret;
ofs += CFIDEV_BUSWIDTH;
buf += CFIDEV_BUSWIDTH;
(*retlen) += CFIDEV_BUSWIDTH;
len -= CFIDEV_BUSWIDTH;
if (ofs >> cfi->chipshift) {
chipnum ++;
ofs = 0;
if (chipnum == cfi->numchips)
return 0;
}
}
if (len & (CFIDEV_BUSWIDTH-1)) {
int i = 0, n = 0;
u_char tmp_buf[8];
cfi_word datum;
while (len
tmp_buf[i++] = buf[n++];
while (i < CFIDEV_BUSWIDTH)
tmp_buf[i++] = 0xff;
if (cfi_buswidth_is_2()) {
datum = *(__u16*)tmp_buf;
} else if (cfi_buswidth_is_4()) {
datum = *(__u32*)tmp_buf;
} else if (cfi_buswidth_is_8()) {
datum = *(__u64*)tmp_buf;
} else {
return -EINVAL; /* should never happen, but be safe */
}
ret = do_write_oneword(map, &cfi->chips[chipnum],
ofs, datum);
if (ret)
return ret;
(*retlen) += n;
}
return 0;
}
static inline int do_write_buffer(struct map_info *map, struct flchip *chip,
unsigned long adr, const u_char *buf, int len)
{
struct cfi_private *cfi = map->fldrv_priv;
struct cfi_pri_intelext *extp = cfi->cmdset_priv;
cfi_word status, status_OK;
unsigned long cmd_adr, timeo;
DECLARE_WAITQUEUE(wait, current);
int wbufsize, z, suspended=0, ret=0;
wbufsize = CFIDEV_INTERLEAVE << cfi->cfiq->MaxBufWriteSize;
adr += chip->start;
cmd_adr = adr & ~(wbufsize-1);
/* Let's determine this according to the interleave only once */
status_OK = CMD(0x80);
timeo = jiffies + HZ;
retry:
spin_lock(chip->mutex);
/* Check that the chip's ready to talk to us.
* Later, we can actually think about interrupting it
* if it's in FL_ERASING state.
* Not just yet, though.
*/
switch (chip->state) {
case FL_READY:
case FL_CFI_QUERY:
case FL_JEDEC_QUERY:
cfi_write(map, CMD(0x70), cmd_adr);
chip->state = FL_STATUS;
case FL_STATUS:
status = cfi_read(map, cmd_adr);
if ((status & status_OK) == status_OK)
break;
/* Urgh. Chip not yet ready to talk to us. */
if (time_after(jiffies, timeo)) {
spin_unlock(chip->mutex);
printk(KERN_ERR "waiting for chip to be ready timed out in buffer write\n");
return -EIO;
}
/* Latency issues. Drop the lock, wait a while and retry */
spin_unlock(chip->mutex);
cfi_udelay(1);
goto retry;
case FL_ERASING:
if (!extp ||
!((extp->FeatureSupport & 2) && (extp->SuspendCmdSupport & 1)))
goto sleep; /* We don't support erase suspend */
cfi_write (map, CMD(0xb0), adr);
/* If the flash has finished erasing, then 'erase suspend'
* appears to make some (28F320) flash devices switch to
* 'read' mode. Make sure that we switch to 'read status'
* mode so we get the right data. --rmk
*/
cfi_write(map, CMD(0x70), adr);
chip->oldstate = FL_ERASING;
chip->state = FL_ERASE_SUSPENDING;
for (;;) {
status = cfi_read(map, adr);
if ((status & status_OK) == status_OK)
break;
if (time_after(jiffies, timeo)) {
/* Urgh */
cfi_write(map, CMD(0xd0), adr);
/* make sure we're in 'read status' mode */
cfi_write(map, CMD(0x70), adr);
chip->state = FL_ERASING;
spin_unlock(chip->mutex);
printk(KERN_ERR "Chip not ready after erase "
"suspended: status = 0x%x\n", status);
return -EIO;
}
spin_unlock(chip->mutex);
cfi_udelay(1);
spin_lock(chip->mutex);
}
suspended = 1;
chip->state = FL_STATUS;
break;
default:
sleep:
/* Stick ourselves on a wait queue to be woken when
someone changes the status */
set_current_state(<API key>);
add_wait_queue(&chip->wq, &wait);
spin_unlock(chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
timeo = jiffies + HZ;
goto retry;
}
/* We know we're now in FL_STATUS mode, and 'status' is current */
if (status & CMD(0x30)) {
printk(KERN_WARNING "SR.4 or SR.5 bits set in buffer write (status %x). Clearing.\n", status);
cfi_write(map, CMD(0x50), cmd_adr);
cfi_write(map, CMD(0x70), cmd_adr);
}
ENABLE_VPP(map);
chip->state = <API key>;
z = 0;
for (;;) {
cfi_write(map, CMD(0xe8), cmd_adr);
status = cfi_read(map, cmd_adr);
if ((status & status_OK) == status_OK)
break;
spin_unlock(chip->mutex);
cfi_udelay(1);
spin_lock(chip->mutex);
if (++z > 20) {
/* Argh. Not ready for write to buffer */
cfi_write(map, CMD(0x70), cmd_adr);
chip->state = FL_STATUS;
DISABLE_VPP(map);
printk(KERN_ERR "Chip not ready for buffer write. Xstatus = %llx, status = %llx\n", (__u64)status, (__u64)cfi_read(map, cmd_adr));
/* Odd. Clear status bits */
cfi_write(map, CMD(0x50), cmd_adr);
cfi_write(map, CMD(0x70), cmd_adr);
ret = -EIO;
goto out;
}
}
/* Write length of data to come */
cfi_write(map, CMD(len/CFIDEV_BUSWIDTH-1), cmd_adr );
/* Write data */
for (z = 0; z < len; z += CFIDEV_BUSWIDTH) {
if (cfi_buswidth_is_1()) {
map->write8 (map, *((__u8*)buf)++, adr+z);
} else if (cfi_buswidth_is_2()) {
map->write16 (map, *((__u16*)buf)++, adr+z);
} else if (cfi_buswidth_is_4()) {
map->write32 (map, *((__u32*)buf)++, adr+z);
} else if (cfi_buswidth_is_8()) {
map->write64 (map, *((__u64*)buf)++, adr+z);
} else {
DISABLE_VPP(map);
ret = -EINVAL;
goto out;
}
}
/* GO GO GO */
cfi_write(map, CMD(0xd0), cmd_adr);
chip->state = FL_WRITING;
spin_unlock(chip->mutex);
cfi_udelay(chip->buffer_write_time);
spin_lock(chip->mutex);
timeo = jiffies + (HZ/2);
z = 0;
for (;;) {
if (chip->state != FL_WRITING) {
/* Someone's suspended the write. Sleep */
set_current_state(<API key>);
add_wait_queue(&chip->wq, &wait);
spin_unlock(chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
timeo = jiffies + (HZ / 2); /* FIXME */
spin_lock(chip->mutex);
continue;
}
status = cfi_read(map, cmd_adr);
if ((status & status_OK) == status_OK)
break;
/* OK Still waiting */
if (time_after(jiffies, timeo)) {
chip->state = FL_STATUS;
DISABLE_VPP(map);
printk(KERN_ERR "waiting for chip to be ready timed out in bufwrite\n");
ret = -EIO;
goto out;
}
/* Latency issues. Drop the lock, wait a while and retry */
spin_unlock(chip->mutex);
cfi_udelay(1);
z++;
spin_lock(chip->mutex);
}
if (!z) {
chip->buffer_write_time
if (!chip->buffer_write_time)
chip->buffer_write_time++;
}
if (z > 1)
chip->buffer_write_time++;
/* Done and happy. */
chip->state = FL_STATUS;
/* check for lock bit */
if (status & CMD(0x02)) {
/* clear status */
cfi_write(map, CMD(0x50), cmd_adr);
/* put back into read status register mode */
cfi_write(map, CMD(0x70), adr);
ret = -EROFS;
goto out;
}
out:
if (suspended) {
chip->state = chip->oldstate;
/* What if one interleaved chip has finished and the
other hasn't? The old code would leave the finished
one in READY mode. That's bad, and caused -EROFS
errors to be returned from do_erase_oneblock because
that's the only bit it checked for at the time.
As the state machine appears to explicitly allow
sending the 0x70 (Read Status) command to an erasing
chip and expecting it to be ignored, that's what we
do. */
cfi_write(map, CMD(0xd0), adr);
cfi_write(map, CMD(0x70), adr);
} else
DISABLE_VPP(map); /* must not clear the VPP if there is a suspended erase to be resumed */
wake_up(&chip->wq);
spin_unlock(chip->mutex);
return ret;
}
static int <API key> (struct mtd_info *mtd, loff_t to,
size_t len, size_t *retlen, const u_char *buf)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
int wbufsize = CFIDEV_INTERLEAVE << cfi->cfiq->MaxBufWriteSize;
int ret = 0;
int chipnum;
unsigned long ofs;
*retlen = 0;
if (!len)
return 0;
chipnum = to >> cfi->chipshift;
ofs = to - (chipnum << cfi->chipshift);
/* If it's not bus-aligned, do the first word write */
if (ofs & (CFIDEV_BUSWIDTH-1)) {
size_t local_len = (-ofs)&(CFIDEV_BUSWIDTH-1);
if (local_len > len)
local_len = len;
ret = <API key>(mtd, to, local_len,
retlen, buf);
if (ret)
return ret;
ofs += local_len;
buf += local_len;
len -= local_len;
if (ofs >> cfi->chipshift) {
chipnum ++;
ofs = 0;
if (chipnum == cfi->numchips)
return 0;
}
}
/* Write buffer is worth it only if more than one word to write... */
while(len > CFIDEV_BUSWIDTH) {
/* We must not cross write block boundaries */
int size = wbufsize - (ofs & (wbufsize-1));
if (size > len)
size = len & ~(CFIDEV_BUSWIDTH-1);
ret = do_write_buffer(map, &cfi->chips[chipnum],
ofs, buf, size);
if (ret)
return ret;
ofs += size;
buf += size;
(*retlen) += size;
len -= size;
if (ofs >> cfi->chipshift) {
chipnum ++;
ofs = 0;
if (chipnum == cfi->numchips)
return 0;
}
}
/* ... and write the remaining bytes */
if (len > 0) {
size_t local_retlen;
ret = <API key>(mtd, ofs + (chipnum << cfi->chipshift),
len, &local_retlen, buf);
if (ret)
return ret;
(*retlen) += local_retlen;
}
return 0;
}
typedef int (*varsize_frob_t)(struct map_info *map, struct flchip *chip,
unsigned long adr, void *thunk);
static int <API key>(struct mtd_info *mtd, varsize_frob_t frob,
loff_t ofs, size_t len, void *thunk)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
unsigned long adr;
int chipnum, ret = 0;
int i, first;
struct <API key> *regions = mtd->eraseregions;
if (ofs > mtd->size)
return -EINVAL;
if ((len + ofs) > mtd->size)
return -EINVAL;
/* Check that both start and end of the requested erase are
* aligned with the erasesize at the appropriate addresses.
*/
i = 0;
/* Skip all erase regions which are ended before the start of
the requested erase. Actually, to save on the calculations,
we skip to the first erase region which starts after the
start of the requested erase, and then go back one.
*/
while (i < mtd->numeraseregions && ofs >= regions[i].offset)
i++;
i
/* OK, now i is pointing at the erase region in which this
erase request starts. Check the start of the requested
erase range is aligned with the erase size which is in
effect here.
*/
if (ofs & (regions[i].erasesize-1))
return -EINVAL;
/* Remember the erase region we start on */
first = i;
/* Next, check that the end of the requested erase is aligned
* with the erase region at that address.
*/
while (i<mtd->numeraseregions && (ofs + len) >= regions[i].offset)
i++;
/* As before, drop back one to point at the region in which
the address actually falls
*/
i
if ((ofs + len) & (regions[i].erasesize-1))
return -EINVAL;
chipnum = ofs >> cfi->chipshift;
adr = ofs - (chipnum << cfi->chipshift);
i=first;
while(len) {
ret = (*frob)(map, &cfi->chips[chipnum], adr, thunk);
if (ret)
return ret;
adr += regions[i].erasesize;
len -= regions[i].erasesize;
if (adr % (1<< cfi->chipshift) == ((regions[i].offset + (regions[i].erasesize * regions[i].numblocks)) %( 1<< cfi->chipshift)))
i++;
if (adr >> cfi->chipshift) {
adr = 0;
chipnum++;
if (chipnum >= cfi->numchips)
break;
}
}
return 0;
}
static int do_erase_oneblock(struct map_info *map, struct flchip *chip, unsigned long adr, void *thunk)
{
struct cfi_private *cfi = map->fldrv_priv;
cfi_word status, status_OK;
unsigned long timeo;
int retries = 3;
DECLARE_WAITQUEUE(wait, current);
int ret = 0;
adr += chip->start;
/* Let's determine this according to the interleave only once */
status_OK = CMD(0x80);
timeo = jiffies + HZ;
retry:
spin_lock(chip->mutex);
/* Check that the chip's ready to talk to us. */
switch (chip->state) {
case FL_CFI_QUERY:
case FL_JEDEC_QUERY:
case FL_READY:
cfi_write(map, CMD(0x70), adr);
chip->state = FL_STATUS;
case FL_STATUS:
status = cfi_read(map, adr);
if ((status & status_OK) == status_OK)
break;
/* Urgh. Chip not yet ready to talk to us. */
if (time_after(jiffies, timeo)) {
spin_unlock(chip->mutex);
printk(KERN_ERR "waiting for chip to be ready timed out in erase\n");
return -EIO;
}
/* Latency issues. Drop the lock, wait a while and retry */
spin_unlock(chip->mutex);
cfi_udelay(1);
goto retry;
default:
/* Stick ourselves on a wait queue to be woken when
someone changes the status */
set_current_state(<API key>);
add_wait_queue(&chip->wq, &wait);
spin_unlock(chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
timeo = jiffies + HZ;
goto retry;
}
ENABLE_VPP(map);
/* Clear the status register first */
cfi_write(map, CMD(0x50), adr);
/* Now erase */
cfi_write(map, CMD(0x20), adr);
cfi_write(map, CMD(0xD0), adr);
chip->state = FL_ERASING;
chip->oldstate = 0;
spin_unlock(chip->mutex);
set_current_state(<API key>);
schedule_timeout((chip->erase_time*HZ)/(2*1000));
spin_lock(chip->mutex);
/* FIXME. Use a timer to check this, and return immediately. */
/* Once the state machine's known to be working I'll do that */
timeo = jiffies + (HZ*20);
for (;;) {
if (chip->state != FL_ERASING) {
/* Someone's suspended the erase. Sleep */
set_current_state(<API key>);
add_wait_queue(&chip->wq, &wait);
spin_unlock(chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
spin_lock(chip->mutex);
continue;
}
if (chip->oldstate) {
/* This erase was suspended and resumed.
Adjust the timeout */
timeo = jiffies + (HZ*20); /* FIXME */
chip->oldstate = 0;
}
status = cfi_read(map, adr);
if ((status & status_OK) == status_OK)
break;
/* OK Still waiting */
if (time_after(jiffies, timeo)) {
cfi_write(map, CMD(0x70), adr);
chip->state = FL_STATUS;
printk(KERN_ERR "waiting for erase at %08lx to complete timed out. Xstatus = %llx, status = %llx.\n",
adr, (__u64)status, (__u64)cfi_read(map, adr));
/* Clear status bits */
cfi_write(map, CMD(0x50), adr);
cfi_write(map, CMD(0x70), adr);
DISABLE_VPP(map);
spin_unlock(chip->mutex);
return -EIO;
}
/* Latency issues. Drop the lock, wait a while and retry */
spin_unlock(chip->mutex);
set_current_state(<API key>);
schedule_timeout(1);
spin_lock(chip->mutex);
}
DISABLE_VPP(map);
ret = 0;
/* We've broken this before. It doesn't hurt to be safe */
cfi_write(map, CMD(0x70), adr);
chip->state = FL_STATUS;
status = cfi_read(map, adr);
/* check for lock bit */
if (status & CMD(0x3a)) {
unsigned char chipstatus = status;
if (status != CMD(status & 0xff)) {
int i;
for (i = 1; i<CFIDEV_INTERLEAVE; i++) {
chipstatus |= status >> (cfi->device_type * 8);
}
printk(KERN_WARNING "Status is not identical for all chips: 0x%llx. Merging to give 0x%02x\n", (__u64)status, chipstatus);
}
/* Reset the error bits */
cfi_write(map, CMD(0x50), adr);
cfi_write(map, CMD(0x70), adr);
if ((chipstatus & 0x30) == 0x30) {
printk(KERN_NOTICE "Chip reports improper command sequence: status 0x%llx\n", (__u64)status);
ret = -EIO;
} else if (chipstatus & 0x02) {
/* Protection bit set */
ret = -EROFS;
} else if (chipstatus & 0x8) {
/* Voltage */
printk(KERN_WARNING "Chip reports voltage low on erase: status 0x%llx\n", (__u64)status);
ret = -EIO;
} else if (chipstatus & 0x20) {
if (retries
printk(KERN_DEBUG "Chip erase failed at 0x%08lx: status 0x%llx. Retrying...\n", adr, (__u64)status);
timeo = jiffies + HZ;
chip->state = FL_STATUS;
spin_unlock(chip->mutex);
goto retry;
}
printk(KERN_DEBUG "Chip erase failed at 0x%08lx: status 0x%llx\n", adr, (__u64)status);
ret = -EIO;
}
}
wake_up(&chip->wq);
spin_unlock(chip->mutex);
return ret;
}
int <API key>(struct mtd_info *mtd, struct erase_info *instr)
{
unsigned long ofs, len;
int ret;
ofs = instr->addr;
len = instr->len;
ret = <API key>(mtd, do_erase_oneblock, ofs, len, 0);
if (ret)
return ret;
instr->state = MTD_ERASE_DONE;
if (instr->callback)
instr->callback(instr);
return 0;
}
static void cfi_intelext_sync (struct mtd_info *mtd)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
int i;
struct flchip *chip;
int ret = 0;
DECLARE_WAITQUEUE(wait, current);
for (i=0; !ret && i<cfi->numchips; i++) {
chip = &cfi->chips[i];
retry:
spin_lock(chip->mutex);
switch(chip->state) {
case FL_READY:
case FL_STATUS:
case FL_CFI_QUERY:
case FL_JEDEC_QUERY:
chip->oldstate = chip->state;
chip->state = FL_SYNCING;
/* No need to wake_up() on this state change -
* as the whole point is that nobody can do anything
* with the chip now anyway.
*/
case FL_SYNCING:
spin_unlock(chip->mutex);
break;
default:
/* Not an idle state */
add_wait_queue(&chip->wq, &wait);
spin_unlock(chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
goto retry;
}
}
/* Unlock the chips again */
for (i--; i >=0; i--) {
chip = &cfi->chips[i];
spin_lock(chip->mutex);
if (chip->state == FL_SYNCING) {
chip->state = chip->oldstate;
wake_up(&chip->wq);
}
spin_unlock(chip->mutex);
}
}
#ifdef DEBUG_LOCK_BITS
static int <API key>(struct map_info *map, struct flchip *chip, unsigned long adr, void *thunk)
{
struct cfi_private *cfi = map->fldrv_priv;
int ofs_factor = cfi->interleave * cfi->device_type;
cfi_send_gen_cmd(0x90, 0x55, 0, map, cfi, cfi->device_type, NULL);
printk(KERN_DEBUG "block status register for 0x%08lx is %x\n",
adr, cfi_read_query(map, adr+(2*ofs_factor)));
cfi_send_gen_cmd(0xff, 0x55, 0, map, cfi, cfi->device_type, NULL);
return 0;
}
#endif
#define <API key> ((void *) 1)
#define <API key> ((void *) 2)
static int do_xxlock_oneblock(struct map_info *map, struct flchip *chip, unsigned long adr, void *thunk)
{
struct cfi_private *cfi = map->fldrv_priv;
cfi_word status, status_OK;
unsigned long timeo = jiffies + HZ;
DECLARE_WAITQUEUE(wait, current);
adr += chip->start;
/* Let's determine this according to the interleave only once */
status_OK = CMD(0x80);
timeo = jiffies + HZ;
retry:
spin_lock(chip->mutex);
/* Check that the chip's ready to talk to us. */
switch (chip->state) {
case FL_CFI_QUERY:
case FL_JEDEC_QUERY:
case FL_READY:
cfi_write(map, CMD(0x70), adr);
chip->state = FL_STATUS;
case FL_STATUS:
status = cfi_read(map, adr);
if ((status & status_OK) == status_OK)
break;
/* Urgh. Chip not yet ready to talk to us. */
if (time_after(jiffies, timeo)) {
spin_unlock(chip->mutex);
printk(KERN_ERR "%s: waiting for chip to be ready timed out\n", __FUNCTION__);
return -EIO;
}
/* Latency issues. Drop the lock, wait a while and retry */
spin_unlock(chip->mutex);
cfi_udelay(1);
goto retry;
default:
/* Stick ourselves on a wait queue to be woken when
someone changes the status */
set_current_state(<API key>);
add_wait_queue(&chip->wq, &wait);
spin_unlock(chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
timeo = jiffies + HZ;
goto retry;
}
ENABLE_VPP(map);
cfi_write(map, CMD(0x60), adr);
if (thunk == <API key>) {
cfi_write(map, CMD(0x01), adr);
chip->state = FL_LOCKING;
} else if (thunk == <API key>) {
cfi_write(map, CMD(0xD0), adr);
chip->state = FL_UNLOCKING;
} else
BUG();
spin_unlock(chip->mutex);
schedule_timeout(HZ);
spin_lock(chip->mutex);
/* FIXME. Use a timer to check this, and return immediately. */
/* Once the state machine's known to be working I'll do that */
timeo = jiffies + (HZ*20);
for (;;) {
status = cfi_read(map, adr);
if ((status & status_OK) == status_OK)
break;
/* OK Still waiting */
if (time_after(jiffies, timeo)) {
cfi_write(map, CMD(0x70), adr);
chip->state = FL_STATUS;
printk(KERN_ERR "waiting for unlock to complete timed out. Xstatus = %llx, status = %llx.\n", (__u64)status, (__u64)cfi_read(map, adr));
DISABLE_VPP(map);
spin_unlock(chip->mutex);
return -EIO;
}
/* Latency issues. Drop the lock, wait a while and retry */
spin_unlock(chip->mutex);
cfi_udelay(1);
spin_lock(chip->mutex);
}
/* Done and happy. */
chip->state = FL_STATUS;
DISABLE_VPP(map);
wake_up(&chip->wq);
spin_unlock(chip->mutex);
return 0;
}
static int cfi_intelext_lock(struct mtd_info *mtd, loff_t ofs, size_t len)
{
int ret;
#ifdef DEBUG_LOCK_BITS
printk(KERN_DEBUG "%s: lock status before, ofs=0x%08llx, len=0x%08X\n",
__FUNCTION__, ofs, len);
<API key>(mtd, <API key>,
ofs, len, 0);
#endif
ret = <API key>(mtd, do_xxlock_oneblock,
ofs, len, <API key>);
#ifdef DEBUG_LOCK_BITS
printk(KERN_DEBUG __FUNCTION__
"%s: lock status after, ret=%d\n", __FUNCTION__, ret);
<API key>(mtd, <API key>,
ofs, len, 0);
#endif
return ret;
}
static int cfi_intelext_unlock(struct mtd_info *mtd, loff_t ofs, size_t len)
{
int ret;
#ifdef DEBUG_LOCK_BITS
printk(KERN_DEBUG "%s: lock status before, ofs=0x%08llx, len=0x%08X\n",
__FUNCTION__, ofs, len);
<API key>(mtd, <API key>,
ofs, len, 0);
#endif
ret = <API key>(mtd, do_xxlock_oneblock,
ofs, len, <API key>);
#ifdef DEBUG_LOCK_BITS
printk(KERN_DEBUG "%s: lock status after, ret=%d\n", __FUNCTION__, ret);
<API key>(mtd, <API key>,
ofs, len, 0);
#endif
return ret;
}
static int <API key>(struct mtd_info *mtd)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
int i;
struct flchip *chip;
int ret = 0;
for (i=0; !ret && i<cfi->numchips; i++) {
chip = &cfi->chips[i];
spin_lock(chip->mutex);
switch(chip->state) {
case FL_READY:
case FL_STATUS:
case FL_CFI_QUERY:
case FL_JEDEC_QUERY:
chip->oldstate = chip->state;
chip->state = FL_PM_SUSPENDED;
/* No need to wake_up() on this state change -
* as the whole point is that nobody can do anything
* with the chip now anyway.
*/
case FL_PM_SUSPENDED:
break;
default:
ret = -EAGAIN;
break;
}
spin_unlock(chip->mutex);
}
/* Unlock the chips again */
if (ret) {
for (i--; i >=0; i--) {
chip = &cfi->chips[i];
spin_lock(chip->mutex);
if (chip->state == FL_PM_SUSPENDED) {
/* No need to force it into a known state here,
because we're returning failure, and it didn't
get power cycled */
chip->state = chip->oldstate;
wake_up(&chip->wq);
}
spin_unlock(chip->mutex);
}
}
return ret;
}
static void cfi_intelext_resume(struct mtd_info *mtd)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
int i;
struct flchip *chip;
for (i=0; i<cfi->numchips; i++) {
chip = &cfi->chips[i];
spin_lock(chip->mutex);
/* Go to known state. Chip may have been power cycled */
if (chip->state == FL_PM_SUSPENDED) {
cfi_write(map, CMD(0xFF), 0);
chip->state = FL_READY;
wake_up(&chip->wq);
}
spin_unlock(chip->mutex);
}
}
static void <API key>(struct mtd_info *mtd)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
kfree(cfi->cmdset_priv);
kfree(cfi->cfiq);
kfree(cfi);
kfree(mtd->eraseregions);
}
static char im_name_1[]="cfi_cmdset_0001";
static char im_name_3[]="cfi_cmdset_0003";
int __init cfi_intelext_init(void)
{
<API key>(im_name_1, THIS_MODULE, &cfi_cmdset_0001);
<API key>(im_name_3, THIS_MODULE, &cfi_cmdset_0001);
return 0;
}
static void __exit cfi_intelext_exit(void)
{
<API key>(im_name_1);
<API key>(im_name_3);
}
module_init(cfi_intelext_init);
module_exit(cfi_intelext_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("David Woodhouse <dwmw2@infradead.org> et al.");
MODULE_DESCRIPTION("MTD chip driver for Intel/Sharp flash chips"); |
/* PROGRAM NAME: tdbvir.cpp Version 1.2 */
/* This program are the VIR classes DB execution routines. */
/* Include relevant sections of the MariaDB header file. */
#include <my_global.h>
/* Include application header files: */
/* global.h is header containing all global declarations. */
/* plgdbsem.h is header containing the DB application declarations. */
/* xtable.h is header containing the TDBASE declarations. */
/* tdbvir.h is header containing the VIR classes declarations. */
#include "global.h"
#include "plgdbsem.h"
#include "filter.h"
#include "xtable.h"
//#include "reldef.h"
#include "colblk.h"
#include "mycat.h" // for FNC_COL
#include "tabvir.h"
#include "resource.h" // for IDS_COLUMNS
/* Return the unique column definition to MariaDB. */
PQRYRES VirColumns(PGLOBAL g, bool info)
{
int buftyp[] = {TYPE_STRING, TYPE_SHORT, TYPE_STRING,
TYPE_INT, TYPE_STRING, TYPE_STRING};
XFLD fldtyp[] = {FLD_NAME, FLD_TYPE, FLD_TYPENAME,
FLD_PREC, FLD_KEY, FLD_EXTRA};
unsigned int length[] = {8, 4, 16, 4, 16, 16};
int i, n, ncol = sizeof(buftyp) / sizeof(int);
PQRYRES qrp;
PCOLRES crp;
n = (info) ? 0 : 1;
/* Allocate the structures used to refer to the result set. */
if (!(qrp = PlgAllocResult(g, ncol, n, IDS_COLUMNS + 3,
buftyp, fldtyp, length, false, true)))
return NULL;
// Some columns must be renamed before info
for (i = 0, crp = qrp->Colresp; crp; crp = crp->Next)
switch (++i) {
case 5: crp->Name = "Key"; break;
case 6: crp->Name = "Extra"; break;
} // endswitch i
if (info)
return qrp;
/* Now get the results into blocks. */
// Set column name
crp = qrp->Colresp; // Column_Name
crp->Kdata->SetValue("n", 0);
// Set type, type name, precision
crp = crp->Next; // Data_Type
crp->Kdata->SetValue(TYPE_INT, 0);
crp = crp->Next; // Type_Name
crp->Kdata->SetValue(GetTypeName(TYPE_INT), 0);
crp = crp->Next; // Precision
crp->Kdata->SetValue(11, 0);
crp = crp->Next; // Key
crp->Kdata->SetValue("KEY", 0);
crp = crp->Next; // Extra
crp->Kdata->SetValue("SPECIAL=ROWID", 0);
qrp->Nblin = 1;
/* Return the result pointer for use by discovery routines. */
return qrp;
} // end of VirColumns
/* GetTable: makes a new Table Description Block. */
PTDB VIRDEF::GetTable(PGLOBAL g, MODE)
{
// Column blocks will be allocated only when needed.
if (Catfunc == FNC_COL)
return new(g) TDBVICL(this);
else
return new(g) TDBVIR(this);
} // end of GetTable
/* Implementation of the TDBVIR class. */
TDBVIR::TDBVIR(PVIRDEF tdp) : TDBASE(tdp)
{
Size = (tdp->GetElemt()) ? tdp->GetElemt() : 1;
N = -1;
} // end of TDBVIR constructor
/* Analyze the filter and reset the size limit accordingly. */
/* This is possible when a filter contains predicates implying the */
/* special column ROWID. Here we just test for when no more good */
/* records can be met in the remaining of the table. */
int TDBVIR::TestFilter(PFIL filp, bool nop)
{
int i, op = filp->GetOpc(), n = 0, type[2] = {0,0};
int l1 = 0, l2, limit = Size;
PXOB arg[2] = {NULL,NULL};
if (op == OP_GT || op == OP_GE || op == OP_LT || op == OP_LE) {
for (i = 0; i < 2; i++) {
arg[i] = filp->Arg(i);
switch (filp->GetArgType(i)) {
case TYPE_CONST:
if ((l1 = arg[i]->GetIntValue()) >= 0)
type[i] = 1;
break;
case TYPE_COLBLK:
if (((PCOL)arg[i])->GetTo_Tdb() == this &&
((PCOL)arg[i])->GetAmType() == TYPE_AM_ROWID)
type[i] = 2;
break;
default:
break;
} // endswitch ArgType
if (!type[i])
break;
n += type[i];
} // endfor i
if (n == 3) {
// If true it will be ok to delete the filter
BOOL ok = (filp == To_Filter);
if (type[0] == 1)
// Make it always a Column-op-Value
switch (op) {
case OP_GT: op = OP_LT; break;
case OP_GE: op = OP_LE; break;
case OP_LT: op = OP_GT; break;
case OP_LE: op = OP_GE; break;
} // endswitch op
if (!nop) switch (op) {
case OP_LT: l1
case OP_LE: limit = l1; break;
default: ok = false;
} // endswitch op
else switch (op) {
case OP_GE: l1
case OP_GT: limit = l1; break;
default: ok = false;
} // endswitch op
limit = MY_MIN(MY_MAX(0, limit), Size);
// Just one where clause such as Rowid < limit;
if (ok)
To_Filter = NULL;
} else
limit = Size;
} else if ((op == OP_AND && !nop) || (op == OP_OR && nop)) {
l1 = TestFilter((PFIL)filp->Arg(0), nop);
l2 = TestFilter((PFIL)filp->Arg(1), nop);
limit = MY_MIN(l1, l2);
} else if (op == OP_NOT)
limit = TestFilter((PFIL)filp->Arg(0), !nop);
return limit;
} // end of TestFilter
/* Allocate source column description block. */
PCOL TDBVIR::MakeCol(PGLOBAL g, PCOLDEF cdp, PCOL cprec, int n)
{
PCOL colp = NULL;
if (cdp->IsVirtual()) {
colp = new(g) VIRCOL(cdp, this, cprec, n);
} else strcpy(g->Message,
"Virtual tables accept only special or virtual columns");
return colp;
} // end of MakeCol
/* VIR Access Method opening routine. */
bool TDBVIR::OpenDB(PGLOBAL g)
{
if (Use == USE_OPEN) {
// Table already open
N = -1;
return false;
} // endif use
if (Mode != MODE_READ) {
strcpy(g->Message, "Virtual tables are read only");
return true;
} // endif Mode
/* Analyze the filter and refine Size accordingly. */
if (To_Filter)
Size = TestFilter(To_Filter, false);
return false;
} // end of OpenDB
/* Data Base read routine for the VIR access method. */
int TDBVIR::ReadDB(PGLOBAL)
{
return (++N >= Size) ? RC_EF : RC_OK;
} // end of ReadDB
/* WriteDB: Data Base write routine for the VIR access methods. */
int TDBVIR::WriteDB(PGLOBAL g)
{
sprintf(g->Message, MSG(VIR_READ_ONLY), To_Def->GetType());
return RC_FX;
} // end of WriteDB
/* Data Base delete line routine for the VIR access methods. */
int TDBVIR::DeleteDB(PGLOBAL g, int)
{
sprintf(g->Message, MSG(VIR_NO_DELETE), To_Def->GetType());
return RC_FX;
} // end of DeleteDB
/* VIRCOL public constructor. */
VIRCOL::VIRCOL(PCOLDEF cdp, PTDB tdbp, PCOL cprec, int i, PCSZ)
: COLBLK(cdp, tdbp, i)
{
if (cprec) {
Next = cprec->GetNext();
cprec->SetNext(this);
} else {
Next = tdbp->GetColumns();
tdbp->SetColumns(this);
} // endif cprec
} // end of VIRCOL constructor
/* ReadColumn: */
void VIRCOL::ReadColumn(PGLOBAL g)
{
// This should never be called
sprintf(g->Message, "ReadColumn: Column %s is not virtual", Name);
throw TYPE_COLBLK;
} // end of ReadColumn
/* GetResult: Get the list the VIRTUAL table columns. */
PQRYRES TDBVICL::GetResult(PGLOBAL g)
{
return VirColumns(g, false);
} // end of GetResult |
app.view.context.components = app.view.context.components || {};
app.view.context.components.retagitem = app.lib.element({
displayName: 'context.components.retagitem',
mixins: [app.lib.mixins.rootParent],
getDefaultProps: function () {
return {
filter: null,
tree: [],
active: false, // active is to refresh expander when tags are selected
rootParent: null // to get rootParent of recursively nested components
}
},
getInitialState: function () {
if (this.isRootParent()) {
return {
hasChecked: false,
parents: null,
tags: {
visible: null,
filtered: null
}
}
} else {
return {
parents: null,
tags: {
visible: null,
filtered: null
}
};
}
},
componentWillMount: function () {
this.refreshExpander(this.props);
},
componentDidMount: function () {
this.rootParent().expandedTagHash = _.clone(this.rootParent()._expandedTagHash);
this.rootParent().skipUpdate = false;
},
componentDidUpdate: function () {
this.rootParent().expandedTagHash = _.clone(this.rootParent()._expandedTagHash);
this.rootParent().skipUpdate = false;
},
<API key>: function (nextProps) {
if (this.isRootParent()) {
this.rootParent().forceExpander = (this.props.filter !== nextProps.filter) && nextProps.filter;
//if (true) { // refresh expanders always
if (!this.rootParent().skipUpdate || this.props.filter !== nextProps.filter) { // refresh expanders only on navigate
if (nextProps.filter) {
this.<API key>(nextProps);
} else {
this.refreshExpander(nextProps, this.props.filter !== nextProps.filter);
}
} else {
this.expandedTagHash = {};
this._expandedTagHash = {};
}
}
},
toggle: function (_id, event) {
if (this.isRootParent()) {
event.preventDefault();
event.stopPropagation();
if (typeof (this.props.<API key>[_id]) === 'undefined') {
if (typeof (this.props.selectionHash[_id]) === 'undefined') {
this.props.selectionHash[_id] = true;
} else {
delete this.props.selectionHash[_id];
}
this.forceUpdate();
} else {
if (this.props.selectionHash[_id] === false) {
this.props.selectionHash[_id] = true;
this.forceUpdate();
return;
}
if (this.props.selectionHash[_id] === true) {
if (this.props.<API key>[_id]) {
this.props.selectionHash[_id] = false;
} else {
this.props.selectionHash[_id] = this.props.<API key>[_id];
}
this.forceUpdate();
return;
}
if (this.props.selectionHash[_id] === null) {
this.props.selectionHash[_id] = false;
this.forceUpdate();
return;
}
}
}
},
refreshExpander: function (props, force) {
if (this.isRootParent() && (props.active || force)) { // active is to refresh expander when tags are selected
this.expandedTagHash = app.data.tags.getParents(_.keys(this.props.selectionHash));
this._expandedTagHash = _.clone(this.expandedTagHash);
this.setState({
tags: {
visible: null,
filtered: null
}
});
}
},
//TODO: add debounce, but in complience with "trackers component" to be streamilned
<API key>: function (props) {
if (this.isRootParent() && props.filter) {
var filter = props.filter.toLowerCase();
var filteredTags = _.filter(app.data.tags.models, function (tag) {
return app.lib.searchText(tag.data('tag').name.toLowerCase(), filter);
//var words = _.words(tag.data('tag').name.toLowerCase());
//return !!_.find(words, function (word) {
// return _.startsWith(word, filter);
}, this);
var filteredIds = _.map(filteredTags, function (item) { return item.get('_id') });
this.expandedTagHash = app.data.tags.getParents(filteredIds);
this._expandedTagHash = _.clone(this.expandedTagHash);
var parentsIds = _.keys(this.expandedTagHash);
var mergedTags = [].concat(filteredIds, parentsIds);
this.setState({
tags: {
visible: _.object(mergedTags, mergedTags),
filtered: filteredIds
}
});
}
},
isExpanded: function (id) {
if (this.isRootParent()) {
if (this.expandedTagHash) {
if (this.expandedTagHash[id]) {
// agains recursion
this.expandedTagHash[id] = false;
return true;
} else {
return false;
}
} else {
return false;
}
}
},
isVisible: function (id) {
if (this.isRootParent()) {
var visible = app.data.tags.get(id).isActive();
if (this.state.tags.visible) {
var show = _.intersection(app.data.tags.getTree(false)[id].up, this.state.tags.filtered).length > 0
return visible && (!!this.state.tags.visible[id] || show);
} else {
return visible;
}
}
},
isChildrenVisible: function (id) {
if (this.isRootParent()) {
var status = app.data.tags.get(id).data('status');
var visible = status === 'all' || status === 'inbox';
if (this.state.tags.visible) {
var show = _.intersection(app.data.tags.getTree(false)[id].up, this.state.tags.filtered).length > 0
return visible && show;
} else {
return visible;
}
}
},
isToggle: function (id) {
if (this.isRootParent()) {
return (typeof (this.props.selectionHash[id]) !== 'undefined' ? this.props.selectionHash[id] : false);
}
},
//TODO: add "Nothing found" message if rootParent has no items
//TODO: replace "key:id" with something shorter like "lib.cid()"
render: function () {
return (
React.DOM.div({ className: 'retag' },
_.map(this.props.tree, function (treeItem) {
var tag = treeItem.tag;
var id = app.data.tags.get(tag).get('_id');
var childrenVisible = this.props.isChildrenVisible || this.rootParent().isChildrenVisible(id);
var visible = (this.rootParent().isVisible(id) || childrenVisible) && app.data.tags.get(id).isActive();
if (visible) {
var newTree = _.reduce(treeItem.down, function (memo, subTag) {
memo[subTag] = app.data.tags[this.props.hasNotes ? 'getTreeTags' : 'getTree'](false)[subTag];
return memo;
}, {}, this);
newTree = app.data.tags.treeToArray(newTree);
var isSelected = this.props.active && !!_.find(app.navigation.query.tags(), function (queryItem) { return queryItem.query === id });
return app.view.sidepane.component.checkitem(
{
key: app.lib.uidmap(id),
text: app.data.tags.get(tag).data('tag').name,
icon: 'icon-blank',
color: app.lib.color(app.data.tags.get(tag).data('color')),
click: this.rootParent().toggle.bind(null, id),
checked: this.rootParent().isToggle(id),
expanded: this.rootParent().isExpanded(id),
forceExpanded: this.rootParent().forceExpander,
visible: visible,
selected: isSelected
},
treeItem.down.length > 0 ? app.view.context.components.retagitem({
tree: newTree,
rootParent: this.props.rootParent || this,
active: this.props.active,
isChildrenVisible: childrenVisible
}) : null
);
} else {
return null
}
}, this)
)
);
}
}); |
module.exports.watch = watch;
module.exports.resetWatchers = resetWatchers;
var debug = require('debug')('nodemon:watch');
var debugRoot = require('debug')('nodemon');
var chokidar = require('chokidar');
var undefsafe = require('undefsafe');
var config = require('../config');
var path = require('path');
var utils = require('../utils');
var bus = utils.bus;
var match = require('./match');
var watchers = [];
var debouncedBus;
bus.on('reset', resetWatchers);
function resetWatchers() {
debugRoot('resetting watchers');
watchers.forEach(function (watcher) {
watcher.close();
});
watchers = [];
}
function watch() {
if (watchers.length) {
debug('early exit on watch, still watching (%s)', watchers.length);
return;
}
var dirs = [].slice.call(config.dirs);
debugRoot('start watch on: %s', dirs.join(', '));
const rootIgnored = config.options.ignore;
debugRoot('ignored', rootIgnored);
var promises = [];
var watchedFiles = [];
dirs.forEach(function (dir) {
var promise = new Promise(function (resolve) {
var dotFilePattern = /[/\\]\./;
var ignored = Array.from(rootIgnored);
// don't ignore dotfiles if explicitly watched.
if (!dir.match(dotFilePattern)) {
ignored.push(dotFilePattern);
}
var watchOptions = {
ignored: ignored,
persistent: true,
usePolling: config.options.legacyWatch || false,
interval: config.options.pollingInterval,
};
if (utils.isWindows) {
watchOptions.disableGlobbing = true;
}
if (process.env.TEST) {
watchOptions.useFsEvents = false;
}
var watcher = chokidar.watch(
dir,
Object.assign({}, watchOptions, config.watchOptions || {})
);
watcher.ready = false;
var total = 0;
watcher.on('change', filterAndRestart);
watcher.on('add', function (file) {
if (watcher.ready) {
return filterAndRestart(file);
}
watchedFiles.push(file);
watchedFiles = Array.from(new Set(watchedFiles)); // ensure no dupes
total = watchedFiles.length;
debug('watching dir: %s', file);
});
watcher.on('ready', function () {
watcher.ready = true;
resolve(total);
debugRoot('watch is complete');
});
watcher.on('error', function (error) {
if (error.code === 'EINVAL') {
utils.log.error(
'Internal watch failed. Likely cause: too many ' +
'files being watched (perhaps from the root of a drive?\n' +
'See https://github.com/paulmillr/chokidar/issues/229 for details'
);
} else {
utils.log.error('Internal watch failed: ' + error.message);
process.exit(1);
}
});
watchers.push(watcher);
});
promises.push(promise);
});
return Promise.all(promises).then(function (res) {
var total = res.reduce(function (acc, curr) {
acc += curr;
return acc;
}, 0);
var count = total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
utils.log.detail('watching ' + count + ' files');
return watchedFiles;
});
}
function filterAndRestart(files) {
if (!Array.isArray(files)) {
files = [files];
}
if (files.length) {
if (utils.isWindows) {
// ensure the drive letter is in uppercase (c:\foo -> C:\foo)
files = files.map(function (f) {
return f[0].toUpperCase() + f.slice(1);
});
}
var cwd = process.cwd();
utils.log.detail(
'files triggering change check: ' +
files
.map(function (file) {
return path.relative(cwd, file);
})
.join(', ')
);
var matched = match(
files,
config.options.monitor,
undefsafe(config, 'options.execOptions.ext')
);
// if there's no matches, then test to see if the changed file is the
// running script, if so, let's allow a restart
if (config.options.execOptions.script) {
const script = path.resolve(config.options.execOptions.script);
if (matched.result.length === 0 && script) {
const length = script.length;
files.find(file => {
if (file.substr(-length, length) === script) {
matched = {
result: [file],
total: 1,
};
return true;
}
});
}
}
utils.log.detail(
'changes after filters (before/after): ' +
[files.length, matched.result.length].join('/')
);
// reset the last check so we're only looking at recently modified files
config.lastStarted = Date.now();
if (matched.result.length) {
if (config.options.delay > 0) {
utils.log.detail('delaying restart for ' + config.options.delay + 'ms');
if (debouncedBus === undefined) {
debouncedBus = debounce(restartBus, config.options.delay);
}
debouncedBus(matched);
} else {
return restartBus(matched);
}
}
}
}
function restartBus(matched) {
utils.log.status('restarting due to changes...');
matched.result.map(function (file) {
utils.log.detail(path.relative(process.cwd(), file));
});
if (config.options.verbose) {
utils.log._log('');
}
bus.emit('restart', matched.result);
}
function debounce(fn, delay) {
var timer = null;
return function () {
var context = this;
var args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
} |
#include "accdet.h"
// add by baibo@yulong 20150313 hookswitch test in factory mode begin
#include <linux/proc_fs.h>
// add by baibo@yulong 20150313 hookswitch test in factory mode end
//#include <mach/mt_boot.h>
#include <cust_eint.h>
#include <cust_gpio_usage.h>
#include <mach/mt_gpio.h>
#include <mach/eint.h>
#include <mach/upmu_common.h>
#include <upmu_hw.h>
#include <linux/timer.h>
#include <linux/of.h>
#include <linux/of_irq.h>
#define <API key>
#define DEBUG_THREAD 1
#define REGISTER_VALUE(x) (x - 1)
#if defined(<API key>)
extern struct i2c_client *ts3a225e_i2c_client;
#endif
static int <API key> = 0x400;
static int debug_enable = 1;
int cur_key = 0;
s8 <API key>;
int accdet_irq;
unsigned int gpiopin,headsetdebounce;
struct <API key> *<API key> = NULL;
extern u32 <API key>(int i);
#define ACCDET_DEBUG(format, args...) do{ \
if(debug_enable) \
{\
printk(KERN_WARNING format,##args);\
}\
}while(0)
static struct switch_dev accdet_data;
static struct input_dev *kpd_accdet_dev;
static struct cdev *accdet_cdev;
static struct class *accdet_class = NULL;
static struct device *accdet_nor_device = NULL;
static dev_t accdet_devno;
static int pre_status = 0;
static int pre_state_swctrl = 0;
static int accdet_status = PLUG_OUT;
static int cable_type = 0;
#ifdef <API key>
//add for new feature PIN recognition
static int <API key> = 0;
static int show_icon_delay = 0;
#endif
#if defined(<API key>)
#define <API key> 0
#define <API key> 1
#define <API key> 2
#define <API key> 3
kal_uint8 ts3a225e_reg_value[7]={0};
kal_uint8 <API key>=<API key>;
extern int ts3a225e_read_byte(kal_uint8 cmd, kal_uint8 *returnData);
extern int ts3a225e_write_byte(kal_uint8 cmd, kal_uint8 writeData);
#endif
//ALPS443614: EINT trigger during accdet irq flow running, need add sync method
//between both
static int <API key> = 0;
static s64 long_press_time_ns = 0 ;
static int g_accdet_first = 1;
static bool IRQ_CLR_FLAG = FALSE;
static volatile int call_status =0;
static volatile int button_status = 0;
struct wake_lock accdet_suspend_lock;
struct wake_lock accdet_irq_lock;
struct wake_lock accdet_key_lock;
struct wake_lock accdet_timer_lock;
static struct work_struct accdet_work;
static struct workqueue_struct * accdet_workqueue = NULL;
static int long_press_time;
static DEFINE_MUTEX(<API key>);
// add by baibo@yulong 20150313 hookswitch test in factory mode begin
#define AUDIO_AUTO_TEST
#ifdef AUDIO_AUTO_TEST
enum audio_hook_mode
{
HOOK_MODE_INVALID = 0x00,
HOOK_MODE_TEST = 0x01,
HOOK_MODE_RECORD = 0x02,
HOOK_MODE_CALL = 0x04,
};
static int g_hook_test = HOOK_MODE_INVALID;
#endif
// add by baibo@yulong 20150313 hookswitch test in factory mode end
static inline void <API key>(void);
static inline void <API key>(void);
#if defined ACCDET_EINT || defined ACCDET_EINT_IRQ
static struct work_struct accdet_eint_work;
static struct workqueue_struct * <API key> = NULL;
static inline void accdet_init(void);
#define <API key> (6 *HZ) //6 seconds
struct timer_list micbias_timer;
static void disable_micbias(unsigned long a);
/* Used to let accdet know if the pin has been fully plugged-in */
#define EINT_PIN_PLUG_IN (1)
#define EINT_PIN_PLUG_OUT (0)
volatile int cur_eint_state = EINT_PIN_PLUG_OUT;
static struct work_struct accdet_disable_work;
static struct workqueue_struct * <API key> = NULL;
#else
//static int <API key> =0;
#endif//end ACCDET_EINT
extern S32 pwrap_read( U32 adr, U32 *rdata );
extern S32 pwrap_write( U32 adr, U32 wdata );
extern struct <API key>* <API key>(void);
extern struct headset_key_custom* <API key>(void);
extern struct file_operations *accdet_get_fops(void);//from accdet_drv.c
extern struct platform_driver accdet_driver_func(void);//from accdet_drv.c
#ifdef DEBUG_THREAD
extern void <API key>(void); //from accdet_drv.c
#endif
static U32 pmic_pwrap_read(U32 addr);
static void pmic_pwrap_write(U32 addr, unsigned int wdata);
// add by baibo@yulong 20150313 hookswitch test in factory mode begin
#ifdef AUDIO_AUTO_TEST
#define <API key> "driver/hook_test"
static int <API key>(char *page, char **start, off_t off,
int count, int *eof, void *_param)
{
char *buf = page;
char *next = buf;
unsigned size = count;
int t = 0;
t = scnprintf(next, size, "button_status=%d, hook_test=0x%x, call_state=%d.\n",
button_status, g_hook_test, call_status);
size -= t;
next += t;
*eof = 1;
return count - size;
}
static int <API key>(struct file *file, const char __user *buffer,
unsigned long count, void *_param)
{
char kbuf[128];
char *buf = kbuf;
unsigned int val = 0;
if (count >= 128)
{
return -EINVAL;
}
if (copy_from_user(buf, buffer, count))
{
return -EINVAL;
}
sscanf(buf, "%d", &val);
g_hook_test = val;
printk(KERN_INFO "<API key> hook_test=%d.\n", val);
#if 0
mutex_lock(&data->lock);
<API key>(data);
mutex_unlock(&data->lock);
#endif
return count;
}
#endif
static const struct file_operations hook_test_fops = {
.write = <API key>,
.read = <API key>,
};
// add by baibo@yulong 20150313 hookswitch test in factory mode end
/*** export function **/
void accdet_detect(void)
{
int ret = 0 ;
ACCDET_DEBUG("[Accdet]accdet_detect\n");
accdet_status = PLUG_OUT;
ret = queue_work(accdet_workqueue, &accdet_work);
if(!ret)
{
ACCDET_DEBUG("[Accdet]accdet_detect:accdet_work return:%d!\n", ret);
}
return;
}
EXPORT_SYMBOL(accdet_detect);
void accdet_state_reset(void)
{
ACCDET_DEBUG("[Accdet]accdet_state_reset\n");
accdet_status = PLUG_OUT;
cable_type = NO_DEVICE;
return;
}
EXPORT_SYMBOL(accdet_state_reset);
int <API key>(void)
{
return cable_type;
}
void <API key>(int enable)
{
if(enable) {
pmic_pwrap_write(ACCDET_EINT_NV, pmic_pwrap_read(ACCDET_EINT_NV)|ACCDET_BF_ON);
//ACCDET_DEBUG("ACCDET enable switch \n");
}else {
pmic_pwrap_write(ACCDET_EINT_NV, pmic_pwrap_read(ACCDET_EINT_NV)&~(ACCDET_BF_ON));
//ACCDET_DEBUG("ACCDET diable switch \n");
}
}
/*******static function defination **/
static U64 <API key>(void)
{
return sched_clock();
}
static BOOL accdet_timeout_ns (U64 start_time_ns, U64 timeout_time_ns)
{
U64 cur_time=0;
U64 elapse_time=0;
// get current tick
cur_time = <API key>();
if(cur_time < start_time_ns){
ACCDET_DEBUG("@@@@Timer overflow! start%lld cur timer%lld\n",start_time_ns,cur_time);
start_time_ns=cur_time;
timeout_time_ns=400*1000; //400us
ACCDET_DEBUG("@@@@reset timer! start%lld setting%lld\n",start_time_ns,timeout_time_ns);
}
elapse_time=<API key>;
// check if timeout
if (timeout_time_ns <= elapse_time)
{
// timeout
ACCDET_DEBUG("@@@@ACCDET IRQ clear Timeout\n");
return FALSE;
}
return TRUE;
}
// pmic wrap read and write func
static U32 pmic_pwrap_read(U32 addr)
{
U32 val =0;
pwrap_read(addr, &val);
//ACCDET_DEBUG("[Accdet]wrap write func addr=0x%x, val=0x%x\n", addr, val);
return val;
}
static void pmic_pwrap_write(unsigned int addr, unsigned int wdata)
{
pwrap_write(addr, wdata);
//ACCDET_DEBUG("[Accdet]wrap write func addr=0x%x, wdate=0x%x\n", addr, wdata);
}
static int <API key>(int deCount)
{
unsigned int vol_val = 0;
pmic_pwrap_write(<API key>, ACCDET_CH_REQ_EN);
//ACCDET_DEBUG("ACCDET read ACCDET_AUXADC_CTL= 0x%x \n\r", pmic_pwrap_read(ACCDET_AUXADC_CTL));
mdelay(3);
while((pmic_pwrap_read(ACCDET_AUXADC_REG)&ACCDET_DATA_READY)!=ACCDET_DATA_READY) {} //wait AUXADC data ready
vol_val = (pmic_pwrap_read(ACCDET_AUXADC_REG) & ACCDET_DATA_MASK);
//ACCDET_DEBUG("ACCDET read RAW data: 0x%x!! \n\r", vol_val);
//vol_val = (vol_val*1800)/32768; //mv
vol_val = (vol_val*1800)/4096;
ACCDET_DEBUG("ACCDET read Voltage: %d mv!! \n\r", vol_val);
ACCDET_DEBUG("ACCDET <API key>: %d mv!! \n\r", <API key>);
vol_val -= <API key>;
ACCDET_DEBUG("ACCDET read Voltage1: %d mv!! \n\r", vol_val);
return vol_val;
}
#if !defined ACCDET_EINT && !defined ACCDET_EINT_IRQ
//detect if remote button is short pressed or long pressed
static bool is_long_press(void)
{
int current_status = 0;
int index = 0;
int count = long_press_time / 100;
while(index++ < count)
{
current_status = ((pmic_pwrap_read(ACCDET_STATE_RG) & 0xc0)>>6);
if(current_status != 0)
{
return false;
}
msleep(100);
}
return true;
}
#endif
#ifdef ACCDET_PIN_SWAP
static void <API key>(void)
{
mt_set_gpio_mode(GPIO_FSA8049_PIN, <API key>);
mt_set_gpio_dir(GPIO_FSA8049_PIN, GPIO_DIR_OUT);
mt_set_gpio_out(GPIO_FSA8049_PIN, GPIO_OUT_ONE);
}
static void <API key>(void)
{
mt_set_gpio_mode(GPIO_FSA8049_PIN, <API key>);
mt_set_gpio_dir(GPIO_FSA8049_PIN, GPIO_DIR_OUT);
mt_set_gpio_out(GPIO_FSA8049_PIN, GPIO_OUT_ZERO);
}
#endif
static void inline headset_plug_out(void)
{
accdet_status = PLUG_OUT;
cable_type = NO_DEVICE;
//update the cable_type
switch_set_state((struct switch_dev *)&accdet_data, cable_type);
ACCDET_DEBUG( " [accdet] set state in cable_type = NO_DEVICE\n");
}
//Accdet only need this func
static void inline enable_accdet(u32 state_swctrl)
{
// enable ACCDET unit
ACCDET_DEBUG("accdet: enable_accdet\n");
//enable clock
pmic_pwrap_write(TOP_CKPDN_CLR, RG_ACCDET_CLK_CLR);
pmic_pwrap_write(ACCDET_STATE_SWCTRL, pmic_pwrap_read(ACCDET_STATE_SWCTRL)|state_swctrl);
pmic_pwrap_write(ACCDET_CTRL, pmic_pwrap_read(ACCDET_CTRL)|ACCDET_ENABLE);
}
static void inline disable_accdet(void)
{
int irq_temp = 0;
//sync with accdet_irq_handler set clear accdet irq bit to avoid set clear accdet irq bit after disable accdet
//disable accdet irq
pmic_pwrap_write(INT_CON_ACCDET_CLR, RG_ACCDET_IRQ_CLR);
<API key>();
udelay(200);
mutex_lock(&<API key>);
while(pmic_pwrap_read(ACCDET_IRQ_STS) & IRQ_STATUS_BIT)
{
ACCDET_DEBUG("[Accdet]check_cable_type: Clear interrupt on-going....\n");
msleep(5);
}
irq_temp = pmic_pwrap_read(ACCDET_IRQ_STS);
irq_temp = irq_temp & (~IRQ_CLR_BIT);
pmic_pwrap_write(ACCDET_IRQ_STS, irq_temp);
//ACCDET_DEBUG("[Accdet]disable_accdet:Clear interrupt:Done[0x%x]!\n", pmic_pwrap_read(ACCDET_IRQ_STS));
mutex_unlock(&<API key>);
// disable ACCDET unit
ACCDET_DEBUG("accdet: disable_accdet\n");
pre_state_swctrl = pmic_pwrap_read(ACCDET_STATE_SWCTRL);
#ifdef ACCDET_EINT
pmic_pwrap_write(ACCDET_STATE_SWCTRL, 0);
pmic_pwrap_write(ACCDET_CTRL, ACCDET_DISABLE);
//disable clock and Analog control
//<API key>(0x0);
pmic_pwrap_write(TOP_CKPDN_SET, RG_ACCDET_CLK_SET);
#endif
#ifdef ACCDET_EINT_IRQ
pmic_pwrap_write(ACCDET_STATE_SWCTRL, ACCDET_EINT_PWM_EN);
pmic_pwrap_write(ACCDET_CTRL, pmic_pwrap_read(ACCDET_CTRL)&(~(ACCDET_ENABLE)));
//mt_set_gpio_out(<API key>, GPIO_OUT_ZERO);
#endif
}
#if defined ACCDET_EINT || defined ACCDET_EINT_IRQ
static void disable_micbias(unsigned long a)
{
int ret = 0;
ret = queue_work(<API key>, &accdet_disable_work);
if(!ret)
{
ACCDET_DEBUG("[Accdet]disable_micbias:accdet_work return:%d!\n", ret);
}
}
static void <API key>(struct work_struct *work)
{
if(cable_type == HEADSET_NO_MIC) {
#ifdef <API key>
show_icon_delay = 0;
<API key> = 0;
ACCDET_DEBUG("[Accdet] <API key> = %d\n", <API key>);
pmic_pwrap_write(ACCDET_PWM_WIDTH, <API key>->pwm_width);
pmic_pwrap_write(ACCDET_PWM_THRESH, <API key>->pwm_thresh);
#endif
// setting pwm idle;
pmic_pwrap_write(ACCDET_STATE_SWCTRL, pmic_pwrap_read(ACCDET_STATE_SWCTRL)&~<API key>);
#ifdef ACCDET_PIN_SWAP
//<API key>(); //disable GPIOxxx for PIN swap
//ACCDET_DEBUG("[Accdet] FSA8049 disable!\n");
#endif
disable_accdet();
ACCDET_DEBUG("[Accdet] more than 5s MICBIAS : Disabled\n");
}
#ifdef <API key>
else if(cable_type == HEADSET_MIC) {
pmic_pwrap_write(ACCDET_PWM_WIDTH, <API key>->pwm_width);
pmic_pwrap_write(ACCDET_PWM_THRESH, <API key>->pwm_thresh);
ACCDET_DEBUG("[Accdet]pin recog after 5s recover micbias polling!\n");
}
#endif
}
static void <API key>(struct work_struct *work)
{
ACCDET_DEBUG("[Accdet]<API key> cur_eint_state=%d\n", cur_eint_state);
#ifdef ACCDET_EINT_IRQ
int irq_temp = 0;
if (cur_eint_state == EINT_PIN_PLUG_IN) {
ACCDET_DEBUG("[Accdet]EINT func :plug-in\n");
mutex_lock(&<API key>);
<API key> = 1;
mutex_unlock(&<API key>);
wake_lock_timeout(&accdet_timer_lock, 7*HZ);
#ifdef ACCDET_PIN_SWAP
//pmic_pwrap_write(0x0400, pmic_pwrap_read(0x0400)|(1<<14));
msleep(800);
<API key>(); //enable GPIOxxx for PIN swap
ACCDET_DEBUG("[Accdet] FSA8049 enable!\n");
msleep(250); //PIN swap need ms
#endif
accdet_init(); // do set pwm_idle on in accdet_init
#ifdef <API key>
show_icon_delay = 1;
//micbias always on during detected PIN recognition
pmic_pwrap_write(ACCDET_PWM_WIDTH, <API key>->pwm_width);
pmic_pwrap_write(ACCDET_PWM_THRESH, <API key>->pwm_width);
ACCDET_DEBUG("[Accdet]pin recog start! micbias always on!\n");
#endif
//set PWM IDLE on
pmic_pwrap_write(ACCDET_STATE_SWCTRL, (pmic_pwrap_read(ACCDET_STATE_SWCTRL)|<API key>));
//enable ACCDET unit
enable_accdet(ACCDET_SWCTRL_EN);
} else {
//EINT_PIN_PLUG_OUT
//Disable ACCDET
ACCDET_DEBUG("[Accdet]EINT func :plug-out\n");
mutex_lock(&<API key>);
<API key> = 0;
mutex_unlock(&<API key>);
del_timer_sync(&micbias_timer);
#ifdef <API key>
show_icon_delay = 0;
<API key> = 0;
#endif
#ifdef ACCDET_PIN_SWAP
//pmic_pwrap_write(0x0400, pmic_pwrap_read(0x0400)&~(1<<14));
<API key>(); //disable GPIOxxx for PIN swap
ACCDET_DEBUG("[Accdet] FSA8049 disable!\n");
#endif
//<API key>(0);
disable_accdet();
headset_plug_out();
//recover EINT irq clear bit
TODO: need think~~~
irq_temp = pmic_pwrap_read(ACCDET_IRQ_STS);
irq_temp = irq_temp & (~IRQ_EINT_CLR_BIT);
pmic_pwrap_write(ACCDET_IRQ_STS, irq_temp);
}
#else
//KE under fastly plug in and plug out
if (cur_eint_state == EINT_PIN_PLUG_IN) {
ACCDET_DEBUG("[Accdet]EINT func :plug-in\n");
mutex_lock(&<API key>);
<API key> = 1;
mutex_unlock(&<API key>);
wake_lock_timeout(&accdet_timer_lock, 7*HZ);
#ifdef ACCDET_PIN_SWAP
//pmic_pwrap_write(0x0400, pmic_pwrap_read(0x0400)|(1<<14));
msleep(800);
<API key>(); //enable GPIOxxx for PIN swap
ACCDET_DEBUG("[Accdet] FSA8049 enable!\n");
msleep(250); //PIN swap need ms
#endif
#if defined(<API key>)
ACCDET_DEBUG("[Accdet] TS3A225E enable!\n");
ts3a225e_write_byte(0x04, 0x01);
msleep(500);
ts3a225e_read_byte(0x02, &ts3a225e_reg_value[1]);
ts3a225e_read_byte(0x03, &ts3a225e_reg_value[2]);
ts3a225e_read_byte(0x05, &ts3a225e_reg_value[4]);
ts3a225e_read_byte(0x06, &ts3a225e_reg_value[5]);
ACCDET_DEBUG("[Accdet] TS3A225E CTRL1=%x!\n", ts3a225e_reg_value[1]);
ACCDET_DEBUG("[Accdet] TS3A225E CTRL2=%x!\n", ts3a225e_reg_value[2]);
ACCDET_DEBUG("[Accdet] TS3A225E DAT1=%x!\n", ts3a225e_reg_value[4]);
ACCDET_DEBUG("[Accdet] TS3A225E INT=%x!\n", ts3a225e_reg_value[5]);
if (ts3a225e_reg_value[5] == 0x01)
{
ACCDET_DEBUG("[Accdet] TS3A225E A standard TSR headset detected, RING2 and SLEEVE shorted!\n");
<API key> = <API key>;
ts3a225e_write_byte(0x02, 0x07);
ts3a225e_write_byte(0x03, 0xf3);
msleep(10);
}
else if (ts3a225e_reg_value[5] == 0x02)
{
ACCDET_DEBUG("[Accdet] TS3A225E A microphone detected on either RING2 or SLEEVE!\n");
if ((ts3a225e_reg_value[4]&0x40) == 0x00)
{
<API key> = <API key>;
}
else
{
<API key> = <API key>;
}
}
else
{
ACCDET_DEBUG("[Accdet] TS3A225E Detection sequence completed without successful!\n");
}
#endif
accdet_init();// do set pwm_idle on in accdet_init
#ifdef <API key>
show_icon_delay = 1;
//micbias always on during detected PIN recognition
pmic_pwrap_write(ACCDET_PWM_WIDTH, <API key>->pwm_width);
pmic_pwrap_write(ACCDET_PWM_THRESH, <API key>->pwm_width);
ACCDET_DEBUG("[Accdet]pin recog start! micbias always on!\n");
#endif
//set PWM IDLE on
pmic_pwrap_write(ACCDET_STATE_SWCTRL, (pmic_pwrap_read(ACCDET_STATE_SWCTRL)|<API key>));
//enable ACCDET unit
enable_accdet(ACCDET_SWCTRL_EN);
} else {
//EINT_PIN_PLUG_OUT
//Disable ACCDET
ACCDET_DEBUG("[Accdet]EINT func :plug-out\n");
mutex_lock(&<API key>);
<API key> = 0;
mutex_unlock(&<API key>);
del_timer_sync(&micbias_timer);
#ifdef <API key>
show_icon_delay = 0;
<API key> = 0;
#endif
#ifdef ACCDET_PIN_SWAP
//pmic_pwrap_write(0x0400, pmic_pwrap_read(0x0400)&~(1<<14));
<API key>(); //disable GPIOxxx for PIN swap
ACCDET_DEBUG("[Accdet] FSA8049 disable!\n");
#endif
#if defined(<API key>)
ACCDET_DEBUG("[Accdet] TS3A225E disable!\n");
<API key> = <API key>;
#endif
//<API key>(0);
disable_accdet();
headset_plug_out();
}
#ifdef CONFIG_OF
enable_irq(accdet_irq);
#else
mt_eint_unmask(<API key>);
#endif
ACCDET_DEBUG("[Accdet]enable_irq !!!!!!\n");
#endif
}
#ifdef CONFIG_OF
static irqreturn_t accdet_eint_func(int irq,void *data)
{
int ret=0;
if(cur_eint_state == EINT_PIN_PLUG_IN )
{
/*
To trigger EINT when the headset was plugged in
We set the polarity back as we initialed.
*/
#ifndef ACCDET_EINT_IRQ
if (<API key> == <API key>){
irq_set_irq_type(accdet_irq,IRQ_TYPE_LEVEL_HIGH);
}else{
irq_set_irq_type(accdet_irq,IRQ_TYPE_LEVEL_LOW);
}
#endif
#ifdef ACCDET_EINT_IRQ
pmic_pwrap_write(ACCDET_EINT_CTL, pmic_pwrap_read(ACCDET_EINT_CTL)&(~(7<<4)));
pmic_pwrap_write(ACCDET_EINT_CTL, pmic_pwrap_read(ACCDET_EINT_CTL)|EINT_IRQ_DE_IN);//debounce=256ms
pmic_pwrap_write(ACCDET_DEBOUNCE3, <API key>->debounce3);
#else
<API key>(gpiopin,headsetdebounce);
#endif
/* update the eint status */
cur_eint_state = EINT_PIN_PLUG_OUT;
//#ifdef ACCDET_LOW_POWER
// del_timer_sync(&micbias_timer);
//#endif
}
else
{
/*
To trigger EINT when the headset was plugged out
We set the opposite polarity to what we initialed.
*/
#ifndef ACCDET_EINT_IRQ
if (<API key> == <API key>){
irq_set_irq_type(accdet_irq,IRQ_TYPE_LEVEL_LOW);
}else{
irq_set_irq_type(accdet_irq,IRQ_TYPE_LEVEL_HIGH);
}
#endif
#ifdef ACCDET_EINT_IRQ
pmic_pwrap_write(ACCDET_EINT_CTL, pmic_pwrap_read(ACCDET_EINT_CTL)&(~(7<<4)));
pmic_pwrap_write(ACCDET_EINT_CTL, pmic_pwrap_read(ACCDET_EINT_CTL)|EINT_IRQ_DE_OUT);//debounce=16ms
#else
<API key>(gpiopin,<API key>*1000);
#endif
/* update the eint status */
cur_eint_state = EINT_PIN_PLUG_IN;
mod_timer(&micbias_timer, jiffies + <API key>);
}
#ifndef ACCDET_EINT_IRQ
disable_irq_nosync(accdet_irq);
#endif
ACCDET_DEBUG("[Accdet]accdet_eint_func after cur_eint_state=%d\n", cur_eint_state);
ret = queue_work(<API key>, &accdet_eint_work);
return IRQ_HANDLED;
}
#else
static void accdet_eint_func(void)
{
int ret=0;
if(cur_eint_state == EINT_PIN_PLUG_IN )
{
/*
To trigger EINT when the headset was plugged in
We set the polarity back as we initialed.
*/
#ifndef ACCDET_EINT_IRQ
if (<API key> == <API key>){
<API key>(<API key>, (1));
}else{
<API key>(<API key>, (0));
}
#endif
#ifdef ACCDET_EINT_IRQ
pmic_pwrap_write(ACCDET_EINT_CTL, pmic_pwrap_read(ACCDET_EINT_CTL)&(~(7<<4)));
pmic_pwrap_write(ACCDET_EINT_CTL, pmic_pwrap_read(ACCDET_EINT_CTL)|EINT_IRQ_DE_IN);//debounce=256ms
#else
<API key>(<API key>, <API key>);
#endif
/* update the eint status */
cur_eint_state = EINT_PIN_PLUG_OUT;
//#ifdef ACCDET_LOW_POWER
// del_timer_sync(&micbias_timer);
//#endif
}
else
{
/*
To trigger EINT when the headset was plugged out
We set the opposite polarity to what we initialed.
*/
#ifndef ACCDET_EINT_IRQ
if (<API key> == <API key>){
<API key>(<API key>, !(1));
}else{
<API key>(<API key>, !(0));
}
#endif
#ifdef ACCDET_EINT_IRQ
pmic_pwrap_write(ACCDET_EINT_CTL, pmic_pwrap_read(ACCDET_EINT_CTL)&(~(7<<4)));
pmic_pwrap_write(ACCDET_EINT_CTL, pmic_pwrap_read(ACCDET_EINT_CTL)|EINT_IRQ_DE_OUT);//debounce=16ms
#else
<API key>(<API key>, <API key>);
#endif
/* update the eint status */
cur_eint_state = EINT_PIN_PLUG_IN;
mod_timer(&micbias_timer, jiffies + <API key>);
}
ACCDET_DEBUG("[Accdet]accdet_eint_func after1 cur_eint_state=%d\n", cur_eint_state);
ret = queue_work(<API key>, &accdet_eint_work);
}
#endif
#ifndef ACCDET_EINT_IRQ
static inline int accdet_setup_eint(void)
{
int ret;
#ifdef CONFIG_OF
u32 ints[2]={0,0};
struct device_node *node;
#endif
/*configure to GPIO function, external interrupt*/
ACCDET_DEBUG("[Accdet]accdet_setup_eint\n");
mt_set_gpio_mode(<API key>, <API key>);
mt_set_gpio_dir(<API key>, GPIO_DIR_IN);
<API key>(<API key>, GPIO_PULL_DISABLE); //To disable GPIO PULL.
#ifdef CONFIG_OF
node = <API key>(NULL,NULL,"mediatek, ACCDET-eint");
if(node) {
<API key>(node,"debounce",ints,ARRAY_SIZE(ints));
gpiopin = ints[0];
headsetdebounce = ints[1];
<API key>(gpiopin,headsetdebounce);
accdet_irq = <API key>(node,0);
ret = request_irq(accdet_irq,accdet_eint_func,IRQF_TRIGGER_NONE,"ACCDET-eint",NULL);
if(ret>0){
ACCDET_DEBUG("[Accdet]EINT IRQ LINE NOT AVAILABLE\n");
}else{
ACCDET_DEBUG("[Accdet]accdet set EINT finished, accdet_irq=%d, headsetdebounce=%d \n", accdet_irq, headsetdebounce);
}
}
else {
ACCDET_DEBUG("[Accdet]%s can't find compatible node\n", __func__);
}
#else
<API key>(<API key>, <API key>);
<API key>(<API key>, <API key>, accdet_eint_func, 0);
ACCDET_DEBUG("[Accdet]accdet set EINT finished, accdet_eint_num=%d, <API key>=%d, <API key>=%d\n", <API key>, <API key>, <API key>);
mt_eint_unmask(<API key>);
#endif
return 0;
}
#endif//ACCDET_EINT_IRQ
#endif//endif ACCDET_EINT
#if defined ACCDET_EINT || defined ACCDET_EINT_IRQ
#define KEY_SAMPLE_PERIOD (60)
#define <API key> (8)
static DEFINE_MUTEX(<API key>);
#define NO_KEY (0x0)
#define UP_KEY (0x01)
#define MD_KEY (0x02)
#define DW_KEY (0x04)
#define AS_KEY (0x08)
#ifndef FOUR_KEY_HEADSET
#define DW_KEY_HIGH_THR (500) //0.50v=500000uv
// modify by baibo@yulong.com 20141118 for hook key detect begin
//#define DW_KEY_THR (220) //0.22v=220000uv
//#define UP_KEY_THR (80) //0.08v=80000uv
#define DW_KEY_THR (170)
#define UP_KEY_THR (90)
// modify by baibo@yulong.com 20141118 for hook key detect end
#define MD_KEY_THR (0)
static int key_check(int b)
{
//ACCDET_DEBUG("adc_data: %d v\n",b);
/* 0.24V ~ */
if((b<DW_KEY_HIGH_THR)&&(b >= DW_KEY_THR))
{
return DW_KEY;
}
else if ((b < DW_KEY_THR)&& (b >= UP_KEY_THR))
{
return UP_KEY;
}
else if ((b < UP_KEY_THR) && (b >= MD_KEY_THR))
{
return MD_KEY;
}
ACCDET_DEBUG("[accdet] leave key_check!!\n");
return NO_KEY;
}
#else
#define DW_KEY_THR (195)
#define UP_KEY_THR (123)
#define AS_KEY_THR (59)
#define MD_KEY_THR (0)
static int key_check(int b)
{
//ACCDET_DEBUG("adc_data: %d v\n",b);
/* 0.24V ~ */
if((b >= DW_KEY_THR))
{
return DW_KEY;
}
else if ((b < DW_KEY_THR)&& (b >= UP_KEY_THR))
{
return UP_KEY;
}
else if ((b < UP_KEY_THR)&& (b >= AS_KEY_THR))
{
return AS_KEY;
}
else if ((b < AS_KEY_THR) && (b >= MD_KEY_THR))
{
return MD_KEY;
}
ACCDET_DEBUG("[accdet] leave key_check!!\n");
return NO_KEY;
}
#endif
static void send_key_event(int keycode,int flag)
{
switch (keycode)
{
case DW_KEY:
input_report_key(kpd_accdet_dev, KEY_VOLUMEDOWN, flag);
input_sync(kpd_accdet_dev);
ACCDET_DEBUG("[accdet]KEY_VOLUMEDOWN %d\n",flag);
break;
case UP_KEY:
input_report_key(kpd_accdet_dev, KEY_VOLUMEUP, flag);
input_sync(kpd_accdet_dev);
ACCDET_DEBUG("[accdet]KEY_VOLUMEUP %d\n",flag);
break;
case MD_KEY:
input_report_key(kpd_accdet_dev, KEY_PLAYPAUSE, flag);
input_sync(kpd_accdet_dev);
ACCDET_DEBUG("[accdet]KEY_PLAYPAUSE %d\n",flag);
break;
case AS_KEY:
input_report_key(kpd_accdet_dev, KEY_VOICECOMMAND, flag);
input_sync(kpd_accdet_dev);
ACCDET_DEBUG("[accdet]KEY_VOICECOMMAND %d\n",flag);
break;
}
}
static void multi_key_detection(int current_status)
{
int m_key = 0;
int cali_voltage=0;
if(0 == current_status){
cali_voltage = <API key>(1);;
m_key = cur_key = key_check(cali_voltage);
}
send_key_event(cur_key, !current_status);
}
#endif
static void <API key>(void)
{
int ret;
ret = queue_work(accdet_workqueue, &accdet_work);
if(!ret)
{
ACCDET_DEBUG("[Accdet]accdet_work return:%d!\n", ret);
}
}
int accdet_irq_handler(void)
{
U64 cur_time = 0;
cur_time = <API key>();
#ifdef ACCDET_EINT_IRQ
ACCDET_DEBUG("[Accdet accdet_irq_handler]<API key>: ACCDET_IRQ_STS = 0x%x\n", pmic_pwrap_read(ACCDET_IRQ_STS));
if((pmic_pwrap_read(ACCDET_IRQ_STS) & IRQ_STATUS_BIT)&&((pmic_pwrap_read(ACCDET_IRQ_STS) & EINT_IRQ_STATUS_BIT)!=EINT_IRQ_STATUS_BIT)) {
<API key>();
if (accdet_status == MIC_BIAS){
//<API key>(1);
pmic_pwrap_write(ACCDET_PWM_WIDTH, REGISTER_VALUE(<API key>->pwm_width));
pmic_pwrap_write(ACCDET_PWM_THRESH, REGISTER_VALUE(<API key>->pwm_width));
}
<API key>();
while(((pmic_pwrap_read(ACCDET_IRQ_STS) & IRQ_STATUS_BIT) && (accdet_timeout_ns(cur_time, ACCDET_TIME_OUT)))) {
}
}else if((pmic_pwrap_read(ACCDET_IRQ_STS) & EINT_IRQ_STATUS_BIT)==EINT_IRQ_STATUS_BIT) {
ACCDET_DEBUG("<API key> = %x\n", <API key>);
if(cur_eint_state == EINT_PIN_PLUG_IN ) {
//#ifdef <API key>
if (<API key> == <API key>){
pmic_pwrap_write(ACCDET_IRQ_STS, pmic_pwrap_read(ACCDET_IRQ_STS)|EINT_IRQ_POL_HIGH);
//#else
}else{
pmic_pwrap_write(ACCDET_IRQ_STS, pmic_pwrap_read(ACCDET_IRQ_STS)&~EINT_IRQ_POL_LOW);
}
//#endif
}else {
//#ifdef <API key>
if (<API key> == <API key>){
pmic_pwrap_write(ACCDET_IRQ_STS, pmic_pwrap_read(ACCDET_IRQ_STS)&~EINT_IRQ_POL_LOW);
}else{
//#else
pmic_pwrap_write(ACCDET_IRQ_STS, pmic_pwrap_read(ACCDET_IRQ_STS)|EINT_IRQ_POL_HIGH);
}
//#endif
}
ACCDET_DEBUG("ACCDET_IRQ_STS = %x\n", pmic_pwrap_read(ACCDET_IRQ_STS));
<API key>();
while(((pmic_pwrap_read(ACCDET_IRQ_STS) & EINT_IRQ_STATUS_BIT) && (accdet_timeout_ns(cur_time, ACCDET_TIME_OUT)))) {
}
accdet_eint_func(accdet_irq, NULL);
}else {
ACCDET_DEBUG("ACCDET IRQ and EINT IRQ don't be triggerred!!\n");
}
#else
if((pmic_pwrap_read(ACCDET_IRQ_STS) & IRQ_STATUS_BIT)) {
<API key>();
}
if (accdet_status == MIC_BIAS){
//<API key>(1);
pmic_pwrap_write(ACCDET_PWM_WIDTH, REGISTER_VALUE(<API key>->pwm_width));
pmic_pwrap_write(ACCDET_PWM_THRESH, REGISTER_VALUE(<API key>->pwm_width));
}
<API key>();
while(((pmic_pwrap_read(ACCDET_IRQ_STS) & IRQ_STATUS_BIT) &&
(accdet_timeout_ns(cur_time, ACCDET_TIME_OUT)))) {
}
#endif
#ifdef ACCDET_NEGV_IRQ
cur_time = <API key>();
if((pmic_pwrap_read(ACCDET_IRQ_STS) & NEGV_IRQ_STATUS_BIT)==NEGV_IRQ_STATUS_BIT) {
ACCDET_DEBUG("[ACCDET NEGV detect]plug in a error Headset\n\r");
pmic_pwrap_write(ACCDET_IRQ_STS, (IRQ_NEGV_CLR_BIT));
while(((pmic_pwrap_read(ACCDET_IRQ_STS) & NEGV_IRQ_STATUS_BIT) &&
(accdet_timeout_ns(cur_time, ACCDET_TIME_OUT)))) {
}
//recover EINT irq clear bit
pmic_pwrap_write(ACCDET_IRQ_STS, (pmic_pwrap_read(ACCDET_IRQ_STS)&(~IRQ_NEGV_CLR_BIT)));
}
#endif
return 1;
}
//clear ACCDET IRQ in accdet register
static inline void <API key>(void)
{
//it is safe by using polling to adjust when to clear IRQ_CLR_BIT
pmic_pwrap_write(ACCDET_IRQ_STS, ((pmic_pwrap_read(ACCDET_IRQ_STS))&0x8000)|(IRQ_CLR_BIT));
//ACCDET_DEBUG("[Accdet]<API key>: ACCDET_IRQ_STS = 0x%x\n", pmic_pwrap_read(ACCDET_IRQ_STS));
}
static inline void <API key>(void)
{
pmic_pwrap_write(ACCDET_IRQ_STS, (((pmic_pwrap_read(ACCDET_IRQ_STS))&0x8000)|IRQ_EINT_CLR_BIT));
//ACCDET_DEBUG("[Accdet]<API key>: ACCDET_IRQ_STS = 0x%x\n", pmic_pwrap_read(ACCDET_IRQ_STS));
}
static inline void check_cable_type(void)
{
int current_status = 0;
int irq_temp = 0; //for clear IRQ_bit
int <API key> = 0;
#ifdef <API key>
int pin_adc_value = 0;
#define PIN_ADC_CHANNEL 5
#endif
current_status = ((pmic_pwrap_read(ACCDET_STATE_RG) & 0xc0)>>6); //A=bit1; B=bit0
ACCDET_DEBUG("[Accdet]accdet interrupt happen:[%s]current AB = %d\n",
<API key>[accdet_status], current_status);
button_status = 0;
pre_status = accdet_status;
//ACCDET_DEBUG("[Accdet]check_cable_type: ACCDET_IRQ_STS = 0x%x\n", pmic_pwrap_read(ACCDET_IRQ_STS));
IRQ_CLR_FLAG = FALSE;
switch(accdet_status)
{
case PLUG_OUT:
#ifdef <API key>
pmic_pwrap_write(ACCDET_DEBOUNCE1, <API key>->debounce1);
#endif
if(current_status == 0)
{
#ifdef <API key>
//micbias always on during detected PIN recognition
pmic_pwrap_write(ACCDET_PWM_WIDTH, <API key>->pwm_width);
pmic_pwrap_write(ACCDET_PWM_THRESH, <API key>->pwm_width);
ACCDET_DEBUG("[Accdet]PIN recognition micbias always on!\n");
ACCDET_DEBUG("[Accdet]before adc read, pin_adc_value = %d mv!\n", pin_adc_value);
msleep(500);
current_status = ((pmic_pwrap_read(ACCDET_STATE_RG) & 0xc0)>>6); //A=bit1; B=bit0
if (current_status == 0 && show_icon_delay != 0)
{
//<API key>(1);//switch on when need to use auxadc read voltage
pin_adc_value = <API key>(1);
ACCDET_DEBUG("[Accdet]pin_adc_value = %d mv!\n", pin_adc_value);
//<API key>(0);
if (180 > pin_adc_value && pin_adc_value> 90)
{
//mt_set_gpio_out(<API key>, GPIO_OUT_ONE);
//ACCDET_DEBUG("[Accdet]PIN recognition change GPIO_OUT!\n");
mutex_lock(&<API key>);
if(1 == <API key>) {
cable_type = HEADSET_NO_MIC;
accdet_status = HOOK_SWITCH;
<API key> = 1;
ACCDET_DEBUG("[Accdet] <API key> = %d\n", <API key>);
}else {
ACCDET_DEBUG("[Accdet] Headset has plugged out\n");
}
mutex_unlock(&<API key>);
}
else
{
mutex_lock(&<API key>);
if(1 == <API key>) {
cable_type = HEADSET_NO_MIC;
accdet_status = HOOK_SWITCH;
}else {
ACCDET_DEBUG("[Accdet] Headset has plugged out\n");
}
mutex_unlock(&<API key>);
}
}
#else
mutex_lock(&<API key>);
if(1 == <API key>) {
cable_type = HEADSET_NO_MIC;
accdet_status = HOOK_SWITCH;
}else {
ACCDET_DEBUG("[Accdet] Headset has plugged out\n");
}
mutex_unlock(&<API key>);
#endif
}
else if(current_status == 1)
{
mutex_lock(&<API key>);
if(1 == <API key>) {
accdet_status = MIC_BIAS;
cable_type = HEADSET_MIC;
pmic_pwrap_write(ACCDET_DEBOUNCE3, <API key>->debounce3*30);//AB=11 debounce=30ms
}else {
ACCDET_DEBUG("[Accdet] Headset has plugged out\n");
}
mutex_unlock(&<API key>);
//ALPS00038030:reduce the time of remote button pressed during incoming call
//solution: reduce hook switch debounce time to 0x400
pmic_pwrap_write(ACCDET_DEBOUNCE0, <API key>);
//recover polling set AB 00-01
#ifdef <API key>
pmic_pwrap_write(ACCDET_PWM_WIDTH, REGISTER_VALUE(<API key>->pwm_width));
pmic_pwrap_write(ACCDET_PWM_THRESH, REGISTER_VALUE(<API key>->pwm_thresh));
#endif
//#ifdef ACCDET_LOW_POWER
//wake_unlock(&accdet_timer_lock);//add for suspend disable accdet more than 5S
//#endif
}
else if(current_status == 3)
{
ACCDET_DEBUG("[Accdet]PLUG_OUT state not change!\n");
#ifdef ACCDET_EINT
ACCDET_DEBUG("[Accdet] do not send plug out event in plug out\n");
#else
mutex_lock(&<API key>);
if(1 == <API key>) {
accdet_status = PLUG_OUT;
cable_type = NO_DEVICE;
}else {
ACCDET_DEBUG("[Accdet] Headset has plugged out\n");
}
mutex_unlock(&<API key>);
#endif
}
else
{
ACCDET_DEBUG("[Accdet]PLUG_OUT can't change to this state!\n");
}
break;
case MIC_BIAS:
//ALPS00038030:reduce the time of remote button pressed during incoming call
//solution: resume hook switch debounce time
pmic_pwrap_write(ACCDET_DEBOUNCE0, <API key>->debounce0);
if(current_status == 0)
{
mutex_lock(&<API key>);
if(1 == <API key>) {
while((pmic_pwrap_read(ACCDET_IRQ_STS) & IRQ_STATUS_BIT) && (<API key><3))
{
ACCDET_DEBUG("[Accdet]check_cable_type: MIC BIAS clear IRQ on-going1....\n");
<API key>++;
msleep(5);
}
irq_temp = pmic_pwrap_read(ACCDET_IRQ_STS);
irq_temp = irq_temp & (~IRQ_CLR_BIT);
pmic_pwrap_write(ACCDET_IRQ_STS, irq_temp);
IRQ_CLR_FLAG = TRUE;
accdet_status = HOOK_SWITCH;
}else {
ACCDET_DEBUG("[Accdet] Headset has plugged out\n");
}
mutex_unlock(&<API key>);
button_status = 1;
if(button_status)
{
// add by baibo@yulong 20150313 hookswitch test in factory mode begin
#ifdef AUDIO_AUTO_TEST
// audio auto test
if (g_hook_test == HOOK_MODE_TEST) // only set test flag
{
ACCDET_DEBUG("@@## AUDIO_AUTO_TEST g_hook_test == HOOK_MODE_TEST\n");
input_report_key(kpd_accdet_dev, KEY_STOPCD, 1);
input_sync(kpd_accdet_dev);
break;
}
#endif // AUDIO_AUTO_TEST
// add by baibo@yulong 20150313 hookswitch test in factory mode end
mutex_lock(&<API key>);
if(1 == <API key>) {
multi_key_detection(current_status);
}else {
ACCDET_DEBUG("[Accdet] multi_key_detection: Headset has plugged out\n");
}
mutex_unlock(&<API key>);
//<API key>(0);
//recover pwm frequency and duty
pmic_pwrap_write(ACCDET_PWM_WIDTH, REGISTER_VALUE(<API key>->pwm_width));
pmic_pwrap_write(ACCDET_PWM_THRESH, REGISTER_VALUE(<API key>->pwm_thresh));
}
}
else if(current_status == 1)
{
mutex_lock(&<API key>);
if(1 == <API key>) {
accdet_status = MIC_BIAS;
cable_type = HEADSET_MIC;
ACCDET_DEBUG("[Accdet]MIC_BIAS state not change!\n");
}else {
ACCDET_DEBUG("[Accdet] Headset has plugged out\n");
}
mutex_unlock(&<API key>);
}
else if(current_status == 3)
{
#if defined ACCDET_EINT || defined ACCDET_EINT_IRQ
ACCDET_DEBUG("[Accdet]do not send plug ou in micbiast\n");
mutex_lock(&<API key>);
if(1 == <API key>) {
accdet_status = PLUG_OUT;
}else {
ACCDET_DEBUG("[Accdet] Headset has plugged out\n");
}
mutex_unlock(&<API key>);
#else
mutex_lock(&<API key>);
if(1 == <API key>) {
accdet_status = PLUG_OUT;
cable_type = NO_DEVICE;
}else {
ACCDET_DEBUG("[Accdet] Headset has plugged out\n");
}
mutex_unlock(&<API key>);
#endif
}
else
{
ACCDET_DEBUG("[Accdet]MIC_BIAS can't change to this state!\n");
}
break;
case HOOK_SWITCH:
if(current_status == 0)
{
mutex_lock(&<API key>);
if(1 == <API key>) {
//for avoid 01->00 framework of Headset will report press key info for Audio
//cable_type = HEADSET_NO_MIC;
//accdet_status = HOOK_SWITCH;
ACCDET_DEBUG("[Accdet]HOOK_SWITCH state not change!\n");
}else {
ACCDET_DEBUG("[Accdet] Headset has plugged out\n");
}
mutex_unlock(&<API key>);
}
else if(current_status == 1)
{
// add by baibo@yulong 20150313 hookswitch test in factory mode begin
#ifdef AUDIO_AUTO_TEST
// audio auto test
if (g_hook_test == HOOK_MODE_TEST) // only set test flag
{
ACCDET_DEBUG("@@## [Accdet] AUDIO_AUTO_TEST press up\n");
input_report_key(kpd_accdet_dev, KEY_STOPCD, 0);
input_sync(kpd_accdet_dev);
break;
}
#endif
// add by baibo@yulong 20150313 hookswitch test in factory mode end
mutex_lock(&<API key>);
if(1 == <API key>) {
multi_key_detection(current_status);
accdet_status = MIC_BIAS;
cable_type = HEADSET_MIC;
}else {
ACCDET_DEBUG("[Accdet] Headset has plugged out\n");
}
mutex_unlock(&<API key>);
//<API key>(0);
#ifdef <API key>
<API key> = 0;
ACCDET_DEBUG("[Accdet] <API key> = %d\n", <API key>);
pmic_pwrap_write(ACCDET_PWM_WIDTH, REGISTER_VALUE(<API key>->pwm_width));
pmic_pwrap_write(ACCDET_PWM_THRESH, REGISTER_VALUE(<API key>->pwm_thresh));
#endif
//ALPS00038030:reduce the time of remote button pressed during incoming call
//solution: reduce hook switch debounce time to 0x400
pmic_pwrap_write(ACCDET_DEBOUNCE0, <API key>);
//#ifdef ACCDET_LOW_POWER
//wake_unlock(&accdet_timer_lock);//add for suspend disable accdet more than 5S
//#endif
}
else if(current_status == 3)
{
#ifdef <API key>
<API key> = 0;
ACCDET_DEBUG("[Accdet] <API key> = %d\n", <API key>);
mutex_lock(&<API key>);
if(1 == <API key>) {
accdet_status = PLUG_OUT;
}else {
ACCDET_DEBUG("[Accdet] Headset has plugged out\n");
}
mutex_unlock(&<API key>);
#endif
#if defined ACCDET_EINT || defined ACCDET_EINT_IRQ
ACCDET_DEBUG("[Accdet] do not send plug out event in hook switch\n");
mutex_lock(&<API key>);
if(1 == <API key>) {
accdet_status = PLUG_OUT;
}else {
ACCDET_DEBUG("[Accdet] Headset has plugged out\n");
}
mutex_unlock(&<API key>);
#else
mutex_lock(&<API key>);
if(1 == <API key>) {
accdet_status = PLUG_OUT;
cable_type = NO_DEVICE;
}else {
ACCDET_DEBUG("[Accdet] Headset has plugged out\n");
}
mutex_unlock(&<API key>);
#endif
}
else
{
ACCDET_DEBUG("[Accdet]HOOK_SWITCH can't change to this state!\n");
}
break;
case STAND_BY:
if(current_status == 3)
{
#if defined ACCDET_EINT || defined ACCDET_EINT_IRQ
ACCDET_DEBUG("[Accdet]accdet do not send plug out event in stand by!\n");
#else
mutex_lock(&<API key>);
if(1 == <API key>) {
accdet_status = PLUG_OUT;
cable_type = NO_DEVICE;
}else {
ACCDET_DEBUG("[Accdet] Headset has plugged out\n");
}
mutex_unlock(&<API key>);
#endif
}
else
{
ACCDET_DEBUG("[Accdet]STAND_BY can't change to this state!\n");
}
break;
default:
ACCDET_DEBUG("[Accdet]check_cable_type: accdet current status error!\n");
break;
}
if(!IRQ_CLR_FLAG)
{
mutex_lock(&<API key>);
if(1 == <API key>) {
while((pmic_pwrap_read(ACCDET_IRQ_STS) & IRQ_STATUS_BIT) && (<API key><3))
{
ACCDET_DEBUG("[Accdet]check_cable_type: Clear interrupt on-going2....\n");
<API key>++;
msleep(5);
}
}
irq_temp = pmic_pwrap_read(ACCDET_IRQ_STS);
irq_temp = irq_temp & (~IRQ_CLR_BIT);
pmic_pwrap_write(ACCDET_IRQ_STS, irq_temp);
mutex_unlock(&<API key>);
IRQ_CLR_FLAG = TRUE;
//ACCDET_DEBUG("[Accdet]check_cable_type:Clear interrupt:Done[0x%x]!\n", pmic_pwrap_read(ACCDET_IRQ_STS));
}
else
{
IRQ_CLR_FLAG = FALSE;
}
ACCDET_DEBUG("[Accdet]cable type:[%s], status switch:[%s]->[%s]\n",
<API key>[cable_type], <API key>[pre_status],
<API key>[accdet_status]);
}
static void <API key>(struct work_struct *work)
{
wake_lock(&accdet_irq_lock);
check_cable_type();
#ifdef ACCDET_PIN_SWAP
#ifdef <API key>
if (<API key> == 1)
{
<API key> = 0;
<API key>();
cable_type = HEADSET_NO_MIC;
accdet_status = PLUG_OUT;
}
#endif
#endif
mutex_lock(&<API key>);
if(1 == <API key>) {
switch_set_state((struct switch_dev *)&accdet_data, cable_type);
}else {
ACCDET_DEBUG("[Accdet] Headset has plugged out don't set accdet state\n");
}
mutex_unlock(&<API key>);
ACCDET_DEBUG( " [accdet] set state in cable_type status\n");
wake_unlock(&accdet_irq_lock);
}
void <API key>(void)
{
s16 efusevalue;
efusevalue = (s16)<API key>(0x10);
ACCDET_DEBUG("accdet efusevalue = 0x%x\n", efusevalue);
//ACCDET_DEBUG("accdet efusevalue[1] = 0x%x\n", efusevalue[1]);
<API key> = (efusevalue>>8)&0xFF;
ACCDET_DEBUG("<API key> = %x\n", <API key>);
ACCDET_DEBUG("<API key> = %d\n", <API key>);
<API key> = (<API key>/2);
ACCDET_DEBUG("<API key> = %x\n", <API key>);
ACCDET_DEBUG("<API key> = %d\n", <API key>);
}
static inline void accdet_init(void)
{
ACCDET_DEBUG("[Accdet]accdet hardware init\n");
//clock
pmic_pwrap_write(TOP_CKPDN_CLR, RG_ACCDET_CLK_CLR);
//ACCDET_DEBUG("[Accdet]accdet TOP_CKPDN=0x%x!\n", pmic_pwrap_read(TOP_CKPDN));
//reset the accdet unit
//ACCDET_DEBUG("ACCDET reset : reset start!! \n\r");
pmic_pwrap_write(TOP_RST_ACCDET_SET, ACCDET_RESET_SET);
//ACCDET_DEBUG("ACCDET reset function test: reset finished!! \n\r");
pmic_pwrap_write(TOP_RST_ACCDET_CLR, ACCDET_RESET_CLR);
//init pwm frequency and duty
pmic_pwrap_write(ACCDET_PWM_WIDTH, REGISTER_VALUE(<API key>->pwm_width));
pmic_pwrap_write(ACCDET_PWM_THRESH, REGISTER_VALUE(<API key>->pwm_thresh));
pmic_pwrap_write(ACCDET_STATE_SWCTRL, 0x07);
//rise and fall delay of PWM
pmic_pwrap_write(ACCDET_EN_DELAY_NUM,
(<API key>->fall_delay << 15 | <API key>->rise_delay));
// init the debounce time
#ifdef <API key>
pmic_pwrap_write(ACCDET_DEBOUNCE0, <API key>->debounce0);
pmic_pwrap_write(ACCDET_DEBOUNCE1, 0xFFFF);//2.0s
pmic_pwrap_write(ACCDET_DEBOUNCE3, <API key>->debounce3);
pmic_pwrap_write(ACCDET_DEBOUNCE4, ACCDET_DE4);
#else
pmic_pwrap_write(ACCDET_DEBOUNCE0, <API key>->debounce0);
pmic_pwrap_write(ACCDET_DEBOUNCE1, <API key>->debounce1);
pmic_pwrap_write(ACCDET_DEBOUNCE3, <API key>->debounce3);
pmic_pwrap_write(ACCDET_DEBOUNCE4, ACCDET_DE4);
#endif
//enable INT
#ifdef ACCDET_EINT_IRQ
pmic_pwrap_write(ACCDET_IRQ_STS, pmic_pwrap_read(ACCDET_IRQ_STS)&(~IRQ_EINT_CLR_BIT));
#endif
#ifdef ACCDET_EINT
pmic_pwrap_write(ACCDET_IRQ_STS, pmic_pwrap_read(ACCDET_IRQ_STS)&(~IRQ_CLR_BIT));
#endif
//ACCDET_DEBUG("[Accdet_init]ACCDET_IRQ_STS = 0x%x\n", pmic_pwrap_read(ACCDET_IRQ_STS));
pmic_pwrap_write(INT_CON_ACCDET_SET, RG_ACCDET_IRQ_SET);
#ifdef ACCDET_EINT_IRQ
pmic_pwrap_write(INT_CON_ACCDET_SET, <API key>);
#endif
#ifdef ACCDET_NEGV_IRQ
pmic_pwrap_write(INT_CON_ACCDET_SET, <API key>);
#endif
#ifndef ACCDET_WQHD
<API key>(<API key>, ACCDET_MIC_VOL);
#else
pmic_pwrap_write(ACCDET_ADC_REG, 0x068F);//for wqhd project
#endif
pmic_pwrap_write(ACCDET_RSV, 0x1290); ///TODO: need confirm pull low,6328 bit[12]=1
#ifdef ACCDET_EINT_IRQ
pmic_pwrap_write(ACCDET_EINT_NV, pmic_pwrap_read(ACCDET_EINT_NV)|ACCDET_EINT_CON_EN);
#endif
#ifdef ACCDET_NEGV_IRQ
pmic_pwrap_write(ACCDET_EINT_NV, pmic_pwrap_read(ACCDET_EINT_NV)|ACCDET_NEGV_DT_EN);
#endif
#if (ACCDET_MIC_MODE==1) // ACC mode
<API key>(<API key>, 0);
#elif (ACCDET_MIC_MODE==2) // Low cost mode without internal bias
pmic_pwrap_write(ACCDET_RSV, pmic_pwrap_read(ACCDET_RSV)|ACCDET_INPUT_MICP);
#elif (ACCDET_MIC_MODE==6) // Low cost mode with internal bias
pmic_pwrap_write(ACCDET_RSV, pmic_pwrap_read(ACCDET_RSV)|ACCDET_INPUT_MICP);
<API key>(<API key>, 1);//switch P internel
#endif
//ACCDET_DEBUG(" ACCDET_ADC_REG =%x\n",pmic_pwrap_read(ACCDET_ADC_REG));
//ACCDET_DEBUG(" ACCDET_EINT_NV =%x\n",pmic_pwrap_read(ACCDET_EINT_NV));
//ACCDET_DEBUG(" ACCDET_RSV =%x\n",pmic_pwrap_read(ACCDET_RSV));
#if defined ACCDET_EINT
// disable ACCDET unit
pre_state_swctrl = pmic_pwrap_read(ACCDET_STATE_SWCTRL);
pmic_pwrap_write(ACCDET_CTRL, ACCDET_DISABLE);
pmic_pwrap_write(ACCDET_STATE_SWCTRL, 0x0);
pmic_pwrap_write(TOP_CKPDN_SET, RG_ACCDET_CLK_SET);
#elif defined ACCDET_EINT_IRQ
if(cur_eint_state == EINT_PIN_PLUG_OUT){
pmic_pwrap_write(ACCDET_EINT_CTL, pmic_pwrap_read(ACCDET_EINT_CTL)|EINT_IRQ_DE_IN);//debounce=256ms
}
pmic_pwrap_write(ACCDET_EINT_CTL, pmic_pwrap_read(ACCDET_EINT_CTL)|EINT_PWM_THRESH);
// disable ACCDET unit, except CLK of ACCDET
pre_state_swctrl = pmic_pwrap_read(ACCDET_STATE_SWCTRL);
pmic_pwrap_write(ACCDET_CTRL, pmic_pwrap_read(ACCDET_CTRL)|ACCDET_DISABLE);
pmic_pwrap_write(ACCDET_STATE_SWCTRL, pmic_pwrap_read(ACCDET_STATE_SWCTRL)&(~ACCDET_SWCTRL_EN));
pmic_pwrap_write(ACCDET_STATE_SWCTRL, pmic_pwrap_read(ACCDET_STATE_SWCTRL)|ACCDET_EINT_PWM_EN);
pmic_pwrap_write(ACCDET_CTRL, pmic_pwrap_read(ACCDET_CTRL)|ACCDET_EINT_EN);
#else
// enable ACCDET unit
// pmic_pwrap_write(ACCDET_STATE_SWCTRL, ACCDET_SWCTRL_EN);
pmic_pwrap_write(ACCDET_CTRL, ACCDET_ENABLE);
#endif
#ifdef ACCDET_NEGV_IRQ
pmic_pwrap_write(<API key>, pmic_pwrap_read(<API key>)&(~0x1F));
pmic_pwrap_write(<API key>, pmic_pwrap_read(<API key>)|0x0F);
pmic_pwrap_write(ACCDET_CTRL, pmic_pwrap_read(ACCDET_CTRL)|ACCDET_NEGV_EN);
#endif
//<API key>(1);
pmic_pwrap_write(<API key>, (pmic_pwrap_read(<API key>)|<API key>));
#ifdef GPIO_FSA8049_PIN
//mt_set_gpio_out(GPIO_FSA8049_PIN, GPIO_OUT_ONE);
#endif
//mt_set_gpio_dir(<API key>, GPIO_DIR_OUT);
//<API key>(<API key>, GPIO_PULL_DISABLE);
//mt_set_gpio_out(<API key>, GPIO_OUT_ZERO);
#ifdef FSA8049_V_POWER
hwPowerOn(FSA8049_V_POWER, VOL_2800, "ACCDET");
#endif
}
#if DEBUG_THREAD
static int dump_register(void)
{
int i=0;
for (i=ACCDET_RSV; i<= ACCDET_RSV_CON1; i+=2)
{
ACCDET_DEBUG(" ACCDET_BASE + %x=%x\n",i,pmic_pwrap_read(ACCDET_BASE + i));
}
ACCDET_DEBUG(" TOP_RST_ACCDET(0x%x) =%x\n", TOP_RST_ACCDET, pmic_pwrap_read(TOP_RST_ACCDET));
ACCDET_DEBUG(" INT_CON_ACCDET(0x%x) =%x\n", INT_CON_ACCDET, pmic_pwrap_read(INT_CON_ACCDET));
ACCDET_DEBUG(" TOP_CKPDN(0x%x) =%x\n", TOP_CKPDN, pmic_pwrap_read(TOP_CKPDN));
ACCDET_DEBUG(" ACCDET_ADC_REG(0x%x) =%x\n", ACCDET_ADC_REG, pmic_pwrap_read(ACCDET_ADC_REG));
#ifdef ACCDET_PIN_SWAP
//ACCDET_DEBUG(" 0x00004000 =%x\n",pmic_pwrap_read(0x00004000));//VRF28 power for PIN swap feature
#endif
return 0;
}
#if defined(<API key>)
static ssize_t <API key>(struct device_driver *ddri, char *buf)
{
ACCDET_DEBUG("[Accdet] TS3A225E <API key>=%d\n", <API key>);
return sprintf(buf, "%u\n", <API key>);
}
static DRIVER_ATTR(<API key>, 0664, <API key>, NULL);
#endif
static ssize_t <API key>(struct device_driver *ddri, const char *buf, size_t count)
{
if (sscanf(buf, "%u", &call_status) != 1) {
ACCDET_DEBUG("accdet: Invalid values\n");
return -EINVAL;
}
switch(call_status)
{
case CALL_IDLE :
ACCDET_DEBUG("[Accdet]accdet call: Idle state!\n");
break;
case CALL_RINGING :
ACCDET_DEBUG("[Accdet]accdet call: ringing state!\n");
break;
case CALL_ACTIVE :
ACCDET_DEBUG("[Accdet]accdet call: active or hold state!\n");
ACCDET_DEBUG("[Accdet]accdet_ioctl : Button_Status=%d (state:%d)\n", button_status, accdet_data.state);
//return button_status;
break;
default:
ACCDET_DEBUG("[Accdet]accdet call : Invalid values\n");
break;
}
return count;
}
//#ifdef <API key>
static ssize_t <API key>(struct device_driver *ddri, char *buf)
{
#ifdef <API key>
ACCDET_DEBUG("ACCDET <API key> = %d\n", <API key>);
return sprintf(buf, "%u\n", <API key>);
#else
return sprintf(buf, "%u\n", 0);
#endif
}
static DRIVER_ATTR(<API key>, 0664, <API key>, NULL);
static DRIVER_ATTR(accdet_call_state, 0664, NULL, <API key>);
static int <API key> =0;
static struct task_struct *thread = NULL;
static int g_dump_register=0;
static int dbug_thread(void *unused)
{
while(<API key>)
{
if(g_dump_register)
{
dump_register();
//dump_pmic_register();
}
msleep(500);
}
return 0;
}
//static ssize_t store_trace_value(struct device_driver *ddri, const char *buf, size_t count)
static ssize_t <API key>(struct device_driver *ddri, const char *buf, size_t count)
{
unsigned int start_flag;
int error;
if (sscanf(buf, "%u", &start_flag) != 1) {
ACCDET_DEBUG("accdet: Invalid values\n");
return -EINVAL;
}
ACCDET_DEBUG("[Accdet] start flag =%d \n",start_flag);
<API key> = start_flag;
if(1 == start_flag)
{
thread = kthread_run(dbug_thread, 0, "ACCDET");
if (IS_ERR(thread))
{
error = PTR_ERR(thread);
ACCDET_DEBUG( " failed to create kernel thread: %d\n", error);
}
}
return count;
}
static ssize_t <API key>(struct device_driver *ddri, const char *buf, size_t count)
{
unsigned int value;
//int error;
if (sscanf(buf, "%u", &value) != 1) {
ACCDET_DEBUG("accdet: Invalid values\n");
return -EINVAL;
}
ACCDET_DEBUG("[Accdet]<API key> value =%d \n",value);
return count;
}
static ssize_t <API key>(struct device_driver *ddri, const char *buf, size_t count)
{
unsigned int value;
// int error;
if (sscanf(buf, "%u", &value) != 1)
{
ACCDET_DEBUG("accdet: Invalid values\n");
return -EINVAL;
}
g_dump_register = value;
ACCDET_DEBUG("[Accdet]<API key> value =%d \n",value);
return count;
}
static DRIVER_ATTR(dump_register, S_IWUSR | S_IRUGO, NULL, <API key>);
static DRIVER_ATTR(set_headset_mode, S_IWUSR | S_IRUGO, NULL, <API key>);
static DRIVER_ATTR(start_debug, S_IWUSR | S_IRUGO, NULL, <API key>);
static struct driver_attribute *accdet_attr_list[] = {
&<API key>,
&<API key>,
&<API key>,
&<API key>,
//#ifdef <API key>
&<API key>,
//#endif
#if defined(<API key>)
&<API key>,
#endif
};
static int accdet_create_attr(struct device_driver *driver)
{
int idx, err = 0;
int num = (int)(sizeof(accdet_attr_list)/sizeof(accdet_attr_list[0]));
if (driver == NULL)
{
return -EINVAL;
}
for(idx = 0; idx < num; idx++)
{
if((err = driver_create_file(driver, accdet_attr_list[idx])))
{
ACCDET_DEBUG("driver_create_file (%s) = %d\n", accdet_attr_list[idx]->attr.name, err);
break;
}
}
return err;
}
#endif
void accdet_int_handler(void)
{
int ret=0;
ACCDET_DEBUG("[accdet_int_handler]....\n");
ret = accdet_irq_handler();
if(0 == ret){
ACCDET_DEBUG("[accdet_int_handler] don't finished\n");
}
}
void <API key>(void)
{
int ret=0;
ACCDET_DEBUG("[<API key>]....\n");
ret = accdet_irq_handler();
if(0 == ret){
ACCDET_DEBUG("[accdet_int_handler] don't finished\n");
}
}
int mt_accdet_probe(void)
{
int ret = 0;
// add by baibo@yulong 20150313 hookswitch test in factory mode begin
#ifdef AUDIO_AUTO_TEST
struct proc_dir_entry *hook_test_entry = NULL;
#endif
// add by baibo@yulong 20150313 hookswitch test in factory mode end
#if defined(<API key>)
if (ts3a225e_i2c_client == NULL)
{
ACCDET_DEBUG("[Accdet]ts3a225e_i2c_client is NULL!\n");
return -EPROBE_DEFER;
}
#endif
#ifdef <API key>
//struct task_struct *keyEvent_thread = NULL;
//int error=0;
#endif
#if DEBUG_THREAD
struct platform_driver accdet_driver_hal = accdet_driver_func();
#endif
struct headset_key_custom* press_key_time = <API key>();
ACCDET_DEBUG("[Accdet]accdet_probe begin!\n");
// below register accdet as switch class
accdet_data.name = "h2w";
accdet_data.index = 0;
accdet_data.state = NO_DEVICE;
<API key> = <API key>();
ret = switch_dev_register(&accdet_data);
if(ret)
{
ACCDET_DEBUG("[Accdet]switch_dev_register returned:%d!\n", ret);
return 1;
}
// Create normal device for auido use
ret = alloc_chrdev_region(&accdet_devno, 0, 1, ACCDET_DEVNAME);
if (ret)
{
ACCDET_DEBUG("[Accdet]alloc_chrdev_region: Get Major number error!\n");
}
accdet_cdev = cdev_alloc();
accdet_cdev->owner = THIS_MODULE;
accdet_cdev->ops = accdet_get_fops();
ret = cdev_add(accdet_cdev, accdet_devno, 1);
if(ret)
{
ACCDET_DEBUG("[Accdet]accdet error: cdev_add\n");
}
accdet_class = class_create(THIS_MODULE, ACCDET_DEVNAME);
// if we want auto creat device node, we must call this
accdet_nor_device = device_create(accdet_class, NULL, accdet_devno, NULL, ACCDET_DEVNAME);
// Create input device
kpd_accdet_dev = <API key>();
if (!kpd_accdet_dev)
{
ACCDET_DEBUG("[Accdet]kpd_accdet_dev : fail!\n");
return -ENOMEM;
}
//INIT the timer to disable micbias.
init_timer(&micbias_timer);
micbias_timer.expires = jiffies + <API key>;
micbias_timer.function = &disable_micbias;
micbias_timer.data = ((unsigned long) 0 );
//define multi-key keycode
__set_bit(EV_KEY, kpd_accdet_dev->evbit);
__set_bit(KEY_CALL, kpd_accdet_dev->keybit);
__set_bit(KEY_ENDCALL, kpd_accdet_dev->keybit);
__set_bit(KEY_NEXTSONG, kpd_accdet_dev->keybit);
__set_bit(KEY_PREVIOUSSONG, kpd_accdet_dev->keybit);
__set_bit(KEY_PLAYPAUSE, kpd_accdet_dev->keybit);
__set_bit(KEY_STOPCD, kpd_accdet_dev->keybit);
__set_bit(KEY_VOLUMEDOWN, kpd_accdet_dev->keybit);
__set_bit(KEY_VOLUMEUP, kpd_accdet_dev->keybit);
__set_bit(KEY_VOICECOMMAND, kpd_accdet_dev->keybit);
kpd_accdet_dev->id.bustype = BUS_HOST;
kpd_accdet_dev->name = "ACCDET";
if(<API key>(kpd_accdet_dev))
{
ACCDET_DEBUG("[Accdet]kpd_accdet_dev register : fail!\n");
}else
{
ACCDET_DEBUG("[Accdet]kpd_accdet_dev register : success!!\n");
}
// Create workqueue
accdet_workqueue = <API key>("accdet");
INIT_WORK(&accdet_work, <API key>);
// wake lock
wake_lock_init(&accdet_suspend_lock, WAKE_LOCK_SUSPEND, "accdet wakelock");
wake_lock_init(&accdet_irq_lock, WAKE_LOCK_SUSPEND, "accdet irq wakelock");
wake_lock_init(&accdet_key_lock, WAKE_LOCK_SUSPEND, "accdet key wakelock");
wake_lock_init(&accdet_timer_lock, WAKE_LOCK_SUSPEND, "accdet timer wakelock");
#if DEBUG_THREAD
if((ret = accdet_create_attr(&accdet_driver_hal.driver))!=0)
{
ACCDET_DEBUG("create attribute err = %d\n", ret);
}
#endif
<API key>(12,accdet_int_handler);
<API key>(13,<API key>);
long_press_time = press_key_time-><API key>;
ACCDET_DEBUG("[Accdet]accdet_probe : ACCDET_INIT\n");
if (g_accdet_first == 1)
{
long_press_time_ns = (s64)long_press_time * NSEC_PER_MSEC;
<API key> = 1;
#ifdef ACCDET_EINT_IRQ
<API key> = <API key>("accdet_eint");
INIT_WORK(&accdet_eint_work, <API key>);
<API key> = <API key>("accdet_disable");
INIT_WORK(&accdet_disable_work, <API key>);
#endif
//Accdet Hardware Init
accdet_init();
<API key>();
queue_work(accdet_workqueue, &accdet_work); //schedule a work for the first detection
#ifdef ACCDET_EINT
<API key> = <API key>("accdet_disable");
INIT_WORK(&accdet_disable_work, <API key>);
<API key> = <API key>("accdet_eint");
INIT_WORK(&accdet_eint_work, <API key>);
accdet_setup_eint();
#endif
g_accdet_first = 0;
}
// add by baibo@yulong 20150313 hookswitch test in factory mode begin
#ifdef AUDIO_AUTO_TEST
g_hook_test = HOOK_MODE_INVALID;
#if 0
hook_test_entry = create_proc_entry(<API key>, 0666, NULL);
if (hook_test_entry != NULL)
{
hook_test_entry->data = NULL;
hook_test_entry->read_proc = <API key>;
hook_test_entry->write_proc = <API key>;
}
#endif
hook_test_entry = proc_create(<API key>, 0666, NULL, &hook_test_fops);
#endif
// add by baibo@yulong 20150313 hookswitch test in factory mode end
ACCDET_DEBUG("[Accdet]accdet_probe done!\n");
//#ifdef ACCDET_PIN_SWAP
//pmic_pwrap_write(0x0400, 0x1000);
//ACCDET_DEBUG("[Accdet]accdet enable VRF28 power!\n");
//#endif
return 0;
}
void mt_accdet_remove(void)
{
ACCDET_DEBUG("[Accdet]accdet_remove begin!\n");
// add by baibo@yulong 20150313 hookswitch test in factory mode begin
#if 0
#ifdef AUDIO_AUTO_TEST
remove_proc_entry(<API key>, NULL);
#endif
#endif
// add by baibo@yulong 20150313 hookswitch test in factory mode end
//cancel_delayed_work(&accdet_work);
#if defined ACCDET_EINT || defined ACCDET_EINT_IRQ
destroy_workqueue(<API key>);
#endif
destroy_workqueue(accdet_workqueue);
<API key>(&accdet_data);
device_del(accdet_nor_device);
class_destroy(accdet_class);
cdev_del(accdet_cdev);
<API key>(accdet_devno,1);
<API key>(kpd_accdet_dev);
ACCDET_DEBUG("[Accdet]accdet_remove Done!\n");
}
void mt_accdet_suspend(void) // only one suspend mode
{
//#ifdef ACCDET_PIN_SWAP
// pmic_pwrap_write(0x0400, 0x0);
// <API key>();
//#endif
#if defined ACCDET_EINT || defined ACCDET_EINT_IRQ
ACCDET_DEBUG("[Accdet] in suspend1: ACCDET_IRQ_STS = 0x%x\n", pmic_pwrap_read(ACCDET_IRQ_STS));
#else
#if 0
// disable ACCDET unit
if(call_status == 0)
{
pre_state_swctrl = accdet_get_swctrl();
accdet_disable_hal();
//disable_clock
accdet_disable_clk();
}
#endif
printk(KERN_DEBUG "[Accdet]accdet_suspend: ACCDET_CTRL=[0x%x], STATE=[0x%x]->[0x%x]\n", pmic_pwrap_read(ACCDET_CTRL), pre_state_swctrl, pmic_pwrap_read(ACCDET_STATE_SWCTRL));
#endif
}
void mt_accdet_resume(void) // wake up
{
//#ifdef ACCDET_PIN_SWAP
// pmic_pwrap_write(0x0400, 0x1000);
// <API key>();
//#endif
#if defined ACCDET_EINT || defined ACCDET_EINT_IRQ
ACCDET_DEBUG("[Accdet] in resume1: ACCDET_IRQ_STS = 0x%x\n", pmic_pwrap_read(ACCDET_IRQ_STS));
#else
#if 0
if(call_status == 0)
{
accdet_enable_hal(pre_state_swctrl);
}
#endif
printk(KERN_DEBUG "[Accdet]accdet_resume: ACCDET_CTRL=[0x%x], STATE_SWCTRL=[0x%x]\n", pmic_pwrap_read(ACCDET_CTRL), pmic_pwrap_read(ACCDET_STATE_SWCTRL));
#endif
}
#ifdef <API key>
struct timer_list <API key>;
static void <API key>(unsigned long a)
{
if (cable_type == NO_DEVICE && <API key> ==0) {
//disable accdet
pre_state_swctrl = pmic_pwrap_read(ACCDET_STATE_SWCTRL);
pmic_pwrap_write(ACCDET_STATE_SWCTRL, 0);
#ifdef ACCDET_EINT
pmic_pwrap_write(ACCDET_CTRL, ACCDET_DISABLE);
//disable clock
pmic_pwrap_write(TOP_CKPDN_SET, RG_ACCDET_CLK_SET);
#endif
#ifdef ACCDET_EINT_IRQ
pmic_pwrap_write(ACCDET_CTRL, pmic_pwrap_read(ACCDET_CTRL)&(~(ACCDET_ENABLE)));
#endif
printk("[Accdet]daccdet_pm_disable: disable!\n");
}
else
{
printk("[Accdet]daccdet_pm_disable: enable!\n");
}
}
#endif
void <API key>(void)
{
int <API key> = 0;
printk("[Accdet]<API key> start!\n");
// enable ACCDET unit
ACCDET_DEBUG("accdet: enable_accdet\n");
//enable clock
pmic_pwrap_write(TOP_CKPDN_CLR, RG_ACCDET_CLK_CLR);
#ifdef ACCDET_EINT_IRQ
pmic_pwrap_write(TOP_CKPDN_CLR, <API key>);
pmic_pwrap_write(ACCDET_RSV, pmic_pwrap_read(ACCDET_RSV)|ACCDET_INPUT_MICP);
pmic_pwrap_write(ACCDET_EINT_NV, pmic_pwrap_read(ACCDET_EINT_NV)|ACCDET_EINT_CON_EN);
pmic_pwrap_write(ACCDET_EINT_NV, pmic_pwrap_read(ACCDET_EINT_NV)|ACCDET_EINT_CON_EN);
pmic_pwrap_write(ACCDET_CTRL, ACCDET_EINT_EN);
#endif
#ifdef ACCDET_NEGV_IRQ
pmic_pwrap_write(TOP_CKPDN_CLR, <API key>);
pmic_pwrap_write(ACCDET_EINT_NV, pmic_pwrap_read(ACCDET_EINT_NV)|ACCDET_NEGV_DT_EN);
pmic_pwrap_write(ACCDET_CTRL, pmic_pwrap_read(ACCDET_CTRL)|ACCDET_NEGV_EN);
#endif
enable_accdet(ACCDET_SWCTRL_EN);
pmic_pwrap_write(ACCDET_STATE_SWCTRL, (pmic_pwrap_read(ACCDET_STATE_SWCTRL)|<API key>));
<API key> = 1;
<API key> = ((pmic_pwrap_read(ACCDET_STATE_RG) & 0xc0)>>6);
switch (<API key>) {
case 0: //AB=0
cable_type = HEADSET_NO_MIC;
accdet_status = HOOK_SWITCH;
break;
case 1: //AB=1
cable_type = HEADSET_MIC;
accdet_status = MIC_BIAS;
break;
case 3: //AB=3
cable_type = NO_DEVICE;
accdet_status = PLUG_OUT;
break;
default:
printk("[Accdet]<API key>: accdet current status error!\n");
break;
}
switch_set_state((struct switch_dev *)&accdet_data, cable_type);
if (cable_type == NO_DEVICE) {
#ifdef <API key>
init_timer(&<API key>);
<API key>.expires = jiffies + 3*HZ;
<API key>.function = &<API key>;
<API key>.data = ((unsigned long) 0 );
add_timer(&<API key>);
printk("[Accdet]enable! pm timer\n");
#else
//disable accdet
pre_state_swctrl = pmic_pwrap_read(ACCDET_STATE_SWCTRL);
#ifdef ACCDET_EINT
pmic_pwrap_write(ACCDET_STATE_SWCTRL, 0);
pmic_pwrap_write(ACCDET_CTRL, ACCDET_DISABLE);
//disable clock
pmic_pwrap_write(TOP_CKPDN_SET, RG_ACCDET_CLK_SET);
#endif
#ifdef ACCDET_EINT_IRQ
pmic_pwrap_write(ACCDET_STATE_SWCTRL, ACCDET_EINT_PWM_EN);
pmic_pwrap_write(ACCDET_CTRL, pmic_pwrap_read(ACCDET_CTRL)&(~(ACCDET_ENABLE)));
#endif
#endif
}
}
/////////////////////////////////IPO_H end/////////////////////////////////////////////
long <API key>(unsigned int cmd, unsigned long arg)
{
// bool ret = true;
switch(cmd)
{
case ACCDET_INIT :
break;
case SET_CALL_STATE :
call_status = (int)arg;
ACCDET_DEBUG("[Accdet]accdet_ioctl : CALL_STATE=%d \n", call_status);
break;
case GET_BUTTON_STATUS :
ACCDET_DEBUG("[Accdet]accdet_ioctl : Button_Status=%d (state:%d)\n", button_status, accdet_data.state);
return button_status;
default:
ACCDET_DEBUG("[Accdet]accdet_ioctl : default\n");
break;
}
return 0;
} |
#include "qemu-common.h"
#include "monitor.h"
#include "qemu-timer.h"
#include "qemu-log.h"
#include "sysemu.h"
#include "migration.h"
#include <sys/time.h>
QEMUClock *rt_clock;
QEMUClock *vm_clock;
FILE *logfile;
struct QEMUBH
{
QEMUBHFunc *cb;
void *opaque;
};
void qemu_service_io(void)
{
}
Monitor *cur_mon;
int monitor_get_fd(Monitor *mon, const char *name)
{
return -1;
}
int monitor_cur_is_qmp(void)
{
return 0;
}
void monitor_set_error(Monitor *mon, QError *qerror)
{
}
void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)
{
}
void monitor_printf(Monitor *mon, const char *fmt, ...)
{
}
void <API key>(Monitor *mon, const char *filename)
{
}
void <API key>(MonitorEvent event, QObject *data)
{
}
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
{
return qemu_malloc(1);
}
void qemu_free_timer(QEMUTimer *ts)
{
qemu_free(ts);
}
void qemu_del_timer(QEMUTimer *ts)
{
}
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
{
}
int qemu_timer_pending(QEMUTimer *ts)
{
return 0;
}
int <API key>(int fd,
IOCanReadHandler *fd_read_poll,
IOHandler *fd_read,
IOHandler *fd_write,
void *opaque)
{
return 0;
}
int64_t qemu_get_clock(QEMUClock *clock)
{
qemu_timeval tv;
qemu_gettimeofday(&tv);
return (tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000)) / 1000000;
}
/*
* XXX: non-functional stub, but we do not need block latency accounting
* in the tools anyway.
*/
int64_t get_clock(void)
{
return 0;
}
void qemu_notify_event(void)
{
}
bool runstate_check(RunState state)
{
return state == RUN_STATE_RUNNING;
}
void <API key>(void)
{
}
void <API key>(void)
{
}
void migrate_add_blocker(Error *reason)
{
}
void migrate_del_blocker(Error *reason)
{
} |
/* File: util.c */
#include "angband.h"
/* Hack for detecting unix stuff. */
#ifdef PRIVATE_USER_PATH
# ifndef HAVE_USLEEP
/*
* For those systems that don't have "usleep()" but need it.
*
* Fake "usleep()" function grabbed from the inl netrek server -cba
*/
int usleep(huge usecs)
{
struct timeval Timer;
int nfds = 0;
#ifdef FD_SET
fd_set *no_fds = NULL;
#else
int *no_fds = NULL;
#endif
/* Was: int readfds, writefds, exceptfds; */
/* Was: readfds = writefds = exceptfds = 0; */
/* Paranoia -- No excessive sleeping */
if (usecs > 4000000L) core("Illegal usleep() call");
/* Wait for it */
Timer.tv_sec = (usecs / 1000000L);
Timer.tv_usec = (usecs % 1000000L);
/* Wait for it */
if (select(nfds, no_fds, no_fds, no_fds, &Timer) < 0)
{
/* Hack -- ignore interrupts */
if (errno != EINTR) return -1;
}
/* Success */
return 0;
}
# endif /* HAVE_USLEEP */
/*
* Find a default user name from the system.
*/
void user_name(char *buf, size_t len, int id)
{
struct passwd *pw;
/* Look up the user name */
if ((pw = getpwuid(id)))
{
/* Get the first 15 characters of the user name */
my_strcpy(buf, pw->pw_name, len);
#ifdef <API key>
/* Hack -- capitalize the user name */
if (islower((unsigned char)buf[0]))
buf[0] = toupper((unsigned char)buf[0]);
#endif /* <API key> */
return;
}
/* Oops. Hack -- default to "PLAYER" */
my_strcpy(buf, "PLAYER", len);
}
#endif /* SET_UID */
/*
* The concept of the "file" routines below (and elsewhere) is that all
* file handling should be done using as few routines as possible, since
* every machine is slightly different, but these routines always have the
* same semantics.
*
* In fact, perhaps we should use the "path_parse()" routine below to convert
* from "canonical" filenames (optional leading tilde's, internal wildcards,
* slash as the path seperator, etc) to "system" filenames (no special symbols,
* system-specific path seperator, etc). This would allow the program itself
* to assume that all filenames are "Unix" filenames, and explicitly "extract"
* such filenames if needed (by "path_parse()", or perhaps "path_canon()").
*
* Note that "path_temp" should probably return a "canonical" filename.
*
* Note that "my_fopen()" and "my_open()" and "my_make()" and "my_kill()"
* and "my_move()" and "my_copy()" should all take "canonical" filenames.
*
* Note that "canonical" filenames use a leading "slash" to indicate an absolute
* path, and a leading "tilde" to indicate a special directory, and default to a
* relative path, but MSDOS uses a leading "drivename plus colon" to indicate the
* use of a "special drive", and then the rest of the path is parsed "normally",
* and MACINTOSH uses a leading colon to indicate a relative path, and an embedded
* colon to indicate a "drive plus absolute path", and finally defaults to a file
* in the current working directory, which may or may not be defined.
*
* We should probably parse a leading "~~/" as referring to "ANGBAND_DIR". (?)
*/
#ifdef ACORN
/*
* Most of the "file" routines for "ACORN" should be in "main-ros.c"
*/
#else /* ACORN */
#ifdef PRIVATE_USER_PATH
/*
* Extract a "parsed" path from an initial filename
* Normally, we simply copy the filename into the buffer
* But leading tilde symbols must be handled in a special way
* Replace "~user/" by the home directory of the user named "user"
* Replace "~/" by the home directory of the current user
*/
errr path_parse(char *buf, int max, cptr file)
{
cptr u, s;
struct passwd *pw;
char user[128];
/* Unused */
(void)max;
/* Assume no result */
buf[0] = '\0';
/* No file? */
if (!file) return (-1);
/* File needs no parsing */
if (file[0] != '~')
{
strcpy(buf, file);
return (0);
}
/* Point at the user */
u = file+1;
/* Look for non-user portion of the file */
s = strstr(u, PATH_SEP);
/* Hack -- no long user names */
if (s && (s >= u + sizeof(user))) return (1);
/* Extract a user name */
if (s)
{
int i;
for (i = 0; u < s; ++i) user[i] = *u++;
user[i] = '\0';
u = user;
}
/* Look up the "current" user */
if (u[0] == '\0') u = getlogin();
/* Look up a user (or "current" user) */
if (u) pw = getpwnam(u);
else pw = getpwuid(getuid());
/* Nothing found? */
if (!pw) return (1);
/* Make use of the info */
strcpy(buf, pw->pw_dir);
/* Append the rest of the filename, if any */
if (s) strcat(buf, s);
/* Success */
return (0);
}
#else /* PRIVATE_USER_PATH */
/*
* Extract a "parsed" path from an initial filename
*
* This requires no special processing on simple machines,
* except for verifying the size of the filename.
*/
errr path_parse(char *buf, int max, cptr file)
{
/* Accept the filename */
strnfmt(buf, max, "%s", file);
/* Success */
return (0);
}
#endif /* SET_UID */
#ifndef HAVE_MKSTEMP
/*
* Hack -- acquire a "temporary" file name if possible
*
* This filename is always in "system-specific" form.
*/
static errr path_temp(char *buf, int max)
{
cptr s;
/* Temp file */
s = tmpnam(NULL);
/* Oops */
if (!s) return (-1);
/* Format to length */
strnfmt(buf, max, "%s", s);
/* Success */
return (0);
}
#endif /* HAVE_MKSTEMP */
/*
* Create a new path by appending a file (or directory) to a path
*
* This requires no special processing on simple machines, except
* for verifying the size of the filename, but note the ability to
* bypass the given "path" with certain special file-names.
*
* Note that the "file" may actually be a "sub-path", including
* a path and a file.
*
* Note that this function yields a path which must be "parsed"
* using the "parse" function above.
*/
errr path_build(char *buf, int max, cptr path, cptr file)
{
/* Special file */
if (file[0] == '~')
{
/* Use the file itself */
strnfmt(buf, max, "%s", file);
}
/* Absolute file, on "normal" systems */
else if (prefix(file, PATH_SEP) && !streq(PATH_SEP, ""))
{
/* Use the file itself */
strnfmt(buf, max, "%s", file);
}
/* No path given */
else if (!path[0])
{
/* Use the file itself */
strnfmt(buf, max, "%s", file);
}
/* Path and File */
else
{
/* Build the new path */
strnfmt(buf, max, "%s%s%s", path, PATH_SEP, file);
}
/* Success */
return (0);
}
/*
* Hack -- replacement for "fopen()"
*/
FILE *my_fopen(cptr file, cptr mode)
{
char buf[1024];
FILE *fff;
/* Hack -- Try to parse the path */
if (path_parse(buf, 1024, file)) return (NULL);
/* Attempt to fopen the file anyway */
fff = (fopen(buf, mode));
#if 0 /*defined(MAC_MPW) || defined(MACH_O_CARBON)*/
/* Set file creator and type */
if (fff && strchr(mode, 'w')) fsetfileinfo(buf, _fcreator, _ftype);
#endif
return fff;
}
/*
* Hack -- replacement for "fclose()"
*/
errr my_fclose(FILE *fff)
{
/* Require a file */
if (!fff) return (-1);
/* Close, check for error */
if (fclose(fff) == EOF) return (1);
/* Success */
return (0);
}
#endif /* ACORN */
#ifdef HAVE_MKSTEMP
FILE *my_fopen_temp(char *buf, int max)
{
int fd;
/* Prepare the buffer for mkstemp */
strncpy(buf, "/tmp/anXXXXXX", max);
/* Secure creation of a temporary file */
fd = mkstemp(buf);
/* Check the file-descriptor */
if (fd < 0) return (NULL);
/* Return a file stream */
return (fdopen(fd, "w"));
}
#else /* HAVE_MKSTEMP */
FILE *my_fopen_temp(char *buf, int max)
{
/* Generate a temporary filename */
if (path_temp(buf, max)) return (NULL);
/* Open the file */
return (my_fopen(buf, "w"));
}
#endif /* HAVE_MKSTEMP */
/*
* Hack -- replacement for "fgets()"
*
* Read a string, without a newline, to a file
*
* Process tabs, strip internal non-printables
*/
errr my_fgets(FILE *fff, char *buf, size_t n)
{
huge i = 0;
char *s;
char tmp[1024];
/* Read a line */
if (fgets(tmp, 1024, fff))
{
/* Convert weirdness */
for (s = tmp; *s; s++)
{
/* Handle newline */
if (*s == '\n')
{
/* Terminate */
buf[i] = '\0';
/* Success */
return (0);
}
/* Handle tabs */
else if (*s == '\t')
{
/* Hack -- require room */
if (i + 8 >= n) break;
/* Append 1-8 spaces */
do { buf[i++] = ' '; } while (i % 8);
}
/* Handle printables */
else if (isprint(*s))
{
/* Copy */
buf[i++] = *s;
/* Check length */
if (i >= n) break;
}
}
}
/* Nothing */
buf[0] = '\0';
/* Failure */
return (1);
}
/*
* Hack -- replacement for "fputs()"
*
* Dump a string, plus a newline, to a file
*
* Perhaps this function should handle internal weirdness.
*/
errr my_fputs(FILE *fff, cptr buf, size_t n)
{
/* Unused paramter */
(void)n;
/* Dump, ignore errors */
(void)fprintf(fff, "%s\n", buf);
/* Success */
return (0);
}
#ifdef ACORN
/*
* Most of the "file" routines for "ACORN" should be in "main-ros.c"
*
* Many of them can be rewritten now that only "fd_open()" and "fd_make()"
* and "my_fopen()" should ever create files.
*/
#else /* ACORN */
/*
* Several systems have no "O_BINARY" flag
*/
#ifndef O_BINARY
# define O_BINARY 0
#endif /* O_BINARY */
/*
* Hack -- attempt to delete a file
*/
errr fd_kill(cptr file)
{
char buf[1024];
/* Hack -- Try to parse the path */
if (path_parse(buf, 1024, file)) return (-1);
/* Remove */
(void)remove(buf);
/* Assume success XXX XXX XXX */
return (0);
}
/*
* Hack -- attempt to move a file
*/
errr fd_move(cptr file, cptr what)
{
char buf[1024];
char aux[1024];
/* Hack -- Try to parse the path */
if (path_parse(buf, 1024, file)) return (-1);
/* Hack -- Try to parse the path */
if (path_parse(aux, 1024, what)) return (-1);
/* Rename */
(void)rename(buf, aux);
/* Assume success XXX XXX XXX */
return (0);
}
/*
* Hack -- attempt to copy a file
*/
errr fd_copy(cptr file, cptr what)
{
char buf[1024];
char aux[1024];
/* Hack -- Try to parse the path */
if (path_parse(buf, 1024, file)) return (-1);
/* Hack -- Try to parse the path */
if (path_parse(aux, 1024, what)) return (-1);
/* Copy XXX XXX XXX */
/* (void)rename(buf, aux); */
/* Assume success XXX XXX XXX */
return (1);
}
/*
* Hack -- attempt to open a file descriptor (create file)
*
* This function should fail if the file already exists
*
* Note that we assume that the file should be "binary"
*/
int fd_make(cptr file, int mode)
{
char buf[1024];
int fd;
/* Hack -- Try to parse the path */
if (path_parse(buf, 1024, file)) return (-1);
#ifdef MACINTOSH
/* Create the file, fail if exists, write-only, binary */
fd = (open(buf, O_CREAT | O_EXCL | O_WRONLY | O_BINARY));
#else
/* Create the file, fail if exists, write-only, binary */
fd = (open(buf, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, mode));
#endif
#ifdef <API key>
/* Set file creator and type */
if (fd >= 0) fsetfileinfo(buf, _fcreator, _ftype);
#endif
return fd;
}
/*
* Hack -- attempt to open a file descriptor (existing file)
*
* Note that we assume that the file should be "binary"
*/
int fd_open(cptr file, int flags)
{
char buf[1024];
/* Hack -- Try to parse the path */
if (path_parse(buf, 1024, file)) return (-1);
#if defined(MACINTOSH) || defined(WINDOWS)
/* Attempt to open the file */
return (open(buf, flags | O_BINARY));
#else
/* Attempt to open the file */
return (open(buf, flags | O_BINARY, 0));
#endif
}
errr fd_lock(int fd, int what)
{
/* Verify the fd */
if (fd < 0) return (-1);
#ifdef SET_UID
# ifdef USG
# if defined(F_ULOCK) && defined(F_LOCK)
/* Un-Lock */
if (what == F_UNLCK)
{
/* Unlock it, Ignore errors */
lockf(fd, F_ULOCK, 0);
}
/* Lock */
else
{
/* Lock the score file */
if (lockf(fd, F_LOCK, 0) != 0) return (1);
}
# endif /* defined(F_ULOCK) && defined(F_LOCK) */
# else
# if defined(LOCK_UN) && defined(LOCK_EX)
/* Un-Lock */
if (what == F_UNLCK)
{
/* Unlock it, Ignore errors */
(void)flock(fd, LOCK_UN);
}
/* Lock */
else
{
/* Lock the score file */
if (flock(fd, LOCK_EX) != 0) return (1);
}
# endif /* defined(LOCK_UN) && defined(LOCK_EX) */
# endif /* USG */
#else /* SET_UID */
/* Unused parameter */
(void)what;
#endif /* SET_UID */
/* Success */
return (0);
}
/*
* Hack -- attempt to seek on a file descriptor
*/
errr fd_seek(int fd, long n)
{
long p;
/* Verify fd */
if (fd < 0) return (-1);
/* Seek to the given position */
p = lseek(fd, n, SEEK_SET);
/* Failure */
if (p < 0) return (1);
/* Failure */
if (p != n) return (1);
/* Success */
return (0);
}
/*
* Hack -- attempt to read data from a file descriptor
*/
errr fd_read(int fd, char *buf, size_t n)
{
/* Verify the fd */
if (fd < 0) return (-1);
#ifndef SET_UID
/* Read pieces */
while (n >= 16384)
{
/* Read a piece */
if (read(fd, buf, 16384) != 16384) return (1);
/* Shorten the task */
buf += 16384;
/* Shorten the task */
n -= 16384;
}
#endif
/* Read the final piece */
if (read(fd, buf, n) != (int)n) return (1);
/* Success */
return (0);
}
/*
* Hack -- Attempt to write data to a file descriptor
*/
errr fd_write(int fd, cptr buf, size_t n)
{
/* Verify the fd */
if (fd < 0) return (-1);
#ifndef SET_UID
/* Write pieces */
while (n >= 16384)
{
/* Write a piece */
if (write(fd, buf, 16384) != 16384) return (1);
/* Shorten the task */
buf += 16384;
/* Shorten the task */
n -= 16384;
}
#endif
/* Write the final piece */
if (write(fd, buf, n) != (int)n) return (1);
/* Success */
return (0);
}
/*
* Hack -- attempt to close a file descriptor
*/
errr fd_close(int fd)
{
/* Verify the fd */
if (fd < 0) return (-1);
/* Close */
(void)close(fd);
/* Assume success XXX XXX XXX */
return (0);
}
#ifdef <API key>
# ifdef MACINTOSH
# include <stat.h>
# else
# include <sys/types.h>
# include <sys/stat.h>
# endif /* MACINTOSH */
errr <API key>(int fd, cptr template_file)
{
char buf[1024];
struct stat txt_stat, raw_stat;
/* Build the filename */
path_build(buf, 1024, ANGBAND_DIR_EDIT, template_file);
/* Access stats on text file */
if (stat(buf, &txt_stat))
{
/* No text file - continue */
}
/* Access stats on raw file */
else if (fstat(fd, &raw_stat))
{
/* Error */
return (-1);
}
/* Ensure text file is not newer than raw file */
else if (txt_stat.st_mtime > raw_stat.st_mtime)
{
/* Reprocess text file */
return (-1);
}
return (0);
}
#endif /* <API key> */
#endif /* ACORN */
/*
* Convert a decimal to a single digit hex number
*/
static char hexify(uint i)
{
return (hexsym[i%16]);
}
/*
* Convert a hexidecimal-digit into a decimal
*/
static int dehex(char c)
{
if (isdigit(c)) return (D2I(c));
if (isalpha(c)) return (A2I(tolower(c)) + 10);
return (0);
}
/*
* Hack -- convert a printable string into real ascii
*
* This function will not work on non-ascii systems.
*
* To be safe, "buf" should be at least as large as "str".
*/
void text_to_ascii(char *buf, int len, cptr str)
{
char *s = buf;
/* Analyze the "ascii" string */
while (*str)
{
/* Check if the buffer is long enough */
if (s >= buf + len - 1) break;
/* Backslash codes */
if (*str == '\\')
{
/* Skip the backslash */
str++;
/* Paranoia */
if (!(*str)) break;
/* Hack -- simple way to specify Escape */
if (*str == 'e')
{
*s++ = ESCAPE;
}
/* Hack -- simple way to specify "space" */
else if (*str == 's')
{
*s++ = ' ';
}
/* Backspace */
else if (*str == 'b')
{
*s++ = '\b';
}
/* Newline */
else if (*str == 'n')
{
*s++ = '\n';
}
/* Return */
else if (*str == 'r')
{
*s++ = '\r';
}
/* Tab */
else if (*str == 't')
{
*s++ = '\t';
}
/* Bell */
else if (*str == 'a')
{
*s++ = '\a';
}
/* Actual "backslash" */
else if (*str == '\\')
{
*s++ = '\\';
}
/* Hack -- Actual "caret" */
else if (*str == '^')
{
*s++ = '^';
}
/* Hack -- Hex-mode */
else if (*str == 'x')
{
*s = 16 * dehex(*++str);
*s++ += dehex(*++str);
}
/* Oops */
else
{
*s = *str;
}
/* Skip the final char */
str++;
}
/* Normal Control codes */
else if (*str == '^')
{
str++;
if (*str)
{
*s++ = KTRL(*str);
str++;
}
}
/* Normal chars */
else
{
*s++ = *str++;
}
}
/* Terminate */
*s = '\0';
}
/*
* Hack -- convert a string into a printable form
*
* This function will not work on non-ascii systems.
*/
void ascii_to_text(char *buf, int len, cptr str)
{
char *s = buf;
/* Analyze the "ascii" string */
while (*str)
{
byte i = (byte)(*str++);
/* Check if the buffer is long enough */
/* HACK - always assume worst case (hex-value + '\0') */
if (s >= buf + len - 5) break;
if (i == ESCAPE)
{
*s++ = '\\';
*s++ = 'e';
}
else if (i == ' ')
{
*s++ = '\\';
*s++ = 's';
}
else if (i == '\b')
{
*s++ = '\\';
*s++ = 'b';
}
else if (i == '\t')
{
*s++ = '\\';
*s++ = 't';
}
else if (i == '\a')
{
*s++ = '\\';
*s++ = 'a';
}
else if (i == '\n')
{
*s++ = '\\';
*s++ = 'n';
}
else if (i == '\r')
{
*s++ = '\\';
*s++ = 'r';
}
else if (i == '\\')
{
*s++ = '\\';
*s++ = '\\';
}
else if (i == '^')
{
*s++ = '\\';
*s++ = '^';
}
else if (i < 32)
{
*s++ = '^';
*s++ = i + 64;
}
else if (i < 127)
{
*s++ = i;
}
else
{
*s++ = '\\';
*s++ = 'x';
*s++ = hexify(i / 16);
*s++ = hexify(i % 16);
}
}
/* Terminate */
*s = '\0';
}
/*
* The "macro" package
*
* Functions are provided to manipulate a collection of macros, each
* of which has a trigger pattern string and a resulting action string
* and a small set of flags.
*/
/*
* Determine if any macros have ever started with a given character.
*/
static bool macro__use[256];
/*
* Find the macro (if any) which exactly matches the given pattern
*/
sint macro_find_exact(cptr pat)
{
int i;
/* Nothing possible */
if (!macro__use[(byte)(pat[0])])
{
return (-1);
}
/* Scan the macros */
for (i = 0; i < macro__num; ++i)
{
/* Skip macros which do not match the pattern */
if (!streq(macro__pat[i], pat)) continue;
/* Found one */
return (i);
}
/* No matches */
return (-1);
}
/*
* Find the first macro (if any) which contains the given pattern
*/
static sint macro_find_check(cptr pat)
{
int i;
/* Nothing possible */
if (!macro__use[(byte)(pat[0])])
{
return (-1);
}
/* Scan the macros */
for (i = 0; i < macro__num; ++i)
{
/* Skip macros which do not contain the pattern */
if (!prefix(macro__pat[i], pat)) continue;
/* Found one */
return (i);
}
/* Nothing */
return (-1);
}
/*
* Find the first macro (if any) which contains the given pattern and more
*/
static sint macro_find_maybe(cptr pat)
{
int i;
/* Nothing possible */
if (!macro__use[(byte)(pat[0])])
{
return (-1);
}
/* Scan the macros */
for (i = 0; i < macro__num; ++i)
{
/* Skip macros which do not contain the pattern */
if (!prefix(macro__pat[i], pat)) continue;
/* Skip macros which exactly match the pattern XXX XXX */
if (streq(macro__pat[i], pat)) continue;
/* Found one */
return (i);
}
/* Nothing */
return (-1);
}
/*
* Find the longest macro (if any) which starts with the given pattern
*/
static sint macro_find_ready(cptr pat)
{
int i, t, n = -1, s = -1;
/* Nothing possible */
if (!macro__use[(byte)(pat[0])])
{
return (-1);
}
/* Scan the macros */
for (i = 0; i < macro__num; ++i)
{
/* Skip macros which are not contained by the pattern */
if (!prefix(pat, macro__pat[i])) continue;
/* Obtain the length of this macro */
t = strlen(macro__pat[i]);
/* Only track the "longest" pattern */
if ((n >= 0) && (s > t)) continue;
/* Track the entry */
n = i;
s = t;
}
/* Result */
return (n);
}
/*
* Add a macro definition (or redefinition).
*
* We should use "act == NULL" to "remove" a macro, but this might make it
* impossible to save the "removal" of a macro definition. XXX XXX XXX
*
* We should consider refusing to allow macros which contain existing macros,
* or which are contained in existing macros, because this would simplify the
* macro analysis code. XXX XXX XXX
*
* We should consider removing the "command macro" crap, and replacing it
* with some kind of "powerful keymap" ability, but this might make it hard
* to change the "roguelike" option from inside the game. XXX XXX XXX
*/
errr macro_add(cptr pat, cptr act)
{
int n;
/* Paranoia -- require data */
if (!pat || !act) return (-1);
/* Look for any existing macro */
n = macro_find_exact(pat);
/* Replace existing macro */
if (n >= 0)
{
/* Free the old macro action */
string_free(macro__act[n]);
}
/* Create a new macro */
else
{
/* Get a new index */
n = macro__num++;
/* Save the pattern */
macro__pat[n] = string_make(pat);
}
/* Save the action */
macro__act[n] = string_make(act);
/* Efficiency */
macro__use[(byte)(pat[0])] = TRUE;
/* Success */
return (0);
}
/*
* Initialize the "macro" package
*/
errr macro_init(void)
{
/* Macro patterns */
macro__pat = (char**)C_ZNEW(MACRO_MAX, cptr);
/* Macro actions */
macro__act = (char**)C_ZNEW(MACRO_MAX, cptr);
/* Success */
return (0);
}
/*
* Flush all pending input.
*
* Actually, remember the flush, using the "inkey_xtra" flag, and in the
* next call to "inkey()", perform the actual flushing, for efficiency,
* and correctness of the "inkey()" function.
*/
void flush(void)
{
/* Do it later */
inkey_xtra = TRUE;
}
/*
* Local variable -- we are inside a "macro action"
*
* Do not match any macros until "ascii 30" is found.
*/
static bool parse_macro = FALSE;
/*
* Local variable -- we are inside a "macro trigger"
*
* Strip all keypresses until a low ascii value is found.
*/
static bool parse_under = FALSE;
static key_event inkey_aux(void)
{
int k, n;
int p = 0, w = 0;
key_event ke, ke0;
char ch;
cptr pat, act;
char buf[1024];
/* Initialize the no return */
ke0.key = 0;
ke0.mousebutton = 0; /* To fix GCC warnings on X11 */
ke0.mousey = 0;
ke0.mousex = 0;
/* Wait for a keypress */
(void)(Term_inkey(&ke, TRUE, TRUE));
ch = ke.key;
/* End "macro action" */
if ((ch == 30) || (ch == '\xff'))
{
parse_macro = FALSE;
return (ke);
}
/* Inside "macro action" */
if (ch == 30) return (ke);
/* Inside "macro action" */
if (parse_macro) return (ke);
/* Inside "macro trigger" */
if (parse_under) return (ke);
/* Save the first key, advance */
buf[p++] = ch;
buf[p] = '\0';
/* Check for possible macro */
k = macro_find_check(buf);
/* No macro pending */
if (k < 0) return (ke);
/* Wait for a macro, or a timeout */
while (TRUE)
{
/* Check for pending macro */
k = macro_find_maybe(buf);
/* No macro pending */
if (k < 0) break;
/* Check for (and remove) a pending key */
if (0 == Term_inkey(&ke, FALSE, TRUE))
{
/* Append the key */
buf[p++] = ke.key;
buf[p] = '\0';
/* Restart wait */
w = 0;
}
/* No key ready */
else
{
/* Increase "wait" */
w += 10;
/* Excessive delay */
if (w >= 100) break;
/* Delay */
Term_xtra(TERM_XTRA_DELAY, w);
}
}
/* Check for available macro */
k = macro_find_ready(buf);
/* No macro available */
if (k < 0)
{
/* Push all the keys back on the queue */
while (p > 0)
{
/* Push the key, notice over-flow */
if (Term_key_push(buf[--p])) return (ke0);
}
/* Wait for (and remove) a pending key */
(void)Term_inkey(&ke, TRUE, TRUE);
/* Return the key */
return (ke);
}
/* Get the pattern */
pat = macro__pat[k];
/* Get the length of the pattern */
n = strlen(pat);
/* Push the "extra" keys back on the queue */
while (p > n)
{
/* Push the key, notice over-flow */
if (Term_key_push(buf[--p])) return (ke0);
}
/* Begin "macro action" */
parse_macro = TRUE;
/* Push the "end of macro action" key */
if (Term_key_push(30)) return (ke0);
/* Get the macro action */
act = macro__act[k];
/* Get the length of the action */
n = strlen(act);
/* Push the macro "action" onto the key queue */
while (n > 0)
{
/* Push the key, notice over-flow */
if (Term_key_push(act[--n])) return (ke0);
}
/* Hack -- Force "inkey()" to call us again */
return (ke0);
}
/*
* Mega-Hack -- special "inkey_next" pointer. XXX XXX XXX
*
* This special pointer allows a sequence of keys to be "inserted" into
* the stream of keys returned by "inkey()". This key sequence will not
* trigger any macros, and cannot be bypassed by the Borg. It is used
* in Angband to handle "keymaps".
*/
static cptr inkey_next = NULL;
#ifdef ALLOW_BORG
/*
* Mega-Hack -- special "inkey_hack" hook. XXX XXX XXX
*
* This special function hook allows the "Borg" (see elsewhere) to take
* control of the "inkey()" function, and substitute in fake keypresses.
*/
char (*inkey_hack)(int flush_first) = NULL;
#endif /* ALLOW_BORG */
/*
* Get a keypress, mouse click or mouse move from the user
*
* This function recognizes a few "global parameters". These are variables
* which, if set to TRUE before calling this function, will have an effect
* on this function, and which are always reset to FALSE by this function
* before this function returns. Thus they function just like normal
* parameters, except that most calls to this function can ignore them.
*
* If "inkey_xtra" is TRUE, then all pending keypresses will be flushed,
* and any macro processing in progress will be aborted. This flag is
* set by the "flush()" function, which does not actually flush anything
* itself, but rather, triggers delayed input flushing via "inkey_xtra".
*
* If "inkey_scan" is TRUE, then we will immediately return "zero" if no
* keypress is available, instead of waiting for a keypress.
*
* If "inkey_base" is TRUE, then all macro processing will be bypassed.
* If "inkey_base" and "inkey_scan" are both TRUE, then this function will
* not return immediately, but will wait for a keypress for as long as the
* normal macro matching code would, allowing the direct entry of macro
* triggers. The "inkey_base" flag is extremely dangerous!
*
* If "inkey_flag" is TRUE, then we will assume that we are waiting for a
* normal command, and we will only show the cursor if "hilite_player" is
* TRUE (or if the player is in a store), instead of always showing the
* cursor. The various "main-xxx.c" files should avoid saving the game
* in response to a "menu item" request unless "inkey_flag" is TRUE, to
* prevent savefile corruption.
*
* If we are waiting for a keypress, and no keypress is ready, then we will
* refresh (once) the window which was active when this function was called.
*
* Note that "back-quote" is automatically converted into "escape" for
* convenience on machines with no "escape" key. This is done after the
* macro matching, so the user can still make a macro for "backquote".
*
* Note the special handling of "ascii 30" (ctrl-caret, aka ctrl-shift-six)
* and "ascii 31" (ctrl-underscore, aka ctrl-shift-minus), which are used to
* provide support for simple keyboard "macros". These keys are so strange
* that their loss as normal keys will probably be noticed by nobody. The
* "ascii 30" key is used to indicate the "end" of a macro action, which
* allows recursive macros to be avoided. The "ascii 31" key is used by
* some of the "main-xxx.c" files to introduce macro trigger sequences.
*
* Hack -- we use "ascii 29" (ctrl-right-bracket) as a special "magic" key,
* which can be used to give a variety of "sub-commands" which can be used
* any time. These sub-commands could include commands to take a picture of
* the current screen, to start/stop recording a macro action, etc.
*
* If "term_screen" is not active, we will make it active during this
* function, so that the various "main-xxx.c" files can assume that input
* is only requested (via "Term_inkey()") when "term_screen" is active.
*
* Mega-Hack -- This function is used as the entry point for clearing the
* "signal_count" variable, and of the "character_saved" variable.
*
* Hack -- Note the use of "inkey_next" to allow "keymaps" to be processed.
*
* Mega-Hack -- Note the use of "inkey_hack" to allow the "Borg" to steal
* control of the keyboard from the user.
*/
key_event inkey_ex(void)
{
key_event kk = {0, 0, 0, 0};
key_event ke = {0, 0, 0, 0};
bool done = FALSE;
term *old = Term;
bool cursor_state[ANGBAND_TERM_MAX];
int j;
/* Initialise keypress */
ke.key = 0;
/* Hack -- Use the "inkey_next" pointer */
if (inkey_next && *inkey_next && !inkey_xtra)
{
/* Get next character, and advance */
ke.key = *inkey_next++;
/* Cancel the various "global parameters" */
inkey_base = inkey_xtra = inkey_flag = inkey_scan = FALSE;
/* Accept result */
return (ke);
}
/* Forget pointer */
inkey_next = NULL;
#ifdef ALLOW_BORG
/* Mega-Hack -- Use the special hook */
if (inkey_hack && ((ke.key = (*inkey_hack)(inkey_xtra)) != 0))
{
/* Cancel the various "global parameters" */
inkey_base = inkey_xtra = inkey_flag = inkey_scan = FALSE;
/* Accept result */
return (ke);
}
#endif /* ALLOW_BORG */
/* Hack -- handle delayed "flush()" */
if (inkey_xtra)
{
/* End "macro action" */
parse_macro = FALSE;
/* End "macro trigger" */
parse_under = FALSE;
/* Forget old keypresses */
Term_flush();
}
/* Show the cursor if waiting, except sometimes in "command" mode */
if (!inkey_scan && (!inkey_flag || hilite_player /*|| character_icky*/))
{
/* Scan windows */
for (j = 0; j < ANGBAND_TERM_MAX; j++)
{
term *t = angband_term[j];
/* No window */
if (!t) continue;
/* No relevant flags */
if ((j > 0) && !(op_ptr->window_flag[j] & (PW_MAP)))
continue;
/* Activate the map term */
Term_activate(t);
/* Get the cursor state */
(void)Term_get_cursor(&cursor_state[j]);
/* Show the cursor */
(void)Term_set_cursor(TRUE);
/* Refresh the term to draw the cursor */
/*
* The main screen is ignored because of some screen
* flickering when "show_lists" is on. -DG-
*/
if ((j > 0) && !cursor_state[j]) (void)Term_fresh();
}
}
/* Hack -- Activate main screen */
Term_activate(term_screen);
/* Get a key */
while (!ke.key)
{
/* Hack -- Handle "inkey_scan" */
if (!inkey_base && inkey_scan &&
(0 != Term_inkey(&kk, FALSE, FALSE)))
{
break;
}
/* Hack -- Flush output once when no key ready */
if (!done && (0 != Term_inkey(&kk, FALSE, FALSE)))
{
/* Hack -- activate proper term */
Term_activate(old);
/* Flush output */
Term_fresh();
/* Hack -- activate main screen */
Term_activate(term_screen);
/* Mega-Hack -- reset saved flag */
character_saved = FALSE;
/* Mega-Hack -- reset signal counter */
signal_count = 0;
/* Only once */
done = TRUE;
}
/* Hack -- Handle "inkey_base" */
if (inkey_base)
{
int w = 0;
/* Wait forever */
if (!inkey_scan)
{
/* Wait for (and remove) a pending key */
if (0 == Term_inkey(&ke, TRUE, TRUE))
{
/* Done */
break;
}
/* Oops */
break;
}
/* Wait */
while (TRUE)
{
/* Check for (and remove) a pending key */
if (0 == Term_inkey(&ke, FALSE, TRUE))
{
/* Done */
break;
}
/* No key ready */
else
{
/* Increase "wait" */
w += 10;
/* Excessive delay */
if (w >= 100) break;
/* Delay */
Term_xtra(TERM_XTRA_DELAY, w);
}
}
/* Done */
break;
}
/* Get a key (see above) */
ke = inkey_aux();
/* Handle "<API key>" */
if (ke.key == 29)
{
/* Strip this key */
ke.key = 0;
/* Hack -- always do an html dump */
dump_html();
/* Continue */
continue;
}
/* Treat back-quote as escape */
if (ke.key == '`') ke.key = ESCAPE;
/* End "macro trigger" */
if (parse_under && (ke.key <= 32))
{
/* Strip this key */
ke.key = 0;
/* End "macro trigger" */
parse_under = FALSE;
}
/* Handle "control-caret" */
if (ke.key == 30)
{
/* Strip this key */
ke.key = 0;
}
/* Handle "control-underscore" */
else if (ke.key == 31)
{
/* Strip this key */
ke.key = 0;
/* Begin "macro trigger" */
parse_under = TRUE;
}
/* Inside "macro trigger" */
else if (parse_under)
{
/* Strip this key */
ke.key = 0;
}
}
/* Hide the cursor again */
if (!inkey_scan && (!inkey_flag || hilite_player/* || character_icky*/))
{
/* Scan windows */
for (j = 0; j < ANGBAND_TERM_MAX; j++)
{
term *t = angband_term[j];
/* No window */
if (!t) continue;
/* No relevant flags */
if ((j > 0) && !(op_ptr->window_flag[j] & PW_MAP)) continue;
/* Activate the term */
Term_activate(t);
/* Restore the cursor */
(void)Term_set_cursor(cursor_state[j]);
/* Refresh to erase the cursor
* The main screen is ignored because of some screen
* flickering when "show_lists" is on. -DG-
*/
if ((j > 0) && !cursor_state[j])
{
(void)Term_fresh();
}
}
}
/* Hack -- restore the term */
Term_activate(old);
/* Cancel the various "global parameters" */
inkey_base = inkey_xtra = inkey_flag = inkey_scan = FALSE;
/* Return the keypress */
return (ke);
}
/*
* Get a keypress or mouse click from the user.
*/
key_event anykey(void)
{
key_event ke = {0, 0, 0, 0};
/* Only accept a keypress or mouse click*/
do
{
ke = inkey_ex();
} while ((ke.key == '\xff') && !(ke.mousebutton));
return ke;
}
/*
* Get a keypress from the user.
*/
char inkey(void)
{
key_event ke;
/* Only accept a keypress */
do
{
ke = inkey_ex();
} while (ke.key == '\xff');
return ke.key;
}
/*
* We are delaying message display
*/
static bool must_more = FALSE;
/*
* Flush the screen, make a noise
*/
void bell(cptr reason)
{
/* Mega-Hack -- Flush the output */
Term_fresh();
/* Hack -- memorize the reason if possible */
if (character_generated && reason && !must_more) message_add(reason, MSG_BELL);
/* Make a bell noise (if allowed) */
if (ring_bell) Term_xtra(TERM_XTRA_NOISE, 0);
/* Flush the input (later!) */
flush();
}
/*
* Hack -- Make a (relevant?) sound
*/
void sound(int val)
{
/* No sound */
if (!use_sound) return;
/* Make a sound (if allowed) */
Term_xtra(TERM_XTRA_SOUND, val);
}
/*
* The "quark" package
*
* This package is used to reduce the memory usage of object inscriptions.
*
* We use dynamic string allocation because otherwise it is necessary to
* pre-guess the amount of quark activity. We limit the total number of
* quarks, but this is much easier to "expand" as needed. XXX XXX XXX
*
* Two objects with the same inscription will have the same "quark" index.
*
* Some code uses "zero" to indicate the non-existance of a quark.
*
* Note that "quark zero" is NULL and should never be "dereferenced".
*
* ToDo: Add reference counting for quarks, so that unused quarks can
* be overwritten.
*
* ToDo: Automatically resize the array if necessary.
*/
/*
* The number of quarks (first quark is NULL)
*/
static s16b quark__num = 1;
/*
* The array[QUARK_MAX] of pointers to the quarks
*/
static char **quark__str;
/*
* Add a new "quark" to the set of quarks.
*/
s16b quark_add(cptr str)
{
int i;
/* Look for an existing quark */
for (i = 1; i < quark__num; i++)
{
/* Check for equality */
if (streq(quark__str[i], str)) return (i);
}
/* Hack -- Require room XXX XXX XXX */
if (quark__num == QUARK_MAX) return (0);
/* New quark */
i = quark__num++;
/* Add a new quark */
quark__str[i] = string_make(str);
/* Return the index */
return (i);
}
/*
* This function looks up a quark
*/
cptr quark_str(s16b i)
{
cptr q;
/* Verify */
if ((i < 0) || (i >= quark__num)) i = 0;
/* Get the quark */
q = quark__str[i];
/* Return the quark */
return (q);
}
/*
* Initialize the "quark" package
*/
errr quarks_init(void)
{
/* Quark variables */
quark__str = (char**)C_ZNEW(QUARK_MAX, cptr);
/* Success */
return (0);
}
/*
* Free the "quark" package
*/
errr quarks_free(void)
{
int i;
/* Free the "quarks" */
for (i = 1; i < quark__num; i++)
{
string_free(quark__str[i]);
}
/* Free the list of "quarks" */
FREE(quark__str);
/* Success */
return (0);
}
/*
* The "message memorization" package.
*
* Each call to "message_add(s)" will add a new "most recent" message
* to the "message recall list", using the contents of the string "s".
*
* The number of memorized messages is available as "message_num()".
*
* Old messages can be retrieved by "message_str(age)", where the "age"
* of the most recently memorized message is zero, and the oldest "age"
* which is available is "message_num() - 1". Messages outside this
* range are returned as the empty string.
*
* The messages are stored in a special manner that maximizes "efficiency",
* that is, we attempt to maximize the number of semi-sequential messages
* that can be retrieved, given a limited amount of storage space, without
* causing the memorization of new messages or the recall of old messages
* to be too expensive.
*
* We keep a buffer of chars to hold the "text" of the messages, more or
* less in the order they were memorized, and an array of offsets into that
* buffer, representing the actual messages, but we allow the "text" to be
* "shared" by two messages with "similar" ages, as long as we never cause
* sharing to reach too far back in the the buffer.
*
* The implementation is complicated by the fact that both the array of
* offsets, and the buffer itself, are both treated as "circular arrays"
* for efficiency purposes, but the strings may not be "broken" across
* the ends of the array.
*
* When we want to memorize a new message, we attempt to "reuse" the buffer
* space by checking for message duplication within the recent messages.
*
* Otherwise, if we need more buffer space, we grab a full quarter of the
* total buffer space at a time, to keep the reclamation code efficient.
*
* The "message_add()" function is rather "complex", because it must be
* extremely efficient, both in space and time, for use with the Borg.
*/
/*
* The next "free" index to use
*/
static u16b message__next;
/*
* The index of the oldest message (none yet)
*/
static u16b message__last;
/*
* The next "free" offset
*/
static u16b message__head;
/*
* The offset to the oldest used char (none yet)
*/
static u16b message__tail;
/*
* The next message to display for the easy_more code (none yet)
*/
static u16b message__easy;
/*
* The array[MESSAGE_MAX] of offsets, by index
*/
static u16b *message__ptr;
/*
* The array[MESSAGE_BUF] of chars, by offset
*/
static char *message__buf;
/*
* The array[MESSAGE_MAX] of u16b for the types of messages
*/
static u16b *message__type;
/*
* Table of colors associated to message-types
*/
static byte message__color[MSG_MAX];
/*
* How many messages are "available"?
*/
s16b message_num(void)
{
/* Determine how many messages are "available" */
return (message__next + MESSAGE_MAX - message__last) % MESSAGE_MAX;
}
/*
* Recall the "text" of a saved message
*/
cptr message_str(s16b age)
{
s16b x;
s16b o;
cptr s;
/* Forgotten messages have no text */
if ((age < 0) || (age >= message_num())) return ("");
/* Get the "logical" index */
x = (message__next + MESSAGE_MAX - (age + 1)) % MESSAGE_MAX;
/* Get the "offset" for the message */
o = message__ptr[x];
/* Get the message text */
s = &message__buf[o];
/* Return the message text */
return (s);
}
/*
* Recall the "type" of a saved message
*/
u16b message_type(s16b age)
{
s16b x;
/* Paranoia */
if (!message__type) return (MSG_GENERIC);
/* Forgotten messages are generic */
if ((age < 0) || (age >= message_num())) return (MSG_GENERIC);
/* Get the "logical" index */
x = (message__next + MESSAGE_MAX - (age + 1)) % MESSAGE_MAX;
/* Return the message type */
return (message__type[x]);
}
/*
* Recall the "color" of a message type
*/
byte message_type_color(u16b type)
{
byte color = message__color[type];
if (color == TERM_DARK) color = TERM_WHITE;
return (color);
}
/*
* Recall the "color" of a saved message
*/
byte message_color(s16b age)
{
return message_type_color(message_type(age));
}
errr <API key>(u16b type, byte color)
{
if (type >= MSG_MAX) return (1);
/* Store the color */
message__color[type] = color;
/* Success */
return (0);
}
/*
* Add a new message, with great efficiency
*
* We must ignore long messages to prevent internal overflow, since we
* assume that we can always get enough space by advancing "message__tail"
* by one quarter the total buffer space.
*
* We must not attempt to optimize using a message index or buffer space
* which is "far away" from the most recent entries, or we will lose a lot
* of messages when we "expire" the old message index and/or buffer space.
*
* We attempt to minimize the use of "string compare" operations in this
* function, because they are expensive when used in mass quantities.
*/
void message_add(cptr str, u16b type)
{
int n, k, i, x, o;
cptr s;
cptr t;
cptr u;
char *v;
/*** Step 1 -- Analyze the message ***/
/* Hack -- Ignore "non-messages" */
if (!str) return;
/* Message length */
n = strlen(str);
/* Hack -- Ignore "long" messages */
if (n >= MESSAGE_BUF / 4) return;
/*** Step 2 -- Attempt to optimize ***/
/* Limit number of messages to check */
k = message_num() / 4;
/* Limit number of messages to check */
if (k > 32) k = 32;
/* Start just after the most recent message */
i = message__next;
/* Check the last few messages for duplication */
for ( ; k; k
{
u16b q;
cptr old;
/* Back up, wrap if needed */
if (i-- == 0) i = MESSAGE_MAX - 1;
/* Stop before oldest message */
if (i == message__last) break;
/* Index */
o = message__ptr[i];
/* Extract "distance" from "head" */
q = (message__head + MESSAGE_BUF - o) % MESSAGE_BUF;
/* Do not optimize over large distances */
if (q >= MESSAGE_BUF / 4) continue;
/* Get the old string */
old = &message__buf[o];
/* Inline 'streq(str, old)' */
for (s = str, t = old; (*s == *t) && *s; ++s, ++t) /* loop */ ;
/* Continue if not equal */
if (*s) continue;
/* Get the next available message index */
x = message__next;
/* Advance 'message__next', wrap if needed */
if (++message__next == MESSAGE_MAX) message__next = 0;
/* Kill last message if needed */
if (message__next == message__last)
{
/* Update the 'message__easy', wrap if needed */
if ((message__last == message__easy) && (++message__last == MESSAGE_MAX)) message__easy = 0;
/* Advance 'message__last', wrap if needed */
if (++message__last == MESSAGE_MAX) message__last = 0;
}
/* Assign the starting address */
message__ptr[x] = message__ptr[i];
/* Store the message type */
message__type[x] = type;
/* Success */
return;
}
/*** Step 3 -- Ensure space before end of buffer ***/
/* Kill messages, and wrap, if needed */
if (message__head + (n + 1) >= MESSAGE_BUF)
{
bool update_easy = FALSE;
/* Kill all "dead" messages */
for (i = message__last; TRUE; i++)
{
/* Wrap if needed */
if (i == MESSAGE_MAX) i = 0;
/* Stop before the new message */
if (i == message__next) break;
/* Update message__easy if required */
if (i == message__easy) update_easy = TRUE;
/* Get offset */
o = message__ptr[i];
/* Kill "dead" messages */
if (o >= message__head)
{
/* Track oldest message */
message__last = i + 1;
/* Update easy if required */
if (update_easy) message__easy = i + 1;
}
}
/* Wrap "tail" if needed */
if (message__tail >= message__head) message__tail = 0;
/* Start over */
message__head = 0;
}
/*** Step 4 -- Ensure space for actual characters ***/
/* Kill messages, if needed */
if (message__head + (n + 1) > message__tail)
{
bool update_easy = FALSE;
/* Advance to new "tail" location */
message__tail += (MESSAGE_BUF / 4);
/* Kill all "dead" messages */
for (i = message__last; TRUE; i++)
{
/* Wrap if needed */
if (i == MESSAGE_MAX) i = 0;
/* Stop before the new message */
if (i == message__next) break;
/* Update message__easy if required */
if (i == message__easy) update_easy = TRUE;
/* Get offset */
o = message__ptr[i];
/* Kill "dead" messages */
if ((o >= message__head) && (o < message__tail))
{
/* Track oldest message */
message__last = i + 1;
/* Update easy if required */
if (update_easy) message__easy = i + 1;
}
}
}
/*** Step 5 -- Grab a new message index ***/
/* Get the next available message index */
x = message__next;
/* Advance 'message__next', wrap if needed */
if (++message__next == MESSAGE_MAX) message__next = 0;
/* Kill last message if needed */
if (message__next == message__last)
{
/* Update the 'message__easy', wrap if needed */
if ((message__last == message__easy) && (++message__last == MESSAGE_MAX)) message__easy = 0;
/* Advance 'message__last', wrap if needed */
if (++message__last == MESSAGE_MAX) message__last = 0;
}
/*** Step 6 -- Insert the message text ***/
/* Assign the starting address */
message__ptr[x] = message__head;
/* Inline 'strcpy(message__buf + message__head, str)' */
v = message__buf + message__head;
for (u = str; *u; ) *v++ = *u++;
*v = '\0';
/* Advance the "head" pointer */
message__head += (n + 1);
/* Store the message type */
message__type[x] = type;
}
/*
* This displays all the messages on the screen, trying to
* minimise the amount of times the -more- key has to be
* pressed, by using all the available screen space.
*
* If command is set to true, we re-display the command
* prompt once this is done, and pass back the last key
* press as a command.
*/
void messages_easy(bool command)
{
int y, x, w, h;
byte a = TERM_L_BLUE;
key_event ke;
char *t;
char buf[1024];
/* Easy more option not selected. */
if (!easy_more)
{
message__easy = message__next;
return;
}
/* Nothing to display. */
else if (!must_more)
{
return;
}
/* Nothing to display. */
else if (message__easy == message__next)
{
return;
}
/* Don't display if character is dead or not yet generated */
else if (!character_generated || p_ptr->is_dead)
{
return;
}
/* Save the screen */
screen_save();
/* Obtain the size */
(void)Term_get_size(&w, &h);
/* Display remaining messages on line 2 of the display onwards */
for (y = (msg_flag ? 0 : 1), x = 0 ; (message__easy != message__next); )
{
/* Get the "offset" for the message */
int o = message__ptr[message__easy];
/* Get the message text */
cptr msg = &message__buf[o];
/* Get the color */
byte color = message_type_color(message__type[message__easy]);
int n = strlen(msg);
bool long_line = FALSE;
if ((x) && (x + n) > (w))
{
/* Go to next row if required */
x = 0;
y++;
}
/* Improve legibility of long entries */
if (n > (w - 8)) long_line = TRUE;
/* Copy it */
strncpy(buf, msg, sizeof(buf));
buf[sizeof(buf)-1] = '\0';
/* Analyze the buffer */
t = buf;
/* Split message */
while (n > (w - 1))
{
char oops;
int check, split;
/* Default split */
split = (w - 1);
/* Find the "best" split point */
for (check = (w / 2); check < (w - 1); check++)
{
/* Found a valid split point */
if (t[check] == ' ') split = check;
}
/* Save the split character */
oops = t[split];
/* Split the message */
t[split] = '\0';
/* Display part of the message */
Term_putstr(x, y, split, color, t);
/* Erase to end of line to improve legibility */
if (long_line)
{
/* Clear top line */
Term_erase(x + split, y, 255);
}
else
{
/* Add a space for legibility */
Term_putstr(x + split, y, -1, TERM_WHITE, " ");
}
/* Restore the split character */
t[split] = oops;
/* Prepare to recurse on the rest of "buf" */
t += split; n -= split;
/* Reset column and line */
x = 0;
y++;
}
/* Display the tail of the message */
Term_putstr(x, y, n, color, t);
/* Add a space for legibility */
Term_putstr(x + n, y, -1, TERM_WHITE, " ");
/* Get next message */
message__easy = (message__easy + 1) % MESSAGE_MAX;
/* Get next position */
x += n + 1;
/* Display more prompt if reached near end of page */
if ((y >= (h < 12 ? h - (show_sidebar ? 3 : 2) : (h > 23 ? (h / 2) - (show_sidebar ? 2 : 1) : 11 - (show_sidebar ? 3 : 2))))
/* Display more prompt if out of messages */
|| (message__easy == message__next))
{
/* Pause for response */
Term_putstr(0, y + 1, -1, a, message__easy == message__next ? "-end-" : "-more-");
/* Get keypress */
ke = inkey_ex();
/* Get an acceptable keypress. */
while (1)
{
while ((ke.key == '\xff') && !(ke.mousebutton))
{
int yi = KEY_GRID_Y(ke);
int xi = KEY_GRID_X(ke);
int room = dun_room[p_ptr->py/BLOCK_HGT][p_ptr->px/BLOCK_WID];
ke = <API key>(yi, xi, &room, TARGET_PEEK, (use_mouse ? "*,left-click to target, right-click to go to" : "*"));
}
#if 0
if ((p_ptr->chp < warning) && (ke.key != 'c')) { bell("Press c to continue."); continue; }
#endif
if (quick_messages) break;
if ((ke.key == ESCAPE) || (ke.key == ' ')) break;
if ((ke.key == '\n') || (ke.key == '\r')) break;
if ((ke.key == '\xff') && (ke.mousebutton == 1)) break;
bell("Illegal response to a 'more' prompt!");
/* Get keypress */
ke = inkey_ex();
}
/* Refresh screen */
screen_load();
/* Tried a command - avoid rest of messages */
if (ke.key != ' ') break;
if (message__easy != message__next) screen_save();
/* Start at top left hand side */
y = (use_trackmouse ? 1 : 0);
x = 0;
}
}
/* Allow 1 line messages again */
must_more = FALSE;
/* Clear the message flag */
msg_flag = FALSE;
/* Clear top line */
Term_erase(0, 0, 255);
/* Display command prompt */
if (command)
{
Term_putstr(0, 0, -1, TERM_WHITE, "Command:");
/* Requeue command just pressed */
p_ptr->command_new = ke;
/* Hack -- Process "Escape"/"Spacebar"/"Return" */
if ((p_ptr->command_new.key == ESCAPE) ||
/*(p_ptr->command_new.key == ' ') ||*/
(p_ptr->command_new.key == '\r') ||
(p_ptr->command_new.key == '\n'))
{
/* Reset stuff */
p_ptr->command_new.key = 0;
}
}
}
/*
* Initialize the "message" package
*/
errr messages_init(void)
{
/* Message variables */
message__ptr = C_ZNEW(MESSAGE_MAX, u16b);
message__buf = C_ZNEW(MESSAGE_BUF, char);
message__type = C_ZNEW(MESSAGE_MAX, u16b);
/* Init the message colors to white */
memset(message__color,TERM_WHITE,MSG_MAX * sizeof(byte));
/* Hack -- No messages yet */
message__tail = MESSAGE_BUF;
/* Hack -- No messages for easy_more */
message__easy = MESSAGE_BUF;
/* Success */
return (0);
}
/*
* Free the "message" package
*/
void messages_free(void)
{
/* Free the messages */
FREE(message__ptr);
FREE(message__buf);
FREE(message__type);
}
/*
* Move the cursor
*/
void move_cursor(int row, int col)
{
Term_gotoxy(col, row);
}
/*
* Hack -- flush
*/
static void msg_flush(int x)
{
byte a = TERM_L_BLUE;
/* Handle easy_more */
if (easy_more) return;
#if 0
int warning = (p_ptr->mhp * op_ptr->hitpoint_warn / 10);
/* Pause for response */
if (p_ptr->chp < warning)
{
Term_putstr(x, 0, -1, a, "-c to continue-");
}
else
{
#endif
/* Pause for response */
Term_putstr(x, 0, -1, a, "-more-");
#if 0
}
#endif
/* Get an acceptable keypress */
while (1)
{
key_event ke;
ke = anykey();
if ((ke.key == '\xff') && !(ke.mousebutton)) continue;
#if 0
if ((p_ptr->chp < warning) && (ke.key != 'c')) { bell("Press c to continue."); continue; }
#endif
if (quick_messages) break;
if ((ke.key == ESCAPE) || (ke.key == ' ')) break;
if ((ke.key == '\n') || (ke.key == '\r')) break;
if ((ke.key == '\xff') && (ke.mousebutton == 1)) break;
bell("Illegal response to a 'more' prompt!");
}
/* Clear the line */
Term_erase(0, 0, 255);
}
static int message_column = 0;
/*
* Output a message to the top line of the screen.
*
* Break long messages into multiple pieces (40-72 chars).
*
* Allow multiple short messages to "share" the top line.
*
* Prompt the user to make sure he has a chance to read them.
*
* These messages are memorized for later reference (see above).
*
* We could do a "Term_fresh()" to provide "flicker" if needed.
*
* The global "msg_flag" variable can be cleared to tell us to "erase" any
* "pending" messages still on the screen, instead of using "msg_flush()".
* This should only be done when the user is known to have read the message.
*
* We must be very careful about using the "msg_print()" functions without
* explicitly calling the special "msg_print(NULL)" function, since this may
* result in the loss of information if the screen is cleared, or if anything
* is displayed on the top line.
*
* Hack -- Note that "msg_print(NULL)" will clear the top line even if no
* messages are pending.
*/
static void msg_print_aux(u16b type, cptr msg)
{
int n;
char *t;
char buf[1024];
byte color;
int w, h;
#ifdef ALLOW_BORG
/* Hack -- No messages for the borg */
if ((count_stop) && !(auto_more) && !(must_more)) return;
#endif
/* Obtain the size */
(void)Term_get_size(&w, &h);
/* Hack -- Reset */
if (!msg_flag) message_column = 0;
/* Message Length */
n = (msg ? strlen(msg) : 0);
/* Hack -- flush when requested or needed */
if ((message_column || easy_more) && (!msg || ((message_column + n) > (w))))
{
bool hack_use_first_line = (easy_more && !must_more && !message_column && msg && !use_trackmouse);
bool hack_flush = (easy_more && message_column && !use_trackmouse && ((message_column + n) <= (w)) && !must_more && !msg);
/* Handle easy_more */
if (easy_more && msg && !must_more)
{
/* Display messages from this point onwards */
message__easy = message__next;
/* Delay displaying remaining messages */
must_more = TRUE;
}
/* Hack -- allow single line '-more-' */
if (hack_flush) easy_more = FALSE;
/* Flush */
msg_flush(message_column);
/* Hack -- allow single line '-more-' */
if (hack_flush) easy_more = TRUE;
/* Forget it */
msg_flag = hack_use_first_line;
/* Reset */
message_column = 0;
}
/* No message */
if (!msg) return;
/* Paranoia */
if (n > 1000) return;
if (character_generated && !(p_ptr->is_dead))
message_add(msg, type);
/* Window stuff */
p_ptr->window |= (PW_MESSAGE);
/* Handle "auto_more"/"must_more"/"use_trackmouse" */
if ((auto_more && !easy_more) || must_more)
{
/* Force window update */
window_stuff();
/* Done */
return;
}
/* Copy it */
strncpy(buf, msg, sizeof(buf));
buf[sizeof(buf)-1] = '\0';
/* Analyze the buffer */
t = buf;
/* Get the color of the message */
color = message_type_color(type);
/* Split message */
while (n > (w))
{
char oops;
int check, split;
/* Default split */
split = (w);
/* Find the "best" split point */
for (check = (w / 2); check < (w); check++)
{
/* Found a valid split point */
if (t[check] == ' ') split = check;
}
/* Save the split character */
oops = t[split];
/* Split the message */
t[split] = '\0';
/* Display part of the message */
Term_putstr(0, 0, split, color, t);
/* Flush it */
msg_flush(split + 1);
/* Restore the split character */
t[split] = oops;
/* Insert a space */
t[--split] = ' ';
/* Prepare to recurse on the rest of "buf" */
t += split; n -= split;
}
/* Insert a space */
t[n] = ' ';
/* Display the tail of the message */
Term_putstr(message_column, 0, n + 1, color, t);
/* Remember the message */
msg_flag = TRUE;
/* Remember the position */
message_column += n + 1;
}
/*
* Print a message in the default color (white)
*/
void msg_print(cptr msg)
{
msg_print_aux(MSG_GENERIC, msg);
}
/*
* Display a formatted message, using "vstrnfmt()" and "msg_print()".
*/
void msg_format(cptr fmt, ...)
{
va_list vp;
char buf[1024];
/* Begin the Varargs Stuff */
va_start(vp, fmt);
/* Format the args, save the length */
(void)vstrnfmt(buf, 1024, fmt, vp);
/* End the Varargs Stuff */
va_end(vp);
/* Display */
msg_print_aux(MSG_GENERIC, buf);
}
/*
* Display a message and play the associated sound.
*
* The "extra" parameter is currently unused.
*/
void message(u16b message_type, s16b extra, cptr message)
{
/* Unused parameter */
(void)extra;
sound(message_type);
msg_print_aux(message_type, message);
}
/*
* Display a formatted message and play the associated sound.
*
* The "extra" parameter is currently unused.
*/
void message_format(u16b message_type, s16b extra, cptr fmt, ...)
{
va_list vp;
char buf[1024];
/* Begin the Varargs Stuff */
va_start(vp, fmt);
/* Format the args, save the length */
(void)vstrnfmt(buf, 1024, fmt, vp);
/* End the Varargs Stuff */
va_end(vp);
/* Display */
message(message_type, extra, buf);
}
/*
* Print the queued messages.
*
* Note we'd like to call messages_easy here but can't
* because this causes an infinite loop between here,
* messages_easy and screen_save.
*/
void message_flush(void)
{
/* Hack -- Reset */
if (!msg_flag) message_column = 0;
/* Flush when needed */
if (message_column)
{
/* Print pending messages */
msg_flush(message_column);
/* Forget it */
msg_flag = FALSE;
/* Reset */
message_column = 0;
}
}
/*
* Hack -- prevent "accidents" in "screen_save()" or "screen_load()"
*/
static int screen_depth = 0;
/*
* Save the screen, and increase the "icky" depth.
*
* This function must match exactly one call to "screen_load()".
*/
void screen_save(void)
{
/* Hack -- Flush messages */
message_flush();
if (screen_depth++ == 0) Term_save();
/* Increase "icky" depth */
character_icky++;
}
/*
* Load the screen, and decrease the "icky" depth.
*
* This function must match exactly one call to "screen_save()".
*/
void screen_load(void)
{
/* Hack -- Flush messages */
message_flush();
if (--screen_depth == 0) Term_load();
/* Decrease "icky" depth */
character_icky
}
/*
* Display a string on the screen using an attribute.
*
* At the given location, using the given attribute, if allowed,
* add the given string. Do not clear the line.
*/
void c_put_str(byte attr, cptr str, int row, int col)
{
/* Position cursor, Dump the attr/text */
Term_putstr(col, row, -1, attr, str);
}
/*
* As above, but in "white"
*/
void put_str(cptr str, int row, int col)
{
/* Spawn */
Term_putstr(col, row, -1, TERM_WHITE, str);
}
/*
* Display a string on the screen using an attribute, and clear
* to the end of the line.
*/
void c_prt(byte attr, cptr str, int row, int col)
{
/* Clear line, position cursor */
Term_erase(col, row, 255);
/* Dump the attr/text */
Term_addstr(-1, attr, str);
}
/*
* As above, but in "white"
*/
void prt(cptr str, int row, int col)
{
/* Spawn */
c_prt(TERM_WHITE, str, row, col);
}
void text_out_to_screen(byte a, cptr str)
{
int x, y;
int wid, h;
int wrap;
cptr s;
/* Obtain the size */
(void)Term_get_size(&wid, &h);
/* Obtain the cursor */
(void)Term_locate(&x, &y);
/* Use special wrapping boundary? */
if ((text_out_wrap > 0) && (text_out_wrap < wid))
wrap = text_out_wrap;
else
wrap = wid - 1;
/* Process the string */
for (s = str; *s; s++)
{
char ch;
/* Force wrap */
if (*s == '\n')
{
/* Wrap */
x = text_out_indent;
y++;
/* Clear line, move cursor */
Term_erase(x, y, 255);
continue;
}
/* Clean up the char */
ch = (isprint((unsigned char)*s) ? *s : ' ');
/* Wrap words as needed */
if ((x >= wrap - 1) && (ch != ' '))
{
int i, n = 0;
byte av[256];
char cv[256];
/* Wrap word */
if (x < wrap)
{
n = wrap - 1;
/* Scan existing text */
for (i = wrap - 2; i >= 0; i
{
/* Grab existing attr/char */
Term_what(i, y, &av[i], &cv[i]);
/* Break on space */
if (cv[i] == ' ') break;
/* Track current word */
n = i;
}
}
/* Special case */
if (n == 0) n = wrap;
/* Clear line */
Term_erase(n, y, 255);
/* Wrap */
x = text_out_indent;
y++;
/* Clear line, move cursor */
Term_erase(x, y, 255);
/* Indent after the wrap */
/* Term_addch(TERM_DARK, ' ');*/
x++;
/* Wrap the word (if any) */
for (i = n; i < wrap - 1; i++)
{
/* Dump */
Term_addch(av[i], cv[i]);
/* Advance (no wrap) */
if (++x > wrap) x = wrap;
}
}
/* Dump */
Term_addch(a, ch);
/* Advance */
if (++x > wrap) x = wrap;
}
}
/*
* Write text to the given file and apply line-wrapping.
*
* Hook function for text_out(). Make sure that text_out_file points
* to an open text-file.
*
* Long lines will be wrapped at text_out_wrap, or at column 80 if that
* is not set; or at a newline character.
*
* You must be careful to end all file output with a newline character
* to "flush" the stored line position.
*/
void text_out_to_file(byte a, cptr str)
{
/* Current position on the line */
static int pos = 0;
/* Is this a continuation of a wrapped line? */
bool wrapped = FALSE;
/* Wrap width */
int wrap = (text_out_wrap ? text_out_wrap : 80);
/* Current location within "str" */
cptr s = str;
/* Unused parameter */
(void)a;
/* Process the string */
while (*s)
{
char ch;
int n = 0;
int len = wrap - pos;
int l_space = 0;
/* If we are at the start of the line... */
if (pos == 0)
{
int i;
/* Output the indent */
for (i = 0; i < text_out_indent; i++)
{
fputc(' ', text_out_file);
pos++;
}
/* Additional indent if continuation of a wrapped line */
if (wrapped)
{
fputc(' ', text_out_file);
pos++;
}
}
/* Find length of line up to next newline or end-of-string */
while ((n < len) && !((s[n] == '\n') || (s[n] == '\0')))
{
/* Mark the most recent space in the string */
if (s[n] == ' ') l_space = n;
/* Increment */
n++;
}
/* If we have encountered no spaces nor newlines */
if (l_space == 0 && n == len)
{
/* If we are mid-line */
if (pos != text_out_indent)
{
/* Begin a new line */
fputc('\n', text_out_file);
/* Reset */
pos = 0;
/* Skip whitespace */
while (*s == ' ') s++;
wrapped = TRUE;
continue;
}
/* else if we are at the start, we'll just print and split at len */
}
else
{
/* Wrap at the newline */
if ((s[n] == '\n') || (s[n] == '\0'))
{
len = n;
wrapped = FALSE;
}
/* Wrap at the last space */
else
{
len = l_space;
wrapped = TRUE;
}
}
/* Write that line to file */
for (n = 0; n < len; n++)
{
/* Ensure the character is printable */
ch = (isprint(s[n]) ? s[n] : ' ');
/* Write out the character */
fputc(ch, text_out_file);
/* Increment */
pos++;
}
/* Move 's' past the stuff we've written */
s += len;
/* If we are at the end of the string, end */
if (*s == '\0') return;
/* Skip newlines */
if (*s == '\n') s++;
/* Begin a new line */
fputc('\n', text_out_file);
/* Reset */
pos = 0;
/* Skip whitespace */
while (*s == ' ') s++;
}
/* We are done */
return;
}
/*
* Output text to the screen or to a file depending on the selected
* text_out hook.
*/
void text_out(cptr str)
{
text_out_c(TERM_WHITE, str);
}
/*
* Output text to the screen (in color) or to a file depending on the
* selected hook.
*/
void text_out_c(byte a, cptr str)
{
text_out_hook(a, str);
}
/*
* Clear part of the screen
*/
void clear_from(int row)
{
int y;
/* Erase requested rows */
for (y = row; y < Term->hgt; y++)
{
/* Erase part of the screen */
Term_erase(0, y, 255);
}
}
/*
* Get some input at the cursor location.
*
* The buffer is assumed to have been initialized to a default string.
* Note that this string is often "empty" (see below).
*
* The default buffer is displayed in yellow until cleared, which happens
* on the first keypress, unless that keypress is Return.
*
* Normal chars clear the default and append the char.
* Backspace clears the default or deletes the final char.
* Return accepts the current buffer contents and returns TRUE.
* Escape clears the buffer and the window and returns FALSE.
*
* Note that 'len' refers to the size of the buffer. The maximum length
* of the input is 'len-1'.
*/
bool askfor_aux(char *buf, int len)
{
int y, x;
int k = 0;
key_event ke;
bool done = FALSE;
ke.key = '\0';
/* Locate the cursor */
Term_locate(&x, &y);
/* Paranoia */
if (len < 0) len = 0;
/* Paranoia */
if ((x < 0) || (x >= 80)) x = 0;
/* Restrict the length */
if (x + len > 80) len = 80 - x;
/* Truncate the default entry */
buf[len-1] = '\0';
/* Display the default answer */
Term_erase(x, y, len);
Term_putstr(x, y, -1, TERM_YELLOW, buf);
/* Process input */
while (!done)
{
/* Place cursor */
Term_gotoxy(x + k, y);
/* Get a key */
ke = inkey_ex();
/* Analyze the key */
switch (ke.key)
{
case ESCAPE:
{
k = 0;
done = TRUE;
break;
}
case '\n':
case '\r':
{
k = strlen(buf);
done = TRUE;
break;
}
case 0x7F:
case '\010':
{
if (k > 0) k
break;
}
case '\xff':
{
if ((ke.mousebutton) && !(k))
{
if (ke.mousebutton == 1)
{
k = strlen(buf);
done = TRUE;
}
else if (ke.mousebutton == 2)
{
ke.key = ESCAPE;
done = TRUE;
}
break;
}
else continue;
}
default:
{
if ((k < len-1) && (isprint(ke.key)))
{
buf[k++] = ke.key;
}
else
{
bell("Illegal edit key!");
}
break;
}
}
/* Terminate */
buf[k] = '\0';
/* Update the entry */
Term_erase(x, y, len);
Term_putstr(x, y, -1, TERM_WHITE, buf);
}
/* Done */
return (ke.key != ESCAPE);
}
/*
* Prompt for a string from the user.
*
* The "prompt" should take the form "Prompt: ".
*
* See "askfor_aux" for some notes about "buf" and "len", and about
* the return value of this function.
*/
bool get_string(cptr prompt, char *buf, int len)
{
bool res;
/* Paranoia XXX XXX XXX */
message_flush();
/* Display prompt */
prt(prompt, 0, 0);
/* Ask the user for a string */
res = askfor_aux(buf, len);
/* Clear prompt */
prt("", 0, 0);
/* Result */
return (res);
}
/*
* Request a "quantity" from the user
*
* Allow "p_ptr->command_arg" to specify a quantity
*/
int get_quantity_aux(cptr prompt, int max, int amt)
{
/* Use "command_arg" */
if (p_ptr->command_arg)
{
/* Extract a number */
amt = p_ptr->command_arg;
/* Clear "command_arg" */
p_ptr->command_arg = 0;
}
#ifdef ALLOW_REPEAT
/* Get the item index */
else if (max != 1 && repeat_pull(&amt))
{
/* nothing */
}
#endif /* ALLOW_REPEAT */
/* Prompt if needed */
else if (max != 1)
{
char tmp[80];
char buf[80];
/* Build a prompt if needed */
if (!prompt)
{
/* Build a prompt */
sprintf(tmp, "Quantity (0-%d): ", max);
/* Use that prompt */
prompt = tmp;
}
/* Build the default */
sprintf(buf, "%d", amt);
/* Ask for a quantity */
if (!get_string(prompt, buf, 7)) return (0);
/* Extract a number */
amt = atoi(buf);
/* A letter means "all" */
if (isalpha(buf[0])) amt = max;
}
/* Enforce the maximum */
if (amt > max) amt = max;
/* Enforce the minimum */
if (amt < 0) amt = 0;
#ifdef ALLOW_REPEAT
if (amt) repeat_push(amt);
#endif /* ALLOW_REPEAT */
/* Return the result */
return (amt);
}
/*
* Request a "quantity" from the user
*
* Allow "p_ptr->command_arg" to specify a quantity
*/
s16b get_quantity(cptr prompt, int max)
{
/* The old get_quantity function */
return(get_quantity_aux(prompt, max, 1));
}
/*
* Verify something with the user
*
* The "prompt" should take the form "Query? "
*
* Note that "[y/n]" is appended to the prompt.
*/
bool get_check(cptr prompt)
{
key_event ke;
char buf[80];
/* Flush easy_more messages */
if (easy_more)
{
msg_print(NULL);
messages_easy(FALSE);
}
/* Paranoia XXX XXX XXX */
else message_flush();
/* Hack -- Build a "useful" prompt */
strnfmt(buf, 78, "%.70s[y/n] ", prompt);
/* Prompt for it */
prt(buf, 0, 0);
/* Get an acceptable answer */
while (TRUE)
{
ke = anykey();
if (ke.mousebutton == 1) ke.key = 'y';
if (ke.mousebutton == 2) ke.key = 'n';
if (quick_messages) break;
if (ke.key == ESCAPE) break;
if (strchr("YyNn", ke.key)) break;
bell("Illegal response to a 'yes/no' question!");
}
/* Erase the prompt */
prt("", 0, 0);
/* Normal negation */
if ((ke.key != 'Y') && (ke.key != 'y')) return (FALSE);
/* Success */
return (TRUE);
}
/*
* Prompts for a keypress
*
* The "prompt" should take the form "Command: "
*
* Returns TRUE unless the character is "Escape"
*/
bool get_com(cptr prompt, char *command)
{
key_event ke;
bool result;
while (1)
{
result = get_com_ex(prompt, &ke);
*command = ke.key;
/* Ignore mouse */
if (ke.key != '\xff') break;
}
return result;
}
/*
* Prompts for a keypress or mouse press
*
* The "prompt" should take the form "Command: "
*
* Returns TRUE unless the character is "Escape"
*/
bool get_com_ex(cptr prompt, key_event *command)
{
key_event ke;
/* Paranoia XXX XXX XXX */
message_flush();
/* Display a prompt */
prt(prompt, 0, 0);
/* Get a key */
ke = inkey_ex();
/* Clear the prompt */
prt("", 0, 0);
/* Save the command */
*command = ke;
/* Done */
return (ke.key != ESCAPE);
}
/*
* Pause for user response
*
* This function is stupid. XXX XXX XXX
*
* Now accepts mouse press
*/
void pause_line(int row)
{
prt("", row, 0);
put_str("[Press any key to continue]", row, 23);
(void)anykey();
prt("", row, 0);
}
/*
* Hack -- special buffer to hold the action of the current keymap
*/
static char <API key>[256];
/*
* Request a command from the user.
*
* Sets p_ptr->command_cmd, p_ptr->command_dir, p_ptr->command_rep,
* p_ptr->command_arg. May modify p_ptr->command_new.
*
* Note that "caret" ("^") is treated specially, and is used to
* allow manual input of control characters. This can be used
* on many machines to request repeated tunneling (Ctrl-H) and
* on the Macintosh to request "Control-Caret".
*
* Note that "backslash" is treated specially, and is used to bypass any
* keymap entry for the following character. This is useful for macros.
*
* Note that this command is used both in the dungeon and in
* stores, and must be careful to work in both situations.
*
* Note that "p_ptr->command_new" may not work any more. XXX XXX XXX
*/
void request_command(bool shopping)
{
int i;
key_event ke = {0, 0, 0, 0};
int mode;
cptr act;
/* Roguelike */
if (rogue_like_commands)
{
mode = KEYMAP_MODE_ROGUE;
}
/* Original */
else
{
mode = KEYMAP_MODE_ORIG;
}
/* No command yet */
p_ptr->command_cmd = 0;
/* No "argument" yet */
p_ptr->command_arg = 0;
/* No "direction" yet */
p_ptr->command_dir = 0;
/* Flush messages */
if (easy_more && must_more) messages_easy(TRUE);
/* Get command */
while (1)
{
/* Hack -- auto-commands */
if (p_ptr->command_new.key)
{
/* Flush messages */
message_flush();
/* Use auto-command */
ke = p_ptr->command_new;
/* Forget it */
p_ptr->command_new.key = 0;
}
/* Get a keypress in "command" mode */
else
{
/* Hack -- no flush needed */
msg_flag = FALSE;
/* Activate "command mode" */
inkey_flag = TRUE;
/* Get a command */
ke = inkey_ex();
}
/* Clear top line */
if ((ke.key != '\xff') || (ke.mousebutton)) prt("", 0, 0);
/* Command Count */
if (ke.key == '0')
{
int old_arg = p_ptr->command_arg;
/* Reset */
p_ptr->command_arg = 0;
/* Begin the input */
prt("Count: ", 0, 0);
/* Get a command count */
while (1)
{
/* Get a new keypress */
ke.key = inkey();
/* Simple editing (delete or backspace) */
if ((ke.key == 0x7F) || (ke.key == KTRL('H')))
{
/* Delete a digit */
p_ptr->command_arg = p_ptr->command_arg / 10;
/* Show current count */
prt(format("Count: %d", p_ptr->command_arg), 0, 0);
}
/* Actual numeric data */
else if (isdigit(ke.key))
{
/* Stop count at 9999 */
if (p_ptr->command_arg >= 1000)
{
/* Warn */
bell("Invalid repeat count!");
/* Limit */
p_ptr->command_arg = 9999;
}
/* Increase count */
else
{
/* Incorporate that digit */
p_ptr->command_arg = p_ptr->command_arg * 10 + D2I(ke.key);
}
/* Show current count */
prt(format("Count: %d", p_ptr->command_arg), 0, 0);
}
/* Exit on "unusable" input */
else
{
break;
}
}
/* Hack -- Handle "zero" */
if (p_ptr->command_arg == 0)
{
/* Default to 99 */
p_ptr->command_arg = 99;
/* Show current count */
prt(format("Count: %d", p_ptr->command_arg), 0, 0);
}
/* Hack -- Handle "old_arg" */
if (old_arg != 0)
{
/* Restore old_arg */
p_ptr->command_arg = old_arg;
/* Show current count */
prt(format("Count: %d", p_ptr->command_arg), 0, 0);
}
/* Hack -- white-space means "enter command now" */
if ((ke.key == ' ') || (ke.key == '\n') || (ke.key == '\r'))
{
/* Get a real command */
if (!get_com("Command: ", &ke.key))
{
/* Clear count */
p_ptr->command_arg = 0;
/* Continue */
continue;
}
}
}
/* Allow "keymaps" to be bypassed */
if (ke.key == '\\')
{
/* Get a real command */
(void)get_com("Command: ", &ke.key);
/* Hack -- bypass keymaps */
if (!inkey_next) inkey_next = "";
}
/* Allow "control chars" to be entered */
if (ke.key == '^')
{
/* Get a new command and controlify it */
if (get_com("Control: ", &ke.key)) ke.key = KTRL(ke.key);
}
/* Look up applicable keymap */
act = keymap_act[mode][(byte)(ke.key)];
/* Apply keymap if not inside a keymap already */
if (act && !inkey_next)
{
/* Install the keymap (limited buffer size) */
strnfmt(<API key>, 256, "%s", act);
/* Start using the buffer */
inkey_next = <API key>;
/* Continue */
continue;
}
/* Paranoia */
if (ke.key == '\0') continue;
/* Use command */
p_ptr->command_cmd = ke.key;
p_ptr->command_cmd_ex = ke;
/* Done */
break;
}
/* Hack -- Auto-repeat certain commands */
if (p_ptr->command_arg <= 0)
{
/* Hack -- auto repeat certain commands */
if (strchr(<API key>, p_ptr->command_cmd))
{
/* Repeat 99 times */
p_ptr->command_arg = 99;
}
}
/* Shopping */
if (shopping)
{
/* Hack -- Convert a few special keys */
switch (p_ptr->command_cmd)
{
/* Command "p" -> "purchase" (get) */
case 'p': p_ptr->command_cmd = 'g'; break;
/* Command "m" -> "purchase" (get) */
case 'm': p_ptr->command_cmd = 'g'; break;
/* Command "s" -> "sell" (drop) */
case 's': p_ptr->command_cmd = 'd'; break;
}
}
/* Hack -- Scan equipment */
for (i = INVEN_WIELD; i < END_EQUIPMENT; i++)
{
cptr s;
object_type *o_ptr = &inventory[i];
/* Skip non-objects */
if (!o_ptr->k_idx) continue;
/* No inscription */
if (!o_ptr->note) continue;
/* Find a '^' */
s = strchr(quark_str(o_ptr->note), '^');
/* Process preventions */
while (s)
{
/* Check the "restriction" character */
if ((s[1] == p_ptr->command_cmd) || (s[1] == '*'))
{
/* Hack -- Verify command */
if (!get_check("Are you sure? "))
{
/* Hack -- Use "newline" */
p_ptr->command_cmd = '\n';
}
}
/* Find another '^' */
s = strchr(s + 1, '^');
}
}
/* Hack -- erase the message line. */
if (ke.key && (ke.key != '\xff' || ke.mousebutton)) prt("", 0, 0);
/* Hack again -- apply the modified key command */
p_ptr->command_cmd_ex.key = p_ptr->command_cmd;
}
/*
* Generates damage for "2d6" style dice rolls
*/
uint damroll(uint num, uint sides)
{
uint i, sum = 0;
/* HACK - rand_die(0) is undefined */
if (sides == 0) return (0);
for (i = 0; i < num; i++)
{
sum += rand_die(sides);
}
return (sum);
}
/*
* Same as above, but always maximal
*/
uint maxroll(uint num, uint sides)
{
return (num * sides);
}
/*
* Check a char for "vowel-hood"
*/
bool is_a_vowel(int ch)
{
switch (ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
return (TRUE);
}
return (FALSE);
}
#if 0
/*
* Replace the first instance of "target" in "buf" with "insert"
* If "insert" is NULL, just remove the first instance of "target"
* In either case, return TRUE if "target" is found.
*
* Could be made more efficient, especially in the case where "insert"
* is smaller than "target".
*/
static bool insert_str(char *buf, cptr target, cptr insert)
{
int i, len;
int b_len, t_len, i_len;
/* Attempt to find the target (modify "buf") */
buf = strstr(buf, target);
/* No target found */
if (!buf) return (FALSE);
/* Be sure we have an insertion string */
if (!insert) insert = "";
/* Extract some lengths */
t_len = strlen(target);
i_len = strlen(insert);
b_len = strlen(buf);
/* How much "movement" do we need? */
len = i_len - t_len;
/* We need less space (for insert) */
if (len < 0)
{
for (i = t_len; i < b_len; ++i) buf[i+len] = buf[i];
}
/* We need more space (for insert) */
else if (len > 0)
{
for (i = b_len-1; i >= t_len; --i) buf[i+len] = buf[i];
}
/* If movement occured, we need a new terminator */
if (len) buf[b_len+len] = '\0';
/* Now copy the insertion string */
for (i = 0; i < i_len; ++i) buf[i] = insert[i];
/* Successful operation */
return (TRUE);
}
#endif
#ifdef ALLOW_REPEAT
#define REPEAT_MAX 20
/* Number of chars saved */
static int repeat__cnt = 0;
/* Current index */
static int repeat__idx = 0;
/* Saved "stuff" */
static int repeat__key[REPEAT_MAX];
/*
* Push data.
*/
void repeat_push(int what)
{
/* Too many keys */
if (repeat__cnt == REPEAT_MAX) return;
/* Push the "stuff" */
repeat__key[repeat__cnt++] = what;
/* Prevents us from pulling keys */
++repeat__idx;
}
/*
* Pull data.
*/
bool repeat_pull(int *what)
{
/* All out of keys */
if (repeat__idx == repeat__cnt) return (FALSE);
/* Grab the next key, advance */
*what = repeat__key[repeat__idx++];
/* Success */
return (TRUE);
}
void repeat_clear(void)
{
/* Start over from the failed pull */
if (repeat__idx)
repeat__cnt = --repeat__idx;
/* Paranoia */
else
repeat__cnt = repeat__idx;
return;
}
/*
* Repeat previous command, or begin memorizing new command.
*/
void repeat_check(void)
{
int what;
/* Ignore some commands */
if (p_ptr->command_cmd == ESCAPE) return;
if (p_ptr->command_cmd == ' ') return;
if (p_ptr->command_cmd == '\n') return;
if (p_ptr->command_cmd == '\r') return;
/* Repeat Last Command */
if (p_ptr->command_cmd == KTRL('V'))
{
/* Reset */
repeat__idx = 0;
/* Get the command */
if (repeat_pull(&what))
{
/* Save the command */
p_ptr->command_cmd = what;
}
}
/* Start saving new command */
else
{
/* Reset */
repeat__cnt = 0;
repeat__idx = 0;
/* Get the current command */
what = p_ptr->command_cmd;
/* Save this command */
repeat_push(what);
}
}
#endif /* ALLOW_REPEAT */
#ifdef SUPPORT_GAMMA
/* Table of gamma values */
byte gamma_table[256];
/* Table of ln(x / 256) * 256 for x going from 0 -> 255 */
static const s16b gamma_helper[256] =
{
0, -1420, -1242, -1138, -1065, -1007, -961, -921, -887, -857, -830,
-806, -783, -762, -744, -726, -710, -694, -679, -666, -652, -640,
-628, -617, -606, -596, -586, -576, -567, -577, -549, -541, -532,
-525, -517, -509, -502, -495, -488, -482, -475, -469, -463, -457,
-451, -455, -439, -434, -429, -423, -418, -413, -408, -403, -398,
-394, -389, -385, -380, -376, -371, -367, -363, -359, -355, -351,
-347, -343, -339, -336, -332, -328, -325, -321, -318, -314, -311,
-308, -304, -301, -298, -295, -291, -288, -285, -282, -279, -276,
-273, -271, -268, -265, -262, -259, -257, -254, -251, -248, -246,
-243, -241, -238, -236, -233, -231, -228, -226, -223, -221, -219,
-216, -214, -212, -209, -207, -205, -203, -200, -198, -196, -194,
-192, -190, -188, -186, -184, -182, -180, -178, -176, -174, -172,
-170, -168, -166, -164, -162, -160, -158, -156, -155, -153, -151,
-149, -147, -146, -144, -142, -140, -139, -137, -135, -134, -132,
-130, -128, -127, -125, -124, -122, -120, -119, -117, -116, -114,
-112, -111, -109, -108, -106, -105, -103, -102, -100, -99, -97, -96,
-95, -93, -92, -90, -89, -87, -86, -85, -83, -82, -80, -79, -78,
-76, -75, -74, -72, -71, -70, -68, -67, -66, -65, -63, -62, -61,
-59, -58, -57, -56, -54, -53, -52, -51, -50, -48, -47, -46, -45,
-44, -42, -41, -40, -39, -38, -37, -35, -34, -33, -32, -31, -30,
-29, -27, -26, -25, -24, -23, -22, -21, -20, -19, -18, -17, -16,
-14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1
};
/*
* Build the gamma table so that floating point isn't needed.
*
* Note gamma goes from 0->256. The old value of 100 is now 128.
*/
void build_gamma_table(int gamma)
{
int i, n;
/*
* value is the current sum.
* diff is the new term to add to the series.
*/
long value, diff;
/* Hack - convergence is bad in these cases. */
gamma_table[0] = 0;
gamma_table[255] = 255;
for (i = 1; i < 255; i++)
{
/*
* Initialise the Taylor series
*
* value and diff have been scaled by 256
*/
n = 1;
value = 256L * 256L;
diff = ((long)gamma_helper[i]) * (gamma - 256);
while (diff)
{
value += diff;
n++;
/*
* Use the following identiy to calculate the gamma table.
* exp(x) = 1 + x + x^2/2 + x^3/(2*3) + x^4/(2*3*4) +...
*
* n is the current term number.
*
* The gamma_helper array contains a table of
* ln(x/256) * 256
* This is used because a^b = exp(b*ln(a))
*
* In this case:
* a is i / 256
* b is gamma.
*
* Note that everything is scaled by 256 for accuracy,
* plus another factor of 256 for the final result to
* be from 0-255. Thus gamma_helper[] * gamma must be
* divided by 256*256 each itteration, to get back to
* the original power series.
*/
diff = (((diff / 256) * gamma_helper[i]) * (gamma - 256)) / (256 * n);
}
/*
* Store the value in the table so that the
* floating point pow function isn't needed.
*/
gamma_table[i] = (byte)(((long)(value / 256) * i) / 256);
}
}
#endif /* SUPPORT_GAMMA */
int color_char_to_attr(char c)
{
int a;
/* Is negative -- spit it right back out */
if (c < 0) return (c);
/* Is a space or '\0' -- return black */
if (c == '\0' || c == ' ') return (TERM_DARK);
/* Search the color table */
for (a = 0; a < BASE_COLORS; a++)
{
/* Look for the index */
if (color_table[a].index_char == c) break;
}
/* If we don't find the color, we assume white */
if (a == BASE_COLORS) return (TERM_WHITE);
/* Return the color */
return (a);
}
/*
* Converts a string to a terminal color byte.
*/
int color_text_to_attr(cptr name)
{
int a;
for (a = 0; a < BASE_COLORS; a++)
{
if (my_stricmp(name, color_table[a].name) == 0) return (a);
}
/* Default to white */
return (TERM_WHITE);
}
/*
* Extract a textual representation of an attribute
*/
cptr attr_to_text(byte a)
{
if (a < BASE_COLORS) return (color_table[a].name);
/* Oops */
return ("Icky");
}
u16b rsqrt(s32b input)
{
s32b tmp = input;
s32b tmp2, tmp3;
s32b root;
int i = 0;
if (input <= 0L) return (0);
/* Find out how many powers of two this number contains */
while (tmp)
{
tmp /= 2;
i++;
}
/*
* A decent first guess with Newton's method is input / 2. A much
* better one is to remove half the powers of two (rounded down).
*/
tmp = input >> (i / 2);
/* Close in on the truncated square root */
while (TRUE)
{
/* Get a better guess */
root = ((input / tmp) + tmp) / 2;
/* Require good-enough accuracy (we correct any error later). */
if ((root >= tmp - 1) && (root <= tmp + 1)) break;
/* Save current guess */
else tmp = root;
}
/* Get the square of the truncated square root */
tmp2 = root * root;
/* Get the square of the next higher integer */
tmp3 = (root + 1) * (root + 1);
/* If input > than the midpoint between these two values, round up */
if (input > (tmp2 + tmp3) / 2) root++;
/* Return */
return (u16b)(root);
}
/*
* Round a given value.
*
* "frac" controls the maximum amount of rounding compared to the given
* value. If "frac" is 8, for example, the given value must be at least
* 80 for it to be rounded to the nearest 10.
*/
s32b round_it(const s32b v, int frac)
{
s32b round = 5L;
s32b abs_v = ABS(v);
/* Rounding fraction must be at least 2, or no rounding happens */
if (frac < 2) return (v);
/* Small numbers aren't rounded */
if (v / frac < 2L) return (v);
/* Round by 5, then by 10, then by 25, then by 50, ... */
while (TRUE)
{
if (v / frac < round) break;
round *= 2L; /* 10, 100, ... */
if (v / frac < round) break;
round *= 5L;
round /= 2L; /* 25, 250, ... */
if (v / frac < round) break;
round *= 2L; /* 50, 500, ... */
}
/* Apply rounding */
if ((abs_v % round) >= round / 2) abs_v += (round - (abs_v % round));
else abs_v -= (abs_v % round);
/* Return signed value */
if (v < 0) return (-abs_v);
return (abs_v);
}
/*
* Accept values for y and x (considered as the endpoints of lines) between
* 0 and 40, and return an angle in degrees (divided by two). -LM-
*
* This table's input and output need some processing:
*
* Because this table gives degrees for a whole circle, up to radius 20, its
* origin is at (x,y) = (20, 20). Therefore, the input code needs to find
* the origin grid (where the lines being compared come from), and then map
* it to table grid 20,20. Do not, however, actually try to compare the
* angle of a line that begins and ends at the origin with any other line -
* it is impossible mathematically, and the table will return the value "255".
*
* The output of this table also needs to be massaged, in order to avoid the
* discontinuity at 0/180 degrees. This can be done by:
* rotate = 90 - first value
* this rotates the first input to the 90 degree line)
* tmp = ABS(second value + rotate) % 180
* diff = ABS(90 - tmp) = the angular difference (divided by two) between
* the first and second values.
*
* Note that grids diagonal to the origin have unique angles.
*/
byte get_angle_to_grid[41][41] =
{
{ 68, 67, 66, 65, 64, 63, 62, 62, 60, 59, 58, 57, 56, 55, 53, 52, 51, 49, 48, 46, 45, 44, 42, 41, 39, 38, 37, 35, 34, 33, 32, 31, 30, 28, 28, 27, 26, 25, 24, 24, 23 },
{ 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 56, 55, 54, 52, 51, 49, 48, 47, 45, 43, 42, 41, 39, 38, 36, 35, 34, 32, 31, 30, 29, 28, 27, 26, 25, 24, 24, 23, 22 },
{ 69, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 58, 57, 56, 54, 53, 51, 50, 48, 47, 45, 43, 42, 40, 39, 37, 36, 34, 33, 32, 30, 29, 28, 27, 26, 25, 24, 24, 23, 22, 21 },
{ 70, 69, 69, 68, 67, 66, 65, 64, 63, 61, 60, 59, 58, 56, 55, 53, 52, 50, 48, 47, 45, 43, 42, 40, 38, 37, 35, 34, 32, 31, 30, 29, 27, 26, 25, 24, 24, 23, 22, 21, 20 },
{ 71, 70, 69, 69, 68, 67, 66, 65, 63, 62, 61, 60, 58, 57, 55, 54, 52, 50, 49, 47, 45, 43, 41, 40, 38, 36, 35, 33, 32, 30, 29, 28, 27, 25, 24, 24, 23, 22, 21, 20, 19 },
{ 72, 71, 70, 69, 69, 68, 67, 65, 64, 63, 62, 60, 59, 58, 56, 54, 52, 51, 49, 47, 45, 43, 41, 39, 38, 36, 34, 32, 31, 30, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18 },
{ 73, 72, 71, 70, 69, 69, 68, 66, 65, 64, 63, 61, 60, 58, 57, 55, 53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, 32, 30, 29, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17 },
{ 73, 73, 72, 71, 70, 70, 69, 68, 66, 65, 64, 62, 61, 59, 57, 56, 54, 51, 49, 47, 45, 43, 41, 39, 36, 34, 33, 31, 29, 28, 26, 25, 24, 23, 21, 20, 20, 19, 18, 17, 17 },
{ 75, 74, 73, 72, 72, 71, 70, 69, 68, 66, 65, 63, 62, 60, 58, 56, 54, 52, 50, 47, 45, 43, 40, 38, 36, 34, 32, 30, 28, 27, 25, 24, 23, 21, 20, 19, 18, 18, 17, 16, 15 },
{ 76, 75, 74, 74, 73, 72, 71, 70, 69, 68, 66, 65, 63, 61, 59, 57, 55, 53, 50, 48, 45, 42, 40, 37, 35, 33, 31, 29, 27, 25, 24, 23, 21, 20, 19, 18, 17, 16, 16, 15, 14 },
{ 77, 76, 75, 75, 74, 73, 72, 71, 70, 69, 68, 66, 64, 62, 60, 58, 56, 53, 51, 48, 45, 42, 39, 37, 34, 32, 30, 28, 26, 24, 23, 21, 20, 19, 18, 17, 16, 15, 15, 14, 13 },
{ 78, 77, 77, 76, 75, 75, 74, 73, 72, 70, 69, 68, 66, 64, 62, 60, 57, 54, 51, 48, 45, 42, 39, 36, 33, 30, 28, 26, 24, 23, 21, 20, 18, 17, 16, 15, 15, 14, 13, 13, 12 },
{ 79, 79, 78, 77, 77, 76, 75, 74, 73, 72, 71, 69, 68, 66, 63, 61, 58, 55, 52, 49, 45, 41, 38, 35, 32, 29, 27, 24, 23, 21, 19, 18, 17, 16, 15, 14, 13, 13, 12, 11, 11 },
{ 80, 80, 79, 79, 78, 77, 77, 76, 75, 74, 73, 71, 69, 68, 65, 63, 60, 57, 53, 49, 45, 41, 37, 33, 30, 27, 25, 23, 21, 19, 17, 16, 15, 14, 13, 13, 12, 11, 11, 10, 10 },
{ 82, 81, 81, 80, 80, 79, 78, 78, 77, 76, 75, 73, 72, 70, 68, 65, 62, 58, 54, 50, 45, 40, 36, 32, 28, 25, 23, 20, 18, 17, 15, 14, 13, 12, 12, 11, 10, 10, 9, 9, 8 },
{ 83, 83, 82, 82, 81, 81, 80, 79, 79, 78, 77, 75, 74, 72, 70, 68, 64, 60, 56, 51, 45, 39, 34, 30, 26, 23, 20, 18, 16, 15, 13, 12, 11, 11, 10, 9, 9, 8, 8, 7, 7 },
{ 84, 84, 84, 83, 83, 83, 82, 81, 81, 80, 79, 78, 77, 75, 73, 71, 68, 63, 58, 52, 45, 38, 32, 27, 23, 19, 17, 15, 13, 12, 11, 10, 9, 9, 8, 7, 7, 7, 6, 6, 6 },
{ 86, 86, 85, 85, 85, 84, 84, 84, 83, 82, 82, 81, 80, 78, 77, 75, 72, 68, 62, 54, 45, 36, 28, 23, 18, 15, 13, 12, 10, 9, 8, 8, 7, 6, 6, 6, 5, 5, 5, 4, 4 },
{ 87, 87, 87, 87, 86, 86, 86, 86, 85, 85, 84, 84, 83, 82, 81, 79, 77, 73, 68, 58, 45, 32, 23, 17, 13, 11, 9, 8, 7, 6, 6, 5, 5, 4, 4, 4, 4, 3, 3, 3, 3 },
{ 89, 88, 88, 88, 88, 88, 88, 88, 88, 87, 87, 87, 86, 86, 85, 84, 83, 81, 77, 68, 45, 23, 13, 9, 7, 6, 5, 4, 4, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1 },
{ 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 91, 92, 92, 92, 92, 92, 92, 92, 92, 93, 93, 93, 94, 94, 95, 96, 97, 99, 103, 113, 135, 158, 167, 171, 173, 174, 175, 176, 176, 177, 177, 177, 178, 178, 178, 178, 178, 178, 178, 178, 179 },
{ 93, 93, 93, 93, 94, 94, 94, 94, 95, 95, 96, 96, 97, 98, 99, 101, 103, 107, 113, 122, 135, 148, 158, 163, 167, 169, 171, 172, 173, 174, 174, 175, 175, 176, 176, 176, 176, 177, 177, 177, 177 },
{ 94, 94, 95, 95, 95, 96, 96, 96, 97, 98, 98, 99, 100, 102, 103, 105, 108, 113, 118, 126, 135, 144, 152, 158, 162, 165, 167, 168, 170, 171, 172, 172, 173, 174, 174, 174, 175, 175, 175, 176, 176 },
{ 96, 96, 96, 97, 97, 97, 98, 99, 99, 100, 101, 102, 103, 105, 107, 109, 113, 117, 122, 128, 135, 142, 148, 153, 158, 161, 163, 165, 167, 168, 169, 170, 171, 171, 172, 173, 173, 173, 174, 174, 174 },
{ 97, 97, 98, 98, 99, 99, 100, 101, 101, 102, 103, 105, 106, 108, 110, 113, 116, 120, 124, 129, 135, 141, 146, 150, 154, 158, 160, 162, 164, 165, 167, 168, 169, 169, 170, 171, 171, 172, 172, 173, 173 },
{ 98, 99, 99, 100, 100, 101, 102, 102, 103, 104, 105, 107, 108, 110, 113, 115, 118, 122, 126, 130, 135, 140, 144, 148, 152, 155, 158, 160, 162, 163, 165, 166, 167, 168, 168, 169, 170, 170, 171, 171, 172 },
{ 100, 100, 101, 101, 102, 103, 103, 104, 105, 106, 107, 109, 111, 113, 115, 117, 120, 123, 127, 131, 135, 139, 143, 147, 150, 153, 155, 158, 159, 161, 163, 164, 165, 166, 167, 167, 168, 169, 169, 170, 170 },
{ 101, 101, 102, 103, 103, 104, 105, 106, 107, 108, 109, 111, 113, 114, 117, 119, 122, 125, 128, 131, 135, 139, 142, 145, 148, 151, 153, 156, 158, 159, 161, 162, 163, 164, 165, 166, 167, 167, 168, 169, 169 },
{ 102, 103, 103, 104, 105, 105, 106, 107, 108, 110, 111, 113, 114, 116, 118, 120, 123, 126, 129, 132, 135, 138, 141, 144, 147, 150, 152, 154, 156, 158, 159, 160, 162, 163, 164, 165, 165, 166, 167, 167, 168 },
{ 103, 104, 105, 105, 106, 107, 108, 109, 110, 111, 113, 114, 116, 118, 120, 122, 124, 127, 129, 132, 135, 138, 141, 143, 146, 148, 150, 152, 154, 156, 158, 159, 160, 161, 162, 163, 164, 165, 165, 166, 167 },
{ 104, 105, 106, 106, 107, 108, 109, 110, 111, 113, 114, 115, 117, 119, 121, 123, 125, 127, 130, 132, 135, 138, 140, 143, 145, 147, 149, 151, 153, 155, 156, 158, 159, 160, 161, 162, 163, 164, 164, 165, 166 },
{ 105, 106, 107, 108, 108, 109, 110, 111, 113, 114, 115, 117, 118, 120, 122, 124, 126, 128, 130, 133, 135, 137, 140, 142, 144, 146, 148, 150, 152, 153, 155, 156, 158, 159, 160, 161, 162, 162, 163, 164, 165 },
{ 107, 107, 108, 109, 110, 110, 111, 113, 114, 115, 116, 118, 119, 121, 123, 124, 126, 129, 131, 133, 135, 137, 139, 141, 144, 146, 147, 149, 151, 152, 154, 155, 156, 158, 159, 160, 160, 161, 162, 163, 163 },
{ 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 119, 120, 122, 123, 125, 127, 129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 148, 150, 151, 153, 154, 155, 156, 158, 159, 159, 160, 161, 162, 163 },
{ 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 120, 121, 122, 124, 126, 128, 129, 131, 133, 135, 137, 139, 141, 142, 144, 146, 148, 149, 150, 152, 153, 154, 155, 157, 158, 159, 159, 160, 161, 162 },
{ 109, 110, 111, 112, 113, 114, 114, 115, 117, 118, 119, 120, 122, 123, 125, 126, 128, 130, 131, 133, 135, 137, 139, 140, 142, 144, 145, 147, 148, 150, 151, 152, 153, 155, 156, 157, 158, 159, 159, 160, 161 },
{ 110, 111, 112, 113, 114, 114, 115, 116, 117, 119, 120, 121, 122, 124, 125, 127, 128, 130, 132, 133, 135, 137, 138, 140, 142, 143, 145, 146, 148, 149, 150, 151, 153, 154, 155, 156, 157, 158, 159, 159, 160 },
{ 111, 112, 113, 114, 114, 115, 116, 117, 118, 119, 120, 122, 123, 124, 126, 127, 129, 130, 132, 133, 135, 137, 138, 140, 141, 143, 144, 146, 147, 148, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 159 },
{ 112, 113, 114, 114, 115, 116, 117, 118, 119, 120, 121, 122, 124, 125, 126, 128, 129, 131, 132, 133, 135, 137, 138, 139, 141, 142, 144, 145, 146, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159 },
{ 113, 114, 114, 115, 116, 117, 118, 118, 120, 121, 122, 123, 124, 125, 127, 128, 129, 131, 132, 134, 135, 136, 138, 139, 141, 142, 143, 145, 146, 147, 148, 149, 150, 152, 152, 153, 154, 155, 156, 157, 158 }
};
/*
* Calculates and returns the angle to the target or in the given
* direction.
*
* Note: If a compass direction is supplied, we ignore any target.
* Note: We supply the angle divided by 2.
*/
int get_angle_to_target(int y0, int x0, int y1, int x1, int dir)
{
int ny, nx;
int dist_conv;
/* No valid compass direction given */
if ((dir == 0) || (dir == 5) || (dir > 9))
{
/* Check for a valid target */
if ((y1) && (x1))
{
/* Get absolute distance between source and target */
int dy = ABS(y1 - y0);
int dx = ABS(x1 - x0);
/* Calculate distance conversion factor */
if ((dy > 20) || (dx > 20))
{
if (dy > dx) dist_conv = 1 + (10 * dy / 20);
else dist_conv = 1 + (10 * dx / 20);
}
else
{
dist_conv = 10;
}
/* Convert and reorient grid for table access */
ny = 20 + 10 * (y1 - y0) / dist_conv;
nx = 20 + 10 * (x1 - x0) / dist_conv;
if ((ny < 0) || (ny > 40) || (nx < 0) || (nx > 40))
{
/* Note error */
return (-1);
}
}
/* No compass direction and no target --> note error */
else
{
return (-1);
}
}
/* We have a valid compass direction */
else
{
/* Step in that direction a bunch of times, get target */
y1 = y0 + (ddy_ddd[dir] * 10);
x1 = x0 + (ddx_ddd[dir] * 10);
/* Convert to table grids */
ny = 20 + (y1 - y0);
nx = 20 + (x1 - x0);
}
/* Get angle to target. */
return (get_angle_to_grid[ny][nx]);
}
/*
* Using the angle given, find a grid that is in that direction from the
* origin.
*
* Note: This function does not yield very good results when the
* character is adjacent to the outer wall of the dungeon and the projection
* heads towards it.
*/
void <API key>(int angle, int y0, int x0, int *ty, int *tx)
{
int y, x;
int best_y = 0, best_x = 0;
int diff;
int this_angle;
int fudge = 180;
if ((angle < 0) || (angle >= 180)) return;
/* Scan the table, get as good a match as possible */
for (y = 0; y < 41; y++)
{
for (x = 0; x < 41; x++)
{
/* Corresponding grid in dungeon must be fully in bounds XXX */
if (!in_bounds_fully(y0 - 20 + y, x0 - 20 + x)) continue;
/* Check this table grid */
this_angle = get_angle_to_grid[y][x];
/* Get inaccuracy of this angle */
diff = ABS(angle - this_angle);
/* Inaccuracy is lower than previous best */
if (diff < fudge)
{
/* Note coordinates */
best_y = y;
best_x = x;
/* Save inaccuracy as a new best */
fudge = diff;
/* Note perfection */
if (fudge == 0) break;
}
}
/* Note perfection */
if (fudge == 0) break;
}
/* We have an unacceptably large fudge factor */
if (fudge >= 30)
{
/* Set target to original grid */
*ty = y0;
*tx = x0;
}
/* Usual case */
else
{
/* Set target */
*ty = y0 - 20 + best_y;
*tx = x0 - 20 + best_x;
}
}
/* Purpose: Path finding algorithm */
static int terrain[MAX_PF_RADIUS][MAX_PF_RADIUS];
static int ox,oy,ex,ey;
bool is_valid_pf(int y, int x)
{
int feat;
s16b this_region_piece, next_region_piece = 0;
/* Hack -- assume unvisited is permitted */
if (!(play_info[y][x] & (PLAY_MARK))) return (TRUE);
/* Get mimiced feat */
feat = f_info[cave_feat[y][x]].mimic;
/* Optionally alter known traps/doors on (non-jumping) movement */
if ((easy_alter)
&& ( (f_info[feat].flags1 & (FF1_DISARM)) ||
( !(f_info[feat].flags1 & (FF1_MOVE)) &&
!(f_info[feat].flags3 & (FF3_EASY_CLIMB)) &&
(f_info[feat].flags1 & (FF1_OPEN)))))
{
return (TRUE);
}
/* Require moveable space*/
if (!(f_info[feat].flags1 & (FF1_MOVE)) && !(f_info[feat].flags3 & (FF3_EASY_CLIMB))) return (FALSE);
/* Don't move over known dangerous terrain */
if ((f_info[feat].blow.method) || (f_info[feat].spell)) return (FALSE);
/* Don't move over known deep or filled terrain */
if (f_info[feat].flags2 & (FF2_DEEP | FF2_FILLED)) return (FALSE);
/* Don't move over known regions */
for (this_region_piece = cave_region_piece[y][x]; this_region_piece; this_region_piece = next_region_piece)
{
region_piece_type *rp_ptr = ®ion_piece_list[this_region_piece];
region_type *r_ptr = ®ion_list[rp_ptr->region];
/* Get the next region */
next_region_piece = rp_ptr->next_in_grid;
/* Skip dead regions */
if (!r_ptr->type) continue;
/* Displaying region */
if (((cheat_hear) || ((r_ptr->flags1 & (RE1_NOTICE)) != 0)) &&
(((play_info[y][x] & (PLAY_REGN | PLAY_SEEN)) != 0) ||
(((play_info[y][x] & (PLAY_VIEW)) != 0) && ((r_ptr->flags1 & (RE1_SHINING)) != 0))) &&
((r_ptr->flags1 & (RE1_DISPLAY)) != 0))
{
return (FALSE);
}
}
/* Otherwise good */
return (TRUE);
}
static void fill_terrain_info(void)
{
int i,j;
ox = MAX(p_ptr->px - MAX_PF_RADIUS / 2,0);
oy = MAX(p_ptr->py - MAX_PF_RADIUS / 2,0);
ex = MIN(p_ptr->px + MAX_PF_RADIUS / 2 - 1,DUNGEON_WID);
ey = MIN(p_ptr->py + MAX_PF_RADIUS / 2 - 1,DUNGEON_HGT);
for (i=0;i<MAX_PF_RADIUS;i++)
for(j=0;j<MAX_PF_RADIUS;j++)
terrain[i][j] = -1;
for (j=oy;j<ey;j++)
for (i=ox;i<ex;i++)
if (is_valid_pf(j,i))
terrain[j-oy][i-ox] = MAX_PF_LENGTH;
terrain[p_ptr->py-oy][p_ptr->px-ox] = 1;
}
#define MARK_DISTANCE(c,d) if ((c <= MAX_PF_LENGTH) && (c > d)) { c = d; try_again = (TRUE); }
bool findpath(int y, int x)
{
int i,j,dir;
bool try_again;
int cur_distance;
fill_terrain_info();
terrain[p_ptr->py-oy][p_ptr->px-ox] = 1;
if ((x >= ox) && (x < ex) && (y >= oy) && (y < ey))
{
if ((cave_m_idx[y][x] > 0) && (m_list[cave_m_idx[y][x]].ml))
{
terrain[y-oy][x-ox] = MAX_PF_LENGTH;
}
/*else if (terrain[y-oy][x-ox] != MAX_PF_LENGTH)
{
bell("Target blocked");
return (FALSE);
}*/
terrain[y-oy][x-ox] = MAX_PF_LENGTH;
}
else
{
bell("Target out of range.");
return (FALSE);
}
if (terrain[y-oy][x-ox] == -1)
{
bell("Target space forbidden");
return (FALSE);
}
/*
* And now starts the very naive and very
* inefficient pathfinding algorithm
*/
do
{
try_again = (FALSE);
for (j=oy+1;j<ey-1;j++)
for (i=ox+1;i<ex-1;i++)
{
cur_distance = terrain[j-oy][i-ox]+1;
if ((cur_distance > 0) && (cur_distance < MAX_PF_LENGTH))
{
for (dir=1;dir<10;dir++)
{
if (dir==5)
dir++;
MARK_DISTANCE(terrain[j-oy+ddy[dir]][i-ox+ddx[dir]],cur_distance);
}
}
}
if (terrain[y-oy][x-ox] < MAX_PF_LENGTH)
try_again = (FALSE);
} while (try_again);
/* Failure */
if (terrain[y-oy][x-ox] == MAX_PF_LENGTH)
{
bell("Target space unreachable.");
return (FALSE);
}
/* Success */
i = x;
j = y;
pf_result_index = 0;
while ((i != p_ptr->px) || (j != p_ptr->py))
{
cur_distance = terrain[j-oy][i-ox] - 1;
for (dir=1;dir<10;dir++)
if (terrain[j-oy+ddy[dir]][i-ox+ddx[dir]] == cur_distance)
break;
/* Should never happend */
if (dir == 10)
{
bell("Wtf ?");
return (FALSE);
}
if (dir == 5)
{
bell("Heyyy !");
return (FALSE);
}
pf_result[pf_result_index++] = '0' + (char)(10-dir);
i += ddx[dir];
j += ddy[dir];
}
pf_result_index
return (TRUE);
}
/*
* Break scalar time -- from T.o.M.E
*/
s32b bst(s32b what, s32b t)
{
s32b turns = t + (10 * TOWN_DAWN) + SUNRISE * HOUR * 10;
switch (what)
{
case MINUTE:
return ((turns / 10 / MINUTE) % 60);
case HOUR:
return (turns / 10 / (HOUR) % 24);
case DAY:
return (turns / 10 / (DAY) % 365);
case YEAR:
return (turns / 10 / (YEAR));
default:
return (0);
}
}
/*
* Get day name function -- from T.o.M.E
*/
cptr get_day(int day)
{
static char buf[20];
cptr p = "th";
if ((day / 10) == 1) ;
else if ((day % 10) == 1) p = "st";
else if ((day % 10) == 2) p = "nd";
else if ((day % 10) == 3) p = "rd";
sprintf(buf, "%d%s", day, p);
return (buf);
}
/*
* Get month name function -- from T.o.M.E
*/
cptr get_month_name(int day, bool full, bool compact)
{
int i = 8;
static char buf[40];
/* Find the period name */
while ((i > 0) && (day < month_day[i]))
{
i
}
switch (i)
{
/* Yestare/Mettare */
case 0:
case 8:
{
char buf2[20];
sprintf(buf2, get_day(day + 1));
if (full) sprintf(buf, "%s (%s day)", month_name[i], buf2);
else sprintf(buf, "%s", month_name[i]);
break;
}
/* 'Normal' months + Enderi */
default:
{
char buf2[20];
char buf3[20];
sprintf(buf2, get_day(day + 1 - month_day[i]));
sprintf(buf3, get_day(day + 1));
if (full) sprintf(buf, "%s day of %s (%s day)", buf2, month_name[i], buf3);
else if (compact) sprintf(buf, "%s day of %s", buf2, month_name[i]);
else sprintf(buf, "%s %s", buf2, month_name[i]);
break;
}
}
return (buf);
}
/*
* Generic display a list and pick a choice function. Returns TRUE selection or -1 if not selection made.
*/
bool get_list(print_list_func print_list, const s16b *sn, int num, cptr p, cptr q, cptr r, int y, int x, list_command_func list_command, int *selection)
{
int i;
bool flag, redraw;
key_event ke;
char out_val[160];
/* Clear messages */
if (easy_more) messages_easy(FALSE);
/* Nothing chosen yet */
flag = FALSE;
/* No redraw yet */
redraw = FALSE;
/* Show the list */
if (show_lists)
{
/* Show list */
redraw = TRUE;
/* Save screen */
screen_save();
/* Display the list */
print_list(sn, num, y, x);
}
/* Build a prompt (accept all spells) */
strnfmt(out_val, 78, "(%s %c-%c%s, *=List, ESC=exit) %s? ",
p, I2A(0), I2A(num - 1), r, q);
/* Get a spell from the user */
while (!flag && get_com_ex(out_val, &ke))
{
if (ke.key == '\xff')
{
if (ke.mousebutton)
{
if (redraw) ke.key = 'a' + ke.mousey - 2;
else ke.key = ' ';
}
else continue;
}
/* Request redraw */
if ((ke.key == ' ') || (ke.key == '*'))
{
/* Hide the list */
if (redraw)
{
/* Load screen */
screen_load();
/* Hide list */
redraw = FALSE;
}
/* Show the list */
else
{
/* Show list */
redraw = TRUE;
/* Save screen */
screen_save();
/* Display a list of spells */
print_list(sn, num, y, x);
}
/* Ask again */
continue;
}
/* Extract request */
i = (islower(ke.key) ? A2I(ke.key) : -1);
if ((i < 0) || (i >= num))
{
if (list_command(ke.key, sn, i, &redraw))
{
if (redraw)
{
/* Save screen */
screen_save();
/* Display a list of spells */
print_list(sn, num, y, x);
}
}
else
{
bell("Illegal choice!");
}
continue;
}
/* Get selection */
*selection = sn[i];
/* Stop the loop */
flag = TRUE;
}
/* Restore the screen */
if (redraw)
{
/* Load screen */
screen_load();
/* Hack -- forget redraw */
/* redraw = FALSE; */
}
/* Return success / failure */
return (flag);
}
/*
* Create a new grid queue. "q" must be a pointer to an unitialized
* grid_queue_type structure. That structure must be already allocated
* (it can be in the system stack).
* You must supply the maximum number of grids for the queue
*/
void grid_queue_create(grid_queue_type *q, size_t max_size)
{
/* Remember the maximum size */
q->max_size = max_size;
/* Allocate the grid storage */
q->data = C_ZNEW(max_size, coord);
/* Initialize head and tail of the queue */
q->head = q->tail = 0;
}
/*
* Free the resources used by a queue
*/
void grid_queue_destroy(grid_queue_type *q)
{
/* Free the allocated grid storage */
if (q->data)
{
FREE(q->data);
}
/* Clear all */
WIPE(q, grid_queue_type);
}
/*
* Append a grid at the tail of the queue, given the coordinates of that grid.
* Returns FALSE if the queue is full, or TRUE on success.
*/
bool grid_queue_push(grid_queue_type *q, byte y, byte x)
{
/* Check space */
if (GRID_QUEUE_FULL(q)) return (FALSE);
/* Append the grid */
q->data[q->tail].y = y;
q->data[q->tail].x = x;
/*
* Update the tail of the queue.
* The queue is circular, note tail adjustment
*/
q->tail = (q->tail + 1) % q->max_size;
/* Success */
return (TRUE);
}
/*
* Remove the grid at the front of the queue
*/
void grid_queue_pop(grid_queue_type *q)
{
/* Something to pop? */
if (GRID_QUEUE_EMPTY(q)) return;
/*
* Update the head of the queue.
* The queue is circular, note head adjustment
*/
q->head = (q->head + 1) % q->max_size;
}
int uti_icbrt(int arg)
{
int delta;
int ret;
assert((arg >= 0) && (arg <= 0x7fffffff));
if (arg == 0)
{
return (0);
}
if (arg < 1000)
{
ret = 10;
}
else if (arg < 1000000)
{
ret = 100;
}
else if (arg < 1000000000)
{
ret = 1000;
}
else
{
ret = 1290; /* the largest x for which x**3 < 2**31 */
}
do
{
/* derivative = 3 * x * x yadda yadda, but this seems to works OK */
delta = (arg - ret * ret * ret) / (2 * ret * ret);
ret += delta;
} while (delta);
if (ret * ret * ret > arg)
{
ret
}
return (ret);
} |
#include <acpi/acpi.h>
#include "accommon.h"
#include "acparser.h"
#include "acdispat.h"
#include "acinterp.h"
#include "amlcode.h"
#include "acnamesp.h"
#define _COMPONENT ACPI_EXECUTER
ACPI_MODULE_NAME("exoparg1")
acpi_status <API key>(struct acpi_walk_state *walk_state)
{
acpi_status status = AE_OK;
union acpi_operand_object *return_desc = NULL;
<API key>(ex_opcode_0A_0T_1R,
<API key>(walk_state->opcode));
switch (walk_state->opcode) {
case AML_TIMER_OP:
return_desc = <API key>(ACPI_TYPE_INTEGER);
if (!return_desc) {
status = AE_NO_MEMORY;
goto cleanup;
}
return_desc->integer.value = acpi_os_get_timer();
break;
default:
ACPI_ERROR((AE_INFO, "Unknown AML opcode %X",
walk_state->opcode));
status = AE_AML_BAD_OPCODE;
break;
}
cleanup:
if ((ACPI_FAILURE(status)) || walk_state->result_obj) {
<API key>(return_desc);
walk_state->result_obj = NULL;
} else {
walk_state->result_obj = return_desc;
}
return_ACPI_STATUS(status);
}
acpi_status <API key>(struct acpi_walk_state *walk_state)
{
union acpi_operand_object **operand = &walk_state->operands[0];
acpi_status status = AE_OK;
<API key>(ex_opcode_1A_0T_0R,
<API key>(walk_state->opcode));
switch (walk_state->opcode) {
case AML_RELEASE_OP:
status = <API key>(operand[0], walk_state);
break;
case AML_RESET_OP:
status = <API key>(operand[0]);
break;
case AML_SIGNAL_OP:
status = <API key>(operand[0]);
break;
case AML_SLEEP_OP:
status = <API key>(operand[0]->integer.value);
break;
case AML_STALL_OP:
status =
<API key>((u32) operand[0]->integer.value);
break;
case AML_UNLOAD_OP:
status = <API key>(operand[0]);
break;
default:
ACPI_ERROR((AE_INFO, "Unknown AML opcode %X",
walk_state->opcode));
status = AE_AML_BAD_OPCODE;
break;
}
return_ACPI_STATUS(status);
}
acpi_status <API key>(struct acpi_walk_state *walk_state)
{
acpi_status status = AE_OK;
union acpi_operand_object **operand = &walk_state->operands[0];
<API key>(ex_opcode_1A_1T_0R,
<API key>(walk_state->opcode));
switch (walk_state->opcode) {
case AML_LOAD_OP:
status = acpi_ex_load_op(operand[0], operand[1], walk_state);
break;
default:
ACPI_ERROR((AE_INFO, "Unknown AML opcode %X",
walk_state->opcode));
status = AE_AML_BAD_OPCODE;
goto cleanup;
}
cleanup:
return_ACPI_STATUS(status);
}
acpi_status <API key>(struct acpi_walk_state *walk_state)
{
acpi_status status = AE_OK;
union acpi_operand_object **operand = &walk_state->operands[0];
union acpi_operand_object *return_desc = NULL;
union acpi_operand_object *return_desc2 = NULL;
u32 temp32;
u32 i;
acpi_integer power_of_ten;
acpi_integer digit;
<API key>(ex_opcode_1A_1T_1R,
<API key>(walk_state->opcode));
switch (walk_state->opcode) {
case AML_BIT_NOT_OP:
case <API key>:
case <API key>:
case AML_FROM_BCD_OP:
case AML_TO_BCD_OP:
case AML_COND_REF_OF_OP:
return_desc = <API key>(ACPI_TYPE_INTEGER);
if (!return_desc) {
status = AE_NO_MEMORY;
goto cleanup;
}
switch (walk_state->opcode) {
case AML_BIT_NOT_OP:
return_desc->integer.value = ~operand[0]->integer.value;
break;
case <API key>:
return_desc->integer.value = operand[0]->integer.value;
for (temp32 = 0; return_desc->integer.value &&
temp32 < <API key>; ++temp32) {
return_desc->integer.value >>= 1;
}
return_desc->integer.value = temp32;
break;
case <API key>:
return_desc->integer.value = operand[0]->integer.value;
for (temp32 = 0; return_desc->integer.value &&
temp32 < <API key>; ++temp32) {
return_desc->integer.value <<= 1;
}
return_desc->integer.value =
temp32 ==
0 ? 0 : (<API key> + 1) - temp32;
break;
case AML_FROM_BCD_OP:
power_of_ten = 1;
return_desc->integer.value = 0;
digit = operand[0]->integer.value;
for (i = 0;
(i < <API key>) && (digit > 0);
i++) {
temp32 = ((u32) digit) & 0xF;
if (temp32 > 9) {
ACPI_ERROR((AE_INFO,
"BCD digit too large (not decimal): 0x%X",
temp32));
status = <API key>;
goto cleanup;
}
return_desc->integer.value +=
(((acpi_integer) temp32) * power_of_ten);
digit >>= 4;
power_of_ten *= 10;
}
break;
case AML_TO_BCD_OP:
return_desc->integer.value = 0;
digit = operand[0]->integer.value;
for (i = 0;
(i < <API key>) && (digit > 0);
i++) {
(void)<API key>(digit, 10, &digit,
&temp32);
return_desc->integer.value |=
(((acpi_integer) temp32) << ACPI_MUL_4(i));
}
if (digit > 0) {
ACPI_ERROR((AE_INFO,
"Integer too large to convert to BCD: %8.8X%8.8X",
ACPI_FORMAT_UINT64(operand[0]->
integer.value)));
status = <API key>;
goto cleanup;
}
break;
case AML_COND_REF_OF_OP:
if ((struct acpi_namespace_node *)operand[0] ==
acpi_gbl_root_node) {
return_desc->integer.value = 0;
goto cleanup;
}
status = <API key>(operand[0],
&return_desc2,
walk_state);
if (ACPI_FAILURE(status)) {
goto cleanup;
}
status =
acpi_ex_store(return_desc2, operand[1], walk_state);
<API key>(return_desc2);
return_desc->integer.value = ACPI_INTEGER_MAX;
goto cleanup;
default:
break;
}
break;
case AML_STORE_OP:
status = acpi_ex_store(operand[0], operand[1], walk_state);
if (ACPI_FAILURE(status)) {
return_ACPI_STATUS(status);
}
if (!walk_state->result_obj) {
walk_state->result_obj = operand[0];
walk_state->operands[0] = NULL;
}
return_ACPI_STATUS(status);
case AML_COPY_OP:
status =
<API key>(operand[0], &return_desc,
walk_state);
break;
case AML_TO_DECSTRING_OP:
status = <API key>(operand[0], &return_desc,
<API key>);
if (return_desc == operand[0]) {
<API key>(return_desc);
}
break;
case AML_TO_HEXSTRING_OP:
status = <API key>(operand[0], &return_desc,
<API key>);
if (return_desc == operand[0]) {
<API key>(return_desc);
}
break;
case AML_TO_BUFFER_OP:
status = <API key>(operand[0], &return_desc);
if (return_desc == operand[0]) {
<API key>(return_desc);
}
break;
case AML_TO_INTEGER_OP:
status = <API key>(operand[0], &return_desc,
ACPI_ANY_BASE);
if (return_desc == operand[0]) {
<API key>(return_desc);
}
break;
case <API key>:
case <API key>:
ACPI_ERROR((AE_INFO,
"%s is obsolete and not implemented",
<API key>(walk_state->opcode)));
status = AE_SUPPORT;
goto cleanup;
default:
ACPI_ERROR((AE_INFO, "Unknown AML opcode %X",
walk_state->opcode));
status = AE_AML_BAD_OPCODE;
goto cleanup;
}
if (ACPI_SUCCESS(status)) {
status = acpi_ex_store(return_desc, operand[1], walk_state);
}
cleanup:
if (ACPI_FAILURE(status)) {
<API key>(return_desc);
}
else if (!walk_state->result_obj) {
walk_state->result_obj = return_desc;
}
return_ACPI_STATUS(status);
}
acpi_status <API key>(struct acpi_walk_state *walk_state)
{
union acpi_operand_object **operand = &walk_state->operands[0];
union acpi_operand_object *temp_desc;
union acpi_operand_object *return_desc = NULL;
acpi_status status = AE_OK;
u32 type;
acpi_integer value;
<API key>(ex_opcode_1A_0T_1R,
<API key>(walk_state->opcode));
switch (walk_state->opcode) {
case AML_LNOT_OP:
return_desc = <API key>(ACPI_TYPE_INTEGER);
if (!return_desc) {
status = AE_NO_MEMORY;
goto cleanup;
}
if (!operand[0]->integer.value) {
return_desc->integer.value = ACPI_INTEGER_MAX;
}
break;
case AML_DECREMENT_OP:
case AML_INCREMENT_OP:
return_desc = <API key>(ACPI_TYPE_INTEGER);
if (!return_desc) {
status = AE_NO_MEMORY;
goto cleanup;
}
temp_desc = operand[0];
if (<API key>(temp_desc) ==
<API key>) {
<API key>(temp_desc);
}
status =
<API key>(AML_LNOT_OP, &temp_desc,
walk_state);
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status,
"While resolving operands for [%s]",
<API key>(walk_state->
opcode)));
goto cleanup;
}
if (walk_state->opcode == AML_INCREMENT_OP) {
return_desc->integer.value =
temp_desc->integer.value + 1;
} else {
return_desc->integer.value =
temp_desc->integer.value - 1;
}
<API key>(temp_desc);
status = acpi_ex_store(return_desc, operand[0], walk_state);
break;
case AML_TYPE_OP:
status =
<API key>(walk_state, operand[0], &type,
NULL);
if (ACPI_FAILURE(status)) {
goto cleanup;
}
return_desc = <API key>(ACPI_TYPE_INTEGER);
if (!return_desc) {
status = AE_NO_MEMORY;
goto cleanup;
}
return_desc->integer.value = type;
break;
case AML_SIZE_OF_OP:
status = <API key>(walk_state,
operand[0], &type,
&temp_desc);
if (ACPI_FAILURE(status)) {
goto cleanup;
}
switch (type) {
case ACPI_TYPE_INTEGER:
value = <API key>;
break;
case ACPI_TYPE_STRING:
value = temp_desc->string.length;
break;
case ACPI_TYPE_BUFFER:
status = <API key>(temp_desc);
value = temp_desc->buffer.length;
break;
case ACPI_TYPE_PACKAGE:
status = <API key>(temp_desc);
value = temp_desc->package.count;
break;
default:
ACPI_ERROR((AE_INFO,
"Operand must be Buffer/Integer/String/Package - found type %s",
<API key>(type)));
status = AE_AML_OPERAND_TYPE;
goto cleanup;
}
if (ACPI_FAILURE(status)) {
goto cleanup;
}
return_desc = <API key>(ACPI_TYPE_INTEGER);
if (!return_desc) {
status = AE_NO_MEMORY;
goto cleanup;
}
return_desc->integer.value = value;
break;
case AML_REF_OF_OP:
status =
<API key>(operand[0], &return_desc,
walk_state);
if (ACPI_FAILURE(status)) {
goto cleanup;
}
break;
case AML_DEREF_OF_OP:
if (<API key>(operand[0]) ==
<API key>) {
temp_desc =
<API key>((struct
acpi_namespace_node *)
operand[0]);
if (temp_desc
&& ((temp_desc->common.type == ACPI_TYPE_STRING)
|| (temp_desc->common.type ==
<API key>))) {
operand[0] = temp_desc;
<API key>(temp_desc);
} else {
status = AE_AML_OPERAND_TYPE;
goto cleanup;
}
} else {
switch ((operand[0])->common.type) {
case <API key>:
switch (operand[0]->reference.class) {
case ACPI_REFCLASS_LOCAL:
case ACPI_REFCLASS_ARG:
status =
<API key>
(operand[0]->reference.class,
operand[0]->reference.value,
walk_state, &temp_desc);
if (ACPI_FAILURE(status)) {
goto cleanup;
}
<API key>(operand[0]);
operand[0] = temp_desc;
break;
case ACPI_REFCLASS_REFOF:
temp_desc =
operand[0]->reference.object;
<API key>(operand[0]);
operand[0] = temp_desc;
break;
default:
break;
}
break;
case ACPI_TYPE_STRING:
break;
default:
status = AE_AML_OPERAND_TYPE;
goto cleanup;
}
}
if (<API key>(operand[0]) !=
<API key>) {
if ((operand[0])->common.type == ACPI_TYPE_STRING) {
status =
acpi_ns_get_node(walk_state->scope_info->
scope.node,
operand[0]->string.pointer,
<API key>,
<API key>
(struct
acpi_namespace_node,
&return_desc));
if (ACPI_FAILURE(status)) {
goto cleanup;
}
status =
<API key>
(<API key>
(struct acpi_namespace_node, &return_desc),
walk_state);
goto cleanup;
}
}
if (<API key>(operand[0]) ==
<API key>) {
return_desc = <API key>((struct
acpi_namespace_node
*)
operand[0]);
<API key>(return_desc);
} else {
switch (operand[0]->reference.class) {
case ACPI_REFCLASS_INDEX:
switch (operand[0]->reference.target_type) {
case <API key>:
temp_desc =
operand[0]->reference.object;
return_desc =
<API key>
(ACPI_TYPE_INTEGER);
if (!return_desc) {
status = AE_NO_MEMORY;
goto cleanup;
}
return_desc->integer.value =
temp_desc->buffer.
pointer[operand[0]->reference.
value];
break;
case ACPI_TYPE_PACKAGE:
return_desc =
*(operand[0]->reference.where);
if (return_desc) {
<API key>
(return_desc);
}
break;
default:
ACPI_ERROR((AE_INFO,
"Unknown Index TargetType %X in reference object %p",
operand[0]->reference.
target_type, operand[0]));
status = AE_AML_OPERAND_TYPE;
goto cleanup;
}
break;
case ACPI_REFCLASS_REFOF:
return_desc = operand[0]->reference.object;
if (<API key>(return_desc) ==
<API key>) {
return_desc =
<API key>((struct
acpi_namespace_node
*)
return_desc);
}
<API key>(return_desc);
break;
default:
ACPI_ERROR((AE_INFO,
"Unknown class in reference(%p) - %2.2X",
operand[0],
operand[0]->reference.class));
status = AE_TYPE;
goto cleanup;
}
}
break;
default:
ACPI_ERROR((AE_INFO, "Unknown AML opcode %X",
walk_state->opcode));
status = AE_AML_BAD_OPCODE;
goto cleanup;
}
cleanup:
if (ACPI_FAILURE(status)) {
<API key>(return_desc);
}
else {
walk_state->result_obj = return_desc;
}
return_ACPI_STATUS(status);
} |
/**
* Module page class.
*/
class Module_login
{
/**
* Standard modular info function.
*
* @return ?array Map of module info (NULL: module is disabled).
*/
function info()
{
$info=array();
$info['author']='Chris Graham';
$info['organisation']='ocProducts';
$info['hacked_by']=NULL;
$info['hack_version']=NULL;
$info['version']=2;
$info['locked']=true;
return $info;
}
/**
* Standard modular uninstall function.
*/
function uninstall()
{
$GLOBALS['SITE_DB']->drop_if_exists('failedlogins');
}
/**
* Standard modular install function.
*
* @param ?integer What version we're upgrading from (NULL: new install)
* @param ?integer What hack version we're upgrading from (NULL: new-install/<API key>)
*/
function install($upgrade_from=NULL,$upgrade_from_hack=NULL)
{
$GLOBALS['SITE_DB']->create_table('failedlogins',array(
'id'=>'*AUTO',
'failed_account'=>'ID_TEXT',
'date_and_time'=>'TIME',
'ip'=>'IP'
));
}
/**
* Standard modular entry-point finder function.
*
* @return ?array A map of entry points (type-code=>language-code) (NULL: disabled).
*/
function get_entry_points()
{
if (is_guest()) return array('misc'=>'_LOGIN');
$ret=array('misc'=>'_LOGIN','logout'=>'LOGOUT','concede'=>'CONCEDED_MODE');
if (get_option('is_on_invisibility')=='1') $ret['invisible']='INVISIBLE';
return $ret;
}
/**
* Standard modular run function.
*
* @return tempcode The result of execution.
*/
function run()
{
$type=get_param('type','misc');
if ($type=='login') return $this->login_after();
if ($type=='logout') return $this->logout();
if ($type=='concede') return $this->concede();
if ($type=='invisible') return $this->invisible();
if ($type=='misc') return $this->login_before();
return new ocp_tempcode();
}
/**
* The UI for logging in.
*
* @return tempcode The UI.
*/
function login_before()
{
$title=get_screen_title('_LOGIN');
global $EXTRA_HEAD;
$EXTRA_HEAD->attach('<meta name="robots" content="noindex" />'); // XHTMLXHTML
global $ZONE;
// Where we will be redirected to after login
// It's intentional that we will only go to the zone-default page if an explicitly blank redirect URL is given. If not we go to the given redirect URL or to the made-safe current URL (made-safe=zone root if we posted as we do not want to re-post). Note that 'redirect_passon' is simulated by injecting the self-URL as a URL parameter by access_denied() - as we want re-post in this case.
$redirect_default=get_self_url(true,true); // Still won't redirect to root if we have $_POST, because we relay $_POST values and have intelligence later on
$redirect=get_param('redirect',$redirect_default);
if (($redirect!='') && (strpos($redirect,'page=login')===false) && (strpos($redirect,'/login.htm')===false) && (strpos($redirect,'/login/logout.htm')===false) && (strpos($redirect,'/login/misc.htm')===false) && (strpos($redirect,'/pg/login')===false))
{
$passion=form_input_hidden('redirect',$redirect);
} else
{
$_url=build_url(array('page'=>$ZONE['zone_default_page']),'_SELF');
$url=$_url->evaluate();
$passion=form_input_hidden('redirect',$url);
}
$login_url=build_url(array('page'=>'_SELF','type'=>'login'),'_SELF');
// Test to see if we have any redirect issue that blocks form submissions
if (ocp_srv('HTTP_USER_AGENT')!='ocPortal' && strpos(ocp_srv('HTTP_REFERER'),'logout')===false && running_script('index'))
{
$this_proper_url=build_url(array('page'=>'_SELF','type'=>'misc'),'_SELF');
$_login_url=$this_proper_url->evaluate();
$test=http_download_file($_login_url,0,false,true); // Should return a 200 blank, not an HTTP error or a redirect; actual data would be an ocP error
if ((is_null($test)) && ($GLOBALS['HTTP_MESSAGE']!=='200') && ($GLOBALS['HTTP_MESSAGE']!=='401') && ((!is_file(get_file_base().'/install.php')) || ($GLOBALS['HTTP_MESSAGE']!=='500')))
{
if ((($GLOBALS['HTTP_MESSAGE']=='no-data') || (strpos($GLOBALS['HTTP_MESSAGE'],'Connection refused')!==false)) && (get_option('ip_forwarding')=='0'))
{
attach_message(do_lang_tempcode('config:<API key>',do_lang('config:IP_FORWARDING')),'warn');
} else
{
attach_message(do_lang_tempcode((substr(get_base_url(),0,11)=='http:
}
}
}
if (count($_FILES)==0) // Only if we don't have _FILES (which could never be relayed)
{
$passion->attach(<API key>(array('redirect')));
$redirect_passon=post_param('redirect',NULL);
if (!is_null($redirect_passon))
$passion->attach(form_input_hidden('redirect_passon',$redirect_passon));
}
$username=trim(get_param('username',''));
if (!is_guest()) $username=$GLOBALS['FORUM_DRIVER']->get_username(get_member());
if (get_forum_type()=='ocf')
{
require_lang('ocf');
$forgotten_link=build_url(array('page'=>'lostpassword'),get_module_zone('lostpassword'));
$extra=do_lang_tempcode('<API key>',escape_html($forgotten_link->evaluate()));
} else $extra=new ocp_tempcode();
require_css('login');
<API key>(array());
return do_template('LOGIN_SCREEN',array('_GUID'=>'<API key>','EXTRA'=>$extra,'USERNAME'=>$username,'JOIN_URL'=>$GLOBALS['FORUM_DRIVER']->join_url(),'TITLE'=>$title,'LOGIN_URL'=>$login_url,'PASSION'=>$passion));
}
/**
* The actualiser for logging in.
*
* @return tempcode The UI.
*/
function login_after()
{
<API key>(array(array('_SELF:_SELF:misc',do_lang_tempcode('_LOGIN'))));
$username=trim(post_param('login_username'));
$feedback=$GLOBALS['FORUM_DRIVER']-><API key>($username,NULL,<API key>(trim(post_param('password')),$username),trim(post_param('password')));
$id=$feedback['id'];
if (!is_null($id))
{
$title=get_screen_title('LOGGED_IN');
$url=<API key>(either_param('redirect'));
//set_session_id(get_session_id()); // Just in case something earlier set it to a pre-logged-in one Not needed
if (count($_POST)<=4) // Only the login username, password, remember-me and redirect
{
require_code('site2');
assign_refresh($url,0.0);
$post=new ocp_tempcode();
$refresh=new ocp_tempcode();
} else
{
$post=<API key>(array('redirect','redirect_passon'));
$redirect_passon=post_param('redirect_passon',NULL);
if (!is_null($redirect_passon))
$post->attach(form_input_hidden('redirect',$redirect_passon));
$refresh=do_template('JS_REFRESH',array('_GUID'=>'<API key>','FORM_NAME'=>'redir_form'));
}
decache('side_users_online');
return do_template('<API key>',array('_GUID'=>'<API key>','REFRESH'=>$refresh,'TITLE'=>$title,'TEXT'=>do_lang_tempcode('_LOGIN_TEXT'),'URL'=>$url,'POST'=>$post));
} else
{
$title=get_screen_title('USER_LOGIN_ERROR');
$text=$feedback['error'];
attach_message($text,'warn');
if (get_forum_type()=='ocf')
{
require_lang('ocf');
$forgotten_link=build_url(array('page'=>'lostpassword'),get_module_zone('lostpassword'));
$extra=do_lang_tempcode('<API key>',escape_html($forgotten_link->evaluate()));
attach_message($extra,'inform');
}
return $this->login_before();
}
}
/**
* The actualiser for logging out.
*
* @return tempcode The UI.
*/
function logout()
{
decache('side_users_online');
$title=get_screen_title('LOGGED_OUT');
$url=get_param('redirect',NULL);
if (is_null($url))
{
$_url=build_url(array('page'=>''),'',array('keep_session'=>1));
$url=$_url->evaluate();
}
return redirect_screen($title,$url,do_lang_tempcode('_LOGGED_OUT'));
}
/**
* The actualiser for entering conceded mode.
*
* @return tempcode The UI.
*/
function concede()
{
$title=get_screen_title('CONCEDED_MODE');
$GLOBALS['SITE_DB']->query_update('sessions',array('session_confirmed'=>0),array('the_user'=>get_member(),'the_session'=>get_session_id()),'',1);
global $SESSION_CACHE;
if ($SESSION_CACHE[get_session_id()]['the_user']==get_member()) // A little security
{
$SESSION_CACHE[get_session_id()]['session_confirmed']=0;
if (get_value('session_prudence')!=='1')
{
<API key>('SESSION_CACHE',$SESSION_CACHE);
}
}
$url=get_param('redirect',NULL);
if (is_null($url))
{
$_url=build_url(array('page'=>''),'');
$url=$_url->evaluate();
}
return redirect_screen($title,$url,do_lang_tempcode('LOGIN_CONCEDED'));
}
/**
* The actualiser for toggling invisible mode.
*
* @return tempcode The UI.
*/
function invisible()
{
if (get_option('is_on_invisibility')=='1')
{
$visible=(array_key_exists(get_session_id(),$GLOBALS['SESSION_CACHE'])) && ($GLOBALS['SESSION_CACHE'][get_session_id()]['session_invisible']==0);
} else
{
$visible=false;
}
$title=get_screen_title($visible?'INVISIBLE':'BE_VISIBLE');
$GLOBALS['SITE_DB']->query_update('sessions',array('session_invisible'=>$visible?1:0),array('the_user'=>get_member(),'the_session'=>get_session_id()),'',1);
global $SESSION_CACHE;
if ($SESSION_CACHE[get_session_id()]['the_user']==get_member()) // A little security
{
$SESSION_CACHE[get_session_id()]['session_invisible']=$visible?1:0;
if (get_value('session_prudence')!=='1')
{
<API key>('SESSION_CACHE',$SESSION_CACHE);
}
}
decache('side_users_online');
// Store in cookie, if we have login cookies around
if (array_key_exists(get_member_cookie(),$_COOKIE))
{
require_code('<API key>');
ocp_setcookie(get_member_cookie().'_invisible',strval($visible?1:0));
$_COOKIE[get_member_cookie().'_invisible']=strval($visible?1:0);
}
$url=get_param('redirect',NULL);
if (is_null($url))
{
$_url=build_url(array('page'=>''),'');
$url=$_url->evaluate();
}
return redirect_screen($title,$url,do_lang_tempcode('SUCCESS'));
}
} |
#pragma once
#include "BaseLight.h"
namespace CommonUtilities
{
class DirectionalLight : public BaseLight
{
public:
DirectionalLight();
~DirectionalLight();
void Update(Vector3<float> aDirection, Vector3<float> aColor, float aSpecularPower);
inline const Vector3<float>& GetLightDirection() const;
};
const Vector3<float>& DirectionalLight::GetLightDirection() const
{
return myLightDirection;
}
}namespace CU = CommonUtilities; |
#ifndef DWT_COLUMN_H_
#define DWT_COLUMN_H_
namespace dwt {
struct Column {
enum Alignment {
LEFT,
RIGHT,
CENTER
};
enum AutoWidth {
SIZE_TO_CONTENT = -1,
SIZE_TO_HEADER = -2
};
tstring header;
int width;
Alignment alignment;
Column();
Column(tstring header, int width = -1, Alignment alignment = LEFT);
};
inline Column::Column() { }
inline Column::Column(tstring header, int width, Alignment alignment) : header(header), width(width), alignment(alignment) { }
}
#endif /* COLUMN_H_ */ |
<?php
namespace Magento\CatalogSearch\Helper;
/**
* Catalog search helper
*
* @api
* @since 100.0.2
*/
class Data extends \Magento\Search\Helper\Data
{
/**
* Retrieve advanced search URL
*
* @return string
*/
public function <API key>()
{
return $this->_getUrl('catalogsearch/advanced');
}
} |
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "logging.h"
#include "complex.h"
#include "property.h"
#include "object.h"
#include "variable.h"
// Constructor creates an unnamed instance of the object class.
object::object () {
name = NULL;
prev = next = NULL;
prop = NULL;
ptxt = NULL;
}
// This constructor creates a named instance of the object class.
object::object (const char * n) {
// create a copy of the character array pointed to by n
// and get a pointer to the copy using strdup
name = strdup (n);
prev = next = NULL;
prop = NULL;
ptxt = NULL;
}
/* This copy constructor creates a instance of the object class based
on the given object. */
object::object (const object & o) {
name = o.name ? strdup (o.name) : NULL;
next = o.next;
prev = o.prev;
ptxt = o.ptxt ? strdup (o.ptxt) : NULL;
copyProperties (o.prop);
}
// Destructor deletes an instance of the object class.
object::~object () {
if (name) free (name);
if (ptxt) free (ptxt);
deleteProperties ();
}
// Sets the name of the object.
void object::setName (const char * n) {
if (name) free (name);
name = n ? strdup (n) : NULL;
}
// Returns the name of the object.
char * object::getName (void) {
return name;
}
// The function adds a complete property to the object property list.
void object::addProperty (property * p) {
p->setNext (prop);
prop = p;
}
/* This function adds a property consisting of a key and a string
value to the object. */
property * object::addProperty (const char * n, const char * val) {
property * p = new property (n, val);
addProperty (p);
return p;
}
/* This function sets the specified property consisting of a key and a
string value in the object. */
void object::setProperty (const char * n, char * val) {
property * p = prop->findProperty (n);
if (p != NULL)
p->set (val);
else
addProperty (n, val);
}
/* This function adds a property consisting of a key and a double
value to the object. */
property * object::addProperty (const char * n, nr_double_t val) {
property * p = new property (n, val);
addProperty (p);
return p;
}
/* This function sets the specified property consisting of a key and a
double value in the object. */
void object::setProperty (const char * n, nr_double_t val) {
property * p = prop->findProperty (n);
if (p != NULL)
p->set (val);
else
addProperty (n, val);
}
/* Th function sets the specified property consisting of a key and a
double value in the object. The property is marked a scalability
property. */
void object::setScaledProperty (const char * n, nr_double_t val) {
char prop[64];
sprintf (prop, "Scaled:%s", n);
setProperty (prop, val);
}
/* This function adds a property consisting of a key and a variable
value to the object. */
property * object::addProperty (const char * n, variable * val) {
property * p = new property (n, val);
addProperty (p);
return p;
}
/* Returns the requested property value which has been previously
added as its vector representation. If there is no such property
the function returns NULL. */
vector * object::getPropertyVector (const char * n) {
property * p = prop->findProperty (n);
if (p != NULL) return p->getVector ();
return NULL;
}
/* Returns the requested property value which has been previously
added as its text representation. If there is no such property the
function returns NULL. */
char * object::getPropertyString (const char * n) {
property * p = prop->findProperty (n);
if (p != NULL) return p->getString ();
return NULL;
}
/* Returns the requested property reference variable name. If there
is no such property the function returns NULL. */
char * object::<API key> (const char * n) {
property * p = prop->findProperty (n);
if (p != NULL) return p->getReference ();
return NULL;
}
/* Returns the requested property value which has been previously
added as its double representation. If there is no such property
the function returns zero. */
nr_double_t object::getPropertyDouble (const char * n) {
property * p = prop->findProperty (n);
if (p != NULL) return p->getDouble ();
return 0.0;
}
/* The functions returns the requested (scalability) property value
which has been previously added. If there is no such scaled
property the function returns the standard property or zero. */
nr_double_t object::getScaledProperty (const char * n) {
char txt[64];
sprintf (txt, "Scaled:%s", n);
// try to find scaled property
property * p = prop->findProperty (txt);
if (p != NULL) return p->getDouble ();
// default to standard property
return getPropertyDouble (n);
}
/* Returns the requested property value which has been previously
added as its integer representation. If there is no such property
the function returns zero. */
int object::getPropertyInteger (const char * n) {
property * p = prop->findProperty (n);
if (p != NULL) return p->getInteger ();
return 0;
}
/* The function checks whether the object has got a certain property
value. If so it returns non-zero, otherwise it returns zero. */
bool object::hasProperty (const char * n) {
return (prop && prop->findProperty (n)) ? true : false;
}
/* The function checks whether the object has got a certain property
value and if this has its default value. If so it returns non-zero,
otherwise it returns zero. */
bool object::isPropertyGiven (const char * n) {
if (prop != NULL) {
property * p = prop->findProperty (n);
if (p != NULL && !p->isDefault ()) return true;
}
return false;
}
/* This function copies all properties in the given property list into
an object. */
void object::copyProperties (property * org) {
prop = NULL;
while (org != NULL) {
addProperty (new property (*org));
org = org->getNext ();
}
}
// Deletes all properties of an object.
void object::deleteProperties (void) {
property * n;
for (property * p = prop; p != NULL; p = n) {
n = p->getNext ();
delete p;
}
prop = NULL;
}
// The function returns the number of properties in the object.
int object::countProperties (void) {
int res = 0;
for (property * p = prop; p != NULL; p = p->getNext ()) res++;
return res;
}
// This function returns a text representation of the objects properties.
char * object::propertyList (void) {
if (ptxt) free (ptxt);
int len = countProperties () + 1;
ptxt = (char *) malloc (len); ptxt[0] = '\0';
for (property * p = prop; p != NULL; p = p->getNext ()) {
char * n = p->getName ();
char * val = p->toString ();
char * text = (char *) malloc (strlen (n) + strlen (val) + 4);
sprintf (text, "%s=\"%s\"", n, val);
len += strlen (text);
ptxt = (char *) realloc (ptxt, len);
strcat (ptxt, text);
if (p->getNext () != NULL) strcat (ptxt, " ");
free (text);
}
return ptxt;
} |
div.tabs, .<API key> {
display:none;
} |
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
using KP.GmailClient.Extensions;
namespace KP.GmailClient.Common
{
<summary>Handles requests to the Gmail service and parses the response.</summary>
internal class GmailProxy : IDisposable
{
<summary>The URL to send requests to the Gmail API service.</summary>
public const string ApiBaseUrl = "https:
private static readonly HttpMethod HttpGet = new("GET");
private static readonly HttpMethod HttpPost = new("POST");
private static readonly HttpMethod HttpPut = new("PUT");
private static readonly HttpMethod HttpPatch = new("PATCH");
private readonly HttpClient _client;
<summary>Takes care of all I/O to Gmail.</summary>
<param name="handler">An optional handler to handle authentication or caching for example</param>
internal GmailProxy(DelegatingHandler handler)
{
var compressionHandler = new HttpClientHandler { <API key> = <API key>.GZip | <API key>.Deflate };
HttpMessageHandler mainHandler;
if (handler == null)
{
mainHandler = compressionHandler;
}
else
{
handler.InnerHandler = compressionHandler;
mainHandler = handler;
}
_client = new HttpClient(mainHandler) { BaseAddress = new Uri(string.Concat(ApiBaseUrl, "me/")) };
_client.<API key>.Add("Accept", "application/json");
}
internal async Task<T> Get<T>(string queryString)
{
return await GetResponseAsync<T>(HttpGet, queryString);
}
internal async Task<T> Get<T>(string queryString, ParseOptions options)
{
var element = await GetResponseAsync<JsonElement>(HttpGet, queryString);
return element.GetProperty(options.Path).ToObject<T>();
}
internal async Task<T> Post<T>(string queryString, object content = null)
{
return await GetResponseAsync<T>(HttpPost, queryString, content);
}
internal async Task<T> Put<T>(string queryString, object content = null)
{
return await GetResponseAsync<T>(HttpPut, queryString, content);
}
internal async Task<T> Patch<T>(string queryString, object content)
{
return await GetResponseAsync<T>(HttpPatch, queryString, content);
}
internal async Task Delete(string queryString)
{
var response = await _client.DeleteAsync(queryString);
await <API key>(response);
}
private async Task<T> GetResponseAsync<T>(HttpMethod httpMethod, string queryString, object content = null)
{
var request = new HttpRequestMessage(httpMethod, queryString)
{
Content = content == null ? null : JsonContent.Create(content)
};
HttpResponseMessage response = await _client.SendAsync(request);
await <API key>(response);
using Stream stream = await response.Content.ReadAsStreamAsync();
return await JsonSerializer.DeserializeAsync<T>(stream);
}
private static async Task <API key>(HttpResponseMessage response)
{
if (response.IsSuccessStatusCode)
{
return;
}
using Stream stream = await response.Content.ReadAsStreamAsync();
GmailApiException ex = await ErrorResponseParser.ParseAsync(response.StatusCode, stream);
throw ex;
}
public void Dispose()
{
_client.Dispose();
}
}
} |
<!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.3.1"/>
<title>oRTP: sdes_item Struct 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
 <span id="projectnumber">0.22.0</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.3.1 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="functions.html"><span>Data Fields</span></a></li>
</ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-attribs">Data Fields</a> </div>
<div class="headertitle">
<div class="title">sdes_item Struct Reference</div> </div>
</div><!--header
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a>
Data Fields</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
uint8_t </td><td class="memItemRight" valign="bottom"><b>item_type</b></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
uint8_t </td><td class="memItemRight" valign="bottom"><b>len</b></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="<API key>"></a>
char </td><td class="memItemRight" valign="bottom"><b>content</b> [1]</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<hr/>The documentation for this struct was generated from the following file:<ul>
<li>/Users/jehanmonnier/workspaces/<API key>/linphone-iphone/submodules/linphone/oRTP/include/ortp/<a class="el" href="rtcp_8h_source.html">rtcp.h</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Mon Sep 2 2013 11:14:42 for oRTP by &
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.3.1
</small></address>
</body>
</html> |
#include <math.h>
#include <stdint.h>
#include <string.h>
#include "libavutil/channel_layout.h"
#include "libavutil/float_dsp.h"
#include "libavutil/mathematics.h"
#include "avcodec.h"
#define BITSTREAM_READER_LE
#include "get_bits.h"
#include "internal.h"
#include "lsp.h"
#include "acelp_vectors.h"
#include "acelp_pitch_delay.h"
#include "acelp_filters.h"
#include "celp_filters.h"
#define MAX_SUBFRAME_COUNT 5
#include "sipr.h"
#include "siprdata.h"
typedef struct {
const char *mode_name;
uint16_t bits_per_frame;
uint8_t subframe_count;
uint8_t frames_per_packet;
float pitch_sharp_factor;
/* bitstream parameters */
uint8_t <API key>;
uint8_t ma_predictor_bits; ///< size in bits of the switched MA predictor
/** size in bits of the i-th stage vector of quantizer */
uint8_t vq_indexes_bits[5];
/** size in bits of the adaptive-codebook index for every subframe */
uint8_t pitch_delay_bits[5];
uint8_t gp_index_bits;
uint8_t fc_index_bits[10]; ///< size in bits of the fixed codebook indexes
uint8_t gc_index_bits; ///< size in bits of the gain codebook indexes
} SiprModeParam;
static const SiprModeParam modes[MODE_COUNT] = {
[MODE_16k] = {
.mode_name = "16k",
.bits_per_frame = 160,
.subframe_count = SUBFRAME_COUNT_16k,
.frames_per_packet = 1,
.pitch_sharp_factor = 0.00,
.<API key> = 10,
.ma_predictor_bits = 1,
.vq_indexes_bits = {7, 8, 7, 7, 7},
.pitch_delay_bits = {9, 6},
.gp_index_bits = 4,
.fc_index_bits = {4, 5, 4, 5, 4, 5, 4, 5, 4, 5},
.gc_index_bits = 5
},
[MODE_8k5] = {
.mode_name = "8k5",
.bits_per_frame = 152,
.subframe_count = 3,
.frames_per_packet = 1,
.pitch_sharp_factor = 0.8,
.<API key> = 3,
.ma_predictor_bits = 0,
.vq_indexes_bits = {6, 7, 7, 7, 5},
.pitch_delay_bits = {8, 5, 5},
.gp_index_bits = 0,
.fc_index_bits = {9, 9, 9},
.gc_index_bits = 7
},
[MODE_6k5] = {
.mode_name = "6k5",
.bits_per_frame = 232,
.subframe_count = 3,
.frames_per_packet = 2,
.pitch_sharp_factor = 0.8,
.<API key> = 3,
.ma_predictor_bits = 0,
.vq_indexes_bits = {6, 7, 7, 7, 5},
.pitch_delay_bits = {8, 5, 5},
.gp_index_bits = 0,
.fc_index_bits = {5, 5, 5},
.gc_index_bits = 7
},
[MODE_5k0] = {
.mode_name = "5k0",
.bits_per_frame = 296,
.subframe_count = 5,
.frames_per_packet = 2,
.pitch_sharp_factor = 0.85,
.<API key> = 1,
.ma_predictor_bits = 0,
.vq_indexes_bits = {6, 7, 7, 7, 5},
.pitch_delay_bits = {8, 5, 8, 5, 5},
.gp_index_bits = 0,
.fc_index_bits = {10},
.gc_index_bits = 7
}
};
const float ff_pow_0_5[] = {
1.0/(1 << 1), 1.0/(1 << 2), 1.0/(1 << 3), 1.0/(1 << 4),
1.0/(1 << 5), 1.0/(1 << 6), 1.0/(1 << 7), 1.0/(1 << 8),
1.0/(1 << 9), 1.0/(1 << 10), 1.0/(1 << 11), 1.0/(1 << 12),
1.0/(1 << 13), 1.0/(1 << 14), 1.0/(1 << 15), 1.0/(1 << 16)
};
static void dequant(float *out, const int *idx, const float *cbs[])
{
int i;
int stride = 2;
int num_vec = 5;
for (i = 0; i < num_vec; i++)
memcpy(out + stride*i, cbs[i] + stride*idx[i], stride*sizeof(float));
}
static void lsf_decode_fp(float *lsfnew, float *lsf_history,
const SiprParameters *parm)
{
int i;
float lsf_tmp[LP_FILTER_ORDER];
dequant(lsf_tmp, parm->vq_indexes, lsf_codebooks);
for (i = 0; i < LP_FILTER_ORDER; i++)
lsfnew[i] = lsf_history[i] * 0.33 + lsf_tmp[i] + mean_lsf[i];
<API key>(lsfnew, LP_FILTER_ORDER - 1);
/* Note that a minimum distance is not enforced between the last value and
the previous one, contrary to what is done in <API key>() */
ff_set_min_dist_lsf(lsfnew, LSFQ_DIFF_MIN, LP_FILTER_ORDER - 1);
lsfnew[9] = FFMIN(lsfnew[LP_FILTER_ORDER - 1], 1.3 * M_PI);
memcpy(lsf_history, lsf_tmp, LP_FILTER_ORDER * sizeof(*lsf_history));
for (i = 0; i < LP_FILTER_ORDER - 1; i++)
lsfnew[i] = cos(lsfnew[i]);
lsfnew[LP_FILTER_ORDER - 1] *= 6.153848 / M_PI;
}
/** Apply pitch lag to the fixed vector (AMR section 6.1.2). */
static void pitch_sharpening(int pitch_lag_int, float beta,
float *fixed_vector)
{
int i;
for (i = pitch_lag_int; i < SUBFR_SIZE; i++)
fixed_vector[i] += beta * fixed_vector[i - pitch_lag_int];
}
/**
* Extract decoding parameters from the input bitstream.
* @param parms parameters structure
* @param pgb pointer to initialized GetBitContext structure
*/
static void decode_parameters(SiprParameters* parms, GetBitContext *pgb,
const SiprModeParam *p)
{
int i, j;
if (p->ma_predictor_bits)
parms->ma_pred_switch = get_bits(pgb, p->ma_predictor_bits);
for (i = 0; i < 5; i++)
parms->vq_indexes[i] = get_bits(pgb, p->vq_indexes_bits[i]);
for (i = 0; i < p->subframe_count; i++) {
parms->pitch_delay[i] = get_bits(pgb, p->pitch_delay_bits[i]);
if (p->gp_index_bits)
parms->gp_index[i] = get_bits(pgb, p->gp_index_bits);
for (j = 0; j < p-><API key>; j++)
parms->fc_indexes[i][j] = get_bits(pgb, p->fc_index_bits[j]);
parms->gc_index[i] = get_bits(pgb, p->gc_index_bits);
}
}
static void sipr_decode_lp(float *lsfnew, const float *lsfold, float *Az,
int num_subfr)
{
double lsfint[LP_FILTER_ORDER];
int i,j;
float t, t0 = 1.0 / num_subfr;
t = t0 * 0.5;
for (i = 0; i < num_subfr; i++) {
for (j = 0; j < LP_FILTER_ORDER; j++)
lsfint[j] = lsfold[j] * (1 - t) + t * lsfnew[j];
ff_amrwb_lsp2lpc(lsfint, Az, LP_FILTER_ORDER);
Az += LP_FILTER_ORDER;
t += t0;
}
}
/**
* Evaluate the adaptive impulse response.
*/
static void eval_ir(const float *Az, int pitch_lag, float *freq,
float pitch_sharp_factor)
{
float tmp1[SUBFR_SIZE+1], tmp2[LP_FILTER_ORDER+1];
int i;
tmp1[0] = 1.0;
for (i = 0; i < LP_FILTER_ORDER; i++) {
tmp1[i+1] = Az[i] * ff_pow_0_55[i];
tmp2[i ] = Az[i] * ff_pow_0_7 [i];
}
memset(tmp1 + 11, 0, 37 * sizeof(float));
<API key>(freq, tmp2, tmp1, SUBFR_SIZE,
LP_FILTER_ORDER);
pitch_sharpening(pitch_lag, pitch_sharp_factor, freq);
}
/**
* Evaluate the convolution of a vector with a sparse vector.
*/
static void <API key>(float *out, const AMRFixed *pulses,
const float *shape, int length)
{
int i, j;
memset(out, 0, length*sizeof(float));
for (i = 0; i < pulses->n; i++)
for (j = pulses->x[i]; j < length; j++)
out[j] += pulses->y[i] * shape[j - pulses->x[i]];
}
/**
* Apply postfilter, very similar to AMR one.
*/
static void postfilter_5k0(SiprContext *ctx, const float *lpc, float *samples)
{
float buf[SUBFR_SIZE + LP_FILTER_ORDER];
float *pole_out = buf + LP_FILTER_ORDER;
float lpc_n[LP_FILTER_ORDER];
float lpc_d[LP_FILTER_ORDER];
int i;
for (i = 0; i < LP_FILTER_ORDER; i++) {
lpc_d[i] = lpc[i] * ff_pow_0_75[i];
lpc_n[i] = lpc[i] * ff_pow_0_5 [i];
};
memcpy(pole_out - LP_FILTER_ORDER, ctx->postfilter_mem,
LP_FILTER_ORDER*sizeof(float));
<API key>(pole_out, lpc_d, samples, SUBFR_SIZE,
LP_FILTER_ORDER);
memcpy(ctx->postfilter_mem, pole_out + SUBFR_SIZE - LP_FILTER_ORDER,
LP_FILTER_ORDER*sizeof(float));
<API key>(&ctx->tilt_mem, 0.4, pole_out, SUBFR_SIZE);
memcpy(pole_out - LP_FILTER_ORDER, ctx->postfilter_mem5k0,
LP_FILTER_ORDER*sizeof(*pole_out));
memcpy(ctx->postfilter_mem5k0, pole_out + SUBFR_SIZE - LP_FILTER_ORDER,
LP_FILTER_ORDER*sizeof(*pole_out));
<API key>(samples, lpc_n, pole_out, SUBFR_SIZE,
LP_FILTER_ORDER);
}
static void decode_fixed_sparse(AMRFixed *fixed_sparse, const int16_t *pulses,
SiprMode mode, int low_gain)
{
int i;
switch (mode) {
case MODE_6k5:
for (i = 0; i < 3; i++) {
fixed_sparse->x[i] = 3 * (pulses[i] & 0xf) + i;
fixed_sparse->y[i] = pulses[i] & 0x10 ? -1 : 1;
}
fixed_sparse->n = 3;
break;
case MODE_8k5:
for (i = 0; i < 3; i++) {
fixed_sparse->x[2*i ] = 3 * ((pulses[i] >> 4) & 0xf) + i;
fixed_sparse->x[2*i + 1] = 3 * ( pulses[i] & 0xf) + i;
fixed_sparse->y[2*i ] = (pulses[i] & 0x100) ? -1.0: 1.0;
fixed_sparse->y[2*i + 1] =
(fixed_sparse->x[2*i + 1] < fixed_sparse->x[2*i]) ?
-fixed_sparse->y[2*i ] : fixed_sparse->y[2*i];
}
fixed_sparse->n = 6;
break;
case MODE_5k0:
default:
if (low_gain) {
int offset = (pulses[0] & 0x200) ? 2 : 0;
int val = pulses[0];
for (i = 0; i < 3; i++) {
int index = (val & 0x7) * 6 + 4 - i*2;
fixed_sparse->y[i] = (offset + index) & 0x3 ? -1 : 1;
fixed_sparse->x[i] = index;
val >>= 3;
}
fixed_sparse->n = 3;
} else {
int pulse_subset = (pulses[0] >> 8) & 1;
fixed_sparse->x[0] = ((pulses[0] >> 4) & 15) * 3 + pulse_subset;
fixed_sparse->x[1] = ( pulses[0] & 15) * 3 + pulse_subset + 1;
fixed_sparse->y[0] = pulses[0] & 0x200 ? -1 : 1;
fixed_sparse->y[1] = -fixed_sparse->y[0];
fixed_sparse->n = 2;
}
break;
}
}
static void decode_frame(SiprContext *ctx, SiprParameters *params,
float *out_data)
{
int i, j;
int subframe_count = modes[ctx->mode].subframe_count;
int frame_size = subframe_count * SUBFR_SIZE;
float Az[LP_FILTER_ORDER * MAX_SUBFRAME_COUNT];
float *excitation;
float ir_buf[SUBFR_SIZE + LP_FILTER_ORDER];
float lsf_new[LP_FILTER_ORDER];
float *impulse_response = ir_buf + LP_FILTER_ORDER;
float *synth = ctx->synth_buf + 16; // 16 instead of LP_FILTER_ORDER for
// memory alignment
int t0_first = 0;
AMRFixed fixed_cb;
memset(ir_buf, 0, LP_FILTER_ORDER * sizeof(float));
lsf_decode_fp(lsf_new, ctx->lsf_history, params);
sipr_decode_lp(lsf_new, ctx->lsp_history, Az, subframe_count);
memcpy(ctx->lsp_history, lsf_new, LP_FILTER_ORDER * sizeof(float));
excitation = ctx->excitation + PITCH_DELAY_MAX + L_INTERPOL;
for (i = 0; i < subframe_count; i++) {
float *pAz = Az + i*LP_FILTER_ORDER;
float fixed_vector[SUBFR_SIZE];
int T0,T0_frac;
float pitch_gain, gain_code, avg_energy;
ff_decode_pitch_lag(&T0, &T0_frac, params->pitch_delay[i], t0_first, i,
ctx->mode == MODE_5k0, 6);
if (i == 0 || (i == 2 && ctx->mode == MODE_5k0))
t0_first = T0;
<API key>(excitation, excitation - T0 + (T0_frac <= 0),
ff_b60_sinc, 6,
2 * ((2 + T0_frac)%3 + 1), LP_FILTER_ORDER,
SUBFR_SIZE);
decode_fixed_sparse(&fixed_cb, params->fc_indexes[i], ctx->mode,
ctx->past_pitch_gain < 0.8);
eval_ir(pAz, T0, impulse_response, modes[ctx->mode].pitch_sharp_factor);
<API key>(fixed_vector, &fixed_cb, impulse_response,
SUBFR_SIZE);
avg_energy = (0.01 + <API key>(fixed_vector,
fixed_vector,
SUBFR_SIZE)) /
SUBFR_SIZE;
ctx->past_pitch_gain = pitch_gain = gain_cb[params->gc_index[i]][0];
gain_code = <API key>(gain_cb[params->gc_index[i]][1],
avg_energy, ctx->energy_history,
34 - 15.0/(0.05*M_LN10/M_LN2),
pred);
<API key>(excitation, excitation, fixed_vector,
pitch_gain, gain_code, SUBFR_SIZE);
pitch_gain *= 0.5 * pitch_gain;
pitch_gain = FFMIN(pitch_gain, 0.4);
ctx->gain_mem = 0.7 * ctx->gain_mem + 0.3 * pitch_gain;
ctx->gain_mem = FFMIN(ctx->gain_mem, pitch_gain);
gain_code *= ctx->gain_mem;
for (j = 0; j < SUBFR_SIZE; j++)
fixed_vector[j] = excitation[j] - gain_code * fixed_vector[j];
if (ctx->mode == MODE_5k0) {
postfilter_5k0(ctx, pAz, fixed_vector);
<API key>(ctx->postfilter_syn5k0 + LP_FILTER_ORDER + i*SUBFR_SIZE,
pAz, excitation, SUBFR_SIZE,
LP_FILTER_ORDER);
}
<API key>(synth + i*SUBFR_SIZE, pAz, fixed_vector,
SUBFR_SIZE, LP_FILTER_ORDER);
excitation += SUBFR_SIZE;
}
memcpy(synth - LP_FILTER_ORDER, synth + frame_size - LP_FILTER_ORDER,
LP_FILTER_ORDER * sizeof(float));
if (ctx->mode == MODE_5k0) {
for (i = 0; i < subframe_count; i++) {
float energy = <API key>(ctx->postfilter_syn5k0 + LP_FILTER_ORDER + i * SUBFR_SIZE,
ctx->postfilter_syn5k0 + LP_FILTER_ORDER + i * SUBFR_SIZE,
SUBFR_SIZE);
<API key>(&synth[i * SUBFR_SIZE],
&synth[i * SUBFR_SIZE], energy,
SUBFR_SIZE, 0.9, &ctx->postfilter_agc);
}
memcpy(ctx->postfilter_syn5k0, ctx->postfilter_syn5k0 + frame_size,
LP_FILTER_ORDER*sizeof(float));
}
memmove(ctx->excitation, excitation - PITCH_DELAY_MAX - L_INTERPOL,
(PITCH_DELAY_MAX + L_INTERPOL) * sizeof(float));
<API key>(out_data, synth,
(const float[2]) {-1.99997 , 1.000000000},
(const float[2]) {-1.93307352, 0.935891986},
0.939805806,
ctx->highpass_filt_mem,
frame_size);
}
static av_cold int sipr_decoder_init(AVCodecContext * avctx)
{
SiprContext *ctx = avctx->priv_data;
int i;
switch (avctx->block_align) {
case 20: ctx->mode = MODE_16k; break;
case 19: ctx->mode = MODE_8k5; break;
case 29: ctx->mode = MODE_6k5; break;
case 37: ctx->mode = MODE_5k0; break;
default:
if (avctx->bit_rate > 12200) ctx->mode = MODE_16k;
else if (avctx->bit_rate > 7500 ) ctx->mode = MODE_8k5;
else if (avctx->bit_rate > 5750 ) ctx->mode = MODE_6k5;
else ctx->mode = MODE_5k0;
av_log(avctx, AV_LOG_WARNING,
"Invalid block_align: %d. Mode %s guessed based on bitrate: %d\n",
avctx->block_align, modes[ctx->mode].mode_name, avctx->bit_rate);
}
av_log(avctx, AV_LOG_DEBUG, "Mode: %s\n", modes[ctx->mode].mode_name);
if (ctx->mode == MODE_16k) {
ff_sipr_init_16k(ctx);
ctx->decode_frame = <API key>;
} else {
ctx->decode_frame = decode_frame;
}
for (i = 0; i < LP_FILTER_ORDER; i++)
ctx->lsp_history[i] = cos((i+1) * M_PI / (LP_FILTER_ORDER + 1));
for (i = 0; i < 4; i++)
ctx->energy_history[i] = -14;
avctx->channels = 1;
avctx->channel_layout = AV_CH_LAYOUT_MONO;
avctx->sample_fmt = AV_SAMPLE_FMT_FLT;
return 0;
}
static int sipr_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame_ptr, AVPacket *avpkt)
{
SiprContext *ctx = avctx->priv_data;
AVFrame *frame = data;
const uint8_t *buf=avpkt->data;
SiprParameters parm;
const SiprModeParam *mode_par = &modes[ctx->mode];
GetBitContext gb;
float *samples;
int subframe_size = ctx->mode == MODE_16k ? L_SUBFR_16k : SUBFR_SIZE;
int i, ret;
ctx->avctx = avctx;
if (avpkt->size < (mode_par->bits_per_frame >> 3)) {
av_log(avctx, AV_LOG_ERROR,
"Error processing packet: packet size (%d) too small\n",
avpkt->size);
return -1;
}
/* get output buffer */
frame->nb_samples = mode_par->frames_per_packet * subframe_size *
mode_par->subframe_count;
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
return ret;
}
samples = (float *)frame->data[0];
init_get_bits(&gb, buf, mode_par->bits_per_frame);
for (i = 0; i < mode_par->frames_per_packet; i++) {
decode_parameters(&parm, &gb, mode_par);
ctx->decode_frame(ctx, &parm, samples);
samples += subframe_size * mode_par->subframe_count;
}
*got_frame_ptr = 1;
return mode_par->bits_per_frame >> 3;
}
AVCodec ff_sipr_decoder = {
.name = "sipr",
.long_name = <API key>("RealAudio SIPR / ACELP.NET"),
.type = AVMEDIA_TYPE_AUDIO,
.id = AV_CODEC_ID_SIPR,
.priv_data_size = sizeof(SiprContext),
.init = sipr_decoder_init,
.decode = sipr_decode_frame,
.capabilities = CODEC_CAP_DR1,
}; |
var searchData=
[
['calcmenu',['calcMenu',['../classCCalculator.html#<API key>',1,'CCalculator']]],
['cntconsolematrix',['cntConsoleMatrix',['../classCExpression.html#<API key>',1,'CExpression']]],
['cntnull',['cntNull',['../classCBuilder.html#<API key>',1,'CBuilder']]],
['columns',['columns',['../classAbstractMatrix.html#<API key>',1,'AbstractMatrix::columns()'],['../classCBuilder.html#<API key>',1,'CBuilder::columns()']]]
]; |
<?php
/**
* @package Piwik_Menu
*/
abstract class Piwik_Menu_Abstract {
protected $menu = null;
protected $menuEntries = array();
protected $edits = array();
protected $renames = array();
/*
* Can't enforce static function in 5.2.
*/
//abstract static public function getInstance();
/**
* Builds the menu, applies edits, renames
* and orders the entries.
*
* @return Array
*/
public function get() {
$this->buildMenu();
$this->applyEdits();
$this->applyRenames();
$this->applyOrdering();
return $this->menu;
}
/**
* Adds a new entry to the menu.
*/
public function add($menuName, $subMenuName, $url, $<API key>, $order = 50) {
$this->menuEntries[] = array(
$menuName,
$subMenuName,
$url,
$<API key>,
$order
);
}
/**
* Builds the menu from the $this->menuEntries variable.
*
*/
private function buildMenu() {
foreach ($this->menuEntries as $menuEntry) {
$menuName = $menuEntry[0];
$subMenuName = $menuEntry[1];
if ($menuEntry[3]) {
if (!isset($this->menu[$menuName]) || empty($subMenuName)) {
$this->menu[$menuName]['_url'] = $menuEntry[2];
$this->menu[$menuName]['_order'] = $menuEntry[4];
$this->menu[$menuName]['_hasSubmenu'] = false;
}
if (!empty($subMenuName)) {
$this->menu[$menuName][$subMenuName]['_url'] = $menuEntry[2];
$this->menu[$menuName][$subMenuName]['_order'] = $menuEntry[4];
$this->menu[$menuName]['_hasSubmenu'] = true;
}
}
}
}
/**
* Renames a single menu entry.
*
*/
public function rename($mainMenuOriginal, $subMenuOriginal, $mainMenuRenamed, $subMenuRenamed) {
$this->renames[] = array($mainMenuOriginal, $subMenuOriginal,
$mainMenuRenamed, $subMenuRenamed);
}
/**
* Edits a URL of an existing menu entry.
*
*/
public function editUrl($mainMenuToEdit, $subMenuToEdit, $newUrl) {
$this->edits[] = array($mainMenuToEdit, $subMenuToEdit, $newUrl);
}
/**
* Applies all edits to the menu.
*
*/
private function applyEdits() {
foreach ($this->edits as $edit) {
$mainMenuToEdit = $edit[0];
$subMenuToEdit = $edit[1];
$newUrl = $edit[2];
if (!isset($this->menu[$mainMenuToEdit][$subMenuToEdit])) {
$this->add($mainMenuToEdit, $subMenuToEdit, $newUrl, true);
} else {
$this->menu[$mainMenuToEdit][$subMenuToEdit]['_url'] = $newUrl;
}
}
}
/**
* Applies renames to the menu.
*
*/
private function applyRenames() {
foreach ($this->renames as $rename) {
$mainMenuOriginal = $rename[0];
$subMenuOriginal = $rename[1];
$mainMenuRenamed = $rename[2];
$subMenuRenamed = $rename[3];
// Are we changing a submenu?
if (!empty($subMenuOriginal)) {
if (isset($this->menu[$mainMenuOriginal][$subMenuOriginal])) {
$save = $this->menu[$mainMenuOriginal][$subMenuOriginal];
unset($this->menu[$mainMenuOriginal][$subMenuOriginal]);
$this->menu[$mainMenuRenamed][$subMenuRenamed] = $save;
}
}
// Changing a first-level element
else {
if (isset($this->menu[$mainMenuOriginal])) {
$save = $this->menu[$mainMenuOriginal];
unset($this->menu[$mainMenuOriginal]);
$this->menu[$mainMenuRenamed] = $save;
}
}
}
}
/**
* Orders the menu according to their order.
*
*/
private function applyOrdering() {
uasort($this->menu, array($this, 'menuCompare'));
foreach ($this->menu as $key => &$element) {
if (is_null($element)) {
unset($this->menu[$key]);
} else {
if ($element['_hasSubmenu']) {
uasort($element, array($this, 'menuCompare'));
}
}
}
}
/**
* Compares two menu entries. Used for ordering.
*
* @param <array> $itemOne
* @param <array> $itemTwo
* @return <boolean>
*/
protected function menuCompare($itemOne, $itemTwo) {
if (!is_array($itemOne) || !is_array($itemTwo)
|| !isset($itemOne['_order']) || !isset($itemTwo['_order'])) {
return 0;
}
if ($itemOne['_order'] == $itemTwo['_order']) {
return 0;
}
return ($itemOne['_order'] < $itemTwo['_order']) ? -1 : 1;
}
} |
/*
Operating System GLUe for X WiNdow system
All operating system dependent code for the
X Window System should go here.
This code is descended from Michael Hanni's X
port of vMac, by Philip Cummins.
I learned more about how X programs work by
looking at other programs such as Basilisk II,
the UAE Amiga Emulator, Bochs, QuakeForge,
DooM Legacy, and the FLTK. A few snippets
from them are used here.
Drag and Drop support is based on the specification
"XDND: Drag-and-Drop Protocol for the X Window System"
developed by John Lindal at New Planet Software, and
looking at included examples, one by Paul Sheer.
*/
#include "CNFGRAPI.h"
#include "SYSDEPNS.h"
#include "ENDIANAC.h"
#include "MYOSGLUE.h"
#include "STRCONST.h"
GLOBALOSGLUPROC MyMoveBytes(anyp srcPtr, anyp destPtr, si5b byteCount)
{
(void) memcpy((char *)destPtr, (char *)srcPtr, byteCount);
}
#define <API key> 1
#include "INTLCHAR.h"
LOCALVAR char *d_arg = NULL;
LOCALVAR char *n_arg = NULL;
#if CanGetAppPath
LOCALVAR char *app_parent = NULL;
LOCALVAR char *app_name = NULL;
#endif
LOCALFUNC tMacErr ChildPath(char *x, char *y, char **r)
{
tMacErr err = mnvm_miscErr;
int nx = strlen(x);
int ny = strlen(y);
{
if ((nx > 0) && ('/' == x[nx - 1])) {
--nx;
}
{
int nr = nx + 1 + ny;
char *p = malloc(nr + 1);
if (p != NULL) {
char *p2 = p;
(void) memcpy(p2, x, nx);
p2 += nx;
*p2++ = '/';
(void) memcpy(p2, y, ny);
p2 += ny;
*p2 = 0;
*r = p;
err = mnvm_noErr;
}
}
}
return err;
}
#if UseActvFile || IncludeSonyNew
LOCALFUNC tMacErr FindOrMakeChild(char *x, char *y, char **r)
{
tMacErr err;
struct stat folder_info;
char *r0;
if (mnvm_noErr == (err = ChildPath(x, y, &r0))) {
if (0 != stat(r0, &folder_info)) {
if (0 != mkdir(r0, S_IRWXU)) {
err = mnvm_miscErr;
} else {
*r = r0;
err = mnvm_noErr;
}
} else {
if (! S_ISDIR(folder_info.st_mode)) {
err = mnvm_miscErr;
} else {
*r = r0;
err = mnvm_noErr;
}
}
}
return err;
}
#endif
LOCALPROC MyMayFree(char *p)
{
if (NULL != p) {
free(p);
}
}
#if dbglog_HAVE
#ifndef dbglog_ToStdErr
#define dbglog_ToStdErr 0
#endif
#if ! dbglog_ToStdErr
LOCALVAR FILE *dbglog_File = NULL;
#endif
LOCALFUNC blnr dbglog_open0(void)
{
#if dbglog_ToStdErr
return trueblnr;
#else
dbglog_File = fopen("dbglog.txt", "w");
return (NULL != dbglog_File);
#endif
}
LOCALPROC dbglog_write0(char *s, uimr L)
{
#if dbglog_ToStdErr
(void) fwrite(s, 1, L, stderr);
#else
if (dbglog_File != NULL) {
(void) fwrite(s, 1, L, dbglog_File);
}
#endif
}
LOCALPROC dbglog_close0(void)
{
#if ! dbglog_ToStdErr
if (dbglog_File != NULL) {
fclose(dbglog_File);
dbglog_File = NULL;
}
#endif
}
#endif
#if ! dbglog_HAVE
#define WriteExtraErr(s)
#else
LOCALPROC WriteExtraErr(char *s)
{
dbglog_writeCStr("*** error: ");
dbglog_writeCStr(s);
dbglog_writeReturn();
}
#endif
LOCALVAR Display *x_display = NULL;
#define MyDbgEvents (dbglog_HAVE && 0)
#if MyDbgEvents
LOCALPROC WriteDbgAtom(char *s, Atom x)
{
char *name = XGetAtomName(x_display, x);
if (name != NULL) {
dbglog_writeCStr("Atom ");
dbglog_writeCStr(s);
dbglog_writeCStr(": ");
dbglog_writeCStr(name);
dbglog_writeReturn();
XFree(name);
}
}
#endif
LOCALVAR Atom MyXA_DeleteW = (Atom)0;
#if EnableDragDrop
LOCALVAR Atom MyXA_UriList = (Atom)0;
LOCALVAR Atom MyXA_DndAware = (Atom)0;
LOCALVAR Atom MyXA_DndEnter = (Atom)0;
LOCALVAR Atom MyXA_DndLeave = (Atom)0;
LOCALVAR Atom MyXA_DndDrop = (Atom)0;
LOCALVAR Atom MyXA_DndPosition = (Atom)0;
LOCALVAR Atom MyXA_DndStatus = (Atom)0;
LOCALVAR Atom MyXA_DndActionCopy = (Atom)0;
LOCALVAR Atom <API key> = (Atom)0;
LOCALVAR Atom MyXA_DndSelection = (Atom)0;
LOCALVAR Atom MyXA_DndFinished = (Atom)0;
LOCALVAR Atom <API key> = (Atom)0;
LOCALVAR Atom <API key> = (Atom)0;
LOCALVAR Atom MyXA_NetSupported = (Atom)0;
#endif
#if <API key>
LOCALVAR Atom MyXA_CLIPBOARD = (Atom)0;
LOCALVAR Atom MyXA_TARGETS = (Atom)0;
LOCALVAR Atom MyXA_MinivMac_Clip = (Atom)0;
#endif
LOCALPROC LoadMyXA(void)
{
MyXA_DeleteW = XInternAtom(x_display, "WM_DELETE_WINDOW", False);
#if EnableDragDrop
MyXA_UriList = XInternAtom (x_display, "text/uri-list", False);
MyXA_DndAware = XInternAtom (x_display, "XdndAware", False);
MyXA_DndEnter = XInternAtom(x_display, "XdndEnter", False);
MyXA_DndLeave = XInternAtom(x_display, "XdndLeave", False);
MyXA_DndDrop = XInternAtom(x_display, "XdndDrop", False);
MyXA_DndPosition = XInternAtom(x_display, "XdndPosition", False);
MyXA_DndStatus = XInternAtom(x_display, "XdndStatus", False);
MyXA_DndActionCopy = XInternAtom(x_display,
"XdndActionCopy", False);
<API key> = XInternAtom(x_display,
"XdndActionPrivate", False);
MyXA_DndSelection = XInternAtom(x_display, "XdndSelection", False);
MyXA_DndFinished = XInternAtom(x_display, "XdndFinished", False);
<API key> = XInternAtom(x_display,
"_MinivMac_DndXchng", False);
<API key> = XInternAtom(x_display,
"_NET_ACTIVE_WINDOW", False);
MyXA_NetSupported = XInternAtom(x_display,
"_NET_SUPPORTED", False);
#endif
#if <API key>
MyXA_CLIPBOARD = XInternAtom(x_display, "CLIPBOARD", False);
MyXA_TARGETS = XInternAtom(x_display, "TARGETS", False);
MyXA_MinivMac_Clip = XInternAtom(x_display,
"_MinivMac_Clip", False);
#endif
}
#if EnableDragDrop
LOCALFUNC blnr <API key>(Atom x)
{
/*
Note that the window manager could be replaced at
any time, so don't cache results of this function.
*/
Atom ret_type;
int ret_format;
unsigned long ret_item;
unsigned long remain_byte;
unsigned long i;
unsigned char *s = 0;
blnr foundit = falseblnr;
Window rootwin = XRootWindow(x_display,
DefaultScreen(x_display));
if (Success != XGetWindowProperty(x_display, rootwin,
MyXA_NetSupported,
0, 65535, False, XA_ATOM, &ret_type, &ret_format,
&ret_item, &remain_byte, &s))
{
WriteExtraErr("XGetWindowProperty failed");
} else if (! s) {
WriteExtraErr("XGetWindowProperty failed");
} else if (ret_type != XA_ATOM) {
WriteExtraErr("XGetWindowProperty returns wrong type");
} else {
Atom *v = (Atom *)s;
for (i = 0; i < ret_item; ++i) {
if (v[i] == x) {
foundit = trueblnr;
/* fprintf(stderr, "found the hint\n"); */
}
}
}
if (s) {
XFree(s);
}
return foundit;
}
#endif
#define WantColorTransValid 1
#include "COMOSGLU.h"
#include "PBUFSTDC.h"
#include "CONTROLM.h"
#if IncludePbufs
/* this is table for Windows, any changes needed for X? */
LOCALVAR const ui3b Native2MacRomanTab[] = {
0xAD, 0xB0, 0xE2, 0xC4, 0xE3, 0xC9, 0xA0, 0xE0,
0xF6, 0xE4, 0xB6, 0xDC, 0xCE, 0xB2, 0xB3, 0xB7,
0xB8, 0xD4, 0xD5, 0xD2, 0xD3, 0xA5, 0xD0, 0xD1,
0xF7, 0xAA, 0xC5, 0xDD, 0xCF, 0xB9, 0xC3, 0xD9,
0xCA, 0xC1, 0xA2, 0xA3, 0xDB, 0xB4, 0xBA, 0xA4,
0xAC, 0xA9, 0xBB, 0xC7, 0xC2, 0xBD, 0xA8, 0xF8,
0xA1, 0xB1, 0xC6, 0xD7, 0xAB, 0xB5, 0xA6, 0xE1,
0xFC, 0xDA, 0xBC, 0xC8, 0xDE, 0xDF, 0xF0, 0xC0,
0xCB, 0xE7, 0xE5, 0xCC, 0x80, 0x81, 0xAE, 0x82,
0xE9, 0x83, 0xE6, 0xE8, 0xED, 0xEA, 0xEB, 0xEC,
0xF5, 0x84, 0xF1, 0xEE, 0xEF, 0xCD, 0x85, 0xF9,
0xAF, 0xF4, 0xF2, 0xF3, 0x86, 0xFA, 0xFB, 0xA7,
0x88, 0x87, 0x89, 0x8B, 0x8A, 0x8C, 0xBE, 0x8D,
0x8F, 0x8E, 0x90, 0x91, 0x93, 0x92, 0x94, 0x95,
0xFD, 0x96, 0x98, 0x97, 0x99, 0x9B, 0x9A, 0xD6,
0xBF, 0x9D, 0x9C, 0x9E, 0x9F, 0xFE, 0xFF, 0xD8
};
#endif
#if IncludePbufs
LOCALFUNC tMacErr <API key>(char *x, tPbuf *r)
{
if (NULL == x) {
return mnvm_miscErr;
} else {
ui3p p;
ui5b L = strlen(x);
p = (ui3p)malloc(L);
if (NULL == p) {
return mnvm_miscErr;
} else {
ui3b *p0 = (ui3b *)x;
ui3b *p1 = (ui3b *)p;
int i;
for (i = L; --i >= 0; ) {
ui3b v = *p0++;
if (v >= 128) {
v = Native2MacRomanTab[v - 128];
} else if (10 == v) {
v = 13;
}
*p1++ = v;
}
return PbufNewFromPtr(p, L, r);
}
}
}
#endif
#if IncludePbufs
/* this is table for Windows, any changes needed for X? */
LOCALVAR const ui3b MacRoman2NativeTab[] = {
0xC4, 0xC5, 0xC7, 0xC9, 0xD1, 0xD6, 0xDC, 0xE1,
0xE0, 0xE2, 0xE4, 0xE3, 0xE5, 0xE7, 0xE9, 0xE8,
0xEA, 0xEB, 0xED, 0xEC, 0xEE, 0xEF, 0xF1, 0xF3,
0xF2, 0xF4, 0xF6, 0xF5, 0xFA, 0xF9, 0xFB, 0xFC,
0x86, 0xB0, 0xA2, 0xA3, 0xA7, 0x95, 0xB6, 0xDF,
0xAE, 0xA9, 0x99, 0xB4, 0xA8, 0x80, 0xC6, 0xD8,
0x81, 0xB1, 0x8D, 0x8E, 0xA5, 0xB5, 0x8A, 0x8F,
0x90, 0x9D, 0xA6, 0xAA, 0xBA, 0xAD, 0xE6, 0xF8,
0xBF, 0xA1, 0xAC, 0x9E, 0x83, 0x9A, 0xB2, 0xAB,
0xBB, 0x85, 0xA0, 0xC0, 0xC3, 0xD5, 0x8C, 0x9C,
0x96, 0x97, 0x93, 0x94, 0x91, 0x92, 0xF7, 0xB3,
0xFF, 0x9F, 0xB9, 0xA4, 0x8B, 0x9B, 0xBC, 0xBD,
0x87, 0xB7, 0x82, 0x84, 0x89, 0xC2, 0xCA, 0xC1,
0xCB, 0xC8, 0xCD, 0xCE, 0xCF, 0xCC, 0xD3, 0xD4,
0xBE, 0xD2, 0xDA, 0xDB, 0xD9, 0xD0, 0x88, 0x98,
0xAF, 0xD7, 0xDD, 0xDE, 0xB8, 0xF0, 0xFD, 0xFE
};
#endif
#if IncludePbufs
LOCALFUNC blnr <API key>(tPbuf i, blnr IsFileName,
ui3p *r)
{
ui3p p;
void *Buffer = PbufDat[i];
ui5b L = PbufSize[i];
p = (ui3p)malloc(L + 1);
if (p != NULL) {
ui3b *p0 = (ui3b *)Buffer;
ui3b *p1 = (ui3b *)p;
int j;
if (IsFileName) {
for (j = L; --j >= 0; ) {
ui3b x = *p0++;
if (x < 32) {
x = '-';
} else if (x >= 128) {
x = MacRoman2NativeTab[x - 128];
} else {
switch (x) {
case '/':
case '<':
case '>':
case '|':
case ':':
x = '-';
default:
break;
}
}
*p1++ = x;
}
if ('.' == p[0]) {
p[0] = '-';
}
} else {
for (j = L; --j >= 0; ) {
ui3b x = *p0++;
if (x >= 128) {
x = MacRoman2NativeTab[x - 128];
} else if (13 == x) {
x = '\n';
}
*p1++ = x;
}
}
*p1 = 0;
*r = p;
return trueblnr;
}
return falseblnr;
}
#endif
LOCALPROC NativeStrFromCStr(char *r, char *s)
{
ui3b ps[ClStrMaxLength];
int i;
int L;
ClStrFromSubstCStr(&L, ps, s);
for (i = 0; i < L; ++i) {
r[i] = Cell2PlainAsciiMap[ps[i]];
}
r[L] = 0;
}
#define NotAfileRef NULL
LOCALVAR FILE *Drives[NumDrives]; /* open disk image files */
#if IncludeSonyGetName || IncludeSonyNew
LOCALVAR char *DriveNames[NumDrives];
#endif
LOCALPROC InitDrives(void)
{
/*
This isn't really needed, Drives[i] and DriveNames[i]
need not have valid values when not vSonyIsInserted[i].
*/
tDrive i;
for (i = 0; i < NumDrives; ++i) {
Drives[i] = NotAfileRef;
#if IncludeSonyGetName || IncludeSonyNew
DriveNames[i] = NULL;
#endif
}
}
GLOBALOSGLUFUNC tMacErr vSonyTransfer(blnr IsWrite, ui3p Buffer,
tDrive Drive_No, ui5r Sony_Start, ui5r Sony_Count,
ui5r *Sony_ActCount)
{
tMacErr err = mnvm_miscErr;
FILE *refnum = Drives[Drive_No];
ui5r NewSony_Count = 0;
if (0 == fseek(refnum, Sony_Start, SEEK_SET)) {
if (IsWrite) {
NewSony_Count = fwrite(Buffer, 1, Sony_Count, refnum);
} else {
NewSony_Count = fread(Buffer, 1, Sony_Count, refnum);
}
if (NewSony_Count == Sony_Count) {
err = mnvm_noErr;
}
}
if (nullpr != Sony_ActCount) {
*Sony_ActCount = NewSony_Count;
}
return err; /*& figure out what really to return &*/
}
GLOBALOSGLUFUNC tMacErr vSonyGetSize(tDrive Drive_No, ui5r *Sony_Count)
{
tMacErr err = mnvm_miscErr;
FILE *refnum = Drives[Drive_No];
long v;
if (0 == fseek(refnum, 0, SEEK_END)) {
v = ftell(refnum);
if (v >= 0) {
*Sony_Count = v;
err = mnvm_noErr;
}
}
return err; /*& figure out what really to return &*/
}
#ifndef HaveAdvisoryLocks
#define HaveAdvisoryLocks 1
#endif
/*
What is the difference between fcntl(fd, F_SETLK ...
and flock(fd ... ?
*/
#if HaveAdvisoryLocks
LOCALFUNC blnr MyLockFile(FILE *refnum)
{
blnr IsOk = falseblnr;
#if 1
struct flock fl;
int fd = fileno(refnum);
fl.l_start = 0; /* starting offset */
fl.l_len = 0; /* len = 0 means until end of file */
/* fl.pid_t l_pid; */ /* lock owner, don't need to set */
fl.l_type = F_WRLCK; /* lock type: read/write, etc. */
fl.l_whence = SEEK_SET; /* type of l_start */
if (-1 == fcntl(fd, F_SETLK, &fl)) {
MacMsg(kStrImageInUseTitle, <API key>,
falseblnr);
} else {
IsOk = trueblnr;
}
#else
int fd = fileno(refnum);
if (-1 == flock(fd, LOCK_EX | LOCK_NB)) {
MacMsg(kStrImageInUseTitle, <API key>,
falseblnr);
} else {
IsOk = trueblnr;
}
#endif
return IsOk;
}
#endif
#if HaveAdvisoryLocks
LOCALPROC MyUnlockFile(FILE *refnum)
{
#if 1
struct flock fl;
int fd = fileno(refnum);
fl.l_start = 0; /* starting offset */
fl.l_len = 0; /* len = 0 means until end of file */
/* fl.pid_t l_pid; */ /* lock owner, don't need to set */
fl.l_type = F_UNLCK; /* lock type: read/write, etc. */
fl.l_whence = SEEK_SET; /* type of l_start */
if (-1 == fcntl(fd, F_SETLK, &fl)) {
/* an error occurred */
}
#else
int fd = fileno(refnum);
if (-1 == flock(fd, LOCK_UN)) {
}
#endif
}
#endif
LOCALFUNC tMacErr vSonyEject0(tDrive Drive_No, blnr deleteit)
{
FILE *refnum = Drives[Drive_No];
DiskEjectedNotify(Drive_No);
#if HaveAdvisoryLocks
MyUnlockFile(refnum);
#endif
fclose(refnum);
Drives[Drive_No] = NotAfileRef; /* not really needed */
#if IncludeSonyGetName || IncludeSonyNew
{
char *s = DriveNames[Drive_No];
if (NULL != s) {
if (deleteit) {
remove(s);
}
free(s);
DriveNames[Drive_No] = NULL; /* not really needed */
}
}
#endif
return mnvm_noErr;
}
GLOBALOSGLUFUNC tMacErr vSonyEject(tDrive Drive_No)
{
return vSonyEject0(Drive_No, falseblnr);
}
#if IncludeSonyNew
GLOBALOSGLUFUNC tMacErr vSonyEjectDelete(tDrive Drive_No)
{
return vSonyEject0(Drive_No, trueblnr);
}
#endif
LOCALPROC UnInitDrives(void)
{
tDrive i;
for (i = 0; i < NumDrives; ++i) {
if (vSonyIsInserted(i)) {
(void) vSonyEject(i);
}
}
}
#if IncludeSonyGetName
GLOBALOSGLUFUNC tMacErr vSonyGetName(tDrive Drive_No, tPbuf *r)
{
char *drivepath = DriveNames[Drive_No];
if (NULL == drivepath) {
return mnvm_miscErr;
} else {
char *s = strrchr(drivepath, '/');
if (NULL == s) {
s = drivepath;
} else {
++s;
}
return <API key>(s, r);
}
}
#endif
LOCALFUNC blnr Sony_Insert0(FILE *refnum, blnr locked,
char *drivepath)
{
tDrive Drive_No;
blnr IsOk = falseblnr;
if (! FirstFreeDisk(&Drive_No)) {
MacMsg(<API key>, <API key>,
falseblnr);
} else {
/* printf("Sony_Insert0 %d\n", (int)Drive_No); */
#if HaveAdvisoryLocks
if (locked || MyLockFile(refnum))
#endif
{
Drives[Drive_No] = refnum;
DiskInsertNotify(Drive_No, locked);
#if IncludeSonyGetName || IncludeSonyNew
{
ui5b L = strlen(drivepath);
char *p = malloc(L + 1);
if (p != NULL) {
(void) memcpy(p, drivepath, L + 1);
}
DriveNames[Drive_No] = p;
}
#endif
IsOk = trueblnr;
}
}
if (! IsOk) {
fclose(refnum);
}
return IsOk;
}
LOCALFUNC blnr Sony_Insert1(char *drivepath, blnr silentfail)
{
blnr locked = falseblnr;
/* printf("Sony_Insert1 %s\n", drivepath); */
FILE *refnum = fopen(drivepath, "rb+");
if (NULL == refnum) {
locked = trueblnr;
refnum = fopen(drivepath, "rb");
}
if (NULL == refnum) {
if (! silentfail) {
MacMsg(kStrOpenFailTitle, kStrOpenFailMessage, falseblnr);
}
} else {
return Sony_Insert0(refnum, locked, drivepath);
}
return falseblnr;
}
LOCALFUNC tMacErr LoadMacRomFrom(char *path)
{
tMacErr err;
FILE *ROM_File;
int File_Size;
ROM_File = fopen(path, "rb");
if (NULL == ROM_File) {
err = mnvm_fnfErr;
} else {
File_Size = fread(ROM, 1, kROM_Size, ROM_File);
if (kROM_Size != File_Size) {
if (feof(ROM_File)) {
MacMsgOverride(kStrShortROMTitle,
kStrShortROMMessage);
err = mnvm_eofErr;
} else {
MacMsgOverride(kStrNoReadROMTitle,
<API key>);
err = mnvm_miscErr;
}
} else {
err = ROM_IsValid();
}
fclose(ROM_File);
}
return err;
}
LOCALFUNC blnr Sony_Insert1a(char *drivepath, blnr silentfail)
{
blnr v;
if (! ROM_loaded) {
v = (mnvm_noErr == LoadMacRomFrom(drivepath));
} else {
v = Sony_Insert1(drivepath, silentfail);
}
return v;
}
LOCALFUNC blnr Sony_Insert2(char *s)
{
char *d =
#if CanGetAppPath
(NULL == d_arg) ? app_parent :
#endif
d_arg;
blnr IsOk = falseblnr;
if (NULL == d) {
IsOk = Sony_Insert1(s, trueblnr);
} else {
char *t;
if (mnvm_noErr == ChildPath(d, s, &t)) {
IsOk = Sony_Insert1(t, trueblnr);
free(t);
}
}
return IsOk;
}
LOCALFUNC blnr Sony_InsertIth(int i)
{
blnr v;
if ((i > 9) || ! FirstFreeDisk(nullpr)) {
v = falseblnr;
} else {
char s[] = "disk?.dsk";
s[4] = '0' + i;
v = Sony_Insert2(s);
}
return v;
}
LOCALFUNC blnr LoadInitialImages(void)
{
if (! AnyDiskInserted()) {
int i;
for (i = 1; Sony_InsertIth(i); ++i) {
/* stop on first error (including file not found) */
}
}
return trueblnr;
}
#if IncludeSonyNew
LOCALFUNC blnr WriteZero(FILE *refnum, ui5b L)
{
#define ZeroBufferSize 2048
ui5b i;
ui3b buffer[ZeroBufferSize];
memset(&buffer, 0, ZeroBufferSize);
while (L > 0) {
i = (L > ZeroBufferSize) ? ZeroBufferSize : L;
if (fwrite(buffer, 1, i, refnum) != i) {
return falseblnr;
}
L -= i;
}
return trueblnr;
}
#endif
#if IncludeSonyNew
LOCALPROC MakeNewDisk0(ui5b L, char *drivepath)
{
blnr IsOk = falseblnr;
FILE *refnum = fopen(drivepath, "wb+");
if (NULL == refnum) {
MacMsg(kStrOpenFailTitle, kStrOpenFailMessage, falseblnr);
} else {
if (WriteZero(refnum, L)) {
IsOk = Sony_Insert0(refnum, falseblnr, drivepath);
refnum = NULL;
}
if (refnum != NULL) {
fclose(refnum);
}
if (! IsOk) {
(void) remove(drivepath);
}
}
}
#endif
#if IncludeSonyNew
LOCALPROC MakeNewDisk(ui5b L, char *drivename)
{
char *d =
#if CanGetAppPath
(NULL == d_arg) ? app_parent :
#endif
d_arg;
if (NULL == d) {
MakeNewDisk0(L, drivename); /* in current directory */
} else {
tMacErr err;
char *t = NULL;
char *t2 = NULL;
if (mnvm_noErr == (err = FindOrMakeChild(d, "out", &t)))
if (mnvm_noErr == (err = ChildPath(t, drivename, &t2)))
{
MakeNewDisk0(L, t2);
}
MyMayFree(t2);
MyMayFree(t);
}
}
#endif
#if IncludeSonyNew
LOCALPROC <API key>(ui5b L)
{
char s[ClStrMaxLength + 1];
NativeStrFromCStr(s, "untitled.dsk");
MakeNewDisk(L, s);
}
#endif
LOCALVAR char *rom_path = NULL;
#if 0
#include <pwd.h>
#include <unistd.h>
#endif
LOCALFUNC tMacErr FindUserHomeFolder(char **r)
{
tMacErr err;
char *s;
#if 0
struct passwd *user;
#endif
if (NULL != (s = getenv("HOME"))) {
*r = s;
err = mnvm_noErr;
} else
#if 0
if ((NULL != (user = getpwuid(getuid())))
&& (NULL != (s = user->pw_dir)))
{
/*
From getpwuid man page:
"An application that wants to determine its user's
home directory should inspect the value of HOME
(rather than the value getpwuid(getuid())->pw_dir)
since this allows the user to modify their notion of
"the home directory" during a login session."
But it is possible for HOME to not be set.
Some sources say to use getpwuid in that case.
*/
*r = s;
err = mnvm_noErr;
} else
#endif
{
err = mnvm_fnfErr;
}
return err;
}
LOCALFUNC tMacErr LoadMacRomFromHome(void)
{
tMacErr err;
char *s;
char *t = NULL;
char *t2 = NULL;
char *t3 = NULL;
if (mnvm_noErr == (err = FindUserHomeFolder(&s)))
if (mnvm_noErr == (err = ChildPath(s, ".gryphel", &t)))
if (mnvm_noErr == (err = ChildPath(t, "mnvm_rom", &t2)))
if (mnvm_noErr == (err = ChildPath(t2, RomFileName, &t3)))
{
err = LoadMacRomFrom(t3);
}
MyMayFree(t3);
MyMayFree(t2);
MyMayFree(t);
return err;
}
#if CanGetAppPath
LOCALFUNC tMacErr <API key>(void)
{
tMacErr err;
char *d =
#if CanGetAppPath
(NULL == d_arg) ? app_parent :
#endif
d_arg;
char *t = NULL;
if (NULL == d) {
err = mnvm_fnfErr;
} else {
if (mnvm_noErr == (err = ChildPath(d, RomFileName,
&t)))
{
err = LoadMacRomFrom(t);
}
}
MyMayFree(t);
return err;
}
#endif
LOCALFUNC blnr LoadMacRom(void)
{
tMacErr err;
if ((NULL == rom_path)
|| (mnvm_fnfErr == (err = LoadMacRomFrom(rom_path))))
#if CanGetAppPath
if (mnvm_fnfErr == (err = <API key>()))
#endif
if (mnvm_fnfErr == (err = LoadMacRomFromHome()))
if (mnvm_fnfErr == (err = LoadMacRomFrom(RomFileName)))
{
}
return trueblnr; /* keep launching Mini vMac, regardless */
}
#if UseActvFile
#define ActvCodeFileName "act_1"
LOCALFUNC tMacErr ActvCodeFileLoad(ui3p p)
{
tMacErr err;
char *s;
char *t = NULL;
char *t2 = NULL;
char *t3 = NULL;
if (mnvm_noErr == (err = FindUserHomeFolder(&s)))
if (mnvm_noErr == (err = ChildPath(s, ".gryphel", &t)))
if (mnvm_noErr == (err = ChildPath(t, "mnvm_act", &t2)))
if (mnvm_noErr == (err = ChildPath(t2, ActvCodeFileName, &t3)))
{
FILE *Actv_File;
int File_Size;
Actv_File = fopen(t3, "rb");
if (NULL == Actv_File) {
err = mnvm_fnfErr;
} else {
File_Size = fread(p, 1, ActvCodeFileLen, Actv_File);
if (File_Size != ActvCodeFileLen) {
if (feof(Actv_File)) {
err = mnvm_eofErr;
} else {
err = mnvm_miscErr;
}
} else {
err = mnvm_noErr;
}
fclose(Actv_File);
}
}
MyMayFree(t3);
MyMayFree(t2);
MyMayFree(t);
return err;
}
LOCALFUNC tMacErr ActvCodeFileSave(ui3p p)
{
tMacErr err;
char *s;
char *t = NULL;
char *t2 = NULL;
char *t3 = NULL;
if (mnvm_noErr == (err = FindUserHomeFolder(&s)))
if (mnvm_noErr == (err = FindOrMakeChild(s, ".gryphel", &t)))
if (mnvm_noErr == (err = FindOrMakeChild(t, "mnvm_act", &t2)))
if (mnvm_noErr == (err = ChildPath(t2, ActvCodeFileName, &t3)))
{
FILE *Actv_File;
int File_Size;
Actv_File = fopen(t3, "wb+");
if (NULL == Actv_File) {
err = mnvm_fnfErr;
} else {
File_Size = fwrite(p, 1, ActvCodeFileLen, Actv_File);
if (File_Size != ActvCodeFileLen) {
err = mnvm_miscErr;
} else {
err = mnvm_noErr;
}
fclose(Actv_File);
}
}
MyMayFree(t3);
MyMayFree(t2);
MyMayFree(t);
return err;
}
#endif /* UseActvFile */
LOCALVAR Window my_main_wind = 0;
LOCALVAR GC my_gc = NULL;
LOCALVAR blnr NeedFinishOpen1 = falseblnr;
LOCALVAR blnr NeedFinishOpen2 = falseblnr;
LOCALVAR XColor x_black;
LOCALVAR XColor x_white;
#if MayFullScreen
LOCALVAR short hOffset;
LOCALVAR short vOffset;
#endif
#if VarFullScreen
LOCALVAR blnr UseFullScreen = (WantInitFullScreen != 0);
#endif
#if EnableMagnify
LOCALVAR blnr UseMagnify = (WantInitMagnify != 0);
#endif
LOCALVAR blnr gBackgroundFlag = falseblnr;
LOCALVAR blnr gTrueBackgroundFlag = falseblnr;
LOCALVAR blnr CurSpeedStopped = trueblnr;
#ifndef UseColorImage
#define UseColorImage (0 != vMacScreenDepth)
#endif
LOCALVAR XImage *my_image = NULL;
#if EnableMagnify
LOCALVAR XImage *my_Scaled_image = NULL;
#endif
#if EnableMagnify
#define MaxScale MyWindowScale
#else
#define MaxScale 1
#endif
#define WantScalingTabl (EnableMagnify || UseColorImage)
#if WantScalingTabl
LOCALVAR ui3p ScalingTabl = nullpr;
#define ScalingTablsz1 (256 * MaxScale)
#if UseColorImage
#define ScalingTablsz (ScalingTablsz1 << 5)
#else
#define ScalingTablsz ScalingTablsz1
#endif
#endif /* WantScalingTabl */
#define WantScalingBuff (EnableMagnify || UseColorImage)
#if WantScalingBuff
LOCALVAR ui3p ScalingBuff = nullpr;
#if UseColorImage
#define ScalingBuffsz \
(vMacScreenNumPixels * 4 * MaxScale * MaxScale)
#else
#define ScalingBuffsz ((long)<API key> \
* MaxScale * MaxScale)
#endif
#endif /* WantScalingBuff */
#if EnableMagnify && ! UseColorImage
LOCALPROC SetUpScalingTabl(void)
{
ui3b *p4;
int i;
int j;
int k;
ui3r bitsRemaining;
ui3b t1;
ui3b t2;
p4 = ScalingTabl;
for (i = 0; i < 256; ++i) {
bitsRemaining = 8;
t2 = 0;
for (j = 8; --j >= 0; ) {
t1 = (i >> j) & 1;
for (k = MyWindowScale; --k >= 0; ) {
t2 = (t2 << 1) | t1;
if (--bitsRemaining == 0) {
*p4++ = t2;
bitsRemaining = 8;
t2 = 0;
}
}
}
}
}
#endif
#if EnableMagnify && (0 != vMacScreenDepth) && (vMacScreenDepth < 4)
LOCALPROC <API key>(void)
{
int i;
int j;
int k;
int a;
ui5r v;
ui5p p4;
p4 = (ui5p)ScalingTabl;
for (i = 0; i < 256; ++i) {
for (k = 1 << (3 - vMacScreenDepth); --k >= 0; ) {
j = (i >> (k << vMacScreenDepth)) & (CLUT_size - 1);
v = (((long)CLUT_reds[j] & 0xFF00) << 8)
| ((long)CLUT_greens[j] & 0xFF00)
| (((long)CLUT_blues[j] & 0xFF00) >> 8);
for (a = MyWindowScale; --a >= 0; ) {
*p4++ = v;
}
}
}
}
#endif
#if (0 != vMacScreenDepth) && (vMacScreenDepth < 4)
LOCALPROC SetUpColorTabl(void)
{
int i;
int j;
int k;
ui5p p4;
p4 = (ui5p)ScalingTabl;
for (i = 0; i < 256; ++i) {
for (k = 1 << (3 - vMacScreenDepth); --k >= 0; ) {
j = (i >> (k << vMacScreenDepth)) & (CLUT_size - 1);
*p4++ = (((long)CLUT_reds[j] & 0xFF00) << 8)
| ((long)CLUT_greens[j] & 0xFF00)
| (((long)CLUT_blues[j] & 0xFF00) >> 8);
}
}
}
#endif
#if EnableMagnify && UseColorImage
LOCALPROC <API key>(void)
{
int i;
int k;
int a;
ui5r v;
ui5p p4;
p4 = (ui5p)ScalingTabl;
for (i = 0; i < 256; ++i) {
for (k = 8; --k >= 0; ) {
if (0 != ((i >> k) & 1)) {
v = 0;
} else {
v = 0xFFFFFF;
}
for (a = MyWindowScale; --a >= 0; ) {
*p4++ = v;
}
}
}
}
#endif
#if UseColorImage
LOCALPROC SetUpBW2ColorTabl(void)
{
int i;
int k;
ui5r v;
ui5p p4;
p4 = (ui5p)ScalingTabl;
for (i = 0; i < 256; ++i) {
for (k = 8; --k >= 0; ) {
if (0 != ((i >> k) & 1)) {
v = 0;
} else {
v = 0xFFFFFF;
}
*p4++ = v;
}
}
}
#endif
#if EnableMagnify && ! UseColorImage
#define ScrnMapr_DoMap UpdateScaledBWCopy
#define ScrnMapr_Src GetCurDrawBuff()
#define ScrnMapr_Dst ScalingBuff
#define ScrnMapr_SrcDepth 0
#define ScrnMapr_DstDepth 0
#define ScrnMapr_Map ScalingTabl
#define ScrnMapr_Scale MyWindowScale
#include "SCRNMAPR.h"
#endif
#if (0 != vMacScreenDepth) && (vMacScreenDepth < 4)
#define ScrnMapr_DoMap <API key>
#define ScrnMapr_Src GetCurDrawBuff()
#define ScrnMapr_Dst ScalingBuff
#define ScrnMapr_SrcDepth vMacScreenDepth
#define ScrnMapr_DstDepth 5
#define ScrnMapr_Map ScalingTabl
#include "SCRNMAPR.h"
#endif
#if EnableMagnify && (0 != vMacScreenDepth) && (vMacScreenDepth < 4)
#define ScrnMapr_DoMap <API key>
#define ScrnMapr_Src GetCurDrawBuff()
#define ScrnMapr_Dst ScalingBuff
#define ScrnMapr_SrcDepth vMacScreenDepth
#define ScrnMapr_DstDepth 5
#define ScrnMapr_Map ScalingTabl
#define ScrnMapr_Scale MyWindowScale
#include "SCRNMAPR.h"
#endif
#if vMacScreenDepth >= 4
#define ScrnTrns_DoTrans <API key>
#define ScrnTrns_Src GetCurDrawBuff()
#define ScrnTrns_Dst ScalingBuff
#define ScrnTrns_SrcDepth vMacScreenDepth
#define ScrnTrns_DstDepth 5
#include "SCRNTRNS.h"
#endif
#if EnableMagnify && (vMacScreenDepth >= 4)
#define ScrnTrns_DoTrans <API key>
#define ScrnTrns_Src GetCurDrawBuff()
#define ScrnTrns_Dst ScalingBuff
#define ScrnTrns_SrcDepth vMacScreenDepth
#define ScrnTrns_DstDepth 5
#define ScrnTrns_Scale MyWindowScale
#include "SCRNTRNS.h"
#endif
#if EnableMagnify && UseColorImage
#define ScrnMapr_DoMap <API key>
#define ScrnMapr_Src GetCurDrawBuff()
#define ScrnMapr_Dst ScalingBuff
#define ScrnMapr_SrcDepth 0
#define ScrnMapr_DstDepth 5
#define ScrnMapr_Map ScalingTabl
#define ScrnMapr_Scale MyWindowScale
#include "SCRNMAPR.h"
#endif
#if UseColorImage
#define ScrnMapr_DoMap <API key>
#define ScrnMapr_Src GetCurDrawBuff()
#define ScrnMapr_Dst ScalingBuff
#define ScrnMapr_SrcDepth 0
#define ScrnMapr_DstDepth 5
#define ScrnMapr_Map ScalingTabl
#include "SCRNMAPR.h"
#endif
LOCALPROC <API key>(ui4r top, ui4r left,
ui4r bottom, ui4r right)
{
int XDest;
int YDest;
char *the_data;
#if VarFullScreen
if (UseFullScreen)
#endif
#if MayFullScreen
{
if (top < ViewVStart) {
top = ViewVStart;
}
if (left < ViewHStart) {
left = ViewHStart;
}
if (bottom > ViewVStart + ViewVSize) {
bottom = ViewVStart + ViewVSize;
}
if (right > ViewHStart + ViewHSize) {
right = ViewHStart + ViewHSize;
}
if ((top >= bottom) || (left >= right)) {
goto label_exit;
}
}
#endif
XDest = left;
YDest = top;
#if VarFullScreen
if (UseFullScreen)
#endif
#if MayFullScreen
{
XDest -= ViewHStart;
YDest -= ViewVStart;
}
#endif
#if EnableMagnify
if (UseMagnify) {
XDest *= MyWindowScale;
YDest *= MyWindowScale;
}
#endif
#if VarFullScreen
if (UseFullScreen)
#endif
#if MayFullScreen
{
XDest += hOffset;
YDest += vOffset;
}
#endif
#if EnableMagnify
if (UseMagnify) {
#if UseColorImage
#if 0 != vMacScreenDepth
if (UseColorMode) {
#if vMacScreenDepth < 4
if (! ColorTransValid) {
<API key>();
ColorTransValid = trueblnr;
}
<API key>(top, left, bottom, right);
#else
<API key>(top, left, bottom, right);
#endif
} else
#endif /* 0 != vMacScreenDepth */
{
if (! ColorTransValid) {
<API key>();
ColorTransValid = trueblnr;
}
<API key>(top, left, bottom, right);
}
#else /* ! UseColorImage */
/* assume 0 == vMacScreenDepth */
{
if (! ColorTransValid) {
SetUpScalingTabl();
ColorTransValid = trueblnr;
}
UpdateScaledBWCopy(top, left, bottom, right);
}
#endif /* UseColorImage */
{
char *saveData = my_Scaled_image->data;
my_Scaled_image->data = (char *)ScalingBuff;
XPutImage(x_display, my_main_wind, my_gc, my_Scaled_image,
left * MyWindowScale, top * MyWindowScale,
XDest, YDest,
(right - left) * MyWindowScale,
(bottom - top) * MyWindowScale);
my_Scaled_image->data = saveData;
}
} else
#endif /* EnableMagnify */
{
#if UseColorImage
#if 0 != vMacScreenDepth
if (UseColorMode) {
#if vMacScreenDepth < 4
if (! ColorTransValid) {
SetUpColorTabl();
ColorTransValid = trueblnr;
}
<API key>(top, left, bottom, right);
the_data = (char *)ScalingBuff;
#else
/*
if vMacScreenDepth == 5 and MSBFirst, could
copy directly with the_data = (char *)GetCurDrawBuff();
*/
<API key>(top, left, bottom, right);
the_data = (char *)ScalingBuff;
#endif
} else
#endif /* 0 != vMacScreenDepth */
{
if (! ColorTransValid) {
SetUpBW2ColorTabl();
ColorTransValid = trueblnr;
}
<API key>(top, left, bottom, right);
the_data = (char *)ScalingBuff;
}
#else /* ! UseColorImage */
{
the_data = (char *)GetCurDrawBuff();
}
#endif /* UseColorImage */
{
char *saveData = my_image->data;
my_image->data = the_data;
XPutImage(x_display, my_main_wind, my_gc, my_image,
left, top, XDest, YDest,
right - left, bottom - top);
my_image->data = saveData;
}
}
#if MayFullScreen
label_exit:
;
#endif
}
LOCALPROC <API key>(void)
{
if (ScreenChangedBottom > ScreenChangedTop) {
<API key>(ScreenChangedTop, ScreenChangedLeft,
ScreenChangedBottom, ScreenChangedRight);
ScreenClearChanges();
}
}
/* cursor hiding */
LOCALVAR blnr HaveCursorHidden = falseblnr;
LOCALVAR blnr WantCursorHidden = falseblnr;
LOCALPROC ForceShowCursor(void)
{
if (HaveCursorHidden) {
HaveCursorHidden = falseblnr;
if (my_main_wind) {
XUndefineCursor(x_display, my_main_wind);
}
}
}
LOCALVAR Cursor blankCursor = None;
LOCALFUNC blnr CreateMyBlankCursor(Window rootwin)
{
Pixmap cursormask;
XGCValues xgc;
GC gc;
blnr IsOk = falseblnr;
cursormask = XCreatePixmap(x_display, rootwin, 1, 1, 1);
if (None == cursormask) {
WriteExtraErr("XCreatePixmap failed.");
} else {
xgc.function = GXclear;
gc = XCreateGC(x_display, cursormask, GCFunction, &xgc);
if (None == gc) {
WriteExtraErr("XCreateGC failed.");
} else {
XFillRectangle(x_display, cursormask, gc, 0, 0, 1, 1);
XFreeGC(x_display, gc);
blankCursor = XCreatePixmapCursor(x_display, cursormask,
cursormask, &x_black, &x_white, 0, 0);
if (None == blankCursor) {
WriteExtraErr("XCreatePixmapCursor failed.");
} else {
IsOk = trueblnr;
}
}
XFreePixmap(x_display, cursormask);
/*
assuming that XCreatePixmapCursor doesn't think it
owns the pixmaps passed to it. I've seen code that
assumes this, and other code that seems to assume
the opposite.
*/
}
return IsOk;
}
/* cursor moving */
#if EnableMoveMouse
LOCALFUNC blnr MyMoveMouse(si4b h, si4b v)
{
int NewMousePosh;
int NewMousePosv;
int root_x_return;
int root_y_return;
Window root_return;
Window child_return;
unsigned int mask_return;
blnr IsOk;
int attempts = 0;
#if VarFullScreen
if (UseFullScreen)
#endif
#if MayFullScreen
{
h -= ViewHStart;
v -= ViewVStart;
}
#endif
#if EnableMagnify
if (UseMagnify) {
h *= MyWindowScale;
v *= MyWindowScale;
}
#endif
#if VarFullScreen
if (UseFullScreen)
#endif
#if MayFullScreen
{
h += hOffset;
v += vOffset;
}
#endif
do {
XWarpPointer(x_display, None, my_main_wind, 0, 0, 0, 0, h, v);
XQueryPointer(x_display, my_main_wind,
&root_return, &child_return,
&root_x_return, &root_y_return,
&NewMousePosh, &NewMousePosv,
&mask_return);
IsOk = (h == NewMousePosh) && (v == NewMousePosv);
++attempts;
} while ((! IsOk) && (attempts < 10));
return IsOk;
}
#endif
#if EnableFSMouseMotion
LOCALPROC <API key>(void)
{
if (! HaveMouseMotion) {
if (MyMoveMouse(ViewHStart + (ViewHSize / 2),
ViewVStart + (ViewVSize / 2)))
{
SavedMouseH = ViewHStart + (ViewHSize / 2);
SavedMouseV = ViewVStart + (ViewVSize / 2);
HaveMouseMotion = trueblnr;
}
}
}
#endif
#if EnableFSMouseMotion
LOCALPROC StopSaveMouseMotion(void)
{
if (HaveMouseMotion) {
(void) MyMoveMouse(CurMouseH, CurMouseV);
HaveMouseMotion = falseblnr;
}
}
#endif
/* cursor state */
#if EnableFSMouseMotion
LOCALPROC MyMouseConstrain(void)
{
si4b shiftdh;
si4b shiftdv;
if (SavedMouseH < ViewHStart + (ViewHSize / 4)) {
shiftdh = ViewHSize / 2;
} else if (SavedMouseH > ViewHStart + ViewHSize - (ViewHSize / 4)) {
shiftdh = - ViewHSize / 2;
} else {
shiftdh = 0;
}
if (SavedMouseV < ViewVStart + (ViewVSize / 4)) {
shiftdv = ViewVSize / 2;
} else if (SavedMouseV > ViewVStart + ViewVSize - (ViewVSize / 4)) {
shiftdv = - ViewVSize / 2;
} else {
shiftdv = 0;
}
if ((shiftdh != 0) || (shiftdv != 0)) {
SavedMouseH += shiftdh;
SavedMouseV += shiftdv;
if (! MyMoveMouse(SavedMouseH, SavedMouseV)) {
HaveMouseMotion = falseblnr;
}
}
}
#endif
LOCALPROC MousePositionNotify(int NewMousePosh, int NewMousePosv)
{
blnr <API key> = trueblnr;
#if VarFullScreen
if (UseFullScreen)
#endif
#if MayFullScreen
{
NewMousePosh -= hOffset;
NewMousePosv -= vOffset;
}
#endif
#if EnableMagnify
if (UseMagnify) {
NewMousePosh /= MyWindowScale;
NewMousePosv /= MyWindowScale;
}
#endif
#if VarFullScreen
if (UseFullScreen)
#endif
#if MayFullScreen
{
NewMousePosh += ViewHStart;
NewMousePosv += ViewVStart;
}
#endif
#if EnableFSMouseMotion
if (HaveMouseMotion) {
<API key>(NewMousePosh - SavedMouseH,
NewMousePosv - SavedMouseV);
SavedMouseH = NewMousePosh;
SavedMouseV = NewMousePosv;
} else
#endif
{
if (NewMousePosh < 0) {
NewMousePosh = 0;
<API key> = falseblnr;
} else if (NewMousePosh >= vMacScreenWidth) {
NewMousePosh = vMacScreenWidth - 1;
<API key> = falseblnr;
}
if (NewMousePosv < 0) {
NewMousePosv = 0;
<API key> = falseblnr;
} else if (NewMousePosv >= vMacScreenHeight) {
NewMousePosv = vMacScreenHeight - 1;
<API key> = falseblnr;
}
#if VarFullScreen
if (UseFullScreen)
#endif
#if MayFullScreen
{
<API key> = trueblnr;
}
#endif
/* if (<API key> || CurMouseButton) */
/*
for a game like arkanoid, would like mouse to still
move even when outside window in one direction
*/
MyMousePositionSet(NewMousePosh, NewMousePosv);
}
WantCursorHidden = <API key>;
}
LOCALPROC CheckMouseState(void)
{
int NewMousePosh;
int NewMousePosv;
int root_x_return;
int root_y_return;
Window root_return;
Window child_return;
unsigned int mask_return;
XQueryPointer(x_display, my_main_wind,
&root_return, &child_return,
&root_x_return, &root_y_return,
&NewMousePosh, &NewMousePosv,
&mask_return);
MousePositionNotify(NewMousePosh, NewMousePosv);
}
LOCALVAR KeyCode TheCapsLockCode;
LOCALVAR ui3b KC2MKC[256];
LOCALPROC KC2MKCAssignOne(KeySym ks, ui3r key)
{
KeyCode code = XKeysymToKeycode(x_display, ks);
if (code != NoSymbol) {
KC2MKC[code] = key;
}
#if 0
fprintf(stderr, "%d %d %d\n", (int)ks, key, (int)code);
#endif
}
LOCALFUNC blnr KC2MKCInit(void)
{
int i;
for (i = 0; i < 256; ++i) {
KC2MKC[i] = MKC_None;
}
#if 0 /* find Keysym for a code */
for (i = 0; i < 64 * 1024; ++i) {
KeyCode code = XKeysymToKeycode(x_display, i);
if (115 == code) {
fprintf(stderr, "i %d\n", i);
}
}
#endif
/*
start with redundant mappings, should get overwritten
by main mappings but define them just in case
*/
#ifdef XK_KP_Insert
KC2MKCAssignOne(XK_KP_Insert, MKC_KP0);
#endif
#ifdef XK_KP_End
KC2MKCAssignOne(XK_KP_End, MKC_KP1);
#endif
#ifdef XK_KP_Down
KC2MKCAssignOne(XK_KP_Down, MKC_KP2);
#endif
#ifdef XK_KP_Next
KC2MKCAssignOne(XK_KP_Next, MKC_KP3);
#endif
#ifdef XK_KP_Left
KC2MKCAssignOne(XK_KP_Left, MKC_KP4);
#endif
#ifdef XK_KP_Begin
KC2MKCAssignOne(XK_KP_Begin, MKC_KP5);
#endif
#ifdef XK_KP_Right
KC2MKCAssignOne(XK_KP_Right, MKC_KP6);
#endif
#ifdef XK_KP_Home
KC2MKCAssignOne(XK_KP_Home, MKC_KP7);
#endif
#ifdef XK_KP_Up
KC2MKCAssignOne(XK_KP_Up, MKC_KP8);
#endif
#ifdef XK_KP_Prior
KC2MKCAssignOne(XK_KP_Prior, MKC_KP9);
#endif
#ifdef XK_KP_Delete
KC2MKCAssignOne(XK_KP_Delete, MKC_Decimal);
#endif
KC2MKCAssignOne(XK_asciitilde, MKC_formac_Grave);
KC2MKCAssignOne(XK_underscore, MKC_Minus);
KC2MKCAssignOne(XK_plus, MKC_Equal);
KC2MKCAssignOne(XK_braceleft, MKC_LeftBracket);
KC2MKCAssignOne(XK_braceright, MKC_RightBracket);
KC2MKCAssignOne(XK_bar, <API key>);
KC2MKCAssignOne(XK_colon, MKC_SemiColon);
KC2MKCAssignOne(XK_quotedbl, MKC_SingleQuote);
KC2MKCAssignOne(XK_less, MKC_Comma);
KC2MKCAssignOne(XK_greater, MKC_Period);
KC2MKCAssignOne(XK_question, MKC_formac_Slash);
KC2MKCAssignOne(XK_a, MKC_A);
KC2MKCAssignOne(XK_b, MKC_B);
KC2MKCAssignOne(XK_c, MKC_C);
KC2MKCAssignOne(XK_d, MKC_D);
KC2MKCAssignOne(XK_e, MKC_E);
KC2MKCAssignOne(XK_f, MKC_F);
KC2MKCAssignOne(XK_g, MKC_G);
KC2MKCAssignOne(XK_h, MKC_H);
KC2MKCAssignOne(XK_i, MKC_I);
KC2MKCAssignOne(XK_j, MKC_J);
KC2MKCAssignOne(XK_k, MKC_K);
KC2MKCAssignOne(XK_l, MKC_L);
KC2MKCAssignOne(XK_m, MKC_M);
KC2MKCAssignOne(XK_n, MKC_N);
KC2MKCAssignOne(XK_o, MKC_O);
KC2MKCAssignOne(XK_p, MKC_P);
KC2MKCAssignOne(XK_q, MKC_Q);
KC2MKCAssignOne(XK_r, MKC_R);
KC2MKCAssignOne(XK_s, MKC_S);
KC2MKCAssignOne(XK_t, MKC_T);
KC2MKCAssignOne(XK_u, MKC_U);
KC2MKCAssignOne(XK_v, MKC_V);
KC2MKCAssignOne(XK_w, MKC_W);
KC2MKCAssignOne(XK_x, MKC_X);
KC2MKCAssignOne(XK_y, MKC_Y);
KC2MKCAssignOne(XK_z, MKC_Z);
/*
main mappings
*/
KC2MKCAssignOne(XK_F1, MKC_formac_F1);
KC2MKCAssignOne(XK_F2, MKC_formac_F2);
KC2MKCAssignOne(XK_F3, MKC_formac_F3);
KC2MKCAssignOne(XK_F4, MKC_formac_F4);
KC2MKCAssignOne(XK_F5, MKC_formac_F5);
KC2MKCAssignOne(XK_F6, MKC_F6);
KC2MKCAssignOne(XK_F7, MKC_F7);
KC2MKCAssignOne(XK_F8, MKC_F8);
KC2MKCAssignOne(XK_F9, MKC_F9);
KC2MKCAssignOne(XK_F10, MKC_F10);
KC2MKCAssignOne(XK_F11, MKC_F11);
KC2MKCAssignOne(XK_F12, MKC_F12);
#ifdef XK_Delete
KC2MKCAssignOne(XK_Delete, <API key>);
#endif
#ifdef XK_Insert
KC2MKCAssignOne(XK_Insert, MKC_formac_Help);
#endif
#ifdef XK_Help
KC2MKCAssignOne(XK_Help, MKC_formac_Help);
#endif
#ifdef XK_Home
KC2MKCAssignOne(XK_Home, MKC_formac_Home);
#endif
#ifdef XK_End
KC2MKCAssignOne(XK_End, MKC_formac_End);
#endif
#ifdef XK_Page_Up
KC2MKCAssignOne(XK_Page_Up, MKC_formac_PageUp);
#else
#ifdef XK_Prior
KC2MKCAssignOne(XK_Prior, MKC_formac_PageUp);
#endif
#endif
#ifdef XK_Page_Down
KC2MKCAssignOne(XK_Page_Down, MKC_formac_PageDown);
#else
#ifdef XK_Next
KC2MKCAssignOne(XK_Next, MKC_formac_PageDown);
#endif
#endif
#ifdef XK_Print
KC2MKCAssignOne(XK_Print, MKC_Print);
#endif
#ifdef XK_Scroll_Lock
KC2MKCAssignOne(XK_Scroll_Lock, MKC_ScrollLock);
#endif
#ifdef XK_Pause
KC2MKCAssignOne(XK_Pause, MKC_Pause);
#endif
KC2MKCAssignOne(XK_KP_Add, MKC_KPAdd);
KC2MKCAssignOne(XK_KP_Subtract, MKC_KPSubtract);
KC2MKCAssignOne(XK_KP_Multiply, MKC_KPMultiply);
KC2MKCAssignOne(XK_KP_Divide, MKC_KPDevide);
KC2MKCAssignOne(XK_KP_Enter, MKC_formac_Enter);
KC2MKCAssignOne(XK_KP_Equal, MKC_KPEqual);
KC2MKCAssignOne(XK_KP_0, MKC_KP0);
KC2MKCAssignOne(XK_KP_1, MKC_KP1);
KC2MKCAssignOne(XK_KP_2, MKC_KP2);
KC2MKCAssignOne(XK_KP_3, MKC_KP3);
KC2MKCAssignOne(XK_KP_4, MKC_KP4);
KC2MKCAssignOne(XK_KP_5, MKC_KP5);
KC2MKCAssignOne(XK_KP_6, MKC_KP6);
KC2MKCAssignOne(XK_KP_7, MKC_KP7);
KC2MKCAssignOne(XK_KP_8, MKC_KP8);
KC2MKCAssignOne(XK_KP_9, MKC_KP9);
KC2MKCAssignOne(XK_KP_Decimal, MKC_Decimal);
KC2MKCAssignOne(XK_Left, MKC_Left);
KC2MKCAssignOne(XK_Right, MKC_Right);
KC2MKCAssignOne(XK_Up, MKC_Up);
KC2MKCAssignOne(XK_Down, MKC_Down);
KC2MKCAssignOne(XK_grave, MKC_formac_Grave);
KC2MKCAssignOne(XK_minus, MKC_Minus);
KC2MKCAssignOne(XK_equal, MKC_Equal);
KC2MKCAssignOne(XK_bracketleft, MKC_LeftBracket);
KC2MKCAssignOne(XK_bracketright, MKC_RightBracket);
KC2MKCAssignOne(XK_backslash, <API key>);
KC2MKCAssignOne(XK_semicolon, MKC_SemiColon);
KC2MKCAssignOne(XK_apostrophe, MKC_SingleQuote);
KC2MKCAssignOne(XK_comma, MKC_Comma);
KC2MKCAssignOne(XK_period, MKC_Period);
KC2MKCAssignOne(XK_slash, MKC_formac_Slash);
KC2MKCAssignOne(XK_Escape, MKC_formac_Escape);
KC2MKCAssignOne(XK_Tab, MKC_Tab);
KC2MKCAssignOne(XK_Return, MKC_Return);
KC2MKCAssignOne(XK_space, MKC_Space);
KC2MKCAssignOne(XK_BackSpace, MKC_BackSpace);
KC2MKCAssignOne(XK_Caps_Lock, MKC_formac_CapsLock);
KC2MKCAssignOne(XK_Num_Lock, MKC_Clear);
KC2MKCAssignOne(XK_Meta_L, MKC_formac_Command);
KC2MKCAssignOne(XK_Meta_R, MKC_formac_RCommand);
KC2MKCAssignOne(XK_Mode_switch, MKC_formac_Option);
KC2MKCAssignOne(XK_Menu, MKC_formac_Option);
KC2MKCAssignOne(XK_Super_L, MKC_formac_Option);
KC2MKCAssignOne(XK_Super_R, MKC_formac_ROption);
KC2MKCAssignOne(XK_Hyper_L, MKC_formac_Option);
KC2MKCAssignOne(XK_Hyper_R, MKC_formac_ROption);
KC2MKCAssignOne(XK_F13, MKC_formac_Option);
/*
seen being used in Mandrake Linux 9.2
for windows key
*/
KC2MKCAssignOne(XK_Shift_L, MKC_formac_Shift);
KC2MKCAssignOne(XK_Shift_R, MKC_formac_RShift);
KC2MKCAssignOne(XK_Alt_L, MKC_formac_Command);
KC2MKCAssignOne(XK_Alt_R, MKC_formac_RCommand);
KC2MKCAssignOne(XK_Control_L, MKC_formac_Control);
KC2MKCAssignOne(XK_Control_R, MKC_formac_RControl);
KC2MKCAssignOne(XK_1, MKC_1);
KC2MKCAssignOne(XK_2, MKC_2);
KC2MKCAssignOne(XK_3, MKC_3);
KC2MKCAssignOne(XK_4, MKC_4);
KC2MKCAssignOne(XK_5, MKC_5);
KC2MKCAssignOne(XK_6, MKC_6);
KC2MKCAssignOne(XK_7, MKC_7);
KC2MKCAssignOne(XK_8, MKC_8);
KC2MKCAssignOne(XK_9, MKC_9);
KC2MKCAssignOne(XK_0, MKC_0);
KC2MKCAssignOne(XK_A, MKC_A);
KC2MKCAssignOne(XK_B, MKC_B);
KC2MKCAssignOne(XK_C, MKC_C);
KC2MKCAssignOne(XK_D, MKC_D);
KC2MKCAssignOne(XK_E, MKC_E);
KC2MKCAssignOne(XK_F, MKC_F);
KC2MKCAssignOne(XK_G, MKC_G);
KC2MKCAssignOne(XK_H, MKC_H);
KC2MKCAssignOne(XK_I, MKC_I);
KC2MKCAssignOne(XK_J, MKC_J);
KC2MKCAssignOne(XK_K, MKC_K);
KC2MKCAssignOne(XK_L, MKC_L);
KC2MKCAssignOne(XK_M, MKC_M);
KC2MKCAssignOne(XK_N, MKC_N);
KC2MKCAssignOne(XK_O, MKC_O);
KC2MKCAssignOne(XK_P, MKC_P);
KC2MKCAssignOne(XK_Q, MKC_Q);
KC2MKCAssignOne(XK_R, MKC_R);
KC2MKCAssignOne(XK_S, MKC_S);
KC2MKCAssignOne(XK_T, MKC_T);
KC2MKCAssignOne(XK_U, MKC_U);
KC2MKCAssignOne(XK_V, MKC_V);
KC2MKCAssignOne(XK_W, MKC_W);
KC2MKCAssignOne(XK_X, MKC_X);
KC2MKCAssignOne(XK_Y, MKC_Y);
KC2MKCAssignOne(XK_Z, MKC_Z);
TheCapsLockCode = XKeysymToKeycode(x_display, XK_Caps_Lock);
InitKeyCodes();
return trueblnr;
}
LOCALPROC CheckTheCapsLock(void)
{
int NewMousePosh;
int NewMousePosv;
int root_x_return;
int root_y_return;
Window root_return;
Window child_return;
unsigned int mask_return;
XQueryPointer(x_display, my_main_wind,
&root_return, &child_return,
&root_x_return, &root_y_return,
&NewMousePosh, &NewMousePosv,
&mask_return);
<API key>(MKC_formac_CapsLock,
(mask_return & LockMask) != 0);
}
LOCALPROC DoKeyCode0(int i, blnr down)
{
ui3r key = KC2MKC[i];
if (MKC_None != key) {
<API key>(key, down);
}
}
LOCALPROC DoKeyCode(int i, blnr down)
{
if (i == TheCapsLockCode) {
CheckTheCapsLock();
} else if (i >= 0 && i < 256) {
DoKeyCode0(i, down);
}
}
#if MayFullScreen && GrabKeysFullScreen
LOCALVAR blnr KeyboardIsGrabbed = falseblnr;
#endif
#if MayFullScreen && GrabKeysFullScreen
LOCALPROC MyGrabKeyboard(void)
{
if (! KeyboardIsGrabbed) {
(void) XGrabKeyboard(x_display, my_main_wind,
False, GrabModeAsync, GrabModeAsync,
CurrentTime);
KeyboardIsGrabbed = trueblnr;
}
}
#endif
#if MayFullScreen && GrabKeysFullScreen
LOCALPROC MyUnGrabKeyboard(void)
{
if (KeyboardIsGrabbed && my_main_wind) {
XUngrabKeyboard(x_display, CurrentTime);
KeyboardIsGrabbed = falseblnr;
}
}
#endif
LOCALVAR blnr NoKeyRepeat = falseblnr;
LOCALVAR int SaveKeyRepeat;
LOCALPROC DisableKeyRepeat(void)
{
XKeyboardState r;
XKeyboardControl k;
if ((! NoKeyRepeat) && (x_display != NULL)) {
NoKeyRepeat = trueblnr;
XGetKeyboardControl(x_display, &r);
SaveKeyRepeat = r.global_auto_repeat;
k.auto_repeat_mode = AutoRepeatModeOff;
<API key>(x_display, KBAutoRepeatMode, &k);
}
}
LOCALPROC RestoreKeyRepeat(void)
{
XKeyboardControl k;
if (NoKeyRepeat && (x_display != NULL)) {
NoKeyRepeat = falseblnr;
k.auto_repeat_mode = SaveKeyRepeat;
<API key>(x_display, KBAutoRepeatMode, &k);
}
}
LOCALVAR blnr <API key> = falseblnr;
LOCALPROC GetTheDownKeys(void)
{
char keys_return[32];
int i;
int v;
int j;
XQueryKeymap(x_display, keys_return);
for (i = 0; i < 32; ++i) {
v = keys_return[i];
for (j = 0; j < 8; ++j) {
if (0 != ((1 << j) & v)) {
int k = i * 8 + j;
if (k != TheCapsLockCode) {
DoKeyCode0(k, trueblnr);
}
}
}
}
}
LOCALPROC ReconnectKeyCodes3(void)
{
CheckTheCapsLock();
if (<API key>) {
<API key> = falseblnr;
GetTheDownKeys();
}
}
LOCALPROC DisconnectKeyCodes3(void)
{
DisconnectKeyCodes2();
MyMouseButtonSet(falseblnr);
}
#define dbglog_TimeStuff (0 && dbglog_HAVE)
LOCALVAR ui5b TrueEmulatedTime = 0;
#include "DATE2SEC.h"
#define TicksPerSecond 1000000
LOCALVAR blnr HaveTimeDelta = falseblnr;
LOCALVAR ui5b TimeDelta;
LOCALVAR ui5b NewMacDateInSeconds;
LOCALVAR ui5b LastTimeSec;
LOCALVAR ui5b LastTimeUsec;
LOCALPROC GetCurrentTicks(void)
{
struct timeval t;
gettimeofday(&t, NULL);
if (! HaveTimeDelta) {
time_t Current_Time;
struct tm *s;
(void) time(&Current_Time);
s = localtime(&Current_Time);
TimeDelta = Date2MacSeconds(s->tm_sec, s->tm_min, s->tm_hour,
s->tm_mday, 1 + s->tm_mon, 1900 + s->tm_year) - t.tv_sec;
#if 0 && AutoTimeZone /* how portable is this ? */
CurMacDelta = ((ui5b)(s->tm_gmtoff) & 0x00FFFFFF)
| ((s->tm_isdst ? 0x80 : 0) << 24);
#endif
HaveTimeDelta = trueblnr;
}
NewMacDateInSeconds = t.tv_sec + TimeDelta;
LastTimeSec = (ui5b)t.tv_sec;
LastTimeUsec = (ui5b)t.tv_usec;
}
#define MyInvTimeStep 16626 /* TicksPerSecond / 60.14742 */
LOCALVAR ui5b NextTimeSec;
LOCALVAR ui5b NextTimeUsec;
LOCALPROC IncrNextTime(void)
{
NextTimeUsec += MyInvTimeStep;
if (NextTimeUsec >= TicksPerSecond) {
NextTimeUsec -= TicksPerSecond;
NextTimeSec += 1;
}
}
LOCALPROC InitNextTime(void)
{
NextTimeSec = LastTimeSec;
NextTimeUsec = LastTimeUsec;
IncrNextTime();
}
LOCALPROC StartUpTimeAdjust(void)
{
GetCurrentTicks();
InitNextTime();
}
LOCALFUNC si5b GetTimeDiff(void)
{
return ((si5b)(LastTimeSec - NextTimeSec)) * TicksPerSecond
+ ((si5b)(LastTimeUsec - NextTimeUsec));
}
LOCALPROC <API key>(void)
{
si5b TimeDiff;
GetCurrentTicks();
TimeDiff = GetTimeDiff();
if (TimeDiff >= 0) {
if (TimeDiff > 16 * MyInvTimeStep) {
/* emulation interrupted, forget it */
++TrueEmulatedTime;
InitNextTime();
#if dbglog_TimeStuff
dbglog_writelnNum("emulation interrupted",
TrueEmulatedTime);
#endif
} else {
do {
++TrueEmulatedTime;
IncrNextTime();
TimeDiff -= TicksPerSecond;
} while (TimeDiff >= 0);
}
} else if (TimeDiff < - 16 * MyInvTimeStep) {
/* clock goofed if ever get here, reset */
#if dbglog_TimeStuff
dbglog_writeln("clock set back");
#endif
InitNextTime();
}
}
LOCALFUNC blnr CheckDateTime(void)
{
if (CurMacDateInSeconds != NewMacDateInSeconds) {
CurMacDateInSeconds = NewMacDateInSeconds;
return trueblnr;
} else {
return falseblnr;
}
}
LOCALFUNC blnr InitLocationDat(void)
{
GetCurrentTicks();
CurMacDateInSeconds = NewMacDateInSeconds;
return trueblnr;
}
#if MySoundEnabled
#define kLn2SoundBuffers 4 /* kSoundBuffers must be a power of two */
#define kSoundBuffers (1 << kLn2SoundBuffers)
#define kSoundBuffMask (kSoundBuffers - 1)
#define <API key> 3
/*
if too big then sound lags behind emulation.
if too small then sound will have pauses.
*/
#define kLnOneBuffLen 9
#define kLnAllBuffLen (kLn2SoundBuffers + kLnOneBuffLen)
#define kOneBuffLen (1UL << kLnOneBuffLen)
#define kAllBuffLen (1UL << kLnAllBuffLen)
#define kLnOneBuffSz (kLnOneBuffLen + kLn2SoundSampSz - 3)
#define kLnAllBuffSz (kLnAllBuffLen + kLn2SoundSampSz - 3)
#define kOneBuffSz (1UL << kLnOneBuffSz)
#define kAllBuffSz (1UL << kLnAllBuffSz)
#define kOneBuffMask (kOneBuffLen - 1)
#define kAllBuffMask (kAllBuffLen - 1)
#define dbhBufferSize (kAllBuffSz + kOneBuffSz)
#define dbglog_SoundStuff (0 && dbglog_HAVE)
#define <API key> (0 && dbglog_HAVE)
LOCALVAR tpSoundSamp TheSoundBuffer = nullpr;
LOCALVAR ui4b ThePlayOffset;
LOCALVAR ui4b TheFillOffset;
LOCALVAR ui4b TheWriteOffset;
LOCALVAR ui4b MinFilledSoundBuffs;
LOCALPROC MySound_Start0(void)
{
/* Reset variables */
ThePlayOffset = 0;
TheFillOffset = 0;
TheWriteOffset = 0;
MinFilledSoundBuffs = kSoundBuffers;
}
GLOBALOSGLUFUNC tpSoundSamp MySound_BeginWrite(ui4r n, ui4r *actL)
{
ui4b ToFillLen = kAllBuffLen - (TheWriteOffset - ThePlayOffset);
ui4b WriteBuffContig =
kOneBuffLen - (TheWriteOffset & kOneBuffMask);
if (WriteBuffContig < n) {
n = WriteBuffContig;
}
if (ToFillLen < n) {
/* overwrite previous buffer */
#if dbglog_SoundStuff
dbglog_writeln("sound buffer over flow");
#endif
TheWriteOffset -= kOneBuffLen;
}
*actL = n;
return TheSoundBuffer + (TheWriteOffset & kAllBuffMask);
}
LOCALFUNC blnr MySound_EndWrite0(ui4r actL)
{
blnr v;
TheWriteOffset += actL;
if (0 != (TheWriteOffset & kOneBuffMask)) {
v = falseblnr;
} else {
/* just finished a block */
TheFillOffset = TheWriteOffset;
v = trueblnr;
}
return v;
}
LOCALPROC <API key>(void)
{
if (MinFilledSoundBuffs > <API key>) {
#if dbglog_SoundStuff
dbglog_writeln("MinFilledSoundBuffs too high");
#endif
IncrNextTime();
} else if (MinFilledSoundBuffs < <API key>) {
#if dbglog_SoundStuff
dbglog_writeln("MinFilledSoundBuffs too low");
#endif
++TrueEmulatedTime;
}
MinFilledSoundBuffs = kSoundBuffers;
}
#define SOUND_SAMPLERATE 22255 /* = round(7833600 * 2 / 704) */
#include "SOUNDGLU.h"
#endif
LOCALPROC CheckSavedMacMsg(void)
{
/* called only on quit, if error saved but not yet reported */
if (nullpr != SavedBriefMsg) {
char briefMsg0[ClStrMaxLength + 1];
char longMsg0[ClStrMaxLength + 1];
NativeStrFromCStr(briefMsg0, SavedBriefMsg);
NativeStrFromCStr(longMsg0, SavedLongMsg);
fprintf(stderr, "%s\n", briefMsg0);
fprintf(stderr, "%s\n", longMsg0);
SavedBriefMsg = nullpr;
}
}
#if <API key>
LOCALVAR ui3p MyClipBuffer = NULL;
#endif
#if <API key>
LOCALPROC FreeMyClipBuffer(void)
{
if (MyClipBuffer != NULL) {
free(MyClipBuffer);
MyClipBuffer = NULL;
}
}
#endif
#if <API key>
GLOBALOSGLUFUNC tMacErr HTCEexport(tPbuf i)
{
tMacErr err = mnvm_miscErr;
FreeMyClipBuffer();
if (<API key>(i, falseblnr,
&MyClipBuffer))
{
XSetSelectionOwner(x_display, MyXA_CLIPBOARD,
my_main_wind, CurrentTime);
err = mnvm_noErr;
}
PbufDispose(i);
return err;
}
#endif
#if <API key>
LOCALFUNC blnr <API key>(XEvent *xevent)
{
struct timespec rqt;
struct timespec rmt;
int i;
for (i = 100; --i >= 0; ) {
while (<API key>(x_display, my_main_wind,
SelectionNotify, xevent))
{
if (xevent->xselection.selection != MyXA_CLIPBOARD) {
/*
not what we were looking for. lose it.
(and hope it wasn't too important).
*/
WriteExtraErr("Discarding unwanted SelectionNotify");
} else {
/* this is our event */
return trueblnr;
}
}
rqt.tv_sec = 0;
rqt.tv_nsec = 10000000;
(void) nanosleep(&rqt, &rmt);
}
return falseblnr;
}
#endif
#if <API key>
LOCALPROC HTCEimport_do(void)
{
Window w = XGetSelectionOwner(x_display, MyXA_CLIPBOARD);
if (w == my_main_wind) {
/* We own the clipboard, already have MyClipBuffer */
} else {
FreeMyClipBuffer();
if (w != None) {
XEvent xevent;
XDeleteProperty(x_display, my_main_wind,
MyXA_MinivMac_Clip);
XConvertSelection(x_display, MyXA_CLIPBOARD, XA_STRING,
MyXA_MinivMac_Clip, my_main_wind, CurrentTime);
if (<API key>(&xevent)) {
if (None == xevent.xselection.property) {
/* oops, target not supported */
} else {
if (xevent.xselection.property
!= MyXA_MinivMac_Clip)
{
/* not where we expected it */
} else {
Atom ret_type;
int ret_format;
unsigned long ret_item;
unsigned long remain_byte;
unsigned char *s = NULL;
if ((Success != XGetWindowProperty(
x_display, my_main_wind, MyXA_MinivMac_Clip,
0, 65535, False, AnyPropertyType, &ret_type,
&ret_format, &ret_item, &remain_byte, &s))
|| (ret_type != XA_STRING)
|| (ret_format != 8)
|| (NULL == s))
{
WriteExtraErr(
"XGetWindowProperty failed"
" in HTCEimport_do");
} else {
MyClipBuffer = (ui3p)malloc(ret_item + 1);
if (NULL == MyClipBuffer) {
MacMsg(kStrOutOfMemTitle,
kStrOutOfMemMessage, falseblnr);
} else {
MyMoveBytes((anyp)s, (anyp)MyClipBuffer,
ret_item);
MyClipBuffer[ret_item] = 0;
}
XFree(s);
}
}
XDeleteProperty(x_display, my_main_wind,
MyXA_MinivMac_Clip);
}
}
}
}
}
#endif
#if <API key>
GLOBALOSGLUFUNC tMacErr HTCEimport(tPbuf *r)
{
HTCEimport_do();
return <API key>((char *)MyClipBuffer, r);
}
#endif
#if <API key>
LOCALFUNC blnr <API key>(XEvent *theEvent)
{
blnr RequestFilled = falseblnr;
#if MyDbgEvents
dbglog_writeln("Requested MyXA_CLIPBOARD");
#endif
if (NULL == MyClipBuffer) {
/* our clipboard is empty */
} else if (theEvent->xselectionrequest.target == MyXA_TARGETS) {
Atom a[2];
a[0] = MyXA_TARGETS;
a[1] = XA_STRING;
XChangeProperty(x_display,
theEvent->xselectionrequest.requestor,
theEvent->xselectionrequest.property,
MyXA_TARGETS,
32,
/*
most, but not all, other programs I've
look at seem to use 8 here, but that
can't be right. can it?
*/
PropModeReplace,
(unsigned char *)a,
sizeof(a) / sizeof(Atom));
RequestFilled = trueblnr;
} else if (theEvent->xselectionrequest.target == XA_STRING) {
XChangeProperty(x_display,
theEvent->xselectionrequest.requestor,
theEvent->xselectionrequest.property,
XA_STRING,
8,
PropModeReplace,
(unsigned char *)MyClipBuffer,
strlen((char *)MyClipBuffer));
RequestFilled = trueblnr;
}
return RequestFilled;
}
#endif
#if EnableDragDrop
LOCALPROC MyActivateWind(Time time)
{
if (<API key>(<API key>)) {
XEvent xevent;
Window rootwin = XRootWindow(x_display,
DefaultScreen(x_display));
memset(&xevent, 0, sizeof (xevent));
xevent.xany.type = ClientMessage;
xevent.xclient.send_event = True;
xevent.xclient.window = my_main_wind;
xevent.xclient.message_type = <API key>;
xevent.xclient.format = 32;
xevent.xclient.data.l[0] = 1;
xevent.xclient.data.l[1]= time;
if (0 == XSendEvent(x_display, rootwin, 0,
<API key> | <API key>,
&xevent))
{
WriteExtraErr("XSendEvent failed in MyActivateWind");
}
}
XRaiseWindow(x_display, my_main_wind);
/*
In RedHat 7.1, _NET_ACTIVE_WINDOW supported,
but XSendEvent of _NET_ACTIVE_WINDOW
doesn't raise the window. So just always
call XRaiseWindow. Hopefully calling
XRaiseWindow won't do any harm on window
managers where it isn't needed.
(Such as in Ubuntu 5.10)
*/
XSetInputFocus(x_display, my_main_wind,
RevertToPointerRoot, time);
/* And call this always too, just in case */
}
#endif
#if EnableDragDrop
LOCALPROC ParseOneUri(char *s)
{
/* printf("ParseOneUri %s\n", s); */
if (('f' == s[0]) && ('i' == s[1]) && ('l' == s[2])
&& ('e' == s[3]) && (':' == s[4]))
{
s += 5;
if (('/' == s[0]) && ('/' == s[1])) {
/* skip hostname */
char c;
s += 2;
while ((c = *s) != '/') {
if (0 == c) {
return;
}
++s;
}
}
(void) Sony_Insert1a(s, falseblnr);
}
}
#endif
#if EnableDragDrop
LOCALFUNC int HexChar2Nib(char x)
{
if ((x >= '0') && (x <= '9')) {
return x - '0';
} else if ((x >= 'A') && (x <= 'F')) {
return x - 'A' + 10;
} else if ((x >= 'a') && (x <= 'f')) {
return x - 'a' + 10;
} else {
return -1;
}
}
#endif
#if EnableDragDrop
LOCALPROC ParseUriList(char *s)
{
char *p1 = s;
char *p0 = s;
char *p = s;
char c;
/* printf("ParseUriList %s\n", s); */
while ((c = *p++) != 0) {
if ('%' == c) {
int a;
int b;
if (((a = HexChar2Nib(p[0])) >= 0) &&
((b = HexChar2Nib(p[1])) >= 0))
{
p += 2;
*p1++ = (a << 4) + b;
} else {
*p1++ = c;
}
} else if (('\n' == c) || ('\r' == c)) {
*p1++ = 0;
ParseOneUri(p0);
p0 = p1;
} else {
*p1++ = c;
}
}
*p1++ = 0;
ParseOneUri(p0);
}
#endif
#if EnableDragDrop
LOCALVAR Window PendingDragWindow = None;
#endif
#if EnableDragDrop
LOCALPROC <API key>(XEvent *theEvent)
{
blnr DropOk = falseblnr;
#if MyDbgEvents
dbglog_writeln("Got MyXA_DndSelection");
#endif
if ((theEvent->xselection.property == <API key>)
&& (theEvent->xselection.target == MyXA_UriList))
{
Atom ret_type;
int ret_format;
unsigned long ret_item;
unsigned long remain_byte;
unsigned char *s = NULL;
if ((Success != XGetWindowProperty(x_display, my_main_wind,
<API key>,
0, 65535, False, MyXA_UriList, &ret_type, &ret_format,
&ret_item, &remain_byte, &s))
|| (NULL == s))
{
WriteExtraErr(
"XGetWindowProperty failed in SelectionNotify");
} else {
ParseUriList((char *)s);
DropOk = trueblnr;
XFree(s);
}
} else {
WriteExtraErr("Got Unknown SelectionNotify");
}
XDeleteProperty(x_display, my_main_wind,
<API key>);
if (PendingDragWindow != None) {
XEvent xevent;
memset(&xevent, 0, sizeof(xevent));
xevent.xany.type = ClientMessage;
xevent.xany.display = x_display;
xevent.xclient.window = PendingDragWindow;
xevent.xclient.message_type = MyXA_DndFinished;
xevent.xclient.format = 32;
xevent.xclient.data.l[0] = my_main_wind;
if (DropOk) {
xevent.xclient.data.l[1] = 1;
}
xevent.xclient.data.l[2] = <API key>;
if (0 == XSendEvent(x_display,
PendingDragWindow, 0, 0, &xevent))
{
WriteExtraErr("XSendEvent failed in SelectionNotify");
}
}
if (DropOk && gTrueBackgroundFlag) {
MyActivateWind(theEvent->xselection.time);
<API key> = trueblnr;
}
}
#endif
#if EnableDragDrop
LOCALPROC <API key>(XEvent *theEvent)
{
XEvent xevent;
int xr;
int yr;
unsigned int dr;
unsigned int wr;
unsigned int hr;
unsigned int bwr;
Window rr;
Window srcwin = theEvent->xclient.data.l[0];
#if MyDbgEvents
dbglog_writeln("Got XdndPosition");
#endif
XGetGeometry(x_display, my_main_wind,
&rr, &xr, &yr, &wr, &hr, &bwr, &dr);
memset (&xevent, 0, sizeof(xevent));
xevent.xany.type = ClientMessage;
xevent.xany.display = x_display;
xevent.xclient.window = srcwin;
xevent.xclient.message_type = MyXA_DndStatus;
xevent.xclient.format = 32;
xevent.xclient.data.l[0] = theEvent->xclient.window;
/* Target Window */
xevent.xclient.data.l[1] = 1; /* Accept */
xevent.xclient.data.l[2] = ((xr) << 16) | ((yr) & 0xFFFFUL);
xevent.xclient.data.l[3] = ((wr) << 16) | ((hr) & 0xFFFFUL);
xevent.xclient.data.l[4] = <API key>; /* Action */
if (0 == XSendEvent(x_display, srcwin, 0, 0, &xevent)) {
WriteExtraErr(
"XSendEvent failed in <API key>");
}
}
#endif
#if EnableDragDrop
LOCALPROC <API key>(XEvent *theEvent)
{
Time timestamp = theEvent->xclient.data.l[2];
PendingDragWindow = (Window) theEvent->xclient.data.l[0];
#if MyDbgEvents
dbglog_writeln("Got XdndDrop");
#endif
XConvertSelection(x_display, MyXA_DndSelection, MyXA_UriList,
<API key>, my_main_wind, timestamp);
}
#endif
#if EmLocalTalk
struct xqpr {
int NewMousePosh;
int NewMousePosv;
int root_x_return;
int root_y_return;
Window root_return;
Window child_return;
unsigned int mask_return;
};
typedef struct xqpr xqpr;
LOCALFUNC blnr EntropyGather(void)
{
/*
gather some entropy from several places, just in case
/dev/urandom is not available.
*/
{
struct timeval t;
gettimeofday(&t, NULL);
EntropyPoolAddPtr((ui3p)&t, sizeof(t) / sizeof(ui3b));
}
{
xqpr t;
XQueryPointer(x_display, my_main_wind,
&t.root_return, &t.child_return,
&t.root_x_return, &t.root_y_return,
&t.NewMousePosh, &t.NewMousePosv,
&t.mask_return);
EntropyPoolAddPtr((ui3p)&t, sizeof(t) / sizeof(ui3b));
}
#if 0
/*
Another possible source of entropy. But if available,
almost certainly /dev/urandom is also available.
*/
/* #include <sys/sysinfo.h> */
{
struct sysinfo t;
if (0 != sysinfo(&t)) {
#if dbglog_HAVE
dbglog_writeln("sysinfo fails");
#endif
}
/*
continue even if error, it doesn't hurt anything
if t is garbage.
*/
EntropyPoolAddPtr((ui3p)&t, sizeof(t) / sizeof(ui3b));
}
#endif
{
pid_t t = getpid();
EntropyPoolAddPtr((ui3p)&t, sizeof(t) / sizeof(ui3b));
}
{
ui5b dat[2];
int fd;
if (-1 == (fd = open("/dev/urandom", O_RDONLY))) {
#if dbglog_HAVE
dbglog_writeCStr("open /dev/urandom fails");
dbglog_writeNum(errno);
dbglog_writeCStr(" (");
dbglog_writeCStr(strerror(errno));
dbglog_writeCStr(")");
dbglog_writeReturn();
#endif
} else {
if (read(fd, &dat, sizeof(dat)) < 0) {
#if dbglog_HAVE
dbglog_writeCStr("open /dev/urandom fails");
dbglog_writeNum(errno);
dbglog_writeCStr(" (");
dbglog_writeCStr(strerror(errno));
dbglog_writeCStr(")");
dbglog_writeReturn();
#endif
} else {
#if dbglog_HAVE
dbglog_writeCStr("dat: ");
dbglog_writeHex(dat[0]);
dbglog_writeCStr(" ");
dbglog_writeHex(dat[1]);
dbglog_writeReturn();
#endif
e_p[0] ^= dat[0];
e_p[1] ^= dat[1];
/*
if "/dev/urandom" is working correctly,
this should make the previous contents of e_p
irrelevant. if it is completely broken, like
returning 0, this will not make e_p any less
random.
*/
#if dbglog_HAVE
dbglog_writeCStr("ep: ");
dbglog_writeHex(e_p[0]);
dbglog_writeCStr(" ");
dbglog_writeHex(e_p[1]);
dbglog_writeReturn();
#endif
}
close(fd);
}
}
return trueblnr;
}
#endif
#if EmLocalTalk
#include "LOCALTLK.h"
#endif
#define UseMotionEvents 1
#if UseMotionEvents
LOCALVAR blnr CaughtMouse = falseblnr;
#endif
#if MayNotFullScreen
LOCALVAR int SavedTransH;
LOCALVAR int SavedTransV;
#endif
LOCALPROC HandleTheEvent(XEvent *theEvent)
{
if (theEvent->xany.display != x_display) {
WriteExtraErr("Got event for some other display");
} else switch(theEvent->type) {
case KeyPress:
if (theEvent->xkey.window != my_main_wind) {
WriteExtraErr("Got KeyPress for some other window");
} else {
#if MyDbgEvents
dbglog_writeln("- event - KeyPress");
#endif
MousePositionNotify(theEvent->xkey.x, theEvent->xkey.y);
DoKeyCode(theEvent->xkey.keycode, trueblnr);
}
break;
case KeyRelease:
if (theEvent->xkey.window != my_main_wind) {
WriteExtraErr("Got KeyRelease for some other window");
} else {
#if MyDbgEvents
dbglog_writeln("- event - KeyRelease");
#endif
MousePositionNotify(theEvent->xkey.x, theEvent->xkey.y);
DoKeyCode(theEvent->xkey.keycode, falseblnr);
}
break;
case ButtonPress:
/* any mouse button, we don't care which */
if (theEvent->xbutton.window != my_main_wind) {
WriteExtraErr("Got ButtonPress for some other window");
} else {
/*
could check some modifiers, but don't bother for now
<API key>(MKC_formac_CapsLock,
(theEvent->xbutton.state & LockMask) != 0);
*/
MousePositionNotify(
theEvent->xbutton.x, theEvent->xbutton.y);
MyMouseButtonSet(trueblnr);
}
break;
case ButtonRelease:
/* any mouse button, we don't care which */
if (theEvent->xbutton.window != my_main_wind) {
WriteExtraErr(
"Got ButtonRelease for some other window");
} else {
MousePositionNotify(
theEvent->xbutton.x, theEvent->xbutton.y);
MyMouseButtonSet(falseblnr);
}
break;
#if UseMotionEvents
case MotionNotify:
if (theEvent->xmotion.window != my_main_wind) {
WriteExtraErr("Got MotionNotify for some other window");
} else {
MousePositionNotify(
theEvent->xmotion.x, theEvent->xmotion.y);
}
break;
case EnterNotify:
if (theEvent->xcrossing.window != my_main_wind) {
WriteExtraErr("Got EnterNotify for some other window");
} else {
#if MyDbgEvents
dbglog_writeln("- event - EnterNotify");
#endif
CaughtMouse = trueblnr;
MousePositionNotify(
theEvent->xcrossing.x, theEvent->xcrossing.y);
}
break;
case LeaveNotify:
if (theEvent->xcrossing.window != my_main_wind) {
WriteExtraErr("Got LeaveNotify for some other window");
} else {
#if MyDbgEvents
dbglog_writeln("- event - LeaveNotify");
#endif
MousePositionNotify(
theEvent->xcrossing.x, theEvent->xcrossing.y);
CaughtMouse = falseblnr;
}
break;
#endif
case Expose:
if (theEvent->xexpose.window != my_main_wind) {
WriteExtraErr(
"Got SelectionRequest for some other window");
} else {
int x0 = theEvent->xexpose.x;
int y0 = theEvent->xexpose.y;
int x1 = x0 + theEvent->xexpose.width;
int y1 = y0 + theEvent->xexpose.height;
#if 0 && MyDbgEvents
dbglog_writeln("- event - Expose");
#endif
#if VarFullScreen
if (UseFullScreen)
#endif
#if MayFullScreen
{
x0 -= hOffset;
y0 -= vOffset;
x1 -= hOffset;
y1 -= vOffset;
}
#endif
#if EnableMagnify
if (UseMagnify) {
x0 /= MyWindowScale;
y0 /= MyWindowScale;
x1 = (x1 + (MyWindowScale - 1)) / MyWindowScale;
y1 = (y1 + (MyWindowScale - 1)) / MyWindowScale;
}
#endif
#if VarFullScreen
if (UseFullScreen)
#endif
#if MayFullScreen
{
x0 += ViewHStart;
y0 += ViewVStart;
x1 += ViewHStart;
y1 += ViewVStart;
}
#endif
if (x0 < 0) {
x0 = 0;
}
if (x1 > vMacScreenWidth) {
x1 = vMacScreenWidth;
}
if (y0 < 0) {
y0 = 0;
}
if (y1 > vMacScreenHeight) {
y1 = vMacScreenHeight;
}
if ((x0 < x1) && (y0 < y1)) {
<API key>(y0, x0, y1, x1);
}
NeedFinishOpen1 = falseblnr;
}
break;
#if <API key>
case SelectionRequest:
if (theEvent->xselectionrequest.owner != my_main_wind) {
WriteExtraErr(
"Got SelectionRequest for some other window");
} else {
XEvent xevent;
blnr RequestFilled = falseblnr;
#if MyDbgEvents
dbglog_writeln("- event - SelectionRequest");
WriteDbgAtom("selection",
theEvent->xselectionrequest.selection);
WriteDbgAtom("target",
theEvent->xselectionrequest.target);
WriteDbgAtom("property",
theEvent->xselectionrequest.property);
#endif
if (theEvent->xselectionrequest.selection ==
MyXA_CLIPBOARD)
{
RequestFilled =
<API key>(theEvent);
}
memset(&xevent, 0, sizeof(xevent));
xevent.xselection.type = SelectionNotify;
xevent.xselection.display = x_display;
xevent.xselection.requestor =
theEvent->xselectionrequest.requestor;
xevent.xselection.selection =
theEvent->xselectionrequest.selection;
xevent.xselection.target =
theEvent->xselectionrequest.target;
xevent.xselection.property = (! RequestFilled) ? None
: theEvent->xselectionrequest.property ;
xevent.xselection.time =
theEvent->xselectionrequest.time;
if (0 == XSendEvent(x_display,
xevent.xselection.requestor, False, 0, &xevent))
{
WriteExtraErr(
"XSendEvent failed in SelectionRequest");
}
}
break;
case SelectionClear:
if (theEvent->xselectionclear.window != my_main_wind) {
WriteExtraErr(
"Got SelectionClear for some other window");
} else {
#if MyDbgEvents
dbglog_writeln("- event - SelectionClear");
WriteDbgAtom("selection",
theEvent->xselectionclear.selection);
#endif
if (theEvent->xselectionclear.selection ==
MyXA_CLIPBOARD)
{
FreeMyClipBuffer();
}
}
break;
#endif
#if EnableDragDrop
case SelectionNotify:
if (theEvent->xselection.requestor != my_main_wind) {
WriteExtraErr(
"Got SelectionNotify for some other window");
} else {
#if MyDbgEvents
dbglog_writeln("- event - SelectionNotify");
WriteDbgAtom("selection",
theEvent->xselection.selection);
WriteDbgAtom("target", theEvent->xselection.target);
WriteDbgAtom("property", theEvent->xselection.property);
#endif
if (theEvent->xselection.selection == MyXA_DndSelection)
{
<API key>(theEvent);
} else {
WriteExtraErr(
"Got Unknown selection in SelectionNotify");
}
}
break;
#endif
case ClientMessage:
if (theEvent->xclient.window != my_main_wind) {
WriteExtraErr(
"Got ClientMessage for some other window");
} else {
#if MyDbgEvents
dbglog_writeln("- event - ClientMessage");
WriteDbgAtom("message_type",
theEvent->xclient.message_type);
#endif
#if EnableDragDrop
if (theEvent->xclient.message_type == MyXA_DndEnter) {
/* printf("Got XdndEnter\n"); */
} else if (theEvent->xclient.message_type ==
MyXA_DndLeave)
{
/* printf("Got XdndLeave\n"); */
} else if (theEvent->xclient.message_type ==
MyXA_DndPosition)
{
<API key>(theEvent);
} else if (theEvent->xclient.message_type ==
MyXA_DndDrop)
{
<API key>(theEvent);
} else
#endif
{
if ((32 == theEvent->xclient.format) &&
(theEvent->xclient.data.l[0] == MyXA_DeleteW))
{
/*
I would think that should test that
WM_PROTOCOLS == message_type
but none of the other programs I looked
at did.
*/
RequestMacOff = trueblnr;
}
}
}
break;
case FocusIn:
if (theEvent->xfocus.window != my_main_wind) {
WriteExtraErr("Got FocusIn for some other window");
} else {
#if MyDbgEvents
dbglog_writeln("- event - FocusIn");
#endif
gTrueBackgroundFlag = falseblnr;
#if UseMotionEvents
CheckMouseState();
/*
Doesn't help on x11 for OS X,
can't get new mouse position
in any fashion until mouse moves.
*/
#endif
}
break;
case FocusOut:
if (theEvent->xfocus.window != my_main_wind) {
WriteExtraErr("Got FocusOut for some other window");
} else {
#if MyDbgEvents
dbglog_writeln("- event - FocusOut");
#endif
gTrueBackgroundFlag = trueblnr;
}
break;
default:
break;
}
}
LOCALVAR int my_argc;
LOCALVAR char **my_argv;
LOCALVAR char *display_name = NULL;
LOCALFUNC blnr Screen_Init(void)
{
Window rootwin;
int screen;
Colormap Xcmap;
Visual *Xvisual;
x_display = XOpenDisplay(display_name);
if (NULL == x_display) {
fprintf(stderr, "Cannot connect to X server.\n");
return falseblnr;
}
screen = DefaultScreen(x_display);
rootwin = XRootWindow(x_display, screen);
Xcmap = DefaultColormap(x_display, screen);
Xvisual = DefaultVisual(x_display, screen);
LoadMyXA();
XParseColor(x_display, Xcmap, "#000000", &x_black);
if (! XAllocColor(x_display, Xcmap, &x_black)) {
WriteExtraErr("XParseColor black fails");
}
XParseColor(x_display, Xcmap, "#ffffff", &x_white);
if (! XAllocColor(x_display, Xcmap, &x_white)) {
WriteExtraErr("XParseColor white fails");
}
if (! CreateMyBlankCursor(rootwin)) {
return falseblnr;
}
#if ! UseColorImage
my_image = XCreateImage(x_display, Xvisual, 1, XYBitmap, 0,
NULL /* (char *)image_Mem1 */,
vMacScreenWidth, vMacScreenHeight, 32,
<API key>);
if (NULL == my_image) {
fprintf(stderr, "XCreateImage failed.\n");
return falseblnr;
}
#if 0
fprintf(stderr, "bitmap_bit_order = %d\n",
(int)my_image->bitmap_bit_order);
fprintf(stderr, "byte_order = %d\n", (int)my_image->byte_order);
#endif
my_image->bitmap_bit_order = MSBFirst;
my_image->byte_order = MSBFirst;
#endif
#if UseColorImage
my_image = XCreateImage(x_display, Xvisual, 24, ZPixmap, 0,
NULL /* (char *)image_Mem1 */,
vMacScreenWidth, vMacScreenHeight, 32,
4 * (ui5r)vMacScreenWidth);
if (NULL == my_image) {
fprintf(stderr, "XCreateImage Color failed.\n");
return falseblnr;
}
#if 0
fprintf(stderr, "DefaultDepth = %d\n",
(int)DefaultDepth(x_display, screen));
fprintf(stderr, "MSBFirst = %d\n", (int)MSBFirst);
fprintf(stderr, "LSBFirst = %d\n", (int)LSBFirst);
fprintf(stderr, "bitmap_bit_order = %d\n",
(int)my_image->bitmap_bit_order);
fprintf(stderr, "byte_order = %d\n",
(int)my_image->byte_order);
fprintf(stderr, "bitmap_unit = %d\n",
(int)my_image->bitmap_unit);
fprintf(stderr, "bits_per_pixel = %d\n",
(int)my_image->bits_per_pixel);
fprintf(stderr, "red_mask = %d\n",
(int)my_image->red_mask);
fprintf(stderr, "green_mask = %d\n",
(int)my_image->green_mask);
fprintf(stderr, "blue_mask = %d\n",
(int)my_image->blue_mask);
#endif
#endif /* UseColorImage */
#if EnableMagnify && (! UseColorImage)
my_Scaled_image = XCreateImage(x_display, Xvisual,
1, XYBitmap, 0,
NULL /* (char *)image_Mem1 */,
vMacScreenWidth * MyWindowScale,
vMacScreenHeight * MyWindowScale,
32, <API key> * MyWindowScale);
if (NULL == my_Scaled_image) {
fprintf(stderr, "XCreateImage failed.\n");
return falseblnr;
}
my_Scaled_image->bitmap_bit_order = MSBFirst;
my_Scaled_image->byte_order = MSBFirst;
#endif
#if EnableMagnify && UseColorImage
my_Scaled_image = XCreateImage(x_display, Xvisual,
24, ZPixmap, 0,
NULL /* (char *)image_Mem1 */,
vMacScreenWidth * MyWindowScale,
vMacScreenHeight * MyWindowScale,
32, 4 * (ui5r)vMacScreenWidth * MyWindowScale);
if (NULL == my_Scaled_image) {
fprintf(stderr, "XCreateImage Scaled failed.\n");
return falseblnr;
}
#endif
#if 0 != vMacScreenDepth
ColorModeWorks = trueblnr;
#endif
DisableKeyRepeat();
return trueblnr;
}
LOCALPROC CloseMainWindow(void)
{
if (my_gc != NULL) {
XFreeGC(x_display, my_gc);
my_gc = NULL;
}
if (my_main_wind) {
XDestroyWindow(x_display, my_main_wind);
my_main_wind = 0;
}
}
enum {
kMagStateNormal,
#if EnableMagnify
kMagStateMagnifgy,
#endif
kNumMagStates
};
#define kMagStateAuto kNumMagStates
#if MayNotFullScreen
LOCALVAR int CurWinIndx;
LOCALVAR blnr HavePositionWins[kNumMagStates];
LOCALVAR int WinPositionWinsH[kNumMagStates];
LOCALVAR int WinPositionWinsV[kNumMagStates];
#endif
#if EnableRecreateW
LOCALPROC ZapMyWState(void)
{
my_main_wind = 0;
my_gc = NULL;
}
#endif
LOCALFUNC blnr CreateMainWindow(void)
{
Window rootwin;
int screen;
int xr;
int yr;
unsigned int dr;
unsigned int wr;
unsigned int hr;
unsigned int bwr;
Window rr;
int leftPos;
int topPos;
#if MayNotFullScreen
int WinIndx;
#endif
#if EnableDragDrop
long int xdnd_version = 5;
#endif
int NewWindowHeight = vMacScreenHeight;
int NewWindowWidth = vMacScreenWidth;
/* Get connection to X Server */
screen = DefaultScreen(x_display);
rootwin = XRootWindow(x_display, screen);
XGetGeometry(x_display, rootwin,
&rr, &xr, &yr, &wr, &hr, &bwr, &dr);
#if EnableMagnify
if (UseMagnify) {
NewWindowHeight *= MyWindowScale;
NewWindowWidth *= MyWindowScale;
}
#endif
if (wr > NewWindowWidth) {
leftPos = (wr - NewWindowWidth) / 2;
} else {
leftPos = 0;
}
if (hr > NewWindowHeight) {
topPos = (hr - NewWindowHeight) / 2;
} else {
topPos = 0;
}
#if VarFullScreen
if (UseFullScreen)
#endif
#if MayFullScreen
{
ViewHSize = wr;
ViewVSize = hr;
#if EnableMagnify
if (UseMagnify) {
ViewHSize /= MyWindowScale;
ViewVSize /= MyWindowScale;
}
#endif
if (ViewHSize >= vMacScreenWidth) {
ViewHStart = 0;
ViewHSize = vMacScreenWidth;
} else {
ViewHSize &= ~ 1;
}
if (ViewVSize >= vMacScreenHeight) {
ViewVStart = 0;
ViewVSize = vMacScreenHeight;
} else {
ViewVSize &= ~ 1;
}
}
#endif
#if VarFullScreen
if (! UseFullScreen)
#endif
#if MayNotFullScreen
{
#if EnableMagnify
if (UseMagnify) {
WinIndx = kMagStateMagnifgy;
} else
#endif
{
WinIndx = kMagStateNormal;
}
if (! HavePositionWins[WinIndx]) {
WinPositionWinsH[WinIndx] = leftPos;
WinPositionWinsV[WinIndx] = topPos;
HavePositionWins[WinIndx] = trueblnr;
} else {
leftPos = WinPositionWinsH[WinIndx];
topPos = WinPositionWinsV[WinIndx];
}
}
#endif
#if VarFullScreen
if (UseFullScreen)
#endif
#if MayFullScreen
{
<API key> xattr;
xattr.override_redirect = True;
xattr.background_pixel = x_black.pixel;
xattr.border_pixel = x_white.pixel;
my_main_wind = XCreateWindow(x_display, rr,
0, 0, wr, hr, 0,
CopyFromParent, /* depth */
InputOutput, /* class */
CopyFromParent, /* visual */
CWOverrideRedirect | CWBackPixel | CWBorderPixel,
/* valuemask */
&xattr /* attributes */);
}
#endif
#if VarFullScreen
else
#endif
#if MayNotFullScreen
{
my_main_wind = XCreateSimpleWindow(x_display, rootwin,
leftPos,
topPos,
NewWindowWidth, NewWindowHeight, 4,
x_white.pixel,
x_black.pixel);
}
#endif
if (! my_main_wind) {
WriteExtraErr("XCreateSimpleWindow failed.");
return falseblnr;
} else {
char *win_name =
(NULL != n_arg) ? n_arg : (
#if CanGetAppPath
(NULL != app_name) ? app_name :
#endif
kStrAppName);
XSelectInput(x_display, my_main_wind,
ExposureMask | KeyPressMask | KeyReleaseMask
| ButtonPressMask | ButtonReleaseMask
#if UseMotionEvents
| PointerMotionMask | EnterWindowMask | LeaveWindowMask
#endif
| FocusChangeMask);
XStoreName(x_display, my_main_wind, win_name);
XSetIconName(x_display, my_main_wind, win_name);
{
XClassHint *hints = XAllocClassHint();
if (hints) {
hints->res_name = "minivmac";
hints->res_class = "minivmac";
XSetClassHint(x_display, my_main_wind, hints);
XFree(hints);
}
}
{
XWMHints *hints = XAllocWMHints();
if (hints) {
hints->input = True;
hints->initial_state = NormalState;
hints->flags = InputHint | StateHint;
XSetWMHints(x_display, my_main_wind, hints);
XFree(hints);
}
}
XSetCommand(x_display, my_main_wind, my_argv, my_argc);
/* let us handle a click on the close box */
XSetWMProtocols(x_display, my_main_wind, &MyXA_DeleteW, 1);
#if EnableDragDrop
XChangeProperty (x_display, my_main_wind, MyXA_DndAware,
XA_ATOM, 32, PropModeReplace,
(unsigned char *) &xdnd_version, 1);
#endif
my_gc = XCreateGC(x_display, my_main_wind, 0, NULL);
if (NULL == my_gc) {
WriteExtraErr("XCreateGC failed.");
return falseblnr;
}
XSetState(x_display, my_gc, x_black.pixel, x_white.pixel,
GXcopy, AllPlanes);
#if VarFullScreen
if (! UseFullScreen)
#endif
#if MayNotFullScreen
{
XSizeHints *hints = XAllocSizeHints();
if (hints) {
hints->min_width = NewWindowWidth;
hints->max_width = NewWindowWidth;
hints->min_height = NewWindowHeight;
hints->max_height = NewWindowHeight;
/*
Try again to say where the window ought to go.
I've seen this described as obsolete, but it
seems to work on all x implementations tried
so far, and nothing else does.
*/
hints->x = leftPos;
hints->y = topPos;
hints->width = NewWindowWidth;
hints->height = NewWindowHeight;
hints->flags = PMinSize | PMaxSize | PPosition | PSize;
XSetWMNormalHints(x_display, my_main_wind, hints);
XFree(hints);
}
}
#endif
#if VarFullScreen
if (UseFullScreen)
#endif
#if MayFullScreen
{
hOffset = leftPos;
vOffset = topPos;
}
#endif
DisconnectKeyCodes3();
/* since will lose keystrokes to old window */
#if MayNotFullScreen
CurWinIndx = WinIndx;
#endif
XMapRaised(x_display, my_main_wind);
#if 0
XSync(x_display, 0);
#endif
#if 0
/*
This helps in Red Hat 9 to get the new window
activated, and I've seen other programs
do similar things.
*/
/*
In current scheme, haven't closed old window
yet. If old window full screen, never receive
expose event for new one.
*/
{
XEvent event;
do {
XNextEvent(x_display, &event);
HandleTheEvent(&event);
} while (! ((Expose == event.type)
&& (event.xexpose.window == my_main_wind)));
}
#endif
NeedFinishOpen1 = trueblnr;
NeedFinishOpen2 = trueblnr;
return trueblnr;
}
}
#if MayFullScreen
LOCALVAR blnr GrabMachine = falseblnr;
#endif
#if MayFullScreen
LOCALPROC GrabTheMachine(void)
{
#if EnableFSMouseMotion
<API key>();
#endif
#if GrabKeysFullScreen
MyGrabKeyboard();
#endif
}
#endif
#if MayFullScreen
LOCALPROC UngrabMachine(void)
{
#if EnableFSMouseMotion
StopSaveMouseMotion();
#endif
#if GrabKeysFullScreen
MyUnGrabKeyboard();
#endif
}
#endif
#if EnableRecreateW
struct MyWState {
Window f_my_main_wind;
GC f_my_gc;
#if MayFullScreen
short f_hOffset;
short f_vOffset;
ui4r f_ViewHSize;
ui4r f_ViewVSize;
ui4r f_ViewHStart;
ui4r f_ViewVStart;
#endif
#if VarFullScreen
blnr f_UseFullScreen;
#endif
#if EnableMagnify
blnr f_UseMagnify;
#endif
};
typedef struct MyWState MyWState;
#endif
#if EnableRecreateW
LOCALPROC GetMyWState(MyWState *r)
{
r->f_my_main_wind = my_main_wind;
r->f_my_gc = my_gc;
#if MayFullScreen
r->f_hOffset = hOffset;
r->f_vOffset = vOffset;
r->f_ViewHSize = ViewHSize;
r->f_ViewVSize = ViewVSize;
r->f_ViewHStart = ViewHStart;
r->f_ViewVStart = ViewVStart;
#endif
#if VarFullScreen
r->f_UseFullScreen = UseFullScreen;
#endif
#if EnableMagnify
r->f_UseMagnify = UseMagnify;
#endif
}
#endif
#if EnableRecreateW
LOCALPROC SetMyWState(MyWState *r)
{
my_main_wind = r->f_my_main_wind;
my_gc = r->f_my_gc;
#if MayFullScreen
hOffset = r->f_hOffset;
vOffset = r->f_vOffset;
ViewHSize = r->f_ViewHSize;
ViewVSize = r->f_ViewVSize;
ViewHStart = r->f_ViewHStart;
ViewVStart = r->f_ViewVStart;
#endif
#if VarFullScreen
UseFullScreen = r->f_UseFullScreen;
#endif
#if EnableMagnify
UseMagnify = r->f_UseMagnify;
#endif
}
#endif
#if EnableRecreateW
LOCALVAR blnr WantRestoreCursPos = falseblnr;
LOCALVAR ui4b RestoreMouseH;
LOCALVAR ui4b RestoreMouseV;
#endif
#if EnableRecreateW
LOCALFUNC blnr ReCreateMainWindow(void)
{
MyWState old_state;
MyWState new_state;
#if <API key>
blnr OwnClipboard = falseblnr;
#endif
if (HaveCursorHidden) {
WantRestoreCursPos = trueblnr;
RestoreMouseH = CurMouseH;
RestoreMouseV = CurMouseV;
}
ForceShowCursor(); /* hide/show cursor api is per window */
#if MayNotFullScreen
#if VarFullScreen
if (! UseFullScreen)
#endif
if (my_main_wind)
if (! NeedFinishOpen2)
{
/* save old position */
int xr;
int yr;
unsigned int dr;
unsigned int wr;
unsigned int hr;
unsigned int bwr;
Window rr;
Window rr2;
/* Get connection to X Server */
int screen = DefaultScreen(x_display);
Window rootwin = XRootWindow(x_display, screen);
XGetGeometry(x_display, rootwin,
&rr, &xr, &yr, &wr, &hr, &bwr, &dr);
/*
Couldn't reliably find out where window
is now, due to what seem to be some
broken X implementations, and so instead
track how far window has moved.
*/
XSync(x_display, 0);
if (<API key>(x_display, my_main_wind, rootwin,
0, 0, &xr, &yr, &rr2))
{
int newposh =
WinPositionWinsH[CurWinIndx] + (xr - SavedTransH);
int newposv =
WinPositionWinsV[CurWinIndx] + (yr - SavedTransV);
if ((newposv > 0) && (newposv < hr) && (newposh < wr)) {
WinPositionWinsH[CurWinIndx] = newposh;
WinPositionWinsV[CurWinIndx] = newposv;
SavedTransH = xr;
SavedTransV = yr;
}
}
}
#endif
#if MayFullScreen
if (GrabMachine) {
GrabMachine = falseblnr;
UngrabMachine();
}
#endif
GetMyWState(&old_state);
ZapMyWState();
#if EnableMagnify
UseMagnify = WantMagnify;
#endif
#if VarFullScreen
UseFullScreen = WantFullScreen;
#endif
ColorTransValid = falseblnr;
if (! CreateMainWindow()) {
CloseMainWindow();
SetMyWState(&old_state);
/* avoid retry */
#if VarFullScreen
WantFullScreen = UseFullScreen;
#endif
#if EnableMagnify
WantMagnify = UseMagnify;
#endif
return falseblnr;
} else {
GetMyWState(&new_state);
SetMyWState(&old_state);
#if <API key>
if (my_main_wind) {
if (XGetSelectionOwner(x_display, MyXA_CLIPBOARD) ==
my_main_wind)
{
OwnClipboard = trueblnr;
}
}
#endif
CloseMainWindow();
SetMyWState(&new_state);
#if <API key>
if (OwnClipboard) {
XSetSelectionOwner(x_display, MyXA_CLIPBOARD,
my_main_wind, CurrentTime);
}
#endif
}
return trueblnr;
}
#endif
#if VarFullScreen && EnableMagnify
enum {
kWinStateWindowed,
#if EnableMagnify
kWinStateFullScreen,
#endif
kNumWinStates
};
#endif
#if VarFullScreen && EnableMagnify
LOCALVAR int WinMagStates[kNumWinStates];
#endif
LOCALPROC ZapWinStateVars(void)
{
#if MayNotFullScreen
{
int i;
for (i = 0; i < kNumMagStates; ++i) {
HavePositionWins[i] = falseblnr;
}
}
#endif
#if VarFullScreen && EnableMagnify
{
int i;
for (i = 0; i < kNumWinStates; ++i) {
WinMagStates[i] = kMagStateAuto;
}
}
#endif
}
#if VarFullScreen
LOCALPROC <API key>(void)
{
WantFullScreen = ! WantFullScreen;
#if EnableMagnify
{
int OldWinState =
UseFullScreen ? kWinStateFullScreen : kWinStateWindowed;
int OldMagState =
UseMagnify ? kMagStateMagnifgy : kMagStateNormal;
int NewWinState =
WantFullScreen ? kWinStateFullScreen : kWinStateWindowed;
int NewMagState = WinMagStates[NewWinState];
WinMagStates[OldWinState] = OldMagState;
if (kMagStateAuto != NewMagState) {
WantMagnify = (kMagStateMagnifgy == NewMagState);
} else {
WantMagnify = falseblnr;
if (WantFullScreen) {
Window rootwin;
int xr;
int yr;
unsigned int dr;
unsigned int wr;
unsigned int hr;
unsigned int bwr;
Window rr;
rootwin =
XRootWindow(x_display, DefaultScreen(x_display));
XGetGeometry(x_display, rootwin,
&rr, &xr, &yr, &wr, &hr, &bwr, &dr);
if ((wr >= vMacScreenWidth * MyWindowScale)
&& (hr >= vMacScreenHeight * MyWindowScale)
)
{
WantMagnify = trueblnr;
}
}
}
}
#endif
}
#endif
LOCALPROC LeaveBackground(void)
{
ReconnectKeyCodes3();
DisableKeyRepeat();
}
LOCALPROC EnterBackground(void)
{
RestoreKeyRepeat();
DisconnectKeyCodes3();
ForceShowCursor();
}
LOCALPROC LeaveSpeedStopped(void)
{
#if MySoundEnabled
MySound_Start();
#endif
StartUpTimeAdjust();
}
LOCALPROC EnterSpeedStopped(void)
{
#if MySoundEnabled
MySound_Stop();
#endif
}
LOCALPROC CheckForSavedTasks(void)
{
if (MyEvtQNeedRecover) {
MyEvtQNeedRecover = falseblnr;
/* attempt cleanup, MyEvtQNeedRecover may get set again */
<API key>();
}
if (NeedFinishOpen2 && ! NeedFinishOpen1) {
NeedFinishOpen2 = falseblnr;
#if VarFullScreen
if (UseFullScreen)
#endif
#if MayFullScreen
{
XSetInputFocus(x_display, my_main_wind,
RevertToPointerRoot, CurrentTime);
}
#endif
#if VarFullScreen
else
#endif
#if MayNotFullScreen
{
Window rr;
int screen = DefaultScreen(x_display);
Window rootwin = XRootWindow(x_display, screen);
#if 0
/*
This doesn't work right in Red Hat 6, and may not
be needed anymore, now that using PPosition hint.
*/
XMoveWindow(x_display, my_main_wind,
leftPos, topPos);
/*
Needed after XMapRaised, because some window
managers will apparently ignore where the
window was asked to be put.
*/
#endif
XSync(x_display, 0);
/*
apparently, <API key> can be inaccurate
without this
*/
<API key>(x_display, my_main_wind, rootwin,
0, 0, &SavedTransH, &SavedTransV, &rr);
}
#endif
#if EnableRecreateW
if (WantRestoreCursPos) {
#if EnableFSMouseMotion
if (! HaveMouseMotion)
#endif
{
(void) MyMoveMouse(RestoreMouseH, RestoreMouseV);
WantCursorHidden = trueblnr;
}
WantRestoreCursPos = falseblnr;
}
#endif
}
#if EnableFSMouseMotion
if (HaveMouseMotion) {
MyMouseConstrain();
}
#endif
if (RequestMacOff) {
RequestMacOff = falseblnr;
if (AnyDiskInserted()) {
MacMsgOverride(<API key>,
<API key>);
} else {
ForceMacOff = trueblnr;
}
}
if (ForceMacOff) {
return;
}
if (gTrueBackgroundFlag != gBackgroundFlag) {
gBackgroundFlag = gTrueBackgroundFlag;
if (gTrueBackgroundFlag) {
EnterBackground();
} else {
LeaveBackground();
}
}
if (CurSpeedStopped != (SpeedStopped ||
(gBackgroundFlag && ! RunInBackground
#if EnableAutoSlow && 0
&& (QuietSubTicks >= 4092)
#endif
)))
{
CurSpeedStopped = ! CurSpeedStopped;
if (CurSpeedStopped) {
EnterSpeedStopped();
} else {
LeaveSpeedStopped();
}
}
#if MayFullScreen
if (gTrueBackgroundFlag
#if VarFullScreen
&& WantFullScreen
#endif
)
{
/*
Since often get here on Ubuntu Linux 5.10
running on a slow machine (emulated) when
attempt to enter full screen, don't abort
full screen, but try to fix it.
*/
#if 0
<API key>();
#else
XRaiseWindow(x_display, my_main_wind);
XSetInputFocus(x_display, my_main_wind,
RevertToPointerRoot, CurrentTime);
#endif
}
#endif
#if EnableRecreateW
if (0
#if EnableMagnify
|| (UseMagnify != WantMagnify)
#endif
#if VarFullScreen
|| (UseFullScreen != WantFullScreen)
#endif
)
{
(void) ReCreateMainWindow();
}
#endif
#if MayFullScreen
if (GrabMachine != (
#if VarFullScreen
UseFullScreen &&
#endif
! (gTrueBackgroundFlag || CurSpeedStopped)))
{
GrabMachine = ! GrabMachine;
if (GrabMachine) {
GrabTheMachine();
} else {
UngrabMachine();
}
}
#endif
#if IncludeSonyNew
if (vSonyNewDiskWanted) {
#if IncludeSonyNameNew
if (vSonyNewDiskName != NotAPbuf) {
ui3p NewDiskNameDat;
if (<API key>(vSonyNewDiskName, trueblnr,
&NewDiskNameDat))
{
MakeNewDisk(vSonyNewDiskSize, (char *)NewDiskNameDat);
free(NewDiskNameDat);
}
PbufDispose(vSonyNewDiskName);
vSonyNewDiskName = NotAPbuf;
} else
#endif
{
<API key>(vSonyNewDiskSize);
}
vSonyNewDiskWanted = falseblnr;
/* must be done after may have gotten disk */
}
#endif
if ((nullpr != SavedBriefMsg) & ! MacMsgDisplayed) {
MacMsgDisplayOn();
}
if (NeedWholeScreenDraw) {
NeedWholeScreenDraw = falseblnr;
ScreenChangedAll();
}
#if NeedRequestIthDisk
if (0 != RequestIthDisk) {
Sony_InsertIth(RequestIthDisk);
RequestIthDisk = 0;
}
#endif
if (HaveCursorHidden != (WantCursorHidden
&& ! (gTrueBackgroundFlag || CurSpeedStopped)))
{
HaveCursorHidden = ! HaveCursorHidden;
if (HaveCursorHidden) {
XDefineCursor(x_display, my_main_wind, blankCursor);
} else {
XUndefineCursor(x_display, my_main_wind);
}
}
}
LOCALFUNC blnr ScanCommandLine(void)
{
char *pa;
int i = 1;
label_retry:
if (i < my_argc) {
pa = my_argv[i++];
if ('-' == pa[0]) {
if ((0 == strcmp(pa, "--display"))
|| (0 == strcmp(pa, "-display")))
{
if (i < my_argc) {
display_name = my_argv[i++];
goto label_retry;
}
} else
if ((0 == strcmp(pa, "--rom"))
|| (0 == strcmp(pa, "-r")))
{
if (i < my_argc) {
rom_path = my_argv[i++];
goto label_retry;
}
} else
if (0 == strcmp(pa, "-n"))
{
if (i < my_argc) {
n_arg = my_argv[i++];
goto label_retry;
}
} else
if (0 == strcmp(pa, "-d"))
{
if (i < my_argc) {
d_arg = my_argv[i++];
goto label_retry;
}
} else
#ifndef UsingAlsa
#define UsingAlsa 0
#endif
#if UsingAlsa
if ((0 == strcmp(pa, "--alsadev"))
|| (0 == strcmp(pa, "-alsadev")))
{
if (i < my_argc) {
alsadev_name = my_argv[i++];
goto label_retry;
}
} else
#endif
#if 0
if (0 == strcmp(pa, "-l")) {
SpeedValue = 0;
goto label_retry;
} else
#endif
{
MacMsg(kStrBadArgTitle, kStrBadArgMessage, falseblnr);
}
} else {
(void) Sony_Insert1(pa, falseblnr);
goto label_retry;
}
}
return trueblnr;
}
GLOBALOSGLUPROC <API key>(void)
{
#if EnableFSMouseMotion
if (HaveMouseMotion) {
AutoScrollScreen();
}
#endif
<API key>();
XFlush(x_display);
}
GLOBALOSGLUFUNC blnr ExtraTimeNotOver(void)
{
<API key>();
return TrueEmulatedTime == OnTrueTime;
}
LOCALPROC WaitForTheNextEvent(void)
{
XEvent event;
XNextEvent(x_display, &event);
HandleTheEvent(&event);
}
LOCALPROC <API key>(void)
{
int i = 10;
while ((XEventsQueued(x_display, QueuedAfterReading) > 0)
&& (--i >= 0))
{
WaitForTheNextEvent();
}
}
GLOBALOSGLUPROC WaitForNextTick(void)
{
label_retry:
<API key>();
CheckForSavedTasks();
if (ForceMacOff) {
return;
}
if (CurSpeedStopped) {
<API key>();
WaitForTheNextEvent();
goto label_retry;
}
if (ExtraTimeNotOver()) {
struct timespec rqt;
struct timespec rmt;
si5b TimeDiff = GetTimeDiff();
if (TimeDiff < 0) {
rqt.tv_sec = 0;
rqt.tv_nsec = (- TimeDiff) * 1000;
(void) nanosleep(&rqt, &rmt);
}
goto label_retry;
}
if (CheckDateTime()) {
#if MySoundEnabled
<API key>();
#endif
#if EnableDemoMsg
<API key>();
#endif
}
if ((! gBackgroundFlag)
#if UseMotionEvents
&& (! CaughtMouse)
#endif
)
{
CheckMouseState();
}
OnTrueTime = TrueEmulatedTime;
#if dbglog_TimeStuff
dbglog_writelnNum("WaitForNextTick, OnTrueTime", OnTrueTime);
#endif
}
#include "PROGMAIN.h"
LOCALPROC ZapOSGLUVars(void)
{
InitDrives();
ZapWinStateVars();
}
LOCALPROC ReserveAllocAll(void)
{
#if dbglog_HAVE
dbglog_ReserveAlloc();
#endif
<API key>(&ROM, kROM_Size, 5, falseblnr);
<API key>(&screencomparebuff,
vMacScreenNumBytes, 5, trueblnr);
#if UseControlKeys
<API key>(&CntrlDisplayBuff,
vMacScreenNumBytes, 5, falseblnr);
#endif
#if WantScalingBuff
<API key>(&ScalingBuff,
ScalingBuffsz, 5, falseblnr);
#endif
#if WantScalingTabl
<API key>(&ScalingTabl,
ScalingTablsz, 5, falseblnr);
#endif
#if MySoundEnabled
<API key>((ui3p *)&TheSoundBuffer,
dbhBufferSize, 5, falseblnr);
#endif
<API key>();
}
LOCALFUNC blnr AllocMyMemory(void)
{
uimr n;
blnr IsOk = falseblnr;
ReserveAllocOffset = 0;
<API key> = nullpr;
ReserveAllocAll();
n = ReserveAllocOffset;
<API key> = (ui3p)calloc(1, n);
if (NULL == <API key>) {
MacMsg(kStrOutOfMemTitle, kStrOutOfMemMessage, trueblnr);
} else {
ReserveAllocOffset = 0;
ReserveAllocAll();
if (n != ReserveAllocOffset) {
/* oops, program error */
} else {
IsOk = trueblnr;
}
}
return IsOk;
}
LOCALPROC UnallocMyMemory(void)
{
if (nullpr != <API key>) {
free((char *)<API key>);
}
}
#if HaveAppPathLink
LOCALFUNC blnr ReadLink_Alloc(char *path, char **r)
{
/*
This should work to find size:
struct stat r;
if (lstat(path, &r) != -1) {
r = r.st_size;
IsOk = trueblnr;
}
But observed to return 0 in Ubuntu 10.04 x86-64
*/
char *s;
int sz;
char *p;
blnr IsOk = falseblnr;
size_t s_alloc = 256;
label_retry:
s = (char *)malloc(s_alloc);
if (NULL == s) {
fprintf(stderr, "malloc failed.\n");
} else {
sz = readlink(path, s, s_alloc);
if ((sz < 0) || (sz >= s_alloc)) {
free(s);
if (sz == s_alloc) {
s_alloc <<= 1;
goto label_retry;
} else {
fprintf(stderr, "readlink failed.\n");
}
} else {
p = (char *)malloc(sz + 1);
if (NULL == p) {
fprintf(stderr, "malloc failed.\n");
} else {
(void) memcpy(p, s, sz);
p[sz] = 0;
*r = p;
IsOk = trueblnr;
}
free(s);
}
}
return IsOk;
}
#endif
#if HaveSysctlPath
LOCALFUNC blnr <API key>(char **r)
{
size_t s_alloc;
char *s;
int mib[] = {
CTL_KERN,
KERN_PROC,
KERN_PROC_PATHNAME,
-1
};
blnr IsOk = falseblnr;
if (0 != sysctl(mib, sizeof(mib) / sizeof(int),
NULL, &s_alloc, NULL, 0))
{
fprintf(stderr, "sysctl failed.\n");
} else {
s = (char *)malloc(s_alloc);
if (NULL == s) {
fprintf(stderr, "malloc failed.\n");
} else {
if (0 != sysctl(mib, sizeof(mib) / sizeof(int),
s, &s_alloc, NULL, 0))
{
fprintf(stderr, "sysctl 2 failed.\n");
} else {
*r = s;
IsOk = trueblnr;
}
if (! IsOk) {
free(s);
}
}
}
return IsOk;
}
#endif
#if CanGetAppPath
LOCALFUNC blnr Path2ParentAndName(char *path,
char **parent, char **name)
{
blnr IsOk = falseblnr;
char *t = strrchr(path, '/');
if (NULL == t) {
fprintf(stderr, "no directory.\n");
} else {
int par_sz = t - path;
char *par = (char *)malloc(par_sz + 1);
if (NULL == par) {
fprintf(stderr, "malloc failed.\n");
} else {
(void) memcpy(par, path, par_sz);
par[par_sz] = 0;
{
int s_sz = strlen(path);
int child_sz = s_sz - par_sz - 1;
char *child = (char *)malloc(child_sz + 1);
if (NULL == child) {
fprintf(stderr, "malloc failed.\n");
} else {
(void) memcpy(child, t + 1, child_sz);
child[child_sz] = 0;
*name = child;
IsOk = trueblnr;
/* free(child); */
}
}
if (! IsOk) {
free(par);
} else {
*parent = par;
}
}
}
return IsOk;
}
#endif
#if CanGetAppPath
LOCALFUNC blnr InitWhereAmI(void)
{
char *s;
if (!
#if HaveAppPathLink
ReadLink_Alloc(TheAppPathLink, &s)
#endif
#if HaveSysctlPath
<API key>(&s)
#endif
)
{
fprintf(stderr, "InitWhereAmI fails.\n");
} else {
if (! Path2ParentAndName(s, &app_parent, &app_name)) {
fprintf(stderr, "Path2ParentAndName fails.\n");
} else {
/*
fprintf(stderr, "parent = %s.\n", app_parent);
fprintf(stderr, "name = %s.\n", app_name);
*/
}
free(s);
}
return trueblnr; /* keep going regardless */
}
#endif
#if CanGetAppPath
LOCALPROC UninitWhereAmI(void)
{
MyMayFree(app_parent);
MyMayFree(app_name);
}
#endif
LOCALFUNC blnr InitOSGLU(void)
{
if (AllocMyMemory())
#if CanGetAppPath
if (InitWhereAmI())
#endif
#if dbglog_HAVE
if (dbglog_open())
#endif
if (ScanCommandLine())
if (LoadMacRom())
if (LoadInitialImages())
#if UseActvCode
if (ActvCodeInit())
#endif
if (InitLocationDat())
#if MySoundEnabled
if (MySound_Init())
#endif
if (Screen_Init())
if (CreateMainWindow())
if (KC2MKCInit())
#if EmLocalTalk
if (EntropyGather())
if (InitLocalTalk())
#endif
if (WaitForRom())
{
return trueblnr;
}
return falseblnr;
}
LOCALPROC UnInitOSGLU(void)
{
if (MacMsgDisplayed) {
MacMsgDisplayOff();
}
#if EmLocalTalk
UnInitLocalTalk();
#endif
RestoreKeyRepeat();
#if MayFullScreen
UngrabMachine();
#endif
#if MySoundEnabled
MySound_Stop();
#endif
#if MySoundEnabled
MySound_UnInit();
#endif
#if <API key>
FreeMyClipBuffer();
#endif
#if IncludePbufs
UnInitPbufs();
#endif
UnInitDrives();
ForceShowCursor();
if (blankCursor != None) {
XFreeCursor(x_display, blankCursor);
}
if (my_image != NULL) {
XDestroyImage(my_image);
}
#if EnableMagnify
if (my_Scaled_image != NULL) {
XDestroyImage(my_Scaled_image);
}
#endif
CloseMainWindow();
if (x_display != NULL) {
XCloseDisplay(x_display);
}
#if dbglog_HAVE
dbglog_close();
#endif
#if CanGetAppPath
UninitWhereAmI();
#endif
UnallocMyMemory();
CheckSavedMacMsg();
}
int main(int argc, char **argv)
{
my_argc = argc;
my_argv = argv;
ZapOSGLUVars();
if (InitOSGLU()) {
ProgramMain();
}
UnInitOSGLU();
return 0;
} |
using System;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Windows.Media.Imaging;
namespace Sdl.Community.TuToTm.UiHelpers
{
[ValueConversion(typeof(System.Drawing.Image), typeof(System.Windows.Media.ImageSource))]
public class <API key> : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return null;
}
var image = (System.Drawing.Image)value;
var memoryStream = new MemoryStream();
var bitmap = new BitmapImage();
bitmap.BeginInit();
image.Save(memoryStream, ImageFormat.Png);
memoryStream.Seek(0, SeekOrigin.Begin);
bitmap.StreamSource = memoryStream;
bitmap.EndInit();
bitmap.Freeze();
return bitmap;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new <API key>();
}
}
} |
.select-custom{padding-top:9px !important; padding-bottom:9px !important;}
.img-bordered{border: 1px solid #F2F2F2; padding: 3px; text-align: center; }
.hidden {display:none !important;}
.highlighted {color: #211922; background-color: #ff0 !important;}
.error {font-weight: 300; color: #f00 !important;}
.clear {clear: both !important;}
.noState:hover {background-color: transparent !important;}
.noState:active {color: #221919 !important;}
.noFloat {float: none !important;}
.floatRight {float: right !important;}
.floatLeft {float: left !important;}
.displayB {display:block !important;}
.displayI {display:inline-block !important;}
.display-table {display: table-cell !important;}
.r{ border:1px solid red !important;}
.dashed{ border-bottom:1px dashed #CCCCCC !important;}
.solid{ border-bottom:1px solid #CCCCCC !important;}
/* .solid-all{ border:1px solid #e3e3e3 !important;}*/
.solid-all{ border:1px solid #e2e2e2 !important;}
.solid-l-all{ border:1px solid #f4f4f4 !important;}
.solid-all-bottom{ border-bottom:1px solid #f4f4f4 !important;}
.bottom-dotted{ border-bottom:1px dotted #e3e3e3 !important;}
.bottom-dashed{ border-bottom:1px dashed #e3e3e3 !important;}
.bottom-solid{ border-bottom:1px solid #e3e3e3 !important;}
.noBorder {border-width: 0 !important;}
.noBorderTop {border-top-width: 0 !important;}
.noBorderRight {border-right-width: 0 !important;}
.noBorderBottom {border-bottom-width: 0 !important;}
.noBorderLeft {border-left-width: 0 !important;}
.noMargin {margin: 0 !important;}
.noMarginTop {margin-top: 0 !important;}
.noMarginRight {margin-right: 0 !important;}
.noMarginBottom {margin-bottom: 0 !important;}
.noMarginLeft {margin-left: 0 !important;}
.fixed {position: fixed !important;}
.absolute {position: absolute !important;}
.relative {position: relative !important;
border-bottom: 1px solid #ccc;
padding-bottom: 25px;}
.noTop{top:5px !important;}
.noRight{right:5px !important;}
.invisible {visibility: hidden !important;}
.noScroll {overflow:hidden !important;}
.noscroll.extraScroll {margin-right: 15px;} /* Extra space on the right for FireFox */
.clearfix:after {clear: both; display: block; height: 0; content: " "; visibility: hidden;}
.bgNone{background:none !important}
.ImgLink {display: block; background-color: #fff;}
.ImgLink:active {background-color: #221919;}
.ImgLink img {display: block; margin: 0 auto;}
.ImgLink:hover img,
.ImgLink:active img {opacity: .9; filter: alpha(opacity=90);}
.colorlight,
.colorlight a {color: #ad9c9c;}
.colorless,
.colorless a {color: #8c7e7e;}
.colormuted,
.colormuted a {color: #524d4d;}
.xRound-lr { -<API key>:0 0 5px 5px; -moz-border-radius: 0 0 5px 5px; border-radius: 0 0 5px 5px; }
.xRound { -<API key>: 5px; -moz-border-radius: 5px; border-radius: 5px; }
.xxRound { -<API key>: 8px; -moz-border-radius: 8px; border-radius: 8px; }
.xxxRound { -<API key>: 10px; -moz-border-radius: 10px; border-radius: 10px; }
.trans{ -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)"; filter: alpha(opacity=30); -moz-opacity: 0.3; -khtml-opacity: 0.3; opacity: 0.3;}
.normal-list{list-style: inside; }
.lower-latin-list {list-style: lower-latin; }
.square-list { list-style: square; }
.number-list {list-style: decimal; }
.none-list { list-style: none; }
.circle-list {list-style: circle;}
.italic { font-style:italic;}
.dP-tb-s{padding-top:5px !important; padding-bottom:5px !important;}
.dP-tb-m{padding-top:10px !important; padding-bottom:10px !important;}
.dP-tb-l{padding-top:15px !important; padding-bottom:15px !important;}
.dP-tb-xl{padding-top:20px !important; padding-bottom:20px !important;}
.dP-lr-s{padding-left:5px !important; padding-right:5px !important;}
.dP-lr-m{padding-left:10px !important; padding-right:10px !important;}
.dPx-lr-l{padding-left:15px !important; padding-right:15px !important;}
.dP-lr-xl{padding-left:20px !important; padding-right:20px !important;}
.dP-all-s{padding:5px !important;}
.dP-all-m{padding:10px !important;}
.dP-all-l{padding:15px !important;}
.dP-all-xl{padding:20px !important;}
.noPadding{padding:0px !important}
.noPadding-left{padding-left:0px !important}
.noPadding-right{padding-right:0px !important}
.noPadding-bottom{padding-bottom:0px !important}
.noPadding-top{padding-top:0px !important}
.noPadding-lg{padding-left:0px !important; padding-right:0px !important}
.tM{margin-top:10px !important;}
.tMx{margin-top:15px !important;}
.tMxx{margin-top:20px !important;}
.tMxxx{margin-top:30px !important;}
.dM-xs{margin-bottom:5px !important;}
.dM{margin-bottom:10px !important;}
.dM5{margin-bottom:5px !important;}
.dMx{margin-bottom:15px !important;}
.dMxx{margin-bottom:20px !important;}
.dMxxx{margin-bottom:30px !important;}
.dM-lg{margin-bottom:60px;}
a,a:hover{text-decoration:none;}
.box-shadow {
-moz-box-shadow: 0px 0px 4px #c0c0c0;
-webkit-box-shadow: 0px 0px 4px #c0c0c0;
box-shadow: 0px 0px 4px #c0c0c0;
-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#c0c0c0')";
filter: progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#c0c0c0');
}
.aCenter{text-align:center !important}
.aLeft{text-align:left !important}
.aRight{text-align:right !important}
.fNormal{font-weight:normal !important}
.lNormal{line-height:normal !important}
.minHeight{min-height:auto !important}
.fColor{color:#fff !important}
.yColor{color:#f8a31f !important}
.dColor{color:#333333 !important}
.bColor{color:#3388d9 !important}
.page-title{font-size:16px; color:#7e7e7e; margin:0; padding:0;}
.page-title-diff{font-size: 26px; font-weight: lighter; border-bottom: 1px solid rgba(0, 0, 0, 0.1); margin-bottom: 30px; margin-top: 10px; padding-bottom: 15px; }
.page-title.blue{color:#007fb1;}
.page-title.bold{font-weight:700;}
.page-title.normal{font-weight:400;}
.page-title.dark-black{color:#393939;}
.page-title.white{color:#fff;}
.page-title.light-grey{color:#efefef;}
.page-title span{ font-family: 'Lato', Arial, sans-serif;}
.page-title.inner-color-green > span{color:#51c43a;}
.page-title.inner-color-orange > span{color:#fc8d3a;}
.tUpper{text-transform:uppercase !important;}
.tLower{text-transform:lowercase !important;}
.tColorB{color:#fff !important;}
.tColorW{color:#fff !important;}
.tColorG{color:#8CC53D !important;}
.tBold{font-weight:700 !important;}
.tNormal{font-weight:400 !important;}
.cBwhite{background:#fff !important;}
.title-12{ font-size:12px;}
.title-16{ font-size:16px;}
.title-20{ font-size:20px;}
.title-25{ font-size:25px;}
.title-30{ font-size:30px;}
.title-35{ font-size:35px;}
/* Default Titles ends */
/* Row and column settings */
.col-custom{padding-left:5px; padding-right:5px}
.row-custom{margin-left:-5px; margin-right:-5px}
/* Custom select settings */
.bootstrap-select {
/*width: 220px\9; IE8 and below*/
width: 220px \0;
/*IE9 and below*/
}
.bootstrap-select > .btn {
width: 100%;
padding-right: 25px;
}
.error .bootstrap-select .btn {
border: 1px solid #b94a48;
}
.control-group.error .bootstrap-select .dropdown-toggle {
border-color: #b94a48;
}
.bootstrap-select.fit-width {
width: auto !important;
}
.bootstrap-select:not([class*="col-"]):not([class*="form-control"]):not(.input-group-btn) {
width: 220px;
}
.bootstrap-select .btn:focus {
outline: thin dotted #333333 !important;
outline: 5px auto -<API key> !important;
outline-offset: -2px;
}
.bootstrap-select.form-control {
margin-bottom: 0;
padding: 0;
border: none;
}
.bootstrap-select.form-control:not([class*="col-"]) {
width: 100%;
}
.bootstrap-select.btn-group:not(.input-group-btn),
.bootstrap-select.btn-group[class*="col-"] {
float: none;
display: inline-block;
margin-left: 0;
}
.bootstrap-select.btn-group.dropdown-menu-right,
.bootstrap-select.btn-group[class*="col-"].dropdown-menu-right,
.row-fluid .bootstrap-select.btn-group[class*="col-"].dropdown-menu-right {
float: right;
}
.form-search .bootstrap-select.btn-group,
.form-inline .bootstrap-select.btn-group,
.form-horizontal .bootstrap-select.btn-group,
.form-group .bootstrap-select.btn-group {
margin-bottom: 0;
}
.form-group-lg .bootstrap-select.btn-group.form-control,
.form-group-sm .bootstrap-select.btn-group.form-control {
padding: 0;
}
.form-inline .bootstrap-select.btn-group .form-control {
width: 100%;
}
.input-append .bootstrap-select.btn-group {
margin-left: -1px;
}
.input-prepend .bootstrap-select.btn-group {
margin-right: -1px;
}
.bootstrap-select.btn-group > .disabled {
cursor: not-allowed;
}
.bootstrap-select.btn-group > .disabled:focus {
outline: none !important;
}
.bootstrap-select.btn-group .btn .filter-option {
display: inline-block;
overflow: hidden;
width: 100%;
text-align: left;
}
.bootstrap-select.btn-group .btn .caret {
position: absolute;
top: 50%;
right: 12px;
margin-top: -2px;
vertical-align: middle;
}
.bootstrap-select.btn-group[class*="col-"] .btn {
width: 100%;
}
.bootstrap-select.btn-group .dropdown-menu {
min-width: 100%;
z-index: 1035;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.bootstrap-select.btn-group .dropdown-menu.inner {
position: static;
border: 0;
padding: 0;
margin: 0;
border-radius: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.bootstrap-select.btn-group .dropdown-menu li {
position: relative;
}
.bootstrap-select.btn-group .dropdown-menu li:not(.disabled) a:hover small,
.bootstrap-select.btn-group .dropdown-menu li:not(.disabled) a:focus small,
.bootstrap-select.btn-group .dropdown-menu li.active:not(.disabled) a small {
color: #64b1d8;
color: rgba(100, 177, 216, 0.4);
}
.bootstrap-select.btn-group .dropdown-menu li.disabled a {
cursor: not-allowed;
}
.bootstrap-select.btn-group .dropdown-menu li a {
cursor: pointer;
}
.bootstrap-select.btn-group .dropdown-menu li a.opt {
position: relative;
padding-left: 2.25em;
}
.bootstrap-select.btn-group .dropdown-menu li a span.check-mark {
display: none;
}
.bootstrap-select.btn-group .dropdown-menu li a span.text {
display: inline-block;
}
.bootstrap-select.btn-group .dropdown-menu li small {
padding-left: 0.5em;
}
.bootstrap-select.btn-group .dropdown-menu .notify {
position: absolute;
bottom: 5px;
width: 96%;
margin: 0 2%;
min-height: 26px;
padding: 3px 5px;
background: #f5f5f5;
border: 1px solid #e3e3e3;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
pointer-events: none;
opacity: 0.9;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.bootstrap-select.btn-group .no-results {
padding: 3px;
background: #f5f5f5;
margin: 0 5px;
}
.bootstrap-select.btn-group.fit-width .btn .filter-option {
position: static;
}
.bootstrap-select.btn-group.fit-width .btn .caret {
position: static;
top: auto;
margin-top: -1px;
}
.bootstrap-select.btn-group.show-tick .dropdown-menu li.selected a span.check-mark {
position: absolute;
display: inline-block;
right: 15px;
margin-top: 2.5px;
}
.bootstrap-select.btn-group.show-tick .dropdown-menu li a span.text {
margin-right: 34px;
}
.bootstrap-select.show-menu-arrow.open > .btn {
z-index: 1035 + 1;
}
.bootstrap-select.show-menu-arrow .dropdown-toggle:before {
content: '';
border-left: 7px solid transparent;
border-right: 7px solid transparent;
border-bottom-width: 7px;
border-bottom-style: solid;
border-bottom-color: #cccccc;
border-bottom-color: rgba(204, 204, 204, 0.2);
position: absolute;
bottom: -4px;
left: 9px;
display: none;
}
.bootstrap-select.show-menu-arrow .dropdown-toggle:after {
content: '';
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-bottom: 6px solid white;
position: absolute;
bottom: -4px;
left: 10px;
display: none;
}
.bootstrap-select.show-menu-arrow.dropup .dropdown-toggle:before {
bottom: auto;
top: -3px;
border-bottom: 0;
border-top-width: 7px;
border-top-style: solid;
border-top-color: #cccccc;
border-top-color: rgba(204, 204, 204, 0.2);
}
.bootstrap-select.show-menu-arrow.dropup .dropdown-toggle:after {
bottom: auto;
top: -3px;
border-top: 6px solid white;
border-bottom: 0;
}
.bootstrap-select.show-menu-arrow.pull-right .dropdown-toggle:before {
right: 12px;
left: auto;
}
.bootstrap-select.show-menu-arrow.pull-right .dropdown-toggle:after {
right: 13px;
left: auto;
}
.bootstrap-select.show-menu-arrow.open > .dropdown-toggle:before,
.bootstrap-select.show-menu-arrow.open > .dropdown-toggle:after {
display: block;
}
.bs-searchbox,
.bs-actionsbox {
padding: 4px 8px;
}
.bs-actionsbox {
float: left;
width: 100%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.bs-actionsbox .btn-group button {
width: 50%;
}
.bs-searchbox + .bs-actionsbox {
padding: 0 8px 4px;
}
.bs-searchbox input.form-control {
margin-bottom: 0;
width: 100%;
}
.mobile-device {
position: absolute;
top: 0;
left: 0;
display: block !important;
width: 100%;
height: 100% !important;
opacity: 0;
}
/*# sourceMappingURL=bootstrap-select.css.map */
/* Page border / Global / */
.page-border{border-top: 5px solid #e1202c !important;}
.page-margin{margin-top:20px !important;} |
#pragma once
#include <string>
#include <ctime>
#include "api.h"
using namespace std;
#include "SimulationModule.h"
class SUR_CN:public SimulationModule
{
public:
SUR_CN(void);
~SUR_CN(void);
virtual int Execute();
virtual void SetValue(const char* key, float data);
virtual void Set1DData(const char* key, int n, float* data);
virtual void Set2DData(const char* key, int nrows, int ncols, float** data);
virtual void Get1DData(const char* key, int* n, float** data);
virtual void Get2DData(const char* key, int *nRows, int *nCols, float*** data);
bool CheckInputSize(const char* key, int n);
bool CheckInputData(void);
private:
number of soil layers
int m_nLayers;
depth of the up two layers(The depth are 10mm and 100 mm, respectively).
float m_depth[2];
count of valid cells
int m_nCells;
soil porosity
float** m_porosity;
water content of soil at field capacity
float** m_fieldCap;
plant wilting point moisture
float** m_wiltingPoint;
root depth of plants (m)
float* m_rootDepth;
CN under moisture condition II
float* m_CN2;
Net precipitation calculated in the interception module (mm)
float* m_P_NET;
Initial soil moisture or
soil moisture of each time step
float** m_soilMoisture;
float* m_initSoilMoisture;
Initial depression storage coefficient
//float m_Depre_in;
Depression storage capacity
//float* m_Depression;
depression storage
float* m_SD; // SD(t-1) from the depression storage module
from interpolation module
air temperature of the current day
float *m_tMin, *m_tMax;
snowfall temperature from the parameter database (¡æ)
float m_Tsnow;
threshold soil freezing temperature (¡æ)
float m_Tsoil;
frozen soil moisture relative to saturation above which no infiltration occur (m3/m3)
float m_Sfrozen;
snowmelt threshold temperature from the parameter database (¡æ)
float m_T0;
snowmelt from the snowmelt module (mm)
float* m_SM;
snow accumulation from the snow balance module (mm) at t+1 timestep
float* m_SA;
soil temperature obtained from the soil temperature module (¡æ)
float* m_TS;
from GIS interface Project/model subdirectory
Julian day
int m_julianDay;
// output
the excess precipitation (mm) of the total nCells
float* m_PE;
infiltration map of watershed (mm) of the total nCells
float* m_INFIL;
//add by Zhiqiang
float* m_w1;
float* m_w2;
float* m_sMax;
void initalW1W2();
float Calculate_CN(float sm, int cell);
void initalOutputs();
}; |
#ifndef <API key>
#define <API key>
#include "fs_proxy.h"
#include <AFS/SECURITY/unix_acl.h>
#include <PaF/API/filter.h>
typedef std::map<uint32_t, std::string> uid_gid_mapping_t;
struct T_mount_config : public T_filesystem_config {
std::string remote_path;
std::string mount_point;
std::string mount_options;
uid_gid_mapping_t users_mapping;
uid_gid_mapping_t groups_mapping;
};
typedef boost::shared_ptr<T_mount_config> T_mount_config_ptr;
//! @brief An implementation of filesystem proxy for mounted filesystem
//FIXME Currently only working with NFS!
class <API key> : public T_filesystem_proxy
{
public:
<API key>(<API key> conf);
virtual ~<API key>();
const std::string& host() const { return _config->remote_host; }
const std::string& path() const { return _config->remote_path; }
const std::string& mount_point() const { return _config->mount_point; }
const std::string& mount_options() const { return _config->mount_options; }
const map<uint32_t, uint32_t> user_misses() const
{ return _on_mapping_miss.user_misses; }
const map<uint32_t, uint32_t> group_misses() const
{ return _on_mapping_miss.group_misses; }
virtual void connect();
virtual void disconnect();
virtual T_url_ptr create_url(const N_Uri::T_uri& uri) const;
virtual T_url_ptr create_url(const std::string& fs_path) const;
virtual bool check_if_dir_exists(const T_url& url);
virtual bool <API key>(const T_url& url);
virtual void get_directory_files(const T_url& url,
std::set<std::string>& files);
virtual void <API key>(const T_url& url,
std::set<std::string>& subdirectories);
virtual void read_file_content(const T_url& url,
N_String::T_binary_string& data);
virtual N_Security::ACL <API key>(const T_url& url);
virtual N_Security::ACL <API key>(const string& localpath) ;
virtual time_t read_file_mtime(const T_url& url);
virtual time_t read_file_ctime(const T_url& url);
private:
T_mount_config_ptr _config;
N_Security::<API key> _on_mapping_miss;
};
class T_mount_acl: public T_filesystem_acl
{
public:
T_mount_acl(<API key>&);
virtual ~T_mount_acl();
//! @brief Compute SAR layer
virtual N_Security::SAR compute_sar_layer(const T_url& url);
//! @brief Log the uuid/guid mapping errors
virtual void log_mapping_errors(AFS::PaF::Handle& handle);
private:
<API key>& _mount;
void log_mapping_errors(AFS::PaF::Handle& handle,
const map<uint32_t, uint32_t>& errors,
std::string mapping_type);
};
#endif // <API key> |
// wrapper for dlldata.c
#undef _MERGE_PROXYSTUB
#ifdef _MERGE_PROXYSTUB // merge proxy stub DLL
#define REGISTER_PROXY_DLL //DllRegisterServer, etc.
#define _WIN32_WINNT 0x0500 //for WinNT 4.0 or Win95 with DCOM
#define USE_STUBLESS_PROXY //defined only with MIDL switch /Oicf
#pragma comment(lib, "rpcns4.lib")
#pragma comment(lib, "rpcrt4.lib")
#define ENTRY_PREFIX Prx
#include "..\..\dlldata.c"
#include "..\..\ffmpegShell_p.c"
#endif //_MERGE_PROXYSTUB |
using Newtonsoft.Json;
using <API key>.Models;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace <API key>.Controllers
{
public class <API key> : ApiController
{
private const string APP_KEY = "<API key>";
private RestClient client;
private RestRequest request;
private List<Subscription> subscriptions;
private NotificationStatus status;
[Route("api/AppceleratorApiRest/{channel}")]
public NotificationStatus Post(string channel, PushNotification notification)
{
if (Object.Equals(null, notification.Payload))
return new NotificationStatus { StatusCode = "0", StatusDescription = "Los parámetros son incorrectos" };
try
{
client = new RestClient("https://api.cloud.appcelerator.com");
client.CookieContainer = new System.Net.CookieContainer();
request = new RestRequest("/v1/users/login.json?key={appkey}", Method.POST)
{
RequestFormat = DataFormat.Json,
};
request.AddUrlSegment("appkey", APP_KEY);
request.AddBody(new
{
login = "developer",
password = "developer"
});
var response = client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
dynamic loginResponse = JsonConvert.DeserializeObject(response.Content);
if (loginResponse.response.users.Count > 0)
{
if (notification.Devices.Count == 0)
{
subscriptions = new List<Subscription>();
GetSubscriptions(loginResponse.response.users[0].id.ToString());
}
SendPush(notification, channel);
}
}
else
status = new NotificationStatus { StatusCode = response.StatusCode.ToString(), StatusDescription = response.StatusDescription };
return status;
}
catch (Exception ex)
{
string errorMessage = "Message " + ex.Message + " \n Inner Exception " + ex.InnerException + " \n Stack Trace" + ex.StackTrace;
status = new NotificationStatus { StatusCode = "-1", StatusDescription = errorMessage };
}
return status;
}
private void GetSubscriptions(string idUsuario)
{
try
{
client.BaseUrl = new Uri("https://api.cloud.appcelerator.com");
request.Resource = "/v1/push_notification/query.json?key={appkey}";
request.Method = Method.GET;
request.AddUrlSegment("appkey", APP_KEY);
request.AddParameter("pretty_json", "true");
request.AddParameter("type", "android");
var response = client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK)
{
dynamic <API key> = JsonConvert.DeserializeObject(response.Content);
if (<API key>.response.subscriptions.Count > 0)
subscriptions = <API key>.response.subscriptions.ToObject<List<Subscription>>();
}
status = new NotificationStatus { StatusCode = response.StatusCode.ToString(), StatusDescription = response.StatusDescription };
}
catch (Exception ex)
{
string errorMessage = "Message " + ex.Message + " \n Inner Exception " + ex.InnerException + " \n Stack Trace" + ex.StackTrace;
status = new NotificationStatus { StatusCode = "-1", StatusDescription = errorMessage };
}
}
private void SendPush(PushNotification notification, string channel)
{
if (notification.Devices.Count > 0 || <API key>())
{
try
{
if (string.IsNullOrEmpty(notification.Payload.sound))
notification.Payload.sound = "default";
string payloadStr = JsonConvert.SerializeObject(notification.Payload);
string delimiter = ",";
string tokens = string.Empty;
if(notification.Devices.Count > 0)
{
tokens = String.Join(delimiter, notification.Devices);
} else {
var validSubscriptions = from s in subscriptions
where s.channel.Contains(channel)
select s.device_token;
tokens = String.Join(delimiter, validSubscriptions);
}
client.BaseUrl = new Uri("https://api.cloud.appcelerator.com");
request.Resource = "/v1/push_notification/notify_tokens.json?key={appkey}";
// where={"loc": { "$nearSphere" : { "$geometry" : { "type" : "Point" , "coordinates" : [-122.2708,37.8044] } , "$maxDistance" : 2000 }}}
request.Method = Method.POST;
request.AddUrlSegment("appkey", APP_KEY);
request.AddParameter("channel", channel);
request.AddParameter("to_tokens", tokens);
request.AddParameter("payload", payloadStr);
var response = client.Execute(request);
status = new NotificationStatus { StatusCode = response.StatusCode.ToString(), StatusDescription = response.StatusDescription };
}
catch (Exception ex)
{
string errorMessage = "Message " + ex.Message + " \n Inner Exception " + ex.InnerException + " \n Stack Trace" + ex.StackTrace;
status = new NotificationStatus { StatusCode = "-1", StatusDescription = errorMessage };
}
finally
{
Logout();
}
}
}
private void Logout()
{
try
{
client.BaseUrl = new Uri("https://api.cloud.appcelerator.com");
request.Resource = "/v1/users/logout.json?key={appkey}";
request.Method = Method.GET;
request.AddUrlSegment("appkey", APP_KEY);
request.AddParameter("pretty_json", "true");
var response = client.Execute(request);
status = new NotificationStatus { StatusCode = response.StatusCode.ToString(), StatusDescription = response.StatusDescription };
}
catch (Exception ex)
{
string errorMessage = "Message " + ex.Message + " \n Inner Exception " + ex.InnerException + " \n Stack Trace" + ex.StackTrace;
status = new NotificationStatus { StatusCode = "-1", StatusDescription = errorMessage };
}
}
private bool <API key>()
{
if (Object.Equals(null, subscriptions))
return false;
else if (subscriptions.Count == 0)
return false;
return true;
}
}
} |
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest02102")
public class BenchmarkTest02102 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String param = "";
java.util.Enumeration<String> headers = request.getHeaders("vector");
if (headers.hasMoreElements()) {
param = headers.nextElement(); // just grab first element
}
String bar = doSomething(param);
int length = 1;
if (bar != null) {
length = bar.length();
response.getWriter().write(bar, 0, length);
}
} // end doPost
private static String doSomething(String param) throws ServletException, IOException {
// Chain a bunch of propagators in sequence
String a31029 = param; //assign
StringBuilder b31029 = new StringBuilder(a31029); // stick in stringbuilder
b31029.append(" SafeStuff"); // append some safe content
b31029.replace(b31029.length()-"Chars".length(),b31029.length(),"Chars"); //replace some of the end content
java.util.HashMap<String,Object> map31029 = new java.util.HashMap<String,Object>();
map31029.put("key31029", b31029.toString()); // put in a collection
String c31029 = (String)map31029.get("key31029"); // get it back out
String d31029 = c31029.substring(0,c31029.length()-1); // extract most of it
String e31029 = new String( new sun.misc.BASE64Decoder().decodeBuffer(
new sun.misc.BASE64Encoder().encode( d31029.getBytes() ) )); // B64 encode and decode it
String f31029 = e31029.split(" ")[0]; // split it on a space
org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing();
String g31029 = "<API key>"; // This is static so this whole flow is 'safe'
String bar = thing.doSomething(g31029); // reflection
return bar;
}
} |
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/bootmem.h>
#include <linux/ioport.h>
#include <linux/pm.h>
#include <asm/bootinfo.h>
#include <asm/time.h>
#include <asm/reboot.h>
#include <asm/cacheflush.h>
#include <bcm63xx_board.h>
#include <bcm63xx_cpu.h>
#include <bcm63xx_regs.h>
#include <bcm63xx_io.h>
void <API key>(void)
{
printk(KERN_INFO "System halted\n");
while (1)
;
}
static void bcm6348_a1_reboot(void)
{
u32 reg;
/* soft reset all blocks */
printk(KERN_INFO "soft-reseting all blocks ...\n");
reg = bcm_perf_readl(PERF_SOFTRESET_REG);
reg &= ~SOFTRESET_6348_ALL;
bcm_perf_writel(reg, PERF_SOFTRESET_REG);
mdelay(10);
reg = bcm_perf_readl(PERF_SOFTRESET_REG);
reg |= SOFTRESET_6348_ALL;
bcm_perf_writel(reg, PERF_SOFTRESET_REG);
mdelay(10);
/* Jump to the power on address. */
printk(KERN_INFO "jumping to reset vector.\n");
/* set high vectors (base at 0xbfc00000 */
set_c0_status(ST0_BEV | ST0_ERL);
/* run uncached in kseg0 */
change_c0_config(CONF_CM_CMASK, CONF_CM_UNCACHED);
__flush_cache_all();
/* remove all wired TLB entries */
write_c0_wired(0);
__asm__ __volatile__(
"jr\t%0"
:
: "r" (0xbfc00000));
while (1)
;
}
void <API key>(void)
{
u32 reg;
/* mask and clear all external irq */
reg = bcm_perf_readl(PERF_EXTIRQ_CFG_REG);
reg &= ~EXTIRQ_CFG_MASK_ALL;
reg |= <API key>;
bcm_perf_writel(reg, PERF_EXTIRQ_CFG_REG);
if (BCMCPU_IS_6348() && (bcm63xx_get_cpu_rev() == 0xa1))
bcm6348_a1_reboot();
printk(KERN_INFO "triggering watchdog soft-reset...\n");
reg = bcm_perf_readl(<API key>);
reg |= SYS_PLL_SOFT_RESET;
bcm_perf_writel(reg, <API key>);
while (1)
;
}
static void <API key>(char *p)
{
<API key>();
}
/*
* return system type in /proc/cpuinfo
*/
const char *get_system_type(void)
{
static char buf[128];
snprintf(buf, sizeof(buf), "bcm63xx/%s (0x%04x/0x%04X)",
board_get_name(),
bcm63xx_get_cpu_id(), bcm63xx_get_cpu_rev());
return buf;
}
void __init plat_time_init(void)
{
mips_hpt_frequency = <API key>() / 2;
}
void __init plat_mem_setup(void)
{
add_memory_region(0, <API key>(), BOOT_MEM_RAM);
_machine_halt = <API key>;
_machine_restart = <API key>;
pm_power_off = <API key>;
set_io_port_base(0);
ioport_resource.start = 0;
ioport_resource.end = ~0;
board_setup();
}
int __init <API key>(void)
{
return <API key>();
}
arch_initcall(<API key>); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.