code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
/*
* 12/21/2004
*
* ConfigurableCaret.java - The caret used by RTextArea.
* Copyright (C) 2004 Robert Futrell
* robert_futrell at users.sourceforge.net
* http://fifesoft.com/rsyntaxtextarea
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
package org.fife.ui.rtextarea;
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.awt.event.ActionEvent;
import java.io.*;
import javax.swing.*;
import javax.swing.plaf.*;
import javax.swing.text.*;
/**
* The caret used by {@link RTextArea}. This caret has all of the properties that
* <code>javax.swing.text.DefaultCaret</code> does, as well as adding the following niceties:
*
* <ul>
* <li>This caret can paint itself several different ways:
* <ol>
* <li>As a vertical line (like <code>DefaultCaret</code>)</li>
* <li>As a slightly thicker vertical line (like Eclipse)</li>
* <li>As an underline</li>
* <li>As a "block caret"</li>
* <li>As a rectangle around the current character</li>
* </ol>
* </li>
* <li>On Microsoft Windows and other operating systems that do not support system selection (i.e., selecting text, then
* pasting via the middle mouse button), clicking the middle mouse button will cause a regular paste operation to occur.
* On systems that support system selection (i.e., all UNIX variants), the middle mouse button will behave normally.</li>
* </ul>
*
* @author Robert Futrell
* @version 0.6
*/
public class ConfigurableCaret extends DefaultCaret {
/**
* The minimum value of a caret style.
*/
public static final int MIN_STYLE = 0;
/**
* The vertical line style.
*/
public static final int VERTICAL_LINE_STYLE = 0;
/**
* The horizontal line style.
*/
public static final int UNDERLINE_STYLE = 1;
/**
* The block style.
*/
public static final int BLOCK_STYLE = 2;
/**
* The block border style.
*/
public static final int BLOCK_BORDER_STYLE = 3;
/**
* A thicker vertical line (2 pixels instead of 1).
*/
public static final int THICK_VERTICAL_LINE_STYLE = 4;
/**
* The maximum value of a caret style.
*/
public static final int MAX_STYLE = THICK_VERTICAL_LINE_STYLE;
/**
* Action used to select a word on a double click.
*/
static private transient Action selectWord = null;
/**
* Action used to select a line on a triple click.
*/
static private transient Action selectLine = null;
/**
* holds last MouseEvent which caused the word selection
*/
private transient MouseEvent selectedWordEvent = null;
/**
* Used for fastest-possible retrieval of the character at the caret's position in the document.
*/
private transient Segment seg;
/**
* Whether the caret is a vertical line, a horizontal line, or a block.
*/
private int style;
/**
* The selection painter. By default this paints selections with the text area's selection color.
*/
private ChangeableHighlightPainter selectionPainter;
/**
* Whether this is Java 1.4.
*/
/* TODO: Remove me when 1.4 support is removed. */
private static final boolean IS_JAVA_1_4 =
"1.4".equals(System.getProperty("java.specification.version"));
/**
* Creates the caret using {@link #VERTICAL_LINE_STYLE}.
*/
public ConfigurableCaret() {
this(VERTICAL_LINE_STYLE);
}
/**
* Constructs a new <code>ConfigurableCaret</code>.
*
* @param style
* The style to use when painting the caret. If this is invalid, then {@link #VERTICAL_LINE_STYLE} is
* used.
*/
public ConfigurableCaret(int style) {
seg = new Segment();
setStyle(style);
selectionPainter = new ChangeableHighlightPainter();
}
/**
* Adjusts the caret location based on the MouseEvent.
*/
private void adjustCaret(MouseEvent e) {
if ((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0 && getDot() != -1)
moveCaret(e);
else
positionCaret(e);
}
/**
* Adjusts the focus, if necessary.
*
* @param inWindow
* if true indicates requestFocusInWindow should be used
*/
private void adjustFocus(boolean inWindow) {
RTextArea textArea = getTextArea();
if ((textArea != null) && textArea.isEnabled() &&
textArea.isRequestFocusEnabled()) {
if (inWindow)
textArea.requestFocusInWindow();
else
textArea.requestFocus();
}
}
/**
* Overridden to damage the correct width of the caret, since this caret can be different sizes.
*
* @param r
* The current location of the caret.
*/
protected synchronized void damage(Rectangle r) {
if (r != null) {
validateWidth(r); // Check for "0" or "1" caret width
x = r.x - 1;
y = r.y;
width = r.width + 4;
height = r.height;
repaint();
}
}
/**
* Called when the UI is being removed from the interface of a JTextComponent. This is used to unregister any
* listeners that were attached.
*
* @param c
* The text component. If this is not an <code>RTextArea</code>, an <code>Exception</code> will be
* thrown.
* @see Caret#deinstall
*/
public void deinstall(JTextComponent c) {
if (!(c instanceof RTextArea))
throw new IllegalArgumentException(
"c must be instance of RTextArea");
super.deinstall(c);
}
/**
* Gets the text editor component that this caret is bound to.
*
* @return The <code>RTextArea</code>.
*/
protected RTextArea getTextArea() {
return (RTextArea) getComponent();
}
/**
* Returns whether this caret's selection uses rounded edges.
*
* @return Whether this caret's edges are rounded.
* @see #setRoundedSelectionEdges
*/
public boolean getRoundedSelectionEdges() {
return ((ChangeableHighlightPainter) getSelectionPainter()).
getRoundedEdges();
}
/**
* Gets the painter for the Highlighter. This is overridden to return our custom selection painter.
*
* @return The painter.
*/
protected Highlighter.HighlightPainter getSelectionPainter() {
return selectionPainter;
}
/**
* Gets the current style of this caret.
*
* @return The caret's style.
* @see #setStyle(int)
*/
public int getStyle() {
return style;
}
/**
* Installs this caret on a text component.
*
* @param c
* The text component. If this is not an {@link RTextArea}, an <code>Exception</code> will be thrown.
* @see Caret#install
*/
public void install(JTextComponent c) {
if (!(c instanceof RTextArea))
throw new IllegalArgumentException(
"c must be instance of RTextArea");
super.install(c);
}
/**
* Called when the mouse is clicked. If the click was generated from button1, a double click selects a word, and a
* triple click the current line.
*
* @param e
* the mouse event
* @see MouseListener#mouseClicked
*/
public void mouseClicked(MouseEvent e) {
if (!e.isConsumed()) {
RTextArea textArea = getTextArea();
int nclicks = e.getClickCount();
if (SwingUtilities.isLeftMouseButton(e)) {
if (nclicks <= 2) {
// Only handle these clicks for 1.4. In 1.5 the word
// selection is (also?) handled in mousePressed, and if we
// handle it here, our word selection gets doubled-up.
if (IS_JAVA_1_4) {
if (nclicks == 1) {
selectedWordEvent = null;
}
else { // 2
selectWord(e);
selectedWordEvent = null;
}
}
}
else {
nclicks %= 2; // Alternate selecting word/line.
switch (nclicks) {
case 0:
selectWord(e);
selectedWordEvent = null;
break;
case 1:
Action a = null;
ActionMap map = textArea.getActionMap();
if (map != null)
a = map.get(RTextAreaEditorKit.selectLineAction);
if (a == null) {
if (selectLine == null) {
selectLine = new RTextAreaEditorKit.SelectLineAction();
}
a = selectLine;
}
a.actionPerformed(new ActionEvent(textArea,
ActionEvent.ACTION_PERFORMED,
null, e.getWhen(), e.getModifiers()));
}
}
}
else if (SwingUtilities.isMiddleMouseButton(e)) {
if (nclicks == 1 && textArea.isEditable() && textArea.isEnabled()) {
// Paste the system selection, if it exists (e.g., on UNIX
// platforms, the user can select text, the middle-mouse click
// to paste it; this doesn't work on Windows). If the system
// doesn't support system selection, just do a normal paste.
JTextComponent c = (JTextComponent) e.getSource();
if (c != null) {
try {
Toolkit tk = c.getToolkit();
Clipboard buffer = tk.getSystemSelection();
// If the system supports system selections, (e.g. UNIX),
// try to do it.
if (buffer != null) {
adjustCaret(e);
TransferHandler th = c.getTransferHandler();
if (th != null) {
Transferable trans = buffer.getContents(null);
if (trans != null)
th.importData(c, trans);
}
adjustFocus(true);
}
// If the system doesn't support system selections
// (e.g. Windows), just do a normal paste.
else {
textArea.paste();
}
} catch (HeadlessException he) {
// do nothing... there is no system clipboard
}
} // if (c!=null)
} // if (nclicks == 1 && component.isEditable() && component.isEnabled())
} // else if (SwingUtilities.isMiddleMouseButton(e))
} // if (!c.isConsumed())
}
/**
* Paints the cursor.
*
* @param g
* The graphics context in which to paint.
*/
public void paint(Graphics g) {
// If the cursor is currently visible...
if (isVisible()) {
try {
RTextArea textArea = getTextArea();
g.setColor(textArea.getCaretColor());
TextUI mapper = textArea.getUI();
Rectangle r = mapper.modelToView(textArea, getDot());
// "Correct" the value of rect.width (takes into
// account caret being at EOL (and thus rect.width==1),
// etc.
// We do this even for LINE_STYLE because
// if they change from that caret to block/underline,
// the first time they do so width==1, so it will take
// one caret flash to paint correctly (wider). If we
// do this every time, then it's painted correctly the
// first blink.
validateWidth(r);
// Need to subtract 2 from height, otherwise
// the caret will expand too far vertically.
r.height -= 2;
switch (style) {
// Draw a big rectangle, and xor the foreground color.
case BLOCK_STYLE:
g.setXORMode(Color.WHITE);
// fills x==r.x to x==(r.x+(r.width)-1), inclusive.
g.fillRect(r.x, r.y, r.width, r.height);
break;
// Draw a rectangular border.
case BLOCK_BORDER_STYLE:
// fills x==r.x to x==(r.x+(r.width-1)), inclusive.
g.drawRect(r.x, r.y, r.width - 1, r.height);
break;
// Draw an "underline" below the current position.
case UNDERLINE_STYLE:
g.setXORMode(Color.WHITE);
int y = r.y + r.height;
g.drawLine(r.x, y, r.x + r.width - 1, y);
break;
// Draw a vertical line.
default:
case VERTICAL_LINE_STYLE:
g.drawLine(r.x, r.y, r.x, r.y + r.height);
break;
// A thicker vertical line.
case THICK_VERTICAL_LINE_STYLE:
g.drawLine(r.x, r.y, r.x, r.y + r.height);
r.x++;
g.drawLine(r.x, r.y, r.x, r.y + r.height);
break;
} // End of switch (style).
} catch (BadLocationException ble) {
ble.printStackTrace();
}
} // End of if (isVisible()).
}
/**
* Deserializes a caret. This is overridden to read the caret's style.
*
* @param s
* The stream to read from.
* @throws ClassNotFoundException
* @throws IOException
*/
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException {
s.defaultReadObject();
setStyle(s.readInt());
seg = new Segment();
}
/**
* Selects word based on the MouseEvent
*/
private void selectWord(MouseEvent e) {
if (selectedWordEvent != null
&& selectedWordEvent.getX() == e.getX()
&& selectedWordEvent.getY() == e.getY()) {
// We've already the done selection for this.
return;
}
Action a = null;
RTextArea textArea = getTextArea();
ActionMap map = textArea.getActionMap();
if (map != null) {
a = map.get(RTextAreaEditorKit.selectWordAction);
}
if (a == null) {
if (selectWord == null) {
selectWord = new RTextAreaEditorKit.SelectWordAction();
}
a = selectWord;
}
a.actionPerformed(new ActionEvent(textArea,
ActionEvent.ACTION_PERFORMED,
null, e.getWhen(), e.getModifiers()));
selectedWordEvent = e;
}
/**
* Sets whether this caret's selection should have rounded edges.
*
* @param rounded
* Whether it should have rounded edges.
* @see #getRoundedSelectionEdges()
*/
public void setRoundedSelectionEdges(boolean rounded) {
((ChangeableHighlightPainter) getSelectionPainter()).
setRoundedEdges(rounded);
}
/**
* Overridden to always render the selection, even when the text component loses focus.
*
* @param visible
* Whether the selection should be visible. This parameter is ignored.
*/
public void setSelectionVisible(boolean visible) {
super.setSelectionVisible(true);
}
/**
* Sets the style used when painting the caret.
*
* @param style
* The style to use. If this isn't one of <code>VERTICAL_LINE_STYLE</code>, <code>UNDERLINE_STYLE</code>,
* or <code>BLOCK_STYLE</code>, then <code>VERTICAL_LINE_STYLE</code> is used.
* @see #getStyle()
*/
public void setStyle(int style) {
if (style < MIN_STYLE || style > MAX_STYLE)
style = VERTICAL_LINE_STYLE;
this.style = style;
repaint();
}
/**
* Helper function used by the block and underline carets to ensure the width of the painted caret is valid. This is
* done for the following reasons:
*
* <ul>
* <li>The <code>View</code> classes in the javax.swing.text package always return a width of "1" when
* <code>modelToView</code> is called. We'll be needing the actual width.</li>
* <li>Even in smart views, such as <code>RSyntaxTextArea</code>'s <code>SyntaxView</code> and
* <code>WrappedSyntaxView</code> that return the width of the current character, if the caret is at the end of a
* line for example, the width returned from <code>modelToView</code> will be 0 (as the width of unprintable
* characters such as '\n' is calculated as 0). In this case, we'll use a default width value.</li>
* </ul>
*
* @param rect
* The rectangle returned by the current <code>View</code>'s <code>modelToView</code> method for the
* caret position.
*/
private void validateWidth(Rectangle rect) {
// If the width value > 1, we assume the View is
// a "smart" view that returned the proper width.
// So only worry about this stuff if width <= 1.
if (rect != null && rect.width <= 1) {
// The width is either 1 (most likely, we're using a "dumb" view
// like those in javax.swing.text) or 0 (most likely, we're using
// a "smart" view like org.fife.ui.rsyntaxtextarea.SyntaxView,
// we're at the end of a line, and the width of '\n' is being
// computed as 0).
try {
// Try to get a width for the character at the caret
// position. We use the text area's font instead of g's
// because g's may vary in an RSyntaxTextArea.
RTextArea textArea = getTextArea();
textArea.getDocument().getText(getDot(), 1, seg);
Font font = textArea.getFont();
FontMetrics fm = textArea.getFontMetrics(font);
rect.width = fm.charWidth(seg.array[seg.offset]);
// This width being returned 0 likely means that it is an
// unprintable character (which is almost 100% to be a
// newline char, i.e., we're at the end of a line). So,
// just use the width of a space.
if (rect.width == 0) {
rect.width = fm.charWidth(' ');
}
} catch (BadLocationException ble) {
// This shouldn't ever happen.
ble.printStackTrace();
rect.width = 8;
}
} // End of if (rect!=null && rect.width<=1).
}
/**
* Serializes this caret. This is overridden to write the style of the caret.
*
* @param s
* The stream to write to.
* @throws IOException
* If an IO error occurs.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeInt(getStyle());
}
}
|
rkadle/Tank
|
tools/script_filter/src/main/java/org/fife/ui/rtextarea/ConfigurableCaret.java
|
Java
|
epl-1.0
| 20,621
|
/*******************************************************************************
* Copyright (c) 2017 Eurotech and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.kura.core.deployment.hook;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import org.eclipse.kura.configuration.ConfigurationService;
import org.eclipse.kura.deployment.hook.DeploymentHook;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DeploymentHookManager {
private static final Logger logger = LoggerFactory.getLogger(DeploymentHookManager.class);
private final Map<String, DeploymentHook> registeredHooks = new HashMap<>();
private final Map<String, HookAssociation> associations = new HashMap<>();
private BundleContext bundleContext;
public synchronized void bindHook(ServiceReference<DeploymentHook> hook) {
final Object rawHookId = hook.getProperty(ConfigurationService.KURA_SERVICE_PID);
if (!(rawHookId instanceof String)) {
logger.warn("Found hook with invalid {}, not registering", ConfigurationService.KURA_SERVICE_PID);
return;
}
final String hookId = (String) rawHookId;
if (registeredHooks.containsKey(hookId)) {
logger.warn("Found duplicated hook with id {}, not registering", ConfigurationService.KURA_SERVICE_PID);
return;
}
this.registeredHooks.put(hookId, getBundleContext().getService(hook));
logger.info("Hook registered: {}", hookId);
updateAssociations();
}
public synchronized void unbindHook(ServiceReference<DeploymentHook> hook) {
final Object rawHookId = hook.getProperty(ConfigurationService.KURA_SERVICE_PID);
if (!(rawHookId instanceof String)) {
return;
}
final String hookId = (String) rawHookId;
final DeploymentHook removedHook = this.registeredHooks.remove(hookId);
updateAssociations();
if (removedHook != null) {
getBundleContext().ungetService(hook);
logger.info("Hook unregistered: {}", hookId);
}
}
private BundleContext getBundleContext() {
if (this.bundleContext == null) {
this.bundleContext = FrameworkUtil.getBundle(DeploymentHookManager.class).getBundleContext();
}
return this.bundleContext;
}
public synchronized void updateAssociations(Properties properties) {
this.associations.clear();
if (properties == null) {
return;
}
for (Entry<Object, Object> entry : properties.entrySet()) {
final Object value = entry.getValue();
if (value == null) {
continue;
}
final String type = entry.getKey().toString();
final String hookId = value.toString();
final HookAssociation association = new HookAssociation(type, hookId);
this.associations.put(type, association);
logger.info("Association added: {}", association);
}
updateAssociations();
}
private void updateAssociations() {
for (HookAssociation association : this.associations.values()) {
final DeploymentHook hook = registeredHooks.get(association.hookId);
association.hook = hook;
logger.info("Association updated: {}", association);
}
}
public synchronized DeploymentHook getHook(String type) {
final HookAssociation association = this.associations.get(type);
if (association == null) {
return null;
}
return association.hook;
}
public Map<String, HookAssociation> getHookAssociations() {
return Collections.unmodifiableMap(this.associations);
}
public Map<String, DeploymentHook> getRegisteredHooks() {
return Collections.unmodifiableMap(this.registeredHooks);
}
public static class HookAssociation {
private String type;
private String hookId;
private DeploymentHook hook;
public HookAssociation(String type, String hookId) {
this.type = type;
this.hookId = hookId;
}
public String getRequestType() {
return type;
}
public String getHookId() {
return hookId;
}
public DeploymentHook getDeploymentHook() {
return hook;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("request type: ").append(type).append(" hook id: ").append(hookId).append(" status: ")
.append(hook == null ? "NOT BOUND" : "BOUND");
return builder.toString();
}
}
}
|
gavinying/kura
|
kura/org.eclipse.kura.core.deployment/src/main/java/org/eclipse/kura/core/deployment/hook/DeploymentHookManager.java
|
Java
|
epl-1.0
| 5,275
|
// $Id: tss_pe.cpp 49324 2008-10-13 20:30:13Z anthonyw $
// (C) Copyright Aaron W. LaFramboise, Roland Schwarz, Michael Glassford 2004.
// (C) Copyright 2007 Roland Schwarz
// (C) Copyright 2007 Anthony Williams
// (C) Copyright 2007 David Deakins
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/thread/detail/config.hpp>
#if defined(BOOST_HAS_WINTHREADS) && defined(BOOST_THREAD_BUILD_LIB)
#if defined(__MINGW32__) && !defined(_WIN64)
#include <boost/thread/detail/tss_hooks.hpp>
#include <windows.h>
#include <cstdlib>
extern "C" void tss_cleanup_implemented(void) {}
namespace {
void NTAPI on_tls_callback(void* h, DWORD dwReason, PVOID pv)
{
switch (dwReason)
{
case DLL_THREAD_DETACH:
{
on_thread_exit();
break;
}
}
}
void on_after_ctors(void)
{
on_process_enter();
}
void on_before_dtors(void)
{
on_thread_exit();
}
void on_after_dtors(void)
{
on_process_exit();
}
}
extern "C" {
void (* after_ctors )(void) __attribute__((section(".ctors"))) = on_after_ctors;
void (* before_dtors)(void) __attribute__((section(".dtors"))) = on_before_dtors;
void (* after_dtors )(void) __attribute__((section(".dtors.zzz"))) = on_after_dtors;
ULONG __tls_index__ = 0;
char __tls_end__ __attribute__((section(".tls$zzz"))) = 0;
char __tls_start__ __attribute__((section(".tls"))) = 0;
PIMAGE_TLS_CALLBACK __crt_xl_start__ __attribute__ ((section(".CRT$XLA"))) = 0;
PIMAGE_TLS_CALLBACK __crt_xl_tls_callback__ __attribute__ ((section(".CRT$XLB"))) = on_tls_callback;
PIMAGE_TLS_CALLBACK __crt_xl_end__ __attribute__ ((section(".CRT$XLZ"))) = 0;
}
extern "C" const IMAGE_TLS_DIRECTORY32 _tls_used __attribute__ ((section(".rdata$T"))) =
{
(DWORD) &__tls_start__,
(DWORD) &__tls_end__,
(DWORD) &__tls_index__,
(DWORD) (&__crt_xl_start__+1),
(DWORD) 0,
(DWORD) 0
};
#elif defined(_MSC_VER) && !defined(UNDER_CE)
#include <boost/thread/detail/tss_hooks.hpp>
#include <stdlib.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
//Definitions required by implementation
#if (_MSC_VER < 1300) // 1300 == VC++ 7.0
typedef void (__cdecl *_PVFV)(void);
#define INIRETSUCCESS
#define PVAPI void
#else
typedef int (__cdecl *_PVFV)(void);
#define INIRETSUCCESS 0
#define PVAPI int
#endif
typedef void (NTAPI* _TLSCB)(HINSTANCE, DWORD, PVOID);
//Symbols for connection to the runtime environment
extern "C"
{
extern DWORD _tls_used; //the tls directory (located in .rdata segment)
extern _TLSCB __xl_a[], __xl_z[]; //tls initializers */
}
namespace
{
//Forward declarations
static PVAPI on_tls_prepare(void);
static PVAPI on_process_init(void);
static PVAPI on_process_term(void);
static void NTAPI on_tls_callback(HINSTANCE, DWORD, PVOID);
//The .CRT$Xxx information is taken from Codeguru:
//http://www.codeguru.com/Cpp/misc/misc/threadsprocesses/article.php/c6945__2/
#if (_MSC_VER >= 1400)
#pragma section(".CRT$XIU",long,read)
#pragma section(".CRT$XCU",long,read)
#pragma section(".CRT$XTU",long,read)
#pragma section(".CRT$XLC",long,read)
__declspec(allocate(".CRT$XLC")) _TLSCB __xl_ca=on_tls_callback;
__declspec(allocate(".CRT$XIU"))_PVFV p_tls_prepare = on_tls_prepare;
__declspec(allocate(".CRT$XCU"))_PVFV p_process_init = on_process_init;
__declspec(allocate(".CRT$XTU"))_PVFV p_process_term = on_process_term;
#else
#if (_MSC_VER >= 1300) // 1300 == VC++ 7.0
# pragma data_seg(push, old_seg)
#endif
//Callback to run tls glue code first.
//I don't think it is necessary to run it
//at .CRT$XIB level, since we are only
//interested in thread detachement. But
//this could be changed easily if required.
#pragma data_seg(".CRT$XIU")
static _PVFV p_tls_prepare = on_tls_prepare;
#pragma data_seg()
//Callback after all global ctors.
#pragma data_seg(".CRT$XCU")
static _PVFV p_process_init = on_process_init;
#pragma data_seg()
//Callback for tls notifications.
#pragma data_seg(".CRT$XLB")
_TLSCB p_thread_callback = on_tls_callback;
#pragma data_seg()
//Callback for termination.
#pragma data_seg(".CRT$XTU")
static _PVFV p_process_term = on_process_term;
#pragma data_seg()
#if (_MSC_VER >= 1300) // 1300 == VC++ 7.0
# pragma data_seg(pop, old_seg)
#endif
#endif
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable:4189)
#endif
PVAPI on_tls_prepare(void)
{
//The following line has an important side effect:
//if the TLS directory is not already there, it will
//be created by the linker. In other words, it forces a tls
//directory to be generated by the linker even when static tls
//(i.e. __declspec(thread)) is not used.
//The volatile should prevent the optimizer
//from removing the reference.
DWORD volatile dw = _tls_used;
#if (_MSC_VER < 1300) // 1300 == VC++ 7.0
_TLSCB* pfbegin = __xl_a;
_TLSCB* pfend = __xl_z;
_TLSCB* pfdst = pfbegin;
//pfdst = (_TLSCB*)_tls_used.AddressOfCallBacks;
//The following loop will merge the address pointers
//into a contiguous area, since the tlssup code seems
//to require this (at least on MSVC 6)
while (pfbegin < pfend)
{
if (*pfbegin != 0)
{
*pfdst = *pfbegin;
++pfdst;
}
++pfbegin;
}
*pfdst = 0;
#endif
return INIRETSUCCESS;
}
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
PVAPI on_process_init(void)
{
//Schedule on_thread_exit() to be called for the main
//thread before destructors of global objects have been
//called.
//It will not be run when 'quick' exiting the
//library; however, this is the standard behaviour
//for destructors of global objects, so that
//shouldn't be a problem.
atexit(on_thread_exit);
//Call Boost process entry callback here
on_process_enter();
return INIRETSUCCESS;
}
PVAPI on_process_term(void)
{
on_process_exit();
return INIRETSUCCESS;
}
void NTAPI on_tls_callback(HINSTANCE /*h*/, DWORD dwReason, PVOID /*pv*/)
{
switch (dwReason)
{
case DLL_THREAD_DETACH:
on_thread_exit();
break;
}
}
BOOL WINAPI dll_callback(HANDLE, DWORD dwReason, LPVOID)
{
switch (dwReason)
{
case DLL_THREAD_DETACH:
on_thread_exit();
break;
case DLL_PROCESS_DETACH:
on_process_exit();
break;
}
return true;
}
} //namespace
extern "C"
{
extern BOOL (WINAPI * const _pRawDllMain)(HANDLE, DWORD, LPVOID)=&dll_callback;
}
extern "C" void tss_cleanup_implemented(void)
{
/*
This function's sole purpose is to cause a link error in cases where
automatic tss cleanup is not implemented by Boost.Threads as a
reminder that user code is responsible for calling the necessary
functions at the appropriate times (and for implementing an a
tss_cleanup_implemented() function to eliminate the linker's
missing symbol error).
If Boost.Threads later implements automatic tss cleanup in cases
where it currently doesn't (which is the plan), the duplicate
symbol error will warn the user that their custom solution is no
longer needed and can be removed.
*/
}
#endif //defined(_MSC_VER) && !defined(UNDER_CE)
#endif //defined(BOOST_HAS_WINTHREADS) && defined(BOOST_THREAD_BUILD_LIB)
|
7ofNine/piranha
|
src/boost_thread/win32/tss_pe.cpp
|
C++
|
gpl-2.0
| 8,746
|
;
/*!
* Superfish v1.4.8 - jQuery menu widget
* Copyright (c) 2008 Joel Birch
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
*/
(function($){
$.fn.superfish = function(op){
var sf = $.fn.superfish,
c = sf.c,
$arrow = $(['<span class="',c.arrowClass,'"> »</span>'].join('')),
over = function(){
var $$ = $(this), menu = getMenu($$);
clearTimeout(menu.sfTimer);
$$.showSuperfishUl().siblings().hideSuperfishUl();
},
out = function(){
var $$ = $(this), menu = getMenu($$), o = sf.op;
clearTimeout(menu.sfTimer);
menu.sfTimer = setTimeout(function(){
o.retainPath = ($.inArray($$[0],o.$path) > -1);
$$.hideSuperfishUl();
if (o.$path.length && $$.parents(['li.', o.hoverClass].join('')).length < 1){
over.call(o.$path);
}
}, o.delay);
},
getMenu = function($menu){
var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
sf.op = sf.o[menu.serial];
return menu;
},
addArrow = function($a){
$a.addClass(c.anchorClass).append($arrow.clone());
};
return this.each(function() {
var s = this.serial = sf.o.length;
var o = $.extend({},sf.defaults,op);
o.$path = $('li.' + o.pathClass,this).slice(0, o.pathLevels).each(function(){
$(this).addClass([o.hoverClass,c.bcClass].join(' '))
.filter('li:has(ul)').removeClass(o.pathClass);
});
sf.o[s] = sf.op = o;
$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
if (o.autoArrows) {
addArrow($('>a:first-child',this));
}
})
.not('.' + c.bcClass)
.hideSuperfishUl();
var $a = $('a',this);
$a.each(function(i){
var $li = $a.eq(i).parents('li');
$a.eq(i).focus(function(){
over.call($li);
}).blur(function(){
out.call($li);
});
});
o.onInit.call(this);
}).each(function() {
var menuClasses = [c.menuClass];
if (sf.op.dropShadows && !($.browser.msie && $.browser.version < 7)) {
menuClasses.push(c.shadowClass);
}
$(this).addClass(menuClasses.join(' '));
});
};
var sf = $.fn.superfish;
sf.o = [];
sf.op = {};
sf.IE7fix = function(){
var o = sf.op;
if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity != undefined) {
this.toggleClass(sf.c.shadowClass + '-off');
}
};
sf.c = {
bcClass : 'sf-breadcrumb',
menuClass : 'sf-js-enabled',
anchorClass : 'sf-with-ul',
arrowClass : 'sf-sub-indicator',
shadowClass : 'sf-shadow'
};
sf.defaults = {
hoverClass : 'sfHover',
pathClass : 'overideThisToUse',
pathLevels : 1,
delay : 800,
animation : {
opacity:'show'
},
speed : 'normal',
autoArrows : true,
dropShadows : true,
// true disables hoverIntent detection.
disableHI : false,
onInit : function(){}, // callback functions
onBeforeShow: function(){},
onShow : function(){},
onHide : function(){}
};
$.fn.extend({
hideSuperfishUl : function() {
var o = sf.op,
not = (o.retainPath === true) ? o.$path : '';
o.retainPath = false;
var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
.find('>ul').hide().css('visibility','hidden');
o.onHide.call($ul);
return this;
},
showSuperfishUl : function(){
var o = sf.op,
sh = sf.c.shadowClass + '-off',
$ul = this.addClass(o.hoverClass)
.find('>ul:hidden').css('visibility','visible');
sf.IE7fix.call($ul);
o.onBeforeShow.call($ul);
$ul.animate(o.animation,o.speed,function(){
sf.IE7fix.call($ul);
o.onShow.call($ul);
});
return this;
}
});
})(jQuery);
|
acappellamaniac/eva_website
|
sites/all/modules/nice_menus/js/superfish.js
|
JavaScript
|
gpl-2.0
| 4,275
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl
Copyright (C) 2003, 2004, 2005 StatPro Italia srl
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file mctraits.hpp
\brief Monte Carlo policies
*/
#ifndef quantlib_mc_traits_hpp
#define quantlib_mc_traits_hpp
#include <ql/methods/montecarlo/pathgenerator.hpp>
#include <ql/methods/montecarlo/multipathgenerator.hpp>
#include <ql/methods/montecarlo/pathpricer.hpp>
#include <ql/math/randomnumbers/rngtraits.hpp>
namespace QuantLib {
// path generation and pricing traits
//! default Monte Carlo traits for single-variate models
template <class RNG = PseudoRandom>
struct SingleVariate {
typedef RNG rng_traits;
typedef Path path_type;
typedef PathPricer<path_type> path_pricer_type;
typedef typename RNG::rsg_type rsg_type;
typedef PathGenerator<rsg_type> path_generator_type;
enum { allowsErrorEstimate = RNG::allowsErrorEstimate };
};
//! default Monte Carlo traits for multi-variate models
template <class RNG = PseudoRandom>
struct MultiVariate {
typedef RNG rng_traits;
typedef MultiPath path_type;
typedef PathPricer<path_type> path_pricer_type;
typedef typename RNG::rsg_type rsg_type;
typedef MultiPathGenerator<rsg_type> path_generator_type;
enum { allowsErrorEstimate = RNG::allowsErrorEstimate };
};
}
#endif
|
EuroPlusFinance/Software
|
Quantum Trading Platforms/QuantLib-1.4/ql/methods/montecarlo/mctraits.hpp
|
C++
|
gpl-2.0
| 2,138
|
#
# (C) Copyright 2013 Freescale Semiconductor, Inc.
#
# SPDX-License-Identifier: GPL-2.0+
#
include $(TOPDIR)/config.mk
LIB = $(obj)lib$(BOARD).o
COBJS := wandboard.o
SRCS := $(COBJS:.o=.c)
OBJS := $(addprefix $(obj),$(COBJS))
$(LIB): $(obj).depend $(OBJS)
$(call cmd_link_o_target, $(OBJS))
#########################################################################
# defines $(obj).depend target
include $(SRCTREE)/rules.mk
sinclude $(obj).depend
#########################################################################
|
luckyboy/uboot
|
u-boot-2013.10/board/wandboard/Makefile
|
Makefile
|
gpl-2.0
| 548
|
<?php
/**
* ExternalSearch Recommendation Module
*
* PHP version 7
*
* Copyright (C) Villanova University 2019.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Recommendations
* @author Mark Triggs <vufind-tech@lists.sourceforge.net>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Page
*/
namespace VuFind\Recommend;
/**
* ExternalSearch Recommendation Module
*
* @category VuFind
* @package Recommendations
* @author Chris Hallberg <challber@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Page
*/
class ExternalSearch implements RecommendInterface
{
/**
* Link text
*
* @var string
*/
protected $linkText;
/**
* URL template string
*
* @var string
*/
protected $template;
/**
* Search query
*
* @var string
*/
protected $lookfor;
/**
* Store the configuration of the recommendation module.
*
* @param string $settingsStr Settings from searches.ini.
*
* @return void
*/
public function setConfig($settingsStr)
{
// Parse the settings:
$settings = explode(':', $settingsStr, 2);
$this->linkText = $settings[0] ?? null;
$this->template = $settings[1] ?? null;
}
/**
* Called at the end of the Search Params objects' initFromRequest() method.
* This method is responsible for setting search parameters needed by the
* recommendation module and for reading any existing search parameters that may
* be needed.
*
* @param \VuFind\Search\Base\Params $params Search parameter object
* @param \Laminas\Stdlib\Parameters $request Parameter object representing user
* request.
*
* @return void
*/
public function init($params, $request)
{
$this->lookfor = $request->get('lookfor');
}
/**
* Called after the Search Results object has performed its main search. This
* may be used to extract necessary information from the Search Results object
* or to perform completely unrelated processing.
*
* @param \VuFind\Search\Base\Results $results Search results object
*
* @return void
*/
public function process($results)
{
// no action needed
}
/**
* Get the link text.
*
* @return string
*/
public function getLinkText()
{
return $this->linkText;
}
/**
* Get the link URL.
*
* @return string
*/
public function getUrl()
{
return (false === strpos($this->template, '%%lookfor%%'))
? $this->template . urlencode($this->lookfor)
: str_replace('%%lookfor%%', urlencode($this->lookfor), $this->template);
}
}
|
swissbib/vufind
|
module/VuFind/src/VuFind/Recommend/ExternalSearch.php
|
PHP
|
gpl-2.0
| 3,543
|
/* -*- c++ -*- ----------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
https://www.lammps.org/, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#ifdef FIX_CLASS
// clang-format off
FixStyle(setforce,FixSetForce);
// clang-format on
#else
#ifndef LMP_FIX_SET_FORCE_H
#define LMP_FIX_SET_FORCE_H
#include "fix.h"
namespace LAMMPS_NS {
class FixSetForce : public Fix {
public:
FixSetForce(class LAMMPS *, int, char **);
~FixSetForce() override;
int setmask() override;
void init() override;
void setup(int) override;
void min_setup(int) override;
void post_force(int) override;
void post_force_respa(int, int, int) override;
void min_post_force(int) override;
double compute_vector(int) override;
double memory_usage() override;
protected:
double xvalue, yvalue, zvalue;
int varflag, iregion;
char *xstr, *ystr, *zstr;
char *idregion;
int xvar, yvar, zvar, xstyle, ystyle, zstyle;
double foriginal[3], foriginal_all[3], foriginal_saved[3];
int force_flag;
int nlevels_respa, ilevel_respa;
int maxatom;
double **sforce;
};
} // namespace LAMMPS_NS
#endif
#endif
/* ERROR/WARNING messages:
E: Illegal ... command
Self-explanatory. Check the input script syntax and compare to the
documentation for the command. You can use -echo screen as a
command-line option when running LAMMPS to see the offending line.
E: Region ID for fix setforce does not exist
Self-explanatory.
E: Variable name for fix setforce does not exist
Self-explanatory.
E: Variable for fix setforce is invalid style
Only equal-style variables can be used.
E: Cannot use non-zero forces in an energy minimization
Fix setforce cannot be used in this manner. Use fix addforce
instead.
*/
|
ndtrung81/lammps
|
src/fix_setforce.h
|
C
|
gpl-2.0
| 2,202
|
package ProFTPD::Tests::Config::Directory::Limits;
use lib qw(t/lib);
use base qw(ProFTPD::TestSuite::Child);
use strict;
use Cwd;
use File::Path qw(mkpath);
use File::Spec;
use IO::Handle;
use ProFTPD::TestSuite::FTP;
use ProFTPD::TestSuite::Utils qw(:auth :config :running :test :testsuite);
$| = 1;
my $order = 0;
# A fun collection of various <Directory> and <Limit> configurations
my $TESTS = {
limits_with_glob_then_nonglob_dirs_for_same_path => {
order => ++$order,
test_class => [qw(forking)],
},
limits_with_nonglob_then_glob_dirs_for_same_path => {
order => ++$order,
test_class => [qw(forking)],
},
limits_with_glob_denied_delete_bug3146 => {
order => ++$order,
test_class => [qw(bug forking)],
},
limits_without_glob_denied_delete_bug3146 => {
order => ++$order,
test_class => [qw(bug forking)],
},
limits_commands_comma_space_delimited_deferred_paths_bug3147 => {
order => ++$order,
test_class => [qw(bug forking)],
},
limits_commands_comma_delimited_deferred_paths_bug3147 => {
order => ++$order,
test_class => [qw(bug forking)],
},
limits_commands_no_commas_deferred_paths_bug3147 => {
order => ++$order,
test_class => [qw(bug forking)],
},
limits_rename_dir_ok_write_denied => {
order => ++$order,
test_class => [qw(forking)],
},
limits_rename_dir_failed_rnfr_denied => {
order => ++$order,
test_class => [qw(forking)],
},
limits_one_char_dir_bug3337 => {
order => ++$order,
test_class => [qw(bug forking)],
},
limits_symlink_dir_bug3166 => {
order => ++$order,
test_class => [qw(bug forking rootprivs)],
},
limits_anon_dir_abs_path_bug3283 => {
order => ++$order,
test_class => [qw(bug forking rootprivs)],
},
limits_with_multi_globs_denied_delete => {
order => ++$order,
test_class => [qw(forking)],
},
limits_retr_bug3915 => {
order => ++$order,
test_class => [qw(bug forking)],
},
limits_retr_bug3915_chrooted => {
order => ++$order,
test_class => [qw(bug forking rootprivs)],
},
limits_stor_with_multiple_groups_chrooted => {
order => ++$order,
test_class => [qw(bug forking rootprivs)],
},
};
sub new {
return shift()->SUPER::new(@_);
}
sub list_tests {
return testsuite_get_runnable_tests($TESTS);
}
sub limits_with_glob_then_nonglob_dirs_for_same_path {
my $self = shift;
my $tmpdir = $self->{tmpdir};
my $config_file = "$tmpdir/dir.conf";
my $pid_file = File::Spec->rel2abs("$tmpdir/dir.pid");
my $scoreboard_file = File::Spec->rel2abs("$tmpdir/dir.scoreboard");
my $log_file = test_get_logfile();
my $auth_user_file = File::Spec->rel2abs("$tmpdir/dir.passwd");
my $auth_group_file = File::Spec->rel2abs("$tmpdir/dir.group");
my $user = 'proftpd';
my $passwd = 'test';
my $group = 'ftpd';
my $home_dir = File::Spec->rel2abs("$tmpdir/home/users/$user");
my $uid = 500;
my $gid = 500;
mkpath($home_dir);
# Make sure that, if we're running as root, that the home directory has
# permissions/privs set for the account we create
if ($< == 0) {
unless (chmod(0755, $home_dir)) {
die("Can't set perms on $home_dir to 0755: $!");
}
unless (chown($uid, $gid, $home_dir)) {
die("Can't set owner of $home_dir to $uid/$gid: $!");
}
}
auth_user_write($auth_user_file, $user, $passwd, $uid, $gid, $home_dir,
'/bin/bash');
auth_group_write($auth_group_file, $group, $gid, $user);
my $abs_tmp_dir = File::Spec->rel2abs($tmpdir);
my $config = {
PidFile => $pid_file,
ScoreboardFile => $scoreboard_file,
SystemLog => $log_file,
TraceLog => $log_file,
Trace => 'DEFAULT:10 fsio:0 directory:10 lock:0',
AuthUserFile => $auth_user_file,
AuthGroupFile => $auth_group_file,
DefaultChdir => '~',
IfModules => {
'mod_delay.c' => {
DelayEngine => 'off',
},
},
};
my ($port, $config_user, $config_group) = config_write($config_file, $config);
# In order to ensure that the <Directory> sections appear in the desired
# order in the config file, we write them out here. The config_write()
# function, whilst useful, uses hashrefs, which means the ordering of the
# keys is not necessarily predictable.
if (open(my $fh, ">> $config_file")) {
print $fh <<EOD;
<Directory $abs_tmp_dir/home/*/proftpd>
<Limit ALL>
DenyAll
</Limit>
</Directory>
<Directory $abs_tmp_dir/home/users/proftpd>
<Limit ALL>
AllowAll
</Limit>
</Directory>
EOD
close($fh);
} else {
die("Can't read $config_file: $!");
}
# Open pipes, for use between the parent and child processes. Specifically,
# the child will indicate when it's done with its test by writing a message
# to the parent.
my ($rfh, $wfh);
unless (pipe($rfh, $wfh)) {
die("Can't open pipe: $!");
}
my $ex;
# Fork child
$self->handle_sigchld();
defined(my $pid = fork()) or die("Can't fork: $!");
if ($pid) {
eval {
my $client = ProFTPD::TestSuite::FTP->new('127.0.0.1', $port);
$client->login($user, $passwd);
my ($resp_code, $resp_msg);
my $conn = $client->stor_raw('test.txt');
unless ($conn) {
die("Failed to STOR test.txt: " . $client->response_code() . " " .
$client->response_msg());
};
my $buf = "Hello, World\n";
$conn->write($buf, length($buf));
$conn->close();
$resp_code = $client->response_code();
$resp_msg = $client->response_msg();
my $expected;
$expected = 226;
$self->assert($expected == $resp_code,
test_msg("Expected $expected, got $resp_code"));
$expected = "Transfer complete";
$self->assert($expected eq $resp_msg,
test_msg("Expected '$expected', got '$resp_msg'"));
};
if ($@) {
$ex = $@;
}
$wfh->print("done\n");
$wfh->flush();
} else {
eval { server_wait($config_file, $rfh) };
if ($@) {
warn($@);
exit 1;
}
exit 0;
}
# Stop server
server_stop($pid_file);
$self->assert_child_ok($pid);
if ($ex) {
test_append_logfile($log_file, $ex);
unlink($log_file);
die($ex);
}
unlink($log_file);
}
sub limits_with_nonglob_then_glob_dirs_for_same_path {
my $self = shift;
my $tmpdir = $self->{tmpdir};
my $config_file = "$tmpdir/dir.conf";
my $pid_file = File::Spec->rel2abs("$tmpdir/dir.pid");
my $scoreboard_file = File::Spec->rel2abs("$tmpdir/dir.scoreboard");
my $log_file = test_get_logfile();
my $auth_user_file = File::Spec->rel2abs("$tmpdir/dir.passwd");
my $auth_group_file = File::Spec->rel2abs("$tmpdir/dir.group");
my $user = 'proftpd';
my $passwd = 'test';
my $group = 'ftpd';
my $home_dir = File::Spec->rel2abs("$tmpdir/home/users/$user");
my $uid = 500;
my $gid = 500;
mkpath($home_dir);
# Make sure that, if we're running as root, that the home directory has
# permissions/privs set for the account we create
if ($< == 0) {
unless (chmod(0755, $home_dir)) {
die("Can't set perms on $home_dir to 0755: $!");
}
unless (chown($uid, $gid, $home_dir)) {
die("Can't set owner of $home_dir to $uid/$gid: $!");
}
}
auth_user_write($auth_user_file, $user, $passwd, $uid, $gid, $home_dir,
'/bin/bash');
auth_group_write($auth_group_file, $group, $gid, $user);
my $abs_tmp_dir = File::Spec->rel2abs($tmpdir);
my $config = {
PidFile => $pid_file,
ScoreboardFile => $scoreboard_file,
SystemLog => $log_file,
TraceLog => $log_file,
Trace => 'DEFAULT:10 fsio:0 directory:10 lock:0',
AuthUserFile => $auth_user_file,
AuthGroupFile => $auth_group_file,
DefaultChdir => '~',
IfModules => {
'mod_delay.c' => {
DelayEngine => 'off',
},
},
};
my ($port, $config_user, $config_group) = config_write($config_file, $config);
# In order to ensure that the <Directory> sections appear in the desired
# order in the config file, we write them out here. The config_write()
# function, whilst useful, uses hashrefs, which means the ordering of the
# keys is not necessarily predictable.
if (open(my $fh, ">> $config_file")) {
print $fh <<EOD;
<Directory $abs_tmp_dir/home/users/proftpd>
<Limit ALL>
AllowAll
</Limit>
</Directory>
<Directory $abs_tmp_dir/home/*/proftpd>
<Limit ALL>
DenyAll
</Limit>
</Directory>
EOD
close($fh);
} else {
die("Can't read $config_file: $!");
}
# Open pipes, for use between the parent and child processes. Specifically,
# the child will indicate when it's done with its test by writing a message
# to the parent.
my ($rfh, $wfh);
unless (pipe($rfh, $wfh)) {
die("Can't open pipe: $!");
}
my $ex;
# Fork child
$self->handle_sigchld();
defined(my $pid = fork()) or die("Can't fork: $!");
if ($pid) {
eval {
my $client = ProFTPD::TestSuite::FTP->new('127.0.0.1', $port);
$client->login($user, $passwd);
my ($resp_code, $resp_msg);
my $conn = $client->stor_raw('test.txt');
if ($conn) {
die("STOR test.txt succeeded unexpectedly");
};
$resp_code = $client->response_code();
$resp_msg = $client->response_msg();
my $expected;
$expected = 550;
$self->assert($expected == $resp_code,
test_msg("Expected $expected, got $resp_code"));
$expected = "test.txt: Operation not permitted";
$self->assert($expected eq $resp_msg,
test_msg("Expected '$expected', got '$resp_msg'"));
};
if ($@) {
$ex = $@;
}
$wfh->print("done\n");
$wfh->flush();
} else {
eval { server_wait($config_file, $rfh) };
if ($@) {
warn($@);
exit 1;
}
exit 0;
}
# Stop server
server_stop($pid_file);
$self->assert_child_ok($pid);
if ($ex) {
test_append_logfile($log_file, $ex);
unlink($log_file);
die($ex);
}
unlink($log_file);
}
sub limits_with_glob_denied_delete_bug3146 {
my $self = shift;
my $tmpdir = $self->{tmpdir};
# This config is from:
#
# http://forums.proftpd.org/smf/index.php/topic,3491.0
# http://bugs.proftpd.org/show_bug.cgi?id=3146
my $config_file = "$tmpdir/dir.conf";
my $pid_file = File::Spec->rel2abs("$tmpdir/dir.pid");
my $scoreboard_file = File::Spec->rel2abs("$tmpdir/dir.scoreboard");
my $log_file = test_get_logfile();
my $auth_user_file = File::Spec->rel2abs("$tmpdir/dir.passwd");
my $auth_group_file = File::Spec->rel2abs("$tmpdir/dir.group");
my $user = 'proftpd';
my $passwd = 'test';
my $group = 'ftpd';
my $home_dir = File::Spec->rel2abs("$tmpdir/home/users/$user");
my $uid = 500;
my $gid = 500;
mkpath($home_dir);
my $test_file = File::Spec->rel2abs("$home_dir/test.txt");
if (open(my $fh, "> $test_file")) {
print $fh "Hello, World!\n";
unless (close($fh)) {
die("Can't write $test_file: $!");
}
} else {
die("Can't open $test_file: $!");
}
# Make sure that, if we're running as root, that the home directory has
# permissions/privs set for the account we create
if ($< == 0) {
unless (chmod(0755, $home_dir)) {
die("Can't set perms on $home_dir to 0755: $!");
}
unless (chown($uid, $gid, $home_dir)) {
die("Can't set owner of $home_dir to $uid/$gid: $!");
}
}
auth_user_write($auth_user_file, $user, $passwd, $uid, $gid, $home_dir,
'/bin/bash');
auth_group_write($auth_group_file, $group, $gid, $user);
my $abs_tmp_dir = File::Spec->rel2abs($tmpdir);
my $config = {
PidFile => $pid_file,
ScoreboardFile => $scoreboard_file,
SystemLog => $log_file,
TraceLog => $log_file,
Trace => 'DEFAULT:10 fsio:0 directory:10 lock:0',
AuthUserFile => $auth_user_file,
AuthGroupFile => $auth_group_file,
DefaultChdir => '~',
Directory => {
"$abs_tmp_dir/home/*/proftpd" => {
Limit => {
'ALL' => {
DenyAll => '',
},
'CDUP CWD XCWD XCUP LIST NLST' => {
AllowAll => '',
},
'STOR STOU' => {
AllowAll => '',
},
},
},
},
IfModules => {
'mod_delay.c' => {
DelayEngine => 'off',
},
},
};
my ($port, $config_user, $config_group) = config_write($config_file, $config);
# Open pipes, for use between the parent and child processes. Specifically,
# the child will indicate when it's done with its test by writing a message
# to the parent.
my ($rfh, $wfh);
unless (pipe($rfh, $wfh)) {
die("Can't open pipe: $!");
}
my $ex;
# Fork child
$self->handle_sigchld();
defined(my $pid = fork()) or die("Can't fork: $!");
if ($pid) {
eval {
my $client = ProFTPD::TestSuite::FTP->new('127.0.0.1', $port);
$client->login($user, $passwd);
my ($resp_code, $resp_msg);
eval { $client->dele('test.txt') };
unless ($@) {
die("DELE succeeded unexpectedly");
} else {
$resp_code = $client->response_code();
$resp_msg = $client->response_msg();
}
my $expected;
$expected = 550;
$self->assert($expected == $resp_code,
test_msg("Expected $expected, got $resp_code"));
$expected = "test.txt: Operation not permitted";
$self->assert($expected eq $resp_msg,
test_msg("Expected '$expected', got '$resp_msg'"));
};
if ($@) {
$ex = $@;
}
$wfh->print("done\n");
$wfh->flush();
} else {
eval { server_wait($config_file, $rfh) };
if ($@) {
warn($@);
exit 1;
}
exit 0;
}
# Stop server
server_stop($pid_file);
$self->assert_child_ok($pid);
if ($ex) {
test_append_logfile($log_file, $ex);
unlink($log_file);
die($ex);
}
unlink($log_file);
}
sub limits_without_glob_denied_delete_bug3146 {
my $self = shift;
my $tmpdir = $self->{tmpdir};
# This config is from:
#
# http://forums.proftpd.org/smf/index.php/topic,3491.0
#
# only without the glob pattern, to check for regressions.
my $config_file = "$tmpdir/dir.conf";
my $pid_file = File::Spec->rel2abs("$tmpdir/dir.pid");
my $scoreboard_file = File::Spec->rel2abs("$tmpdir/dir.scoreboard");
my $log_file = test_get_logfile();
my $auth_user_file = File::Spec->rel2abs("$tmpdir/dir.passwd");
my $auth_group_file = File::Spec->rel2abs("$tmpdir/dir.group");
my $user = 'proftpd';
my $passwd = 'test';
my $group = 'ftpd';
my $home_dir = File::Spec->rel2abs("$tmpdir/home/users/$user");
my $uid = 500;
my $gid = 500;
mkpath($home_dir);
my $test_file = File::Spec->rel2abs("$home_dir/test.txt");
if (open(my $fh, "> $test_file")) {
print $fh "Hello, World!\n";
unless (close($fh)) {
die("Can't write $test_file: $!");
}
} else {
die("Can't open $test_file: $!");
}
# Make sure that, if we're running as root, that the home directory has
# permissions/privs set for the account we create
if ($< == 0) {
unless (chmod(0755, $home_dir)) {
die("Can't set perms on $home_dir to 0755: $!");
}
unless (chown($uid, $gid, $home_dir)) {
die("Can't set owner of $home_dir to $uid/$gid: $!");
}
}
auth_user_write($auth_user_file, $user, $passwd, $uid, $gid, $home_dir,
'/bin/bash');
auth_group_write($auth_group_file, $group, $gid, $user);
my $abs_tmp_dir = File::Spec->rel2abs($tmpdir);
my $config = {
PidFile => $pid_file,
ScoreboardFile => $scoreboard_file,
SystemLog => $log_file,
TraceLog => $log_file,
Trace => 'DEFAULT:10 fsio:0 directory:10 lock:0',
AuthUserFile => $auth_user_file,
AuthGroupFile => $auth_group_file,
DefaultChdir => '~',
Directory => {
"$abs_tmp_dir/home/users/proftpd" => {
Limit => {
'ALL' => {
DenyAll => '',
},
'CDUP CWD XCWD XCUP LIST NLST' => {
AllowAll => '',
},
'STOR STOU' => {
AllowAll => '',
},
},
},
},
IfModules => {
'mod_delay.c' => {
DelayEngine => 'off',
},
},
};
my ($port, $config_user, $config_group) = config_write($config_file, $config);
# Open pipes, for use between the parent and child processes. Specifically,
# the child will indicate when it's done with its test by writing a message
# to the parent.
my ($rfh, $wfh);
unless (pipe($rfh, $wfh)) {
die("Can't open pipe: $!");
}
my $ex;
# Fork child
$self->handle_sigchld();
defined(my $pid = fork()) or die("Can't fork: $!");
if ($pid) {
eval {
my $client = ProFTPD::TestSuite::FTP->new('127.0.0.1', $port);
$client->login($user, $passwd);
my ($resp_code, $resp_msg);
eval { $client->dele('test.txt') };
unless ($@) {
die("DELE succeeded unexpectedly");
} else {
$resp_code = $client->response_code();
$resp_msg = $client->response_msg();
}
my $expected;
$expected = 550;
$self->assert($expected == $resp_code,
test_msg("Expected $expected, got $resp_code"));
$expected = "test.txt: Operation not permitted";
$self->assert($expected eq $resp_msg,
test_msg("Expected '$expected', got '$resp_msg'"));
};
if ($@) {
$ex = $@;
}
$wfh->print("done\n");
$wfh->flush();
} else {
eval { server_wait($config_file, $rfh) };
if ($@) {
warn($@);
exit 1;
}
exit 0;
}
# Stop server
server_stop($pid_file);
$self->assert_child_ok($pid);
if ($ex) {
test_append_logfile($log_file, $ex);
unlink($log_file);
die($ex);
}
unlink($log_file);
}
sub limits_commands_comma_space_delimited_deferred_paths_bug3147 {
my $self = shift;
my $tmpdir = $self->{tmpdir};
# This config is from:
#
# http://forums.proftpd.org/smf/index.php/topic,3648.0
# http://bugs.proftpd.org/show_bug.cgi?id=3147
my $config_file = "$tmpdir/dir.conf";
my $pid_file = File::Spec->rel2abs("$tmpdir/dir.pid");
my $scoreboard_file = File::Spec->rel2abs("$tmpdir/dir.scoreboard");
my $log_file = test_get_logfile();
my $auth_user_file = File::Spec->rel2abs("$tmpdir/dir.passwd");
my $auth_group_file = File::Spec->rel2abs("$tmpdir/dir.group");
my $user = 'proftpd';
my $passwd = 'test';
my $group = 'ftpd';
my $home_dir = File::Spec->rel2abs("$tmpdir/home/$user");
my $uid = 500;
my $gid = 500;
mkpath($home_dir);
my $sub_dir = File::Spec->rel2abs("$tmpdir/home/$user/upload");
mkpath($sub_dir);
# Make sure that, if we're running as root, that the home directory has
# permissions/privs set for the account we create
if ($< == 0) {
unless (chmod(0755, $home_dir, $sub_dir)) {
die("Can't set perms on $home_dir, $sub_dir to 0755: $!");
}
unless (chown($uid, $gid, $home_dir, $sub_dir)) {
die("Can't set owner of $home_dir, $sub_dir to $uid/$gid: $!");
}
}
auth_user_write($auth_user_file, $user, $passwd, $uid, $gid, $home_dir,
'/bin/bash');
auth_group_write($auth_group_file, $group, $gid, $user);
my $config = {
PidFile => $pid_file,
ScoreboardFile => $scoreboard_file,
SystemLog => $log_file,
TraceLog => $log_file,
Trace => 'DEFAULT:10 fsio:0 directory:10 lock:0',
AuthUserFile => $auth_user_file,
AuthGroupFile => $auth_group_file,
DefaultChdir => '~',
Directory => {
"~$user" => {
Limit => {
'WRITE' => {
DenyAll => '',
},
},
},
# Bug#3147 happened because proftpd's parsing of the list of commands
# in the <Limit> section was not properly handling commas after the
# command names.
"~$user/upload" => {
Limit => {
'STOR, APPE, MKD, RMD, RNTO, STOU, XMKD, XRMD' => {
AllowAll => '',
},
},
},
},
IfModules => {
'mod_delay.c' => {
DelayEngine => 'off',
},
},
};
my ($port, $config_user, $config_group) = config_write($config_file, $config);
# Open pipes, for use between the parent and child processes. Specifically,
# the child will indicate when it's done with its test by writing a message
# to the parent.
my ($rfh, $wfh);
unless (pipe($rfh, $wfh)) {
die("Can't open pipe: $!");
}
my $ex;
# Fork child
$self->handle_sigchld();
defined(my $pid = fork()) or die("Can't fork: $!");
if ($pid) {
eval {
my $client = ProFTPD::TestSuite::FTP->new('127.0.0.1', $port);
$client->login($user, $passwd);
my ($resp_code, $resp_msg);
my $conn = $client->stor_raw('upload/test.txt');
unless ($conn) {
die("Failed to STOR upload/test.txt: " . $client->response_code() .
" " . $client->response_msg());
}
my $buf = "Hello, World!\n";
$conn->write($buf, length($buf));
$conn->close();
$resp_code = $client->response_code();
$resp_msg = $client->response_msg();
my $expected;
$expected = 226;
$self->assert($expected == $resp_code,
test_msg("Expected $expected, got $resp_code"));
$expected = "Transfer complete";
$self->assert($expected eq $resp_msg,
test_msg("Expected '$expected', got '$resp_msg'"));
};
if ($@) {
$ex = $@;
}
$wfh->print("done\n");
$wfh->flush();
} else {
eval { server_wait($config_file, $rfh) };
if ($@) {
warn($@);
exit 1;
}
exit 0;
}
# Stop server
server_stop($pid_file);
$self->assert_child_ok($pid);
if ($ex) {
test_append_logfile($log_file, $ex);
unlink($log_file);
die($ex);
}
unlink($log_file);
}
sub limits_commands_comma_delimited_deferred_paths_bug3147 {
my $self = shift;
my $tmpdir = $self->{tmpdir};
# This config is from:
#
# http://forums.proftpd.org/smf/index.php/topic,3648.0
# http://bugs.proftpd.org/show_bug.cgi?id=3147
my $config_file = "$tmpdir/dir.conf";
my $pid_file = File::Spec->rel2abs("$tmpdir/dir.pid");
my $scoreboard_file = File::Spec->rel2abs("$tmpdir/dir.scoreboard");
my $log_file = test_get_logfile();
my $auth_user_file = File::Spec->rel2abs("$tmpdir/dir.passwd");
my $auth_group_file = File::Spec->rel2abs("$tmpdir/dir.group");
my $user = 'proftpd';
my $passwd = 'test';
my $group = 'ftpd';
my $home_dir = File::Spec->rel2abs("$tmpdir/home/$user");
my $uid = 500;
my $gid = 500;
mkpath($home_dir);
my $sub_dir = File::Spec->rel2abs("$tmpdir/home/$user/upload");
mkpath($sub_dir);
# Make sure that, if we're running as root, that the home directory has
# permissions/privs set for the account we create
if ($< == 0) {
unless (chmod(0755, $home_dir, $sub_dir)) {
die("Can't set perms on $home_dir, $sub_dir to 0755: $!");
}
unless (chown($uid, $gid, $home_dir, $sub_dir)) {
die("Can't set owner of $home_dir, $sub_dir to $uid/$gid: $!");
}
}
auth_user_write($auth_user_file, $user, $passwd, $uid, $gid, $home_dir,
'/bin/bash');
auth_group_write($auth_group_file, $group, $gid, $user);
my $config = {
PidFile => $pid_file,
ScoreboardFile => $scoreboard_file,
SystemLog => $log_file,
TraceLog => $log_file,
Trace => 'DEFAULT:10 fsio:0 directory:10 lock:0',
AuthUserFile => $auth_user_file,
AuthGroupFile => $auth_group_file,
DefaultChdir => '~',
Directory => {
"~$user" => {
Limit => {
'WRITE' => {
DenyAll => '',
},
},
},
# Bug#3147 happened because proftpd's parsing of the list of commands
# in the <Limit> section was not properly handling commas after the
# command names.
"~$user/upload" => {
Limit => {
'STOR,APPE,MKD,RMD,RNTO,STOU,XMKD,XRMD' => {
AllowAll => '',
},
},
},
},
IfModules => {
'mod_delay.c' => {
DelayEngine => 'off',
},
},
};
my ($port, $config_user, $config_group) = config_write($config_file, $config);
# Open pipes, for use between the parent and child processes. Specifically,
# the child will indicate when it's done with its test by writing a message
# to the parent.
my ($rfh, $wfh);
unless (pipe($rfh, $wfh)) {
die("Can't open pipe: $!");
}
my $ex;
# Fork child
$self->handle_sigchld();
defined(my $pid = fork()) or die("Can't fork: $!");
if ($pid) {
eval {
my $client = ProFTPD::TestSuite::FTP->new('127.0.0.1', $port);
$client->login($user, $passwd);
my ($resp_code, $resp_msg);
my $conn = $client->stor_raw('upload/test.txt');
unless ($conn) {
die("Failed to STOR upload/test.txt: " . $client->response_code() .
" " . $client->response_msg());
}
my $buf = "Hello, World!\n";
$conn->write($buf, length($buf));
$conn->close();
$resp_code = $client->response_code();
$resp_msg = $client->response_msg();
my $expected;
$expected = 226;
$self->assert($expected == $resp_code,
test_msg("Expected $expected, got $resp_code"));
$expected = "Transfer complete";
$self->assert($expected eq $resp_msg,
test_msg("Expected '$expected', got '$resp_msg'"));
};
if ($@) {
$ex = $@;
}
$wfh->print("done\n");
$wfh->flush();
} else {
eval { server_wait($config_file, $rfh) };
if ($@) {
warn($@);
exit 1;
}
exit 0;
}
# Stop server
server_stop($pid_file);
$self->assert_child_ok($pid);
if ($ex) {
test_append_logfile($log_file, $ex);
unlink($log_file);
die($ex);
}
unlink($log_file);
}
sub limits_commands_no_commas_deferred_paths_bug3147 {
my $self = shift;
my $tmpdir = $self->{tmpdir};
# This config is from:
#
# http://forums.proftpd.org/smf/index.php/topic,3648.0
# http://bugs.proftpd.org/show_bug.cgi?id=3147
my $config_file = "$tmpdir/dir.conf";
my $pid_file = File::Spec->rel2abs("$tmpdir/dir.pid");
my $scoreboard_file = File::Spec->rel2abs("$tmpdir/dir.scoreboard");
my $log_file = test_get_logfile();
my $auth_user_file = File::Spec->rel2abs("$tmpdir/dir.passwd");
my $auth_group_file = File::Spec->rel2abs("$tmpdir/dir.group");
my $user = 'proftpd';
my $passwd = 'test';
my $group = 'ftpd';
my $home_dir = File::Spec->rel2abs("$tmpdir/home/$user");
my $uid = 500;
my $gid = 500;
mkpath($home_dir);
my $sub_dir = File::Spec->rel2abs("$tmpdir/home/$user/upload");
mkpath($sub_dir);
# Make sure that, if we're running as root, that the home directory has
# permissions/privs set for the account we create
if ($< == 0) {
unless (chmod(0755, $home_dir, $sub_dir)) {
die("Can't set perms on $home_dir, $sub_dir to 0755: $!");
}
unless (chown($uid, $gid, $home_dir, $sub_dir)) {
die("Can't set owner of $home_dir, $sub_dir to $uid/$gid: $!");
}
}
auth_user_write($auth_user_file, $user, $passwd, $uid, $gid, $home_dir,
'/bin/bash');
auth_group_write($auth_group_file, $group, $gid, $user);
my $config = {
PidFile => $pid_file,
ScoreboardFile => $scoreboard_file,
SystemLog => $log_file,
TraceLog => $log_file,
Trace => 'DEFAULT:10 fsio:0 directory:10 lock:0',
AuthUserFile => $auth_user_file,
AuthGroupFile => $auth_group_file,
DefaultChdir => '~',
Directory => {
"~$user" => {
Limit => {
'WRITE' => {
DenyAll => '',
},
},
},
# Bug#3147 happened because proftpd's parsing of the list of commands
# in the <Limit> section was not properly handling commas after the
# command names. Make sure the fix for Bug#3147 doesn't break command
# lists which DO NOT use commas.
"~$user/upload" => {
Limit => {
'STOR APPE MKD RMD RNTO STOU XMKD XRMD' => {
AllowAll => '',
},
},
},
},
IfModules => {
'mod_delay.c' => {
DelayEngine => 'off',
},
},
};
my ($port, $config_user, $config_group) = config_write($config_file, $config);
# Open pipes, for use between the parent and child processes. Specifically,
# the child will indicate when it's done with its test by writing a message
# to the parent.
my ($rfh, $wfh);
unless (pipe($rfh, $wfh)) {
die("Can't open pipe: $!");
}
my $ex;
# Fork child
$self->handle_sigchld();
defined(my $pid = fork()) or die("Can't fork: $!");
if ($pid) {
eval {
my $client = ProFTPD::TestSuite::FTP->new('127.0.0.1', $port);
$client->login($user, $passwd);
my ($resp_code, $resp_msg);
my $conn = $client->stor_raw('upload/test.txt');
unless ($conn) {
die("Failed to STOR upload/test.txt: " . $client->response_code() .
" " . $client->response_msg());
}
my $buf = "Hello, World!\n";
$conn->write($buf, length($buf));
$conn->close();
$resp_code = $client->response_code();
$resp_msg = $client->response_msg();
my $expected;
$expected = 226;
$self->assert($expected == $resp_code,
test_msg("Expected $expected, got $resp_code"));
$expected = "Transfer complete";
$self->assert($expected eq $resp_msg,
test_msg("Expected '$expected', got '$resp_msg'"));
};
if ($@) {
$ex = $@;
}
$wfh->print("done\n");
$wfh->flush();
} else {
eval { server_wait($config_file, $rfh) };
if ($@) {
warn($@);
exit 1;
}
exit 0;
}
# Stop server
server_stop($pid_file);
$self->assert_child_ok($pid);
if ($ex) {
test_append_logfile($log_file, $ex);
unlink($log_file);
die($ex);
}
unlink($log_file);
}
sub limits_rename_dir_ok_write_denied {
my $self = shift;
my $tmpdir = $self->{tmpdir};
my $config_file = "$tmpdir/dir.conf";
my $pid_file = File::Spec->rel2abs("$tmpdir/dir.pid");
my $scoreboard_file = File::Spec->rel2abs("$tmpdir/dir.scoreboard");
my $log_file = test_get_logfile();
my $auth_user_file = File::Spec->rel2abs("$tmpdir/dir.passwd");
my $auth_group_file = File::Spec->rel2abs("$tmpdir/dir.group");
my $user = 'proftpd';
my $passwd = 'test';
my $group = 'ftpd';
my $home_dir = File::Spec->rel2abs("$tmpdir/home/$user");
my $uid = 500;
my $gid = 500;
mkpath($home_dir);
my $sub_dir = File::Spec->rel2abs("$tmpdir/home/$user/upload");
mkpath($sub_dir);
# Make sure that, if we're running as root, that the home directory has
# permissions/privs set for the account we create
if ($< == 0) {
unless (chmod(0755, $home_dir, $sub_dir)) {
die("Can't set perms on $home_dir, $sub_dir to 0755: $!");
}
unless (chown($uid, $gid, $home_dir, $sub_dir)) {
die("Can't set owner of $home_dir, $sub_dir to $uid/$gid: $!");
}
}
auth_user_write($auth_user_file, $user, $passwd, $uid, $gid, $home_dir,
'/bin/bash');
auth_group_write($auth_group_file, $group, $gid, $user);
my $config = {
PidFile => $pid_file,
ScoreboardFile => $scoreboard_file,
SystemLog => $log_file,
TraceLog => $log_file,
Trace => 'DEFAULT:10 fsio:0 directory:10 lock:0',
AuthUserFile => $auth_user_file,
AuthGroupFile => $auth_group_file,
DefaultChdir => '~',
Directory => {
"~$user/*" => {
Limit => {
'CWD XCWD RNFR RNTO' => {
AllowAll => '',
},
'ALL' => {
DenyAll => '',
},
},
},
"~$user/upload" => {
Limit => {
'WRITE' => {
DenyAll => '',
},
},
},
},
IfModules => {
'mod_delay.c' => {
DelayEngine => 'off',
},
},
};
my ($port, $config_user, $config_group) = config_write($config_file, $config);
# Open pipes, for use between the parent and child processes. Specifically,
# the child will indicate when it's done with its test by writing a message
# to the parent.
my ($rfh, $wfh);
unless (pipe($rfh, $wfh)) {
die("Can't open pipe: $!");
}
my $ex;
# Fork child
$self->handle_sigchld();
defined(my $pid = fork()) or die("Can't fork: $!");
if ($pid) {
eval {
my $client = ProFTPD::TestSuite::FTP->new('127.0.0.1', $port);
$client->login($user, $passwd);
my ($resp_code, $resp_msg);
($resp_code, $resp_msg) = $client->rnfr('upload');
my $expected;
$expected = 350;
$self->assert($expected == $resp_code,
test_msg("Expected $expected, got $resp_code"));
$expected = "File or directory exists, ready for destination name";
$self->assert($expected eq $resp_msg,
test_msg("Expected '$expected', got '$resp_msg'"));
($resp_code, $resp_msg) = $client->rnto('upload2');
$expected = 250;
$self->assert($expected == $resp_code,
test_msg("Expected $expected, got $resp_code"));
$expected = "Rename successful";
$self->assert($expected eq $resp_msg,
test_msg("Expected '$expected', got '$resp_msg'"));
};
if ($@) {
$ex = $@;
}
$wfh->print("done\n");
$wfh->flush();
} else {
eval { server_wait($config_file, $rfh) };
if ($@) {
warn($@);
exit 1;
}
exit 0;
}
# Stop server
server_stop($pid_file);
$self->assert_child_ok($pid);
if ($ex) {
test_append_logfile($log_file, $ex);
unlink($log_file);
die($ex);
}
unlink($log_file);
}
sub limits_rename_dir_failed_rnfr_denied {
my $self = shift;
my $tmpdir = $self->{tmpdir};
my $config_file = "$tmpdir/dir.conf";
my $pid_file = File::Spec->rel2abs("$tmpdir/dir.pid");
my $scoreboard_file = File::Spec->rel2abs("$tmpdir/dir.scoreboard");
my $log_file = test_get_logfile();
my $auth_user_file = File::Spec->rel2abs("$tmpdir/dir.passwd");
my $auth_group_file = File::Spec->rel2abs("$tmpdir/dir.group");
my $user = 'proftpd';
my $passwd = 'test';
my $group = 'ftpd';
my $home_dir = File::Spec->rel2abs("$tmpdir/home/$user");
my $uid = 500;
my $gid = 500;
mkpath($home_dir);
my $sub_dir = File::Spec->rel2abs("$tmpdir/home/$user/upload");
mkpath($sub_dir);
# Make sure that, if we're running as root, that the home directory has
# permissions/privs set for the account we create
if ($< == 0) {
unless (chmod(0755, $home_dir, $sub_dir)) {
die("Can't set perms on $home_dir, $sub_dir to 0755: $!");
}
unless (chown($uid, $gid, $home_dir, $sub_dir)) {
die("Can't set owner of $home_dir, $sub_dir to $uid/$gid: $!");
}
}
auth_user_write($auth_user_file, $user, $passwd, $uid, $gid, $home_dir,
'/bin/bash');
auth_group_write($auth_group_file, $group, $gid, $user);
my $config = {
PidFile => $pid_file,
ScoreboardFile => $scoreboard_file,
SystemLog => $log_file,
TraceLog => $log_file,
Trace => 'DEFAULT:10 fsio:0 directory:10 lock:0',
AuthUserFile => $auth_user_file,
AuthGroupFile => $auth_group_file,
DefaultChdir => '~',
Directory => {
"~$user/*" => {
Limit => {
'CWD XCWD RNFR RNTO' => {
AllowAll => '',
},
'ALL' => {
DenyAll => '',
},
},
},
"~$user/upload" => {
Limit => {
'RNFR' => {
DenyAll => '',
},
},
},
},
IfModules => {
'mod_delay.c' => {
DelayEngine => 'off',
},
},
};
my ($port, $config_user, $config_group) = config_write($config_file, $config);
# Open pipes, for use between the parent and child processes. Specifically,
# the child will indicate when it's done with its test by writing a message
# to the parent.
my ($rfh, $wfh);
unless (pipe($rfh, $wfh)) {
die("Can't open pipe: $!");
}
my $ex;
# Fork child
$self->handle_sigchld();
defined(my $pid = fork()) or die("Can't fork: $!");
if ($pid) {
eval {
my $client = ProFTPD::TestSuite::FTP->new('127.0.0.1', $port);
$client->login($user, $passwd);
my ($resp_code, $resp_msg);
eval { $client->rnfr('upload') };
unless ($@) {
die("RNFR upload succeeded unexpectedly");
} else {
$resp_code = $client->response_code();
$resp_msg = $client->response_msg();
}
my $expected;
$expected = 550;
$self->assert($expected == $resp_code,
test_msg("Expected $expected, got $resp_code"));
$expected = "upload: Operation not permitted";
$self->assert($expected eq $resp_msg,
test_msg("Expected '$expected', got '$resp_msg'"));
};
if ($@) {
$ex = $@;
}
$wfh->print("done\n");
$wfh->flush();
} else {
eval { server_wait($config_file, $rfh) };
if ($@) {
warn($@);
exit 1;
}
exit 0;
}
# Stop server
server_stop($pid_file);
$self->assert_child_ok($pid);
if ($ex) {
test_append_logfile($log_file, $ex);
unlink($log_file);
die($ex);
}
unlink($log_file);
}
sub limits_one_char_dir_bug3337 {
my $self = shift;
my $tmpdir = $self->{tmpdir};
my $config_file = "$tmpdir/dir.conf";
my $pid_file = File::Spec->rel2abs("$tmpdir/dir.pid");
my $scoreboard_file = File::Spec->rel2abs("$tmpdir/dir.scoreboard");
my $log_file = test_get_logfile();
my $auth_user_file = File::Spec->rel2abs("$tmpdir/dir.passwd");
my $auth_group_file = File::Spec->rel2abs("$tmpdir/dir.group");
my $user = 'proftpd';
my $passwd = 'test';
my $group = 'ftpd';
my $home_dir = File::Spec->rel2abs($tmpdir);
my $uid = 500;
my $gid = 500;
my $a_dir = File::Spec->rel2abs("$home_dir/a");
mkpath($a_dir);
my $ab_dir = File::Spec->rel2abs("$home_dir/ab");
mkpath($ab_dir);
# Make sure that, if we're running as root, that the home directory has
# permissions/privs set for the account we create
if ($< == 0) {
unless (chmod(0755, $home_dir, $a_dir, $ab_dir)) {
die("Can't set perms on $home_dir to 0755: $!");
}
unless (chown($uid, $gid, $home_dir, $a_dir, $ab_dir)) {
die("Can't set owner of $home_dir to $uid/$gid: $!");
}
}
auth_user_write($auth_user_file, $user, $passwd, $uid, $gid, $home_dir,
'/bin/bash');
auth_group_write($auth_group_file, $group, $gid, $user);
# Reported in
#
# http://forums.proftpd.org/smf/index.php/topic,4170.0.html
my $config = {
PidFile => $pid_file,
ScoreboardFile => $scoreboard_file,
SystemLog => $log_file,
TraceLog => $log_file,
Trace => 'DEFAULT:10 fsio:0 directory:10 lock:0',
AuthUserFile => $auth_user_file,
AuthGroupFile => $auth_group_file,
DefaultChdir => '~',
Directory => {
"$home_dir" => {
Limit => {
WRITE => {
DenyUser => $user,
},
},
},
"$a_dir" => {
Limit => {
WRITE => {
AllowUser => $user,
},
},
},
"$ab_dir" => {
Limit => {
WRITE => {
AllowUser => $user,
},
},
},
},
IfModules => {
'mod_delay.c' => {
DelayEngine => 'off',
},
},
};
my ($port, $config_user, $config_group) = config_write($config_file, $config);
# Open pipes, for use between the parent and child processes. Specifically,
# the child will indicate when it's done with its test by writing a message
# to the parent.
my ($rfh, $wfh);
unless (pipe($rfh, $wfh)) {
die("Can't open pipe: $!");
}
my $ex;
# Fork child
$self->handle_sigchld();
defined(my $pid = fork()) or die("Can't fork: $!");
if ($pid) {
eval {
my $client = ProFTPD::TestSuite::FTP->new('127.0.0.1', $port);
$client->login($user, $passwd);
$client->cwd('ab');
my $conn = $client->stor_raw('test.txt');
unless ($conn) {
die("STOR test.txt failed: " . $client->response_code() . " " .
$client->response_msg());
}
$conn->close();
my $resp_code = $client->response_code();
my $resp_msg = $client->response_msg();
my $expected;
$expected = 226;
$self->assert($expected == $resp_code,
test_msg("Expected $expected, got $resp_code"));
$expected = "Transfer complete";
$self->assert($expected eq $resp_msg,
test_msg("Expected '$expected', got '$resp_msg'"));
$client->cwd('../a');
$conn = $client->stor_raw('test.txt');
unless ($conn) {
die("STOR test.txt failed: " . $client->response_code() . " " .
$client->response_msg());
}
$conn->close();
$resp_code = $client->response_code();
$resp_msg = $client->response_msg();
$expected = 226;
$self->assert($expected == $resp_code,
test_msg("Expected $expected, got $resp_code"));
$expected = "Transfer complete";
$self->assert($expected eq $resp_msg,
test_msg("Expected '$expected', got '$resp_msg'"));
};
if ($@) {
$ex = $@;
}
$wfh->print("done\n");
$wfh->flush();
} else {
eval { server_wait($config_file, $rfh) };
if ($@) {
warn($@);
exit 1;
}
exit 0;
}
# Stop server
server_stop($pid_file);
$self->assert_child_ok($pid);
if ($ex) {
test_append_logfile($log_file, $ex);
unlink($log_file);
die($ex);
}
unlink($log_file);
}
sub limits_symlink_dir_bug3166 {
my $self = shift;
my $tmpdir = $self->{tmpdir};
my $config_file = "$tmpdir/dir.conf";
my $pid_file = File::Spec->rel2abs("$tmpdir/dir.pid");
my $scoreboard_file = File::Spec->rel2abs("$tmpdir/dir.scoreboard");
my $log_file = test_get_logfile();
my $auth_user_file = File::Spec->rel2abs("$tmpdir/dir.passwd");
my $auth_group_file = File::Spec->rel2abs("$tmpdir/dir.group");
my $user = 'proftpd';
my $passwd = 'test';
my $group = 'ftpd';
my $home_dir = File::Spec->rel2abs($tmpdir);
my $uid = 500;
my $gid = 500;
my $src_dir = File::Spec->rel2abs("$tmpdir/dispatch/$user");
mkpath($src_dir);
my $dst_dir = File::Spec->rel2abs("$tmpdir/writable/dir1");
mkpath($dst_dir);
# Change to the $src_dir in order to create a symlink with a relative
# path (so that it will work in the chroot).
my $cwd = getcwd();
unless (chdir($src_dir)) {
die("Can't chdir to $src_dir: $!");
}
unless (symlink("../../writable/dir1", "dir1")) {
die("Can't symlink '../../writable/dir1' to 'dir1': $!");
}
unless (chdir($cwd)) {
die("Can't chdir to $cwd: $!");
}
# Make sure that, if we're running as root, that the home directory has
# permissions/privs set for the account we create
if ($< == 0) {
unless (chmod(0755, $home_dir, $src_dir, $dst_dir)) {
die("Can't set perms on $home_dir to 0755: $!");
}
unless (chown($uid, $gid, $home_dir, $src_dir, $dst_dir)) {
die("Can't set owner of $home_dir to $uid/$gid: $!");
}
}
auth_user_write($auth_user_file, $user, $passwd, $uid, $gid, $home_dir,
'/bin/bash');
auth_group_write($auth_group_file, $group, $gid, $user);
my $config = {
PidFile => $pid_file,
ScoreboardFile => $scoreboard_file,
SystemLog => $log_file,
TraceLog => $log_file,
Trace => 'DEFAULT:10 fsio:0 directory:10 lock:0',
AuthUserFile => $auth_user_file,
AuthGroupFile => $auth_group_file,
DefaultRoot => '~',
IfModules => {
'mod_delay.c' => {
DelayEngine => 'off',
},
},
};
my ($port, $config_user, $config_group) = config_write($config_file, $config);
if (open(my $fh, ">> $config_file")) {
print $fh <<EOD;
<Directory $src_dir>
<Limit ALL>
Order allow, deny
AllowUser $user
DenyAll
</Limit>
</Directory>
<Directory $home_dir/writable>
<Limit ALL>
Order allow, deny
AllowUser admin
DenyAll
</Limit>
<Limit DIRS PORT PASV EPRT EPSV>
Order allow, deny
AllowUser admin
AllowUser test
DenyAll
</Limit>
</Directory>
<Directory $dst_dir>
# Bug#3166 was caused by using just ALL in this limit; the parent
# directory's limit included the DIRS command group, which took precedence
# over ALL. By adding DIRS to the limit (which includes the test user),
# the desired behavior is achieved.
<Limit ALL DIRS>
Order allow, deny
AllowUser admin
AllowUser $user
DenyAll
</Limit>
</Directory>
EOD
close($fh);
} else {
die("Can't read $config_file: $!");
}
# Open pipes, for use between the parent and child processes. Specifically,
# the child will indicate when it's done with its test by writing a message
# to the parent.
my ($rfh, $wfh);
unless (pipe($rfh, $wfh)) {
die("Can't open pipe: $!");
}
my $ex;
# Fork child
$self->handle_sigchld();
defined(my $pid = fork()) or die("Can't fork: $!");
if ($pid) {
eval {
my $client = ProFTPD::TestSuite::FTP->new('127.0.0.1', $port);
$client->login($user, $passwd);
$client->cwd('dispatch');
$client->nlst();
$client->cwd($user);
$client->nlst();
$client->cwd('dir1');
my ($resp_code, $resp_msg) = $client->pwd();
my $expected;
$expected = 257;
$self->assert($expected == $resp_code,
test_msg("Expected $expected, got $resp_code"));
$expected = '"/writable/dir1" is the current directory';
$self->assert($expected eq $resp_msg,
test_msg("Expected '$expected', got '$resp_msg'"));
};
if ($@) {
$ex = $@;
}
$wfh->print("done\n");
$wfh->flush();
} else {
eval { server_wait($config_file, $rfh) };
if ($@) {
warn($@);
exit 1;
}
exit 0;
}
# Stop server
server_stop($pid_file);
$self->assert_child_ok($pid);
if ($ex) {
test_append_logfile($log_file, $ex);
unlink($log_file);
die($ex);
}
unlink($log_file);
}
sub limits_anon_dir_abs_path_bug3283 {
my $self = shift;
my $tmpdir = $self->{tmpdir};
my $config_file = "$tmpdir/dir.conf";
my $pid_file = File::Spec->rel2abs("$tmpdir/dir.pid");
my $scoreboard_file = File::Spec->rel2abs("$tmpdir/dir.scoreboard");
my $log_file = test_get_logfile();
my $auth_user_file = File::Spec->rel2abs("$tmpdir/dir.passwd");
my $auth_group_file = File::Spec->rel2abs("$tmpdir/dir.group");
my ($user, $group) = config_get_identity();
my $passwd = 'test';
my $anon_dir = File::Spec->rel2abs($tmpdir);
my $uid = 500;
my $gid = 500;
my $hide_dir = File::Spec->rel2abs("$tmpdir/hide");
mkpath($hide_dir);
# Make sure that, if we're running as root, that the home directory has
# permissions/privs set for the account we create
if ($< == 0) {
unless (chmod(0755, $anon_dir, $hide_dir)) {
die("Can't set perms on $anon_dir to 0755: $!");
}
unless (chown($uid, $gid, $anon_dir, $hide_dir)) {
die("Can't set owner of $anon_dir to $uid/$gid: $!");
}
}
auth_user_write($auth_user_file, $user, $passwd, $uid, $gid, '/tmp',
'/bin/bash');
auth_group_write($auth_group_file, $group, $gid, $user);
my $config = {
PidFile => $pid_file,
ScoreboardFile => $scoreboard_file,
SystemLog => $log_file,
TraceLog => $log_file,
Trace => 'DEFAULT:10 fsio:0 directory:10 lock:0',
AuthUserFile => $auth_user_file,
AuthGroupFile => $auth_group_file,
IfModules => {
'mod_delay.c' => {
DelayEngine => 'off',
},
},
};
my ($port, $config_user, $config_group) = config_write($config_file, $config);
if (open(my $fh, ">> $config_file")) {
print $fh <<EOD;
<Anonymous $anon_dir>
User $user
Group $group
UserAlias anonymous $user
RequireValidShell off
<Directory $hide_dir>
<Limit ALL>
DenyAll
</Limit>
</Directory>
</Anonymous>
EOD
close($fh);
} else {
die("Can't read $config_file: $!");
}
# Open pipes, for use between the parent and child processes. Specifically,
# the child will indicate when it's done with its test by writing a message
# to the parent.
my ($rfh, $wfh);
unless (pipe($rfh, $wfh)) {
die("Can't open pipe: $!");
}
my $ex;
# Fork child
$self->handle_sigchld();
defined(my $pid = fork()) or die("Can't fork: $!");
if ($pid) {
eval {
my $client = ProFTPD::TestSuite::FTP->new('127.0.0.1', $port);
$client->login($user, $passwd);
my $conn = $client->list_raw();
unless ($conn) {
die("LIST failed: " . $client->response_code() . " " .
$client->response_msg());
}
my $buf;
$conn->read($buf, 32768, 30);
$conn->close();
my $lines = [split(/\n/, $buf)];
foreach my $line (@$lines) {
if ($line =~ /\s+(\S+)$/) {
my $dir_name = $1;
# The <Directory> with <Limit ALL>DenyAll should not appear in
# the returned list
my $unexpected = 'hide';
$self->assert($unexpected ne $dir_name,
test_msg("Unexpectedly saw '$dir_name' in LIST"));
}
}
$client->quit();
};
if ($@) {
$ex = $@;
}
$wfh->print("done\n");
$wfh->flush();
} else {
eval { server_wait($config_file, $rfh) };
if ($@) {
warn($@);
exit 1;
}
exit 0;
}
# Stop server
server_stop($pid_file);
$self->assert_child_ok($pid);
if ($ex) {
test_append_logfile($log_file, $ex);
unlink($log_file);
die($ex);
}
unlink($log_file);
}
sub limits_with_multi_globs_denied_delete {
my $self = shift;
my $tmpdir = $self->{tmpdir};
# This config is from:
#
# http://forums.proftpd.org/smf/index.php/topic,6807.0.html
my $config_file = "$tmpdir/dir.conf";
my $pid_file = File::Spec->rel2abs("$tmpdir/dir.pid");
my $scoreboard_file = File::Spec->rel2abs("$tmpdir/dir.scoreboard");
my $log_file = test_get_logfile();
my $auth_user_file = File::Spec->rel2abs("$tmpdir/dir.passwd");
my $auth_group_file = File::Spec->rel2abs("$tmpdir/dir.group");
my $user = 'proftpd';
my $passwd = 'test';
my $group = 'ftpd';
my $users_dir = File::Spec->rel2abs("$tmpdir/home/users");
my $home_dir = File::Spec->rel2abs("$users_dir/$user");
my $uid = 500;
my $gid = 500;
mkpath($home_dir);
my $test_file = File::Spec->rel2abs("$home_dir/hiddenfile_foo.txt");
if (open(my $fh, "> $test_file")) {
print $fh "Hello, World!\n";
unless (close($fh)) {
die("Can't write $test_file: $!");
}
} else {
die("Can't open $test_file: $!");
}
# Make sure that, if we're running as root, that the home directory has
# permissions/privs set for the account we create
if ($< == 0) {
unless (chmod(0755, $home_dir)) {
die("Can't set perms on $home_dir to 0755: $!");
}
unless (chown($uid, $gid, $home_dir)) {
die("Can't set owner of $home_dir to $uid/$gid: $!");
}
}
auth_user_write($auth_user_file, $user, $passwd, $uid, $gid, $home_dir,
'/bin/bash');
auth_group_write($auth_group_file, $group, $gid, $user);
my $abs_tmp_dir = File::Spec->rel2abs($tmpdir);
my $glob_expr = "$users_dir/*/hiddenfile_*";
if ($^O eq 'darwin') {
# MacOSX-specific hack/tweak
$glob_expr = '/private' . $glob_expr;
}
my $config = {
PidFile => $pid_file,
ScoreboardFile => $scoreboard_file,
SystemLog => $log_file,
TraceLog => $log_file,
Trace => 'DEFAULT:10 fsio:0 directory:10 lock:0',
AuthUserFile => $auth_user_file,
AuthGroupFile => $auth_group_file,
DefaultChdir => '~',
Directory => {
$glob_expr => {
Limit => {
'ALL' => {
DenyAll => '',
},
},
},
},
IfModules => {
'mod_delay.c' => {
DelayEngine => 'off',
},
},
};
my ($port, $config_user, $config_group) = config_write($config_file, $config);
# Open pipes, for use between the parent and child processes. Specifically,
# the child will indicate when it's done with its test by writing a message
# to the parent.
my ($rfh, $wfh);
unless (pipe($rfh, $wfh)) {
die("Can't open pipe: $!");
}
my $ex;
# Fork child
$self->handle_sigchld();
defined(my $pid = fork()) or die("Can't fork: $!");
if ($pid) {
eval {
my $client = ProFTPD::TestSuite::FTP->new('127.0.0.1', $port);
$client->login($user, $passwd);
my $filename = 'hiddenfile_foo.txt';
eval { $client->dele($filename) };
unless ($@) {
die("DELE succeeded unexpectedly");
}
my $resp_code = $client->response_code();
my $resp_msg = $client->response_msg();
my $expected;
$expected = 550;
$self->assert($expected == $resp_code,
test_msg("Expected $expected, got $resp_code"));
$expected = "$filename: Operation not permitted";
$self->assert($expected eq $resp_msg,
test_msg("Expected '$expected', got '$resp_msg'"));
};
if ($@) {
$ex = $@;
}
$wfh->print("done\n");
$wfh->flush();
} else {
eval { server_wait($config_file, $rfh) };
if ($@) {
warn($@);
exit 1;
}
exit 0;
}
# Stop server
server_stop($pid_file);
$self->assert_child_ok($pid);
if ($ex) {
test_append_logfile($log_file, $ex);
unlink($log_file);
die($ex);
}
unlink($log_file);
}
sub limits_retr_bug3915 {
my $self = shift;
my $tmpdir = $self->{tmpdir};
my $config_file = "$tmpdir/dir.conf";
my $pid_file = File::Spec->rel2abs("$tmpdir/dir.pid");
my $scoreboard_file = File::Spec->rel2abs("$tmpdir/dir.scoreboard");
my $log_file = test_get_logfile();
my $auth_user_file = File::Spec->rel2abs("$tmpdir/dir.passwd");
my $auth_group_file = File::Spec->rel2abs("$tmpdir/dir.group");
my $user = 'proftpd';
my $passwd = 'test';
my $group = 'ftpd';
my $home_dir = File::Spec->rel2abs("$tmpdir/home/users/$user");
my $uid = 500;
my $gid = 500;
mkpath($home_dir);
# Make sure that, if we're running as root, that the home directory has
# permissions/privs set for the account we create
if ($< == 0) {
unless (chmod(0755, $home_dir)) {
die("Can't set perms on $home_dir to 0755: $!");
}
unless (chown($uid, $gid, $home_dir)) {
die("Can't set owner of $home_dir to $uid/$gid: $!");
}
}
auth_user_write($auth_user_file, $user, $passwd, $uid, $gid, $home_dir,
'/bin/bash');
auth_group_write($auth_group_file, $group, $gid, $user);
my $test_file = File::Spec->rel2abs("$home_dir/test.txt");
if (open(my $fh, "> $test_file")) {
print $fh "Hello, World!\n";
unless (close($fh)) {
die("Can't write $test_file: $!");
}
} else {
die("Can't open $test_file: $!");
}
my $config = {
PidFile => $pid_file,
ScoreboardFile => $scoreboard_file,
SystemLog => $log_file,
TraceLog => $log_file,
Trace => 'DEFAULT:10 fsio:0 directory:10 lock:0',
AuthUserFile => $auth_user_file,
AuthGroupFile => $auth_group_file,
DefaultChdir => '~',
IfModules => {
'mod_delay.c' => {
DelayEngine => 'off',
},
},
};
my ($port, $config_user, $config_group) = config_write($config_file, $config);
if (open(my $fh, ">> $config_file")) {
print $fh <<EOC;
<Directory ~$user>
<Limit RETR>
DenyAll
</Limit>
</Directory>
EOC
close($fh);
} else {
die("Can't read $config_file: $!");
}
# Open pipes, for use between the parent and child processes. Specifically,
# the child will indicate when it's done with its test by writing a message
# to the parent.
my ($rfh, $wfh);
unless (pipe($rfh, $wfh)) {
die("Can't open pipe: $!");
}
my $ex;
# Fork child
$self->handle_sigchld();
defined(my $pid = fork()) or die("Can't fork: $!");
if ($pid) {
eval {
my $client = ProFTPD::TestSuite::FTP->new('127.0.0.1', $port);
$client->login($user, $passwd);
my ($resp_code, $resp_msg);
my $conn = $client->retr_raw('test.txt');
if ($conn) {
die("RETR test.txt succeeded unexpectedly");
}
$resp_code = $client->response_code();
$resp_msg = $client->response_msg();
my $expected;
$expected = 550;
$self->assert($expected == $resp_code,
test_msg("Expected response code $expected, got $resp_code"));
$expected = "test.txt: Operation not permitted";
$self->assert($expected eq $resp_msg,
test_msg("Expected response message '$expected', got '$resp_msg'"));
};
if ($@) {
$ex = $@;
}
$wfh->print("done\n");
$wfh->flush();
} else {
eval { server_wait($config_file, $rfh) };
if ($@) {
warn($@);
exit 1;
}
exit 0;
}
# Stop server
server_stop($pid_file);
$self->assert_child_ok($pid);
if ($ex) {
test_append_logfile($log_file, $ex);
unlink($log_file);
die($ex);
}
unlink($log_file);
}
sub limits_retr_bug3915_chrooted {
my $self = shift;
my $tmpdir = $self->{tmpdir};
my $config_file = "$tmpdir/dir.conf";
my $pid_file = File::Spec->rel2abs("$tmpdir/dir.pid");
my $scoreboard_file = File::Spec->rel2abs("$tmpdir/dir.scoreboard");
my $log_file = test_get_logfile();
my $auth_user_file = File::Spec->rel2abs("$tmpdir/dir.passwd");
my $auth_group_file = File::Spec->rel2abs("$tmpdir/dir.group");
my $user = 'proftpd';
my $passwd = 'test';
my $group = 'ftpd';
my $home_dir = File::Spec->rel2abs("$tmpdir/home/users/$user");
my $uid = 500;
my $gid = 500;
mkpath($home_dir);
# Make sure that, if we're running as root, that the home directory has
# permissions/privs set for the account we create
if ($< == 0) {
unless (chmod(0755, $home_dir)) {
die("Can't set perms on $home_dir to 0755: $!");
}
unless (chown($uid, $gid, $home_dir)) {
die("Can't set owner of $home_dir to $uid/$gid: $!");
}
}
auth_user_write($auth_user_file, $user, $passwd, $uid, $gid, $home_dir,
'/bin/bash');
auth_group_write($auth_group_file, $group, $gid, $user);
my $test_file = File::Spec->rel2abs("$home_dir/test.txt");
if (open(my $fh, "> $test_file")) {
print $fh "Hello, World!\n";
unless (close($fh)) {
die("Can't write $test_file: $!");
}
} else {
die("Can't open $test_file: $!");
}
my $config = {
PidFile => $pid_file,
ScoreboardFile => $scoreboard_file,
SystemLog => $log_file,
TraceLog => $log_file,
Trace => 'DEFAULT:10 fsio:0 directory:10 lock:0',
AuthUserFile => $auth_user_file,
AuthGroupFile => $auth_group_file,
DefaultRoot => '~',
IfModules => {
'mod_delay.c' => {
DelayEngine => 'off',
},
},
};
my ($port, $config_user, $config_group) = config_write($config_file, $config);
if (open(my $fh, ">> $config_file")) {
print $fh <<EOC;
<Directory ~$user>
<Limit RETR>
DenyAll
</Limit>
</Directory>
EOC
close($fh);
} else {
die("Can't read $config_file: $!");
}
# Open pipes, for use between the parent and child processes. Specifically,
# the child will indicate when it's done with its test by writing a message
# to the parent.
my ($rfh, $wfh);
unless (pipe($rfh, $wfh)) {
die("Can't open pipe: $!");
}
my $ex;
# Fork child
$self->handle_sigchld();
defined(my $pid = fork()) or die("Can't fork: $!");
if ($pid) {
eval {
my $client = ProFTPD::TestSuite::FTP->new('127.0.0.1', $port);
$client->login($user, $passwd);
my ($resp_code, $resp_msg);
my $conn = $client->retr_raw('test.txt');
if ($conn) {
die("RETR test.txt succeeded unexpectedly");
}
$resp_code = $client->response_code();
$resp_msg = $client->response_msg();
my $expected;
$expected = 550;
$self->assert($expected == $resp_code,
test_msg("Expected response code $expected, got $resp_code"));
$expected = "test.txt: Operation not permitted";
$self->assert($expected eq $resp_msg,
test_msg("Expected response message '$expected', got '$resp_msg'"));
};
if ($@) {
$ex = $@;
}
$wfh->print("done\n");
$wfh->flush();
} else {
eval { server_wait($config_file, $rfh) };
if ($@) {
warn($@);
exit 1;
}
exit 0;
}
# Stop server
server_stop($pid_file);
$self->assert_child_ok($pid);
if ($ex) {
test_append_logfile($log_file, $ex);
unlink($log_file);
die($ex);
}
unlink($log_file);
}
sub limits_stor_with_multiple_groups_chrooted {
my $self = shift;
my $tmpdir = $self->{tmpdir};
my $config_file = "$tmpdir/dir.conf";
my $pid_file = File::Spec->rel2abs("$tmpdir/dir.pid");
my $scoreboard_file = File::Spec->rel2abs("$tmpdir/dir.scoreboard");
my $log_file = test_get_logfile();
my $auth_user_file = File::Spec->rel2abs("$tmpdir/dir.passwd");
my $auth_group_file = File::Spec->rel2abs("$tmpdir/dir.group");
my $user = 'proftpd';
my $passwd = 'test';
my $group = 'ftpd';
my $home_dir = File::Spec->rel2abs($tmpdir);
my $uid = 500;
my $gid = 500;
my $read_group = 'ftpd_read';
my $read_gid = 501;
my $write_group = 'ftpd_write';
my $write_gid = 502;
my $test_dir = File::Spec->rel2abs("$tmpdir/test.d");
mkpath($test_dir);
my $sub_dir = File::Spec->rel2abs("$test_dir/sub.d");
mkpath($sub_dir);
# Make sure that, if we're running as root, that the home directory has
# permissions/privs set for the account we create
if ($< == 0) {
unless (chmod(0755, $home_dir)) {
die("Can't set perms on $home_dir to 0755: $!");
}
unless (chown($uid, $gid, $home_dir)) {
die("Can't set owner of $home_dir to $uid/$gid: $!");
}
unless(chmod(0775, $test_dir, $sub_dir)) {
die("Can't set perms on $test_dir to 0775: $!");
}
unless (chown($uid, $write_gid, $test_dir, $sub_dir)) {
die("Can't set owner of $test_dir to $uid/$write_gid: $!");
}
}
auth_user_write($auth_user_file, $user, $passwd, $uid, $gid, $home_dir,
'/bin/bash');
auth_group_write($auth_group_file, $group, $gid, $user);
auth_group_write($auth_group_file, $read_group, $read_gid, $user);
auth_group_write($auth_group_file, $write_group, $write_gid, $user);
# See:
# https://forums.proftpd.org/smf/index.php/topic,11304.0.html
my $config = {
PidFile => $pid_file,
ScoreboardFile => $scoreboard_file,
SystemLog => $log_file,
TraceLog => $log_file,
Trace => 'DEFAULT:10 fileperms:10 fsio:0 directory:10 lock:0',
AuthUserFile => $auth_user_file,
AuthGroupFile => $auth_group_file,
DefaultRoot => '~',
IfModules => {
'mod_delay.c' => {
DelayEngine => 'off',
},
},
};
my ($port, $config_user, $config_group) = config_write($config_file, $config);
if (open(my $fh, ">> $config_file")) {
print $fh <<EOD;
<Directory $test_dir>
<Limit DIRS READ>
AllowGroup OR $read_group,$write_group
</Limit>
<Limit ALL>
DenyAll
</Limit>
</Directory>
<Directory $sub_dir>
<Limit DIRS READ>
AllowGroup OR $read_group,$write_group
</Limit>
<Limit ALL>
AllowGroup $write_group
DenyAll
</Limit>
</Directory>
EOD
close($fh);
} else {
die("Can't read $config_file: $!");
}
# Open pipes, for use between the parent and child processes. Specifically,
# the child will indicate when it's done with its test by writing a message
# to the parent.
my ($rfh, $wfh);
unless (pipe($rfh, $wfh)) {
die("Can't open pipe: $!");
}
my $ex;
# Fork child
$self->handle_sigchld();
defined(my $pid = fork()) or die("Can't fork: $!");
if ($pid) {
eval {
my $client = ProFTPD::TestSuite::FTP->new('127.0.0.1', $port);
$client->login($user, $passwd);
$client->cwd('test.d/sub.d');
my $conn = $client->stor_raw('test.txt');
unless ($conn) {
die("Failed to STOR test.txt: " . $client->response_code() . " " .
$client->response_msg());
};
my $buf = "Hello, World\n";
$conn->write($buf, length($buf), 25);
eval { $conn->close() };
my $resp_code = $client->response_code();
my $resp_msg = $client->response_msg();
$self->assert_transfer_ok($resp_code, $resp_msg);
$client->quit();
};
if ($@) {
$ex = $@;
}
$wfh->print("done\n");
$wfh->flush();
} else {
eval { server_wait($config_file, $rfh) };
if ($@) {
warn($@);
exit 1;
}
exit 0;
}
# Stop server
server_stop($pid_file);
$self->assert_child_ok($pid);
if ($ex) {
test_append_logfile($log_file, $ex);
unlink($log_file);
die($ex);
}
unlink($log_file);
}
1;
|
pghmcfc/proftpd
|
tests/t/lib/ProFTPD/Tests/Config/Directory/Limits.pm
|
Perl
|
gpl-2.0
| 64,813
|
<?php defined( '_JEXEC') or die( 'Restricted Access' );
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: AbstractMessage.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* This is the default Implementation of Message, which provides
* a convenient base for behavior and association of common endpoints
*
* @package Zend_Amf
* @subpackage Value
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Value_Messaging_AbstractMessage
{
/**
* @var string Client identifier
*/
public $clientId;
/**
* @var string Destination
*/
public $destination;
/**
* @var string Message identifier
*/
public $messageId;
/**
* @var int Message timestamp
*/
public $timestamp;
/**
* @var int Message TTL
*/
public $timeToLive;
/**
* @var object Message headers
*/
public $headers;
/**
* @var string Message body
*/
public $body;
/**
* generate a unique id
*
* Format is: ########-####-####-####-############
* Where # is an uppercase letter or number
* example: 6D9DC7EC-A273-83A9-ABE3-00005FD752D6
*
* @return string
*/
public function generateId()
{
return sprintf(
'%08X-%04X-%04X-%02X%02X-%012X',
mt_rand(),
mt_rand(0, 65535),
bindec(substr_replace(
sprintf('%016b', mt_rand(0, 65535)), '0100', 11, 4)
),
bindec(substr_replace(sprintf('%08b', mt_rand(0, 255)), '01', 5, 2)),
mt_rand(0, 255),
mt_rand()
);
}
}
|
kiennd146/nhazz.com
|
plugins/system/zend/Zend/Amf/Value/Messaging/AbstractMessage.php
|
PHP
|
gpl-2.0
| 2,406
|
/*
* This source code is part of
*
* G R O M A C S
*
* Copyright (c) 1991-2000, University of Groningen, The Netherlands.
* Copyright (c) 2001-2009, The GROMACS Development Team
*
* Gromacs is a library for molecular simulation and trajectory analysis,
* written by Erik Lindahl, David van der Spoel, Berk Hess, and others - for
* a full list of developers and information, check out http://www.gromacs.org
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option) any
* later version.
* As a special exception, you may use this file as part of a free software
* library without restriction. Specifically, if other files instantiate
* templates or use macros or inline functions from this file, or you compile
* this file and link it with other files to produce an executable, this
* file does not by itself cause the resulting executable to be covered by
* the GNU Lesser General Public License.
*
* In plain-speak: do not worry about classes/macros/templates either - only
* changes to the library have to be LGPL, not an application linking with it.
*
* To help fund GROMACS development, we humbly ask that you cite
* the papers people have written on it - you can find them on the website!
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <math.h>
#include "vec.h"
#ifdef GMX_THREAD_SHM_FDECOMP
#include "thread_mpi.h"
#endif
#include "nb_kernel210.h"
/*
* Gromacs nonbonded kernel nb_kernel210
* Coulomb interaction: Reaction field
* VdW interaction: Lennard-Jones
* water optimization: No
* Calculate forces: yes
*/
void nb_kernel210(
int * p_nri,
int * iinr,
int * jindex,
int * jjnr,
int * shift,
real * shiftvec,
real * fshift,
int * gid,
real * pos,
real * faction,
real * charge,
real * p_facel,
real * p_krf,
real * p_crf,
real * Vc,
int * type,
int * p_ntype,
real * vdwparam,
real * Vvdw,
real * p_tabscale,
real * VFtab,
real * invsqrta,
real * dvda,
real * p_gbtabscale,
real * GBtab,
int * p_nthreads,
int * count,
void * mtx,
int * outeriter,
int * inneriter,
real * work)
{
int nri,ntype,nthreads;
real facel,krf,crf,tabscale,gbtabscale;
int n,ii,is3,ii3,k,nj0,nj1,jnr,j3,ggid;
int nn0,nn1,nouter,ninner;
real shX,shY,shZ;
real fscal,tx,ty,tz;
real rinvsq;
real iq;
real qq,vcoul,vctot;
int nti;
int tj;
real rinvsix;
real Vvdw6,Vvdwtot;
real Vvdw12;
real krsq;
real ix1,iy1,iz1,fix1,fiy1,fiz1;
real jx1,jy1,jz1;
real dx11,dy11,dz11,rsq11,rinv11;
real c6,c12;
nri = *p_nri;
ntype = *p_ntype;
nthreads = *p_nthreads;
facel = *p_facel;
krf = *p_krf;
crf = *p_crf;
tabscale = *p_tabscale;
/* Reset outer and inner iteration counters */
nouter = 0;
ninner = 0;
/* Loop over thread workunits */
do
{
#ifdef GMX_THREAD_SHM_FDECOMP
tMPI_Thread_mutex_lock((tMPI_Thread_mutex_t *)mtx);
nn0 = *count;
/* Take successively smaller chunks (at least 10 lists) */
nn1 = nn0+(nri-nn0)/(2*nthreads)+10;
*count = nn1;
tMPI_Thread_mutex_unlock((tMPI_Thread_mutex_t *)mtx);
if(nn1>nri) nn1=nri;
#else
nn0 = 0;
nn1 = nri;
#endif
/* Start outer loop over neighborlists */
for(n=nn0; (n<nn1); n++)
{
/* Load shift vector for this list */
is3 = 3*shift[n];
shX = shiftvec[is3];
shY = shiftvec[is3+1];
shZ = shiftvec[is3+2];
/* Load limits for loop over neighbors */
nj0 = jindex[n];
nj1 = jindex[n+1];
/* Get outer coordinate index */
ii = iinr[n];
ii3 = 3*ii;
/* Load i atom data, add shift vector */
ix1 = shX + pos[ii3+0];
iy1 = shY + pos[ii3+1];
iz1 = shZ + pos[ii3+2];
/* Load parameters for i atom */
iq = facel*charge[ii];
nti = 2*ntype*type[ii];
/* Zero the potential energy for this list */
vctot = 0;
Vvdwtot = 0;
/* Clear i atom forces */
fix1 = 0;
fiy1 = 0;
fiz1 = 0;
for(k=nj0; (k<nj1); k++)
{
/* Get j neighbor index, and coordinate index */
jnr = jjnr[k];
j3 = 3*jnr;
/* load j atom coordinates */
jx1 = pos[j3+0];
jy1 = pos[j3+1];
jz1 = pos[j3+2];
/* Calculate distance */
dx11 = ix1 - jx1;
dy11 = iy1 - jy1;
dz11 = iz1 - jz1;
rsq11 = dx11*dx11+dy11*dy11+dz11*dz11;
/* Calculate 1/r and 1/r2 */
rinv11 = gmx_invsqrt(rsq11);
/* Load parameters for j atom */
qq = iq*charge[jnr];
tj = nti+2*type[jnr];
c6 = vdwparam[tj];
c12 = vdwparam[tj+1];
rinvsq = rinv11*rinv11;
/* Coulomb reaction-field interaction */
krsq = krf*rsq11;
vcoul = qq*(rinv11+krsq-crf);
vctot = vctot+vcoul;
/* Lennard-Jones interaction */
rinvsix = rinvsq*rinvsq*rinvsq;
Vvdw6 = c6*rinvsix;
Vvdw12 = c12*rinvsix*rinvsix;
Vvdwtot = Vvdwtot+Vvdw12-Vvdw6;
fscal = (qq*(rinv11-2.0*krsq)+12.0*Vvdw12-6.0*Vvdw6)*rinvsq;
/* Calculate temporary vectorial force */
tx = fscal*dx11;
ty = fscal*dy11;
tz = fscal*dz11;
/* Increment i atom force */
fix1 = fix1 + tx;
fiy1 = fiy1 + ty;
fiz1 = fiz1 + tz;
/* Decrement j atom force */
faction[j3+0] = faction[j3+0] - tx;
faction[j3+1] = faction[j3+1] - ty;
faction[j3+2] = faction[j3+2] - tz;
/* Inner loop uses 44 flops/iteration */
}
/* Add i forces to mem and shifted force list */
faction[ii3+0] = faction[ii3+0] + fix1;
faction[ii3+1] = faction[ii3+1] + fiy1;
faction[ii3+2] = faction[ii3+2] + fiz1;
fshift[is3] = fshift[is3]+fix1;
fshift[is3+1] = fshift[is3+1]+fiy1;
fshift[is3+2] = fshift[is3+2]+fiz1;
/* Add potential energies to the group for this list */
ggid = gid[n];
Vc[ggid] = Vc[ggid] + vctot;
Vvdw[ggid] = Vvdw[ggid] + Vvdwtot;
/* Increment number of inner iterations */
ninner = ninner + nj1 - nj0;
/* Outer loop uses 12 flops/iteration */
}
/* Increment number of outer iterations */
nouter = nouter + nn1 - nn0;
}
while (nn1<nri);
/* Write outer/inner iteration count to pointers */
*outeriter = nouter;
*inneriter = ninner;
}
/*
* Gromacs nonbonded kernel nb_kernel210nf
* Coulomb interaction: Reaction field
* VdW interaction: Lennard-Jones
* water optimization: No
* Calculate forces: no
*/
void nb_kernel210nf(
int * p_nri,
int * iinr,
int * jindex,
int * jjnr,
int * shift,
real * shiftvec,
real * fshift,
int * gid,
real * pos,
real * faction,
real * charge,
real * p_facel,
real * p_krf,
real * p_crf,
real * Vc,
int * type,
int * p_ntype,
real * vdwparam,
real * Vvdw,
real * p_tabscale,
real * VFtab,
real * invsqrta,
real * dvda,
real * p_gbtabscale,
real * GBtab,
int * p_nthreads,
int * count,
void * mtx,
int * outeriter,
int * inneriter,
real * work)
{
int nri,ntype,nthreads;
real facel,krf,crf,tabscale,gbtabscale;
int n,ii,is3,ii3,k,nj0,nj1,jnr,j3,ggid;
int nn0,nn1,nouter,ninner;
real shX,shY,shZ;
real rinvsq;
real iq;
real qq,vcoul,vctot;
int nti;
int tj;
real rinvsix;
real Vvdw6,Vvdwtot;
real Vvdw12;
real krsq;
real ix1,iy1,iz1;
real jx1,jy1,jz1;
real dx11,dy11,dz11,rsq11,rinv11;
real c6,c12;
nri = *p_nri;
ntype = *p_ntype;
nthreads = *p_nthreads;
facel = *p_facel;
krf = *p_krf;
crf = *p_crf;
tabscale = *p_tabscale;
/* Reset outer and inner iteration counters */
nouter = 0;
ninner = 0;
/* Loop over thread workunits */
do
{
#ifdef GMX_THREAD_SHM_FDECOMP
tMPI_Thread_mutex_lock((tMPI_Thread_mutex_t *)mtx);
nn0 = *count;
/* Take successively smaller chunks (at least 10 lists) */
nn1 = nn0+(nri-nn0)/(2*nthreads)+10;
*count = nn1;
tMPI_Thread_mutex_unlock((tMPI_Thread_mutex_t *)mtx);
if(nn1>nri) nn1=nri;
#else
nn0 = 0;
nn1 = nri;
#endif
/* Start outer loop over neighborlists */
for(n=nn0; (n<nn1); n++)
{
/* Load shift vector for this list */
is3 = 3*shift[n];
shX = shiftvec[is3];
shY = shiftvec[is3+1];
shZ = shiftvec[is3+2];
/* Load limits for loop over neighbors */
nj0 = jindex[n];
nj1 = jindex[n+1];
/* Get outer coordinate index */
ii = iinr[n];
ii3 = 3*ii;
/* Load i atom data, add shift vector */
ix1 = shX + pos[ii3+0];
iy1 = shY + pos[ii3+1];
iz1 = shZ + pos[ii3+2];
/* Load parameters for i atom */
iq = facel*charge[ii];
nti = 2*ntype*type[ii];
/* Zero the potential energy for this list */
vctot = 0;
Vvdwtot = 0;
/* Clear i atom forces */
for(k=nj0; (k<nj1); k++)
{
/* Get j neighbor index, and coordinate index */
jnr = jjnr[k];
j3 = 3*jnr;
/* load j atom coordinates */
jx1 = pos[j3+0];
jy1 = pos[j3+1];
jz1 = pos[j3+2];
/* Calculate distance */
dx11 = ix1 - jx1;
dy11 = iy1 - jy1;
dz11 = iz1 - jz1;
rsq11 = dx11*dx11+dy11*dy11+dz11*dz11;
/* Calculate 1/r and 1/r2 */
rinv11 = gmx_invsqrt(rsq11);
/* Load parameters for j atom */
qq = iq*charge[jnr];
tj = nti+2*type[jnr];
c6 = vdwparam[tj];
c12 = vdwparam[tj+1];
rinvsq = rinv11*rinv11;
/* Coulomb reaction-field interaction */
krsq = krf*rsq11;
vcoul = qq*(rinv11+krsq-crf);
vctot = vctot+vcoul;
/* Lennard-Jones interaction */
rinvsix = rinvsq*rinvsq*rinvsq;
Vvdw6 = c6*rinvsix;
Vvdw12 = c12*rinvsix*rinvsix;
Vvdwtot = Vvdwtot+Vvdw12-Vvdw6;
/* Inner loop uses 27 flops/iteration */
}
/* Add i forces to mem and shifted force list */
/* Add potential energies to the group for this list */
ggid = gid[n];
Vc[ggid] = Vc[ggid] + vctot;
Vvdw[ggid] = Vvdw[ggid] + Vvdwtot;
/* Increment number of inner iterations */
ninner = ninner + nj1 - nj0;
/* Outer loop uses 6 flops/iteration */
}
/* Increment number of outer iterations */
nouter = nouter + nn1 - nn0;
}
while (nn1<nri);
/* Write outer/inner iteration count to pointers */
*outeriter = nouter;
*inneriter = ninner;
}
|
tectronics/force-distribution-analysis.gromacs-4-5-3
|
src/gmxlib/nonbonded/nb_kernel_c/nb_kernel210.c
|
C
|
gpl-2.0
| 16,193
|
<?php
/*
Template Name: Archives Page
*/
?>
<?php get_header() ?>
<div id="container">
<div id="content">
<?php while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID() ?>" class="<?php sandbox_post_class() ?>">
<h2 class="entry-title"><?php the_title() ?></h2>
<div class="entry-content">
<?php the_content() ?>
<ul id="archives-page" class="xoxo">
<li id="category-archives">
<h3><?php _e( 'Archives by Category', 'sandbox' ) ?></h3>
<ul>
<?php wp_list_categories('optioncount=1&title_li=&show_count=1') ?>
</ul>
</li>
<li id="monthly-archives">
<h3><?php _e( 'Archives by Month', 'sandbox' ) ?></h3>
<ul>
<?php wp_get_archives('type=monthly&show_post_count=1') ?>
</ul>
</li>
</ul>
<?php edit_post_link( __( 'Edit', 'sandbox' ), '<span class="edit-link">', '</span>' ) ?>
</div>
</div><!-- .post -->
<?php if ( get_post_custom_values('comments') ) comments_template() // Add a key/value of "comments" to enable comments on pages! ?>
<?php endwhile; // end of the loop. ?>
</div><!-- #content -->
</div><!-- #container -->
<?php get_sidebar() ?>
<?php get_footer() ?>
|
ryanaslett/pgc3
|
wp-content/themes/sandbox-162/archives.php
|
PHP
|
gpl-2.0
| 1,206
|
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucasfilm
// Entertainment Company Ltd. Portions contributed and copyright held by
// others as indicated. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of Industrial Light & Magic nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#include <ImfCompression.h>
bool equivalent (float f1, float f2, Imf::Compression comp);
|
petterreinholdtsen/cinelerra-hv
|
thirdparty/openexr-1.6.1/IlmImfTest/compareFloat.h
|
C
|
gpl-2.0
| 2,046
|
/*
* man2tcl.c --
*
* This file contains a program that turns a man page of the
* form used for Tcl and Tk into a Tcl script that invokes
* a Tcl command for each construct in the man page. The
* script can then be eval'ed to translate the manual entry
* into some other format such as MIF or HTML.
*
* Usage:
*
* man2tcl ?fileName?
*
* Copyright (c) 1995 Sun Microsystems, Inc.
*
* See the file "license.terms" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*
* RCS: @(#) $Id$
*/
static char sccsid[] = "@(#) man2tcl.c 1.3 95/08/12 17:34:08";
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#ifndef NO_ERRNO_H
#include <errno.h>
#endif
/*
* Imported things that aren't defined in header files:
*/
extern int errno;
/*
* Current line number, used for error messages.
*/
static int lineNumber;
/*
* The variable below is set to 1 if an error occurs anywhere
* while reading in the file.
*/
static int status;
/*
* The variable below is set to 1 if output should be generated.
* If it's 0, it means we're doing a pre-pass to make sure that
* the file can be properly parsed.
*/
static int writeOutput;
/*
* Prototypes for procedures defined in this file:
*/
static void DoMacro(char *line);
static void DoText(char *line);
static void QuoteText(char *string, int count);
/*
*----------------------------------------------------------------------
*
* main --
*
* This procedure is the main program, which does all of the work
* of the program.
*
* Results:
* None: exits with a 0 return status to indicate success, or
* 1 to indicate that there were problems in the translation.
*
* Side effects:
* A Tcl script is output to standard output. Error messages may
* be output on standard error.
*
*----------------------------------------------------------------------
*/
int
main(argc, argv)
int argc; /* Number of command-line arguments. */
char **argv; /* Values of command-line arguments. */
{
FILE *f;
#define MAX_LINE_SIZE 500
char line[MAX_LINE_SIZE];
char *p;
/*
* Find the file to read, and open it if it isn't stdin.
*/
if (argc == 1) {
f = stdin;
} else if (argc == 2) {
f = fopen(argv[1], "r");
if (f == NULL) {
fprintf(stderr, "Couldn't read \"%s\": %s\n", argv[1],
strerror(errno));
exit(1);
}
} else {
fprintf(stderr, "Usage: %s ?fileName?\n", argv[0]);
}
/*
* Make two passes over the file. In the first pass, just check
* to make sure we can handle everything. If there are problems,
* generate output and stop. If everything is OK, make a second
* pass to actually generate output.
*/
for (writeOutput = 0; writeOutput < 2; writeOutput++) {
lineNumber = 0;
status = 0;
while (fgets(line, MAX_LINE_SIZE, f) != NULL) {
for (p = line; *p != 0; p++) {
if (*p == '\n') {
*p = 0;
break;
}
}
lineNumber++;
if ((line[0] == '\'') && (line[1] == '\\') && (line[2] == '\"')) {
/*
* This line is a comment. Ignore it.
*/
continue;
}
if ((line[0] == '.') || (line[0] == '\'')) {
/*
* This line is a macro invocation.
*/
DoMacro(line);
} else {
/*
* This line is text, possibly with formatting characters
* embedded in it.
*/
DoText(line);
}
}
if (status != 0) {
break;
}
fseek(f, 0, SEEK_SET);
}
exit(status);
}
/*
*----------------------------------------------------------------------
*
* DoMacro --
*
* This procedure is called to handle a macro invocation.
* It parses the arguments to the macro and generates a
* Tcl command to handle the invocation.
*
* Results:
* None.
*
* Side effects:
* A Tcl command is written to stdout.
*
*----------------------------------------------------------------------
*/
static void
DoMacro(line)
char *line; /* The line of text that contains the
* macro invocation. */
{
char *p, *end;
/*
* If there is no macro name, then just skip the whole line.
*/
if ((line[1] == 0) || (isspace(line[1]))) {
return;
}
if (writeOutput) {
printf("macro");
}
if (*line != '.') {
if (writeOutput) {
printf("2");
}
}
/*
* Parse the arguments to the macro (including the name), in order.
*/
p = line+1;
while (1) {
if (writeOutput) {
putc(' ', stdout);
}
if (*p == '"') {
/*
* The argument is delimited by quotes.
*/
for (end = p+1; *end != '"'; end++) {
if (*end == 0) {
fprintf(stderr,
"Unclosed quote in macro call on line %d.\n",
lineNumber);
status = 1;
break;
}
}
QuoteText(p+1, (end-(p+1)));
} else {
for (end = p+1; (*end != 0) && !isspace(*end); end++) {
/* Empty loop body. */
}
QuoteText(p, end-p);
}
if (*end == 0) {
break;
}
p = end+1;
while (isspace(*p)) {
/*
* Skip empty space before next argument.
*/
p++;
}
if (*p == 0) {
break;
}
}
if (writeOutput) {
putc('\n', stdout);
}
}
/*
*----------------------------------------------------------------------
*
* DoText --
*
* This procedure is called to handle a line of troff text.
* It parses the text, generating Tcl commands for text and
* for formatting stuff such as font changes.
*
* Results:
* None.
*
* Side effects:
* Tcl commands are written to stdout.
*
*----------------------------------------------------------------------
*/
static void
DoText(line)
char *line; /* The line of text. */
{
char *p, *end;
/*
* Divide the line up into pieces consisting of backslash sequences,
* tabs, and other text.
*/
p = line;
while (*p != 0) {
if (*p == '\t') {
if (writeOutput) {
printf("tab\n");
}
p++;
} else if (*p != '\\') {
/*
* Ordinary text.
*/
for (end = p+1; (*end != '\\') && (*end != 0); end++) {
/* Empty loop body. */
}
if (writeOutput) {
printf("text ");
}
QuoteText(p, end-p);
if (writeOutput) {
putc('\n', stdout);
}
p = end;
} else {
/*
* A backslash sequence. There are particular ones
* that we understand; output an error message for
* anything else and just ignore the backslash.
*/
p++;
if (*p == 'f') {
/*
* Font change.
*/
if (writeOutput) {
printf("font %c\n", p[1]);
}
p += 2;
} else if (*p == '-') {
if (writeOutput) {
printf("dash\n");
}
p++;
} else if (*p == 'e') {
if (writeOutput) {
printf("text \\\\\n");
}
p++;
} else if (*p == '.') {
if (writeOutput) {
printf("text .\n");
}
p++;
} else if (*p == '&') {
p++;
} else if (*p == '(') {
if ((p[1] == 0) || (p[2] == 0)) {
fprintf(stderr, "Bad \\( sequence on line %d.\n",
lineNumber);
status = 1;
} else {
if (writeOutput) {
printf("char {\\(%c%c}\n", p[1], p[2]);
}
p += 3;
}
} else if (*p != 0) {
if (writeOutput) {
printf("char {\\%c}\n", *p);
}
p++;
}
}
}
if (writeOutput) {
printf("newline\n");
}
}
/*
*----------------------------------------------------------------------
*
* QuoteText --
*
* Copy the "string" argument to stdout, adding quote characters
* around any special Tcl characters so that they'll just be treated
* as ordinary text.
*
* Results:
* None.
*
* Side effects:
* Text is written to stdout.
*
*----------------------------------------------------------------------
*/
static void
QuoteText(string, count)
char *string; /* The line of text. */
int count; /* Number of characters to write from string. */
{
if (count == 0) {
if (writeOutput) {
printf("{}");
}
return;
}
for ( ; count > 0; string++, count--) {
if ((*string == '$') || (*string == '[') || (*string == '{')
|| (*string == ' ') || (*string == ';') || (*string == '\\')
|| (*string == '"') || (*string == '\t')) {
if (writeOutput) {
putc('\\', stdout);
}
}
if (writeOutput) {
putc(*string, stdout);
}
}
}
|
AndresGG/sn-8.4
|
tcl/tools/man2tcl.c
|
C
|
gpl-2.0
| 8,218
|
<?php
/**
* @file
* Default theme implementation to display a single Drupal page.
*
* Available variables:
*
* General utility variables:
* - $base_path: The base URL path of the Drupal installation. At the very
* least, this will always default to /.
* - $directory: The directory the template is located in, e.g. modules/system
* or themes/garland.
* - $is_front: TRUE if the current page is the front page.
* - $logged_in: TRUE if the user is registered and signed in.
* - $is_admin: TRUE if the user has permission to access administration pages.
*
* Site identity:
* - $front_page: The URL of the front page. Use this instead of $base_path,
* when linking to the front page. This includes the language domain or
* prefix.
* - $logo: The path to the logo image, as defined in theme configuration.
* - $site_name: The name of the site, empty when display has been disabled
* in theme settings.
* - $site_slogan: The slogan of the site, empty when display has been disabled
* in theme settings.
*
* Navigation:
* - $main_menu (array): An array containing the Main menu links for the
* site, if they have been configured.
* - $secondary_menu (array): An array containing the Secondary menu links for
* the site, if they have been configured.
* - $breadcrumb: The breadcrumb trail for the current page.
*
* Page content (in order of occurrence in the default page.tpl.php):
* - $title_prefix (array): An array containing additional output populated by
* modules, intended to be displayed in front of the main title tag that
* appears in the template.
* - $title: The page title, for use in the actual HTML content.
* - $title_suffix (array): An array containing additional output populated by
* modules, intended to be displayed after the main title tag that appears in
* the template.
* - $messages: HTML for status and error messages. Should be displayed
* prominently.
* - $tabs (array): Tabs linking to any sub-pages beneath the current page
* (e.g., the view and edit tabs when displaying a node).
* - $action_links (array): Actions local to the page, such as 'Add menu' on the
* menu administration interface.
* - $feed_icons: A string of all feed icons for the current page.
* - $node: The node object, if there is an automatically-loaded node
* associated with the page, and the node ID is the second argument
* in the page's path (e.g. node/12345 and node/12345/revisions, but not
* comment/reply/12345).
*
* Regions:
* - $page['help']: Dynamic help text, mostly for admin pages.
* - $page['content']: The main content of the current page.
* - $page['sidebar_first']: Items for the first sidebar.
* - $page['sidebar_second']: Items for the second sidebar.
* - $page['header']: Items for the header region.
* - $page['footer']: Items for the footer region.
*
* @see template_preprocess()
* @see template_preprocess_page()
* @see template_process()
*/
?>
<header id="header">
<div class="top-bg"></div>
<div class="layout-978">
<hgroup id="logo-wrap">
<h1 id="site-name">
<a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>">
<?php if ($logo): ?><img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" /><?php endif; ?>
<span><?php print $site_name; ?></span>
</a>
<?php print render($page['tagline']); ?>
</h1>
<?php if ($site_slogan): ?><h2 id="site-slogan"><?php print $site_slogan; ?></h2><?php endif; ?>
</hgroup>
<?php if (theme_get_setting('socialicon_display', 'creative')): ?>
<?php
$twitter_url = check_plain(theme_get_setting('twitter_url', 'creative'));
$facebook_url = check_plain(theme_get_setting('facebook_url', 'creative'));
$google_plus_url = check_plain(theme_get_setting('google_plus_url', 'creative'));
$pinterest_url = check_plain(theme_get_setting('pinterest_url', 'creative'));
?>
<div class="social-icon">
<ul class="social-profile">
<?php if ($facebook_url): ?><li class="facebook">
<a target="_blank" title="<?php print $site_name; ?> in Facebook" href="<?php print $facebook_url; ?>"><?php print $site_name; ?> Facebook </a>
</li><?php endif; ?>
<?php if ($twitter_url): ?><li class="twitter">
<a target="_blank" title="<?php print $site_name; ?> in Twitter" href="<?php print $twitter_url; ?>"><?php print $site_name; ?> Twitter </a>
</li><?php endif; ?>
<?php if ($google_plus_url): ?><li class="google-plus">
<a target="_blank" title="<?php print $site_name; ?> in Google+" href="<?php print $google_plus_url; ?>"><?php print $site_name; ?> Google+ </a>
</li><?php endif; ?>
<?php if ($pinterest_url): ?><li class="pinterest">
<a target="_blank" title="<?php print $site_name; ?> in Pinterest" href="<?php print $pinterest_url; ?>"><?php print $site_name; ?> Twitter </a>
</li><?php endif; ?>
<li class="rss">
<a target="_blank" title="<?php print $site_name; ?> in RSS" href="<?php print $front_page; ?>rss.xml"><?php print $site_name; ?> RSS </a>
</li>
</ul>
</div>
<?php endif; ?>
<div class="row-end"></div>
<nav id="navigation" role="navigation">
<div id="main-menu">
<?php
if (module_exists('i18n_menu')) {
$main_menu_tree = i18n_menu_translated_tree(variable_get('menu_main_links_source', 'main-menu'));
} else {
$main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
}
print drupal_render($main_menu_tree);
?>
</div>
</nav>
<div class="row-end"></div>
<?php if ($is_front): ?>
<?php if (theme_get_setting('slideshow_display','creative')): ?>
<?php
$slide1_desc = check_markup(theme_get_setting('slide1_desc', 'creative'), 'full_html');
$slide2_desc = check_markup(theme_get_setting('slide2_desc', 'creative'), 'full_html');
$slide3_desc = check_markup(theme_get_setting('slide3_desc', 'creative'), 'full_html');
?>
<div class="featured-slider">
<div class="slides displayblock">
<div class="featured">
<div class="slide-image"><span class="img-effect pngfix"></span><img width="976" height="313" src="<?php print base_path() . drupal_get_path('theme', 'creative') . '/images/slide-image-1.jpg'; ?>" class="pngfix"/>
</div> <!-- .slide-image -->
</div> <!-- .featured -->
<?php if($slide1_desc) { print '<div class="featured-text">' . $slide1_desc . '</div>'; } ?><!-- .featured-text -->
</div> <!-- .slides -->
<div class="slides displaynone">
<div class="featured">
<div class="slide-image"><span class="img-effect pngfix"></span><img width="976" height="313" src="<?php print base_path() . drupal_get_path('theme', 'creative') . '/images/slide-image-2.jpg'; ?>" class="pngfix"/>
</div> <!-- .slide-image -->
</div> <!-- .featured -->
<?php if($slide1_desc) { print '<div class="featured-text">' . $slide2_desc . '</div>'; } ?><!-- .featured-text -->
</div> <!-- .slides -->
<div class="slides displaynone">
<div class="featured">
<div class="slide-image"><span class="img-effect pngfix"></span><img width="976" height="313" src="<?php print base_path() . drupal_get_path('theme', 'creative') . '/images/slide-image-3.jpg'; ?>" class="pngfix"/>
</div> <!-- .slide-image -->
</div> <!-- .featured -->
<?php if($slide1_desc) { print '<div class="featured-text">' . $slide3_desc . '</div>'; } ?><!-- .featured-text -->
</div> <!-- .slides -->
</div>
<div id="controllers"></div><!-- #controllers -->
<?php endif; ?>
<?php endif; ?>
</div>
</header>
<div id="preface-head" class="layout-978">
<?php if($page['preface_first'] || $page['preface_middle'] || $page['preface_last']) : ?>
<div id="preface-wrap">
<div class="preface-block col4">
<?php print render ($page['preface_first']); ?>
</div>
<div class="preface-block col4">
<?php print render ($page['preface_middle']); ?>
</div>
<div class="preface-block col4">
<?php print render ($page['preface_last']); ?>
</div>
<div class="row-end"></div>
</div>
<?php endif; ?>
<?php print render($page['header']); ?>
<div class="row-end"></div>
</div>
<div id="main" class="layout-978">
<?php if($page['sidebar_first']) { $col = "col8"; } else { $col= "col12"; } ?>
<section id="content" role="main" class="<?php print $col; ?> no-margin-left">
<?php if (theme_get_setting('breadcrumbs')): ?><?php if ($breadcrumb): ?><div id="breadcrumbs"><?php print $breadcrumb; ?></div><?php endif;?><?php endif; ?>
<?php print $messages; ?>
<?php if ($page['content_top']): ?><div id="content_top"><?php print render($page['content_top']); ?></div><?php endif; ?>
<?php print render($title_prefix); ?>
<?php if ($title): ?><h1 class="page-title"><?php print $title; ?></h1><?php endif; ?>
<?php print render($title_suffix); ?>
<?php if (!empty($tabs['#primary'])): ?><div class="tabs-wrapper clearfix"><?php print render($tabs); ?></div><?php endif; ?>
<?php print render($page['help']); ?>
<?php if ($action_links): ?><ul class="action-links"><?php print render($action_links); ?></ul><?php endif; ?>
<?php print render($page['content']); ?>
</section> <!-- /#main -->
<?php if ($page['sidebar_first']): ?>
<aside id="sidebar" role="complementary" class="col4">
<?php print render($page['sidebar_first']); ?>
</aside>
<?php endif; ?>
<div class="row-end"></div>
</div>
<div id="footer-bottom" class="layout-978">
<?php if ($page['footer_first'] || $page['footer_second'] || $page['tagline']): ?>
<div id="footer-one" class="col4">
<?php print render ($page['footer_first']); ?>
</div>
<div id="footer-two" class="col4">
<?php print render ($page['footer_second']); ?>
</div>
<div id="footer-three" class="col4">
<?php print render($page['tagline']); ?>
</div>
<div class="row-end"></div>
<?php endif; ?>
<?php print render($page['footer']); ?>
</div>
<div id="footer">
<div class="layout-978">
<div class="col7 copyright no-margin-left">
<?php print t('Copyright'); ?> © <?php echo date("Y"); ?>, <a href="<?php print $front_page; ?>"><?php print $site_name; ?></a>
</div>
<div class="col5 powered-by">
<?php print t('Theme by'); ?> <a href="http://www.devsaran.com" target="_blank">Devsaran</a>
</div>
</div>
</div>
|
AbeerKhakwani/drupal_theme_creative
|
sites/all/themes/mycreativetheme/templates/page.tpl.php
|
PHP
|
gpl-2.0
| 10,672
|
/*************************************************************************************
Grid physics library, www.github.com/paboyle/Grid
Source file: ./lib/algorithms/iterative/ConjugateGradientMultiShift.h
Copyright (C) 2015
Author: Azusa Yamaguchi <ayamaguc@staffmail.ed.ac.uk>
Author: Peter Boyle <paboyle@ph.ed.ac.uk>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
See the full license in the file "LICENSE" in the top level distribution directory
*************************************************************************************/
/* END LEGAL */
#ifndef GRID_CONJUGATE_MULTI_SHIFT_GRADIENT_H
#define GRID_CONJUGATE_MULTI_SHIFT_GRADIENT_H
namespace Grid {
/////////////////////////////////////////////////////////////
// Base classes for iterative processes based on operators
// single input vec, single output vec.
/////////////////////////////////////////////////////////////
template<class Field>
class ConjugateGradientMultiShift : public OperatorMultiFunction<Field>,
public OperatorFunction<Field>
{
public:
RealD Tolerance;
Integer MaxIterations;
int verbose;
MultiShiftFunction shifts;
ConjugateGradientMultiShift(Integer maxit,MultiShiftFunction &_shifts) :
MaxIterations(maxit),
shifts(_shifts)
{
verbose=1;
}
void operator() (LinearOperatorBase<Field> &Linop, const Field &src, Field &psi)
{
GridBase *grid = src._grid;
int nshift = shifts.order;
std::vector<Field> results(nshift,grid);
(*this)(Linop,src,results,psi);
}
void operator() (LinearOperatorBase<Field> &Linop, const Field &src, std::vector<Field> &results, Field &psi)
{
int nshift = shifts.order;
(*this)(Linop,src,results);
psi = shifts.norm*src;
for(int i=0;i<nshift;i++){
psi = psi + shifts.residues[i]*results[i];
}
return;
}
void operator() (LinearOperatorBase<Field> &Linop, const Field &src, std::vector<Field> &psi)
{
GridBase *grid = src._grid;
////////////////////////////////////////////////////////////////////////
// Convenience references to the info stored in "MultiShiftFunction"
////////////////////////////////////////////////////////////////////////
int nshift = shifts.order;
std::vector<RealD> &mass(shifts.poles); // Make references to array in "shifts"
std::vector<RealD> &mresidual(shifts.tolerances);
std::vector<RealD> alpha(nshift,1.0);
std::vector<Field> ps(nshift,grid);// Search directions
assert(psi.size()==nshift);
assert(mass.size()==nshift);
assert(mresidual.size()==nshift);
// dynamic sized arrays on stack; 2d is a pain with vector
RealD bs[nshift];
RealD rsq[nshift];
RealD z[nshift][2];
int converged[nshift];
const int primary =0;
//Primary shift fields CG iteration
RealD a,b,c,d;
RealD cp,bp,qq; //prev
// Matrix mult fields
Field r(grid);
Field p(grid);
Field tmp(grid);
Field mmp(grid);
// Check lightest mass
for(int s=0;s<nshift;s++){
assert( mass[s]>= mass[primary] );
converged[s]=0;
}
// Wire guess to zero
// Residuals "r" are src
// First search direction "p" is also src
cp = norm2(src);
for(int s=0;s<nshift;s++){
rsq[s] = cp * mresidual[s] * mresidual[s];
std::cout<<GridLogMessage<<"ConjugateGradientMultiShift: shift "<<s
<<" target resid "<<rsq[s]<<std::endl;
ps[s] = src;
}
// r and p for primary
r=src;
p=src;
//MdagM+m[0]
Linop.HermOpAndNorm(p,mmp,d,qq);
axpy(mmp,mass[0],p,mmp);
RealD rn = norm2(p);
d += rn*mass[0];
// have verified that inner product of
// p and mmp is equal to d after this since
// the d computation is tricky
// qq = real(innerProduct(p,mmp));
// std::cout<<GridLogMessage << "debug equal ? qq "<<qq<<" d "<< d<<std::endl;
b = -cp /d;
// Set up the various shift variables
int iz=0;
z[0][1-iz] = 1.0;
z[0][iz] = 1.0;
bs[0] = b;
for(int s=1;s<nshift;s++){
z[s][1-iz] = 1.0;
z[s][iz] = 1.0/( 1.0 - b*(mass[s]-mass[0]));
bs[s] = b*z[s][iz];
}
// r += b[0] A.p[0]
// c= norm(r)
c=axpy_norm(r,b,mmp,r);
for(int s=0;s<nshift;s++) {
axpby(psi[s],0.,-bs[s]*alpha[s],src,src);
}
// Iteration loop
int k;
for (k=1;k<=MaxIterations;k++){
a = c /cp;
axpy(p,a,p,r);
// Note to self - direction ps is iterated seperately
// for each shift. Does not appear to have any scope
// for avoiding linear algebra in "single" case.
//
// However SAME r is used. Could load "r" and update
// ALL ps[s]. 2/3 Bandwidth saving
// New Kernel: Load r, vector of coeffs, vector of pointers ps
for(int s=0;s<nshift;s++){
if ( ! converged[s] ) {
if (s==0){
axpy(ps[s],a,ps[s],r);
} else{
RealD as =a *z[s][iz]*bs[s] /(z[s][1-iz]*b);
axpby(ps[s],z[s][iz],as,r,ps[s]);
}
}
}
cp=c;
Linop.HermOpAndNorm(p,mmp,d,qq);
axpy(mmp,mass[0],p,mmp);
RealD rn = norm2(p);
d += rn*mass[0];
bp=b;
b=-cp/d;
c=axpy_norm(r,b,mmp,r);
// Toggle the recurrence history
bs[0] = b;
iz = 1-iz;
for(int s=1;s<nshift;s++){
if((!converged[s])){
RealD z0 = z[s][1-iz];
RealD z1 = z[s][iz];
z[s][iz] = z0*z1*bp
/ (b*a*(z1-z0) + z1*bp*(1- (mass[s]-mass[0])*b));
bs[s] = b*z[s][iz]/z0; // NB sign rel to Mike
}
}
for(int s=0;s<nshift;s++){
int ss = s;
// Scope for optimisation here in case of "single".
// Could load psi[0] and pull all ps[s] in.
// if ( single ) ss=primary;
// Bandwith saving in single case is Ls * 3 -> 2+Ls, so ~ 3x saving
// Pipelined CG gain:
//
// New Kernel: Load r, vector of coeffs, vector of pointers ps
// New Kernel: Load psi[0], vector of coeffs, vector of pointers ps
// If can predict the coefficient bs then we can fuse these and avoid write reread cyce
// on ps[s].
// Before: 3 x npole + 3 x npole
// After : 2 x npole (ps[s]) => 3x speed up of multishift CG.
if( (!converged[s]) ) {
axpy(psi[ss],-bs[s]*alpha[s],ps[s],psi[ss]);
}
}
// Convergence checks
int all_converged = 1;
for(int s=0;s<nshift;s++){
if ( (!converged[s]) ){
RealD css = c * z[s][iz]* z[s][iz];
if(css<rsq[s]){
if ( ! converged[s] )
std::cout<<GridLogMessage<<"ConjugateGradientMultiShift k="<<k<<" Shift "<<s<<" has converged"<<std::endl;
converged[s]=1;
} else {
all_converged=0;
}
}
}
if ( all_converged ){
std::cout<<GridLogMessage<< "CGMultiShift: All shifts have converged iteration "<<k<<std::endl;
std::cout<<GridLogMessage<< "CGMultiShift: Checking solutions"<<std::endl;
// Check answers
for(int s=0; s < nshift; s++) {
Linop.HermOpAndNorm(psi[s],mmp,d,qq);
axpy(tmp,mass[s],psi[s],mmp);
axpy(r,-alpha[s],src,tmp);
RealD rn = norm2(r);
RealD cn = norm2(src);
std::cout<<GridLogMessage<<"CGMultiShift: shift["<<s<<"] true residual "<<std::sqrt(rn/cn)<<std::endl;
}
return;
}
}
// ugly hack
std::cout<<GridLogMessage<<"CG multi shift did not converge"<<std::endl;
// assert(0);
}
};
}
#endif
|
FlorisBalm/Grid
|
lib/algorithms/iterative/ConjugateGradientMultiShift.h
|
C
|
gpl-2.0
| 8,022
|
<?php
# ro_RO translation for
# PHP-Calendar, DatePicker Calendar class: http://www.triconsole.com/php/calendar_datepicker.php
# Version: 3.61
# Language: Romanian / Română
# Translator: Ciprian Murariu <ciprianmp@yahoo.com>
# Last file update: 01.09.2011
// Class strings localization
define("L_DAY", "Ziua");
define("L_MONTH", "Luna");
define("L_YEAR", "Anul");
define("L_TODAY", "Azi");
define("L_PREV", "Înapoi");
define("L_NEXT", "Înainte");
define("L_CHK_VAL", "Verifică valoarea");
define("L_SEL_LANG", "Alege Limba");
define("L_SEL_ICON", "Alege Icon-ul");
define("L_SEL_DATE", "Alege data");
define("L_REF_CAL", "Calendarul se reiniţializează...");
define("L_ERR_SEL", "Data selectată nu este validă!");
define("L_NOT_ALLOWED", "Nu este permisă selectarea acestei date!");
define("L_DATE_BEFORE", "Selectaţi o dată înainte de %s!");
define("L_DATE_AFTER", "Selectaţi o dată după %s!");
define("L_DATE_BETWEEN", "Selectaţi o dată între\\n%s şi %s!");
define("L_WEEK_HDR", ""); // Optional Short Name for the column header showing the current Week number (W or CW in English - max 2 letters)
define("L_UNSET", "Anulare");
// Set the first day of the week in your language (0 for Sunday, 1 for Monday)
define("FIRST_DAY", "1");
// Months Long Names
define("L_JAN", "ianuarie");
define("L_FEB", "februarie");
define("L_MAR", "martie");
define("L_APR", "aprilie");
define("L_MAY", "mai");
define("L_JUN", "iunie");
define("L_JUL", "iulie");
define("L_AUG", "august");
define("L_SEP", "septembrie");
define("L_OCT", "octombrie");
define("L_NOV", "noiembrie");
define("L_DEC", "decembrie");
// Months Short Names
define("L_S_JAN", "ian");
define("L_S_FEB", "feb");
define("L_S_MAR", "mar");
define("L_S_APR", "apr");
define("L_S_MAY", "mai");
define("L_S_JUN", "iun");
define("L_S_JUL", "iul");
define("L_S_AUG", "aug");
define("L_S_SEP", "sept");
define("L_S_OCT", "oct");
define("L_S_NOV", "nov");
define("L_S_DEC", "dec");
// Week days Long Names
define("L_MON", "luni");
define("L_TUE", "marţi");
define("L_WED", "miercuri");
define("L_THU", "joi");
define("L_FRI", "vineri");
define("L_SAT", "sâmbătă");
define("L_SUN", "duminică");
// Week days Short Names
define("L_S_MON", "l");
define("L_S_TUE", "ma");
define("L_S_WED", "mi");
define("L_S_THU", "j");
define("L_S_FRI", "v");
define("L_S_SAT", "s");
define("L_S_SUN", "d");
// Windows encoding
define("WIN_DEFAULT", "windows-1250");
define("L_CAL_FORMAT", "%d %B %Y");
if(!defined("L_LANG") || L_LANG == "L_LANG") define("L_LANG", "ro_RO");
// Set the RO specific date/time format
if (stristr(PHP_OS,"win")) {
setlocale(LC_ALL, "ROU_ROU.UTF-8", "ROU_ROU", "romanian.UTF-8", "romanian"); // For Windows servers
} else {
setlocale(LC_ALL, "ro_RO.UTF-8@euro", "ro_RO.UTF-8", "rou.UTF-8", "rou_rou.UTF-8"); // For Unix/FreeBSD servers
}
?>
|
sinan92/Pikawall
|
wp-content/plugins/appointment-calendar/calendar/lang/calendar.ro_RO.php
|
PHP
|
gpl-2.0
| 2,826
|
/* Webkit animation keyframes */
@-webkit-keyframes animate-stripes {
from {
background-position: 0 0;
}
to {
background-position: 44px 0;
}
}
.ui-progress-bar {
position: relative;
height: 35px;
padding-right: 2px;
border-bottom: 10px solid #e0e0e0;
margin-top: -25px;
}
.ui-progress {
position: relative;
display: block;
overflow: hidden;
height: 35px;
border-bottom: 10px solid #8abfed;
}
.ui-progress.two {
border-bottom: 10px solid #b2c676;
}
.ui-progress.three {
border-bottom: 10px solid #b192d0;
}
.ui-progress.four {
border-bottom: 10px solid #e7d18d;
}
.ui-progress.five {
border-bottom: 10px solid #f39191;
}
.ui-progress span.ui-label {
font-family: 'Open Sans', sans-serif;
font-weight: 300;
text-transform: uppercase;
font-size: 16px;
color: #272727;
position: absolute;
right: 0;
line-height: 20px;
padding-right: 12px;
white-space: nowrap;
}
.ui-progress-bar.small {
height: 34px;
border-bottom: 8px solid #e0e0e0;
margin-top: -35px;
}
.ui-progress.small {
height: 34px;
border-bottom: 8px solid #8abfed;
}
.ui-progress.small.two {
border-bottom: 8px solid #b2c676;
}
.ui-progress.small.three {
border-bottom: 8px solid #b192d0;
}
.ui-progress.small.four {
border-bottom: 8px solid #e7d18d;
}
.ui-progress.small.five {
border-bottom: 8px solid #f39191;
}
.ui-progress-bar2 {
position: relative;
height: 46px;
padding-right: 2px;
border-bottom: 10px solid #e0e0e0;
margin-top: -29px;
}
.ui-progress2 {
position: relative;
display: block;
overflow: hidden;
height: 46px;
border-bottom: 10px solid #8abfed;
}
.ui-progress2.two {
border-bottom: 10px solid #b2c676;
}
.ui-progress2.three {
border-bottom: 10px solid #b192d0;
}
.ui-progress2.four {
border-bottom: 10px solid #e7d18d;
}
.ui-progress2.five {
border-bottom: 10px solid #f39191;
}
.ui-progress2 span.ui-label {
font-family: 'Open Sans', sans-serif;
font-weight: 300;
text-transform: uppercase;
font-size: 13px;
color: #fff;
position: absolute;
right: 0;
line-height: 28px;
padding-right: 12px;
white-space: nowrap;
}
.ui-progress2 b {
float: left;
width: 40px;
height: 40px;
text-align: center;
background: url(../images/tooltop-graph.png) no-repeat center top;
background-size: 90%;
}
.ui-progress-bar3 {
position: relative;
height: 40px;
padding-right: 2px;
border-bottom: 20px solid #e0e0e0;
margin-top: -25px;
}
.ui-progress3 {
position: relative;
display: block;
overflow: hidden;
height: 40px;
border-bottom: 10px solid #999;
border-bottom-width: 20px !important;
}
.ui-progress3 span.ui-label {
font-family: 'Open Sans', sans-serif;
font-weight: 300;
text-transform: uppercase;
font-size: 16px;
color: #272727;
position: absolute;
right: 0;
line-height: 20px;
padding-right: 12px;
white-space: nowrap;
}
.ui-progress-bar4 {
position: relative;
height: 27px;
padding-right: 2px;
background-color: #e0e0e0;
margin-top: -10px;
border-radius: 14px;
}
.ui-progress4 {
position: relative;
display: block;
overflow: hidden;
height: 27px;
background-color: #272727;
border-radius: 14px;
border: none;
}
.ui-progress4 span.ui-label {
font-family: 'Open Sans', sans-serif;
font-weight: 300;
text-transform: uppercase;
font-size: 14px;
color: #fff;
position: absolute;
right: 0;
line-height: 27px;
padding-right: 30px;
white-space: nowrap;
}
.ui-progress-bar4.color {
height: 22px;
border-radius: 14px;
margin-top: -5px;
}
.ui-progress4.color {
height: 22px;
border-radius: 14px;
background-color: #e54c4c;
}
.ui-progress4 span.ui-label {
line-height: 22px;
}
.pro_bar h5 {
font-weight: 500;
}
|
pivotlearning/wpsite
|
wp-content/themes/linstar/core/shortcodes/assets/css/ui.progress-bar.css
|
CSS
|
gpl-2.0
| 3,731
|
/* { dg-require-effective-target vect_shift } */
/* { dg-require-effective-target vect_int } */
/* Check the standard integer types for left and right shifts to see if the
compiler replaced a scalar instruction with a vector instruction whether the
correct value is generated. */
#ifdef TRACE
#include <stdio.h>
#endif
#include <stdarg.h>
#include "tree-vect.h"
#ifndef ALIGN
#define ALIGN __attribute__((__aligned__(__BIGGEST_ALIGNMENT__)))
#endif
#ifndef NOINLINE
#define NOINLINE __attribute__((__noinline__))
#endif
#ifdef TRACE
#define TRACE_FUNC(PREFIX, NAME) printf (#PREFIX #NAME "\n")
#define TRACE_DONE() printf ("done!\n")
#define TRACE_ABORT(I,E,G) \
do { \
printf ("Element %d, expected 0x%lx, got 0x%lx\n", \
I, (long)(E), (long)(G)); \
abort (); \
} while (0)
#else
#define TRACE_FUNC(PREFIX, A)
#define TRACE_DONE()
#define TRACE_ABORT(I,E,G) abort ()
#endif
#define NAME(A,B) A ## B
#define VECT_TESTS(PREFIX, TYPE, N) \
/* Restrict the optimizer from optimizing the setup loops. */ \
volatile TYPE NAME (PREFIX, zero) = 0; \
\
TYPE NAME (PREFIX, a)[N] ALIGN; \
TYPE NAME (PREFIX, b)[N] ALIGN; \
TYPE NAME (PREFIX, c)[N] ALIGN; \
TYPE NAME (PREFIX, d)[N] ALIGN; \
\
static void NOINLINE \
NAME (PREFIX, lshift_2) (void) \
{ \
int i; \
\
TRACE_FUNC (PREFIX, lshift_2); \
for (i = 0; i < N; i++) \
NAME (PREFIX, a)[i] = NAME (PREFIX, b)[i] << 2; \
} \
\
static void NOINLINE \
NAME (PREFIX, lshift_var) (int shift) \
{ \
int i; \
\
TRACE_FUNC (PREFIX, lshift_var); \
for (i = 0; i < N; i++) \
NAME (PREFIX, a)[i] = NAME (PREFIX, b)[i] << shift; \
} \
\
static void NOINLINE \
NAME (PREFIX, lshift_vect) (void) \
{ \
int i; \
\
TRACE_FUNC (PREFIX, lshift_vect); \
for (i = 0; i < N; i++) \
NAME (PREFIX, a)[i] = NAME (PREFIX, b)[i] << NAME (PREFIX, c)[i]; \
} \
\
static void NOINLINE \
NAME (PREFIX, rshift_2) (void) \
{ \
int i; \
\
TRACE_FUNC (PREFIX, rshift_2); \
for (i = 0; i < N; i++) \
NAME (PREFIX, a)[i] = NAME (PREFIX, b)[i] >> 2; \
} \
\
static void NOINLINE \
NAME (PREFIX, rshift_var) (int shift) \
{ \
int i; \
\
TRACE_FUNC (PREFIX, rshift_var); \
for (i = 0; i < N; i++) \
NAME (PREFIX, a)[i] = NAME (PREFIX, b)[i] >> shift; \
} \
\
static void NOINLINE \
NAME (PREFIX, rshift_vect) (void) \
{ \
int i; \
\
TRACE_FUNC (PREFIX, rshift_vect); \
for (i = 0; i < N; i++) \
NAME (PREFIX, a)[i] = NAME (PREFIX, b)[i] >> NAME (PREFIX, c)[i]; \
} \
\
static void NOINLINE \
NAME (PREFIX, check) (void) \
{ \
int i; \
\
TRACE_FUNC (PREFIX, check); \
for (i = 0; i < N; i++) \
if (NAME (PREFIX, a)[i] != NAME (PREFIX, d)[i]) \
TRACE_ABORT (i, NAME (PREFIX, d)[i], NAME (PREFIX, a)[i]); \
} \
\
static void NOINLINE \
NAME (PREFIX, tests) (void) \
{ \
int i; \
\
TRACE_FUNC (PREFIX, tests); \
for (i = 0; i < N; i++) \
{ \
NAME (PREFIX, b)[i] = (i + NAME (PREFIX, zero)); \
NAME (PREFIX, c)[i] = 2; \
NAME (PREFIX, d)[i] = (i + NAME (PREFIX, zero)) << 2; \
} \
\
NAME (PREFIX, lshift_2) (); \
NAME (PREFIX, check) (); \
\
NAME (PREFIX, lshift_var) (2); \
NAME (PREFIX, check) (); \
\
NAME (PREFIX, lshift_vect) (); \
NAME (PREFIX, check) (); \
\
for (i = 0; i < N; i++) \
{ \
NAME (PREFIX, b)[i] = ((i + NAME (PREFIX, zero)) << 4) \
| (((TYPE)0x80) << ((sizeof (TYPE) * 8) - 8)); \
NAME (PREFIX, c)[i] = 2; \
NAME (PREFIX, d)[i] = (TYPE)((NAME (PREFIX, b)[i] \
+ NAME (PREFIX, zero)) >> 2); \
} \
\
NAME (PREFIX, rshift_2) (); \
NAME (PREFIX, check) (); \
\
NAME (PREFIX, rshift_var) (2); \
NAME (PREFIX, check) (); \
\
NAME (PREFIX, rshift_vect) (); \
NAME (PREFIX, check) (); \
}
VECT_TESTS(uc_, unsigned char, 16)
VECT_TESTS(us_, unsigned short, 32)
VECT_TESTS(ui_, unsigned int, 32)
VECT_TESTS(ul_, unsigned long, 32)
VECT_TESTS(sc_, signed char, 16)
VECT_TESTS(ss_, short, 32)
VECT_TESTS(si_, int, 32)
VECT_TESTS(sl_, long, 32)
int main ()
{
int i;
check_vect ();
uc_tests ();
us_tests ();
ui_tests ();
ul_tests ();
sc_tests ();
ss_tests ();
si_tests ();
sl_tests ();
TRACE_DONE ();
return 0;
}
/* { dg-final { cleanup-tree-dump "vect" } } */
|
ccompiler4pic32/pic32-gcc
|
gcc/testsuite/gcc.dg/vect/vect-shift-2.c
|
C
|
gpl-2.0
| 4,956
|
from __future__ import absolute_import
from .base import *
|
cr8ivecodesmith/pyort
|
pyort/pyort/settings/production.py
|
Python
|
gpl-2.0
| 59
|
<?
global $wgLogo, $wgSitename, $wgServer;
//List of parameters and default values
$flashvardefault = array(
'backgroundColor' => '336699',
'backgroundImage' => '',
'borderColor' => '333333',
'dropShadow' => '1',
'headerColor' => '000000',
'headerAlpha' => '.2',
'headerBorderColor' => 'FFFFFF',
'headline1' => $wgSitename .' presents',
'headline1Color' => 'CCCCCC',
'headline2' => 'A cool slideshow!',
'headline2Color' => 'FFFFFF',
'clickURL' => $wgServer,
'wikiURLColor' => 'FFFFFF',
'wikiaLogoColor' => 'FFFFFF',
'logo' => $wgLogo,
'type' => 'slideshow',
'slideshowImages' => 'http://images.wikia.com/common/skins/common/flash_widgets/slideshow_placeholder.png,http://images.wikia.com/common/skins/common/flash_widgets/slideshow_placeholder2.png'
);
//Determine if any of the above values have been submitted as GET vars
foreach ($flashvardefault as $key => $value) {
if (!empty($_POST[$key])) {
$use_default_style = false;
break;
} else {
$use_default_style = true;
}
}
//Set $flashvars variable with either default values or user values
$flashvars = 'FlashVars="';
if ($use_default_style) {
foreach ($flashvardefault as $key => $value) {
$flashvars .= $key .'='. urlencode($value) .'&';
$_POST[$key] = $value;
}
} else {
foreach ($flashvardefault as $key => $value) {
//change linebreaks to commas
if ($key == 'slideshowImages') {
$temp_img_array = preg_split("/\n/", trim($_POST[$key]));
$_POST[$key] = implode(',', $temp_img_array);
$flashvars .= $key .'='. urlencode($_POST[$key]) .'&';
break;
}
if (isset($_POST[$key])) {
$flashvars .= $key .'='. urlencode($_POST[$key]) .'&';
}
}
}
$flashvars .= 'logo='. $wgLogo .'"';
?>
<script type="text/javascript">
function backgroundImageInterface(e) {
document.wikia_widget.loadBackground(e.target.value);
}
function myInterface(e) {
if (e.target.value) {
switch (e.target.name) {
case 'backgroundColor':
document.wikia_widget.setColor('background', e.target.value);
break;
case 'borderColor':
document.wikia_widget.setColor('border', e.target.value);
break;
case 'headerColor':
document.wikia_widget.setColor('header', e.target.value);
document.wikia_widget.setColor('footer', e.target.value);
break;
case 'headerAlpha':
document.wikia_widget.setColor('header', document.forms['config'].headerColor.value, e.target.value);
document.wikia_widget.setColor('footer', document.forms['config'].headerColor.value, e.target.value);
case 'headerBorderColor':
document.wikia_widget.setColor('header_border', e.target.value);
document.wikia_widget.setColor('footer_border', e.target.value);
break;
case 'headline1':
document.wikia_widget.headline('headline1', e.target.value, document.forms['config'].headline1Color.value);
break;
case 'headline2':
document.wikia_widget.headline('headline2', e.target.value, document.forms['config'].headline2Color.value);
break;
case 'headline1Color':
document.wikia_widget.headline('headline1', document.forms['config'].headline1.value, e.target.value);
break;
case 'headline2Color':
document.wikia_widget.headline('headline2', document.forms['config'].headline2.value, e.target.value);
break;
case 'wikiaLogoColor':
document.wikia_widget.setColor('wikia_logo', e.target.value);
break;
case 'clickURL':
document.wikia_widget.url(e.target.value, document.forms['config'].wikiURLColor.value);
break;
case 'wikiURLColor':
document.wikia_widget.url(document.forms['config'].clickURL.value, e.target.value);
break;
case 'type':
setType(e.target.value);
break;
case 'dropShadow':
document.wikia_widget.shadow(e.target.checked);
break;
default:
break;
}
}
}
function generateWidgetCode() {
var flashcode = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="300" height="250" align="middle" id="wikia_widget"> <param name="allowScriptAccess" value="always" /> <param name="movie" value="http://images.wikia.com/common/skins/common/flash_widgets/wikia_widget.swf" /> <param name="quality" value="high" /> <param name="wmode" value="transparent" /> <embed src="http://images.wikia.com/common/skins/common/flash_widgets/wikia_widget.swf" ';
var params = 'FlashVars="';
var elements = document.forms['config'].elements;
for (i=0; i<elements.length; i++) {
if (elements[i].name == 'slideshowImages') {
var img_array = elements[i].value.split("\n");
params += elements[i].name + '=' + img_array.join(",") + '&';
} else {
params += elements[i].name + '=' + elements[i].value + '&';
}
}
params += '"';
flashcode += params;
flashcode += ' quality="high" wmode="transparent" width="300" height="250" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" name="wikia_widget" /> </object>';
document.getElementById('codearea').innerHTML = flashcode;
}
</script>
<div style="float: right; margin-left: 10px;">
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="300" height="250" align="middle" id="wikia_widget">
<param name="allowScriptAccess" value="always" />
<param name="movie" value="/skins/common/flash_widgets/wikia_widget.swf" />
<param name="quality" value="high" />
<param name="wmode" value="transparent" />
<embed src="/skins/common/flash_widgets/wikia_widget.swf" <?=$flashvars?> quality="high" wmode="transparent" width="300" height="250" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" name="wikia_widget" />
</object>
</div>
<form name="config" method="POST" action="<?=$_SERVER['PHP_SELF']?>">
<h2>Background colors and images</h2>
<h3>Main background</h3>
<ul>
<li>
<label>Background style</label>
<ul>
<li>
<label>Background color:</label>
#<input type="text" name="backgroundColor" onblur="myInterface(event)" style="width: 6em;" maxlength="6" value="<?=htmlspecialchars($_POST['backgroundColor'])?>" /><br />
<b>or</b>
</li>
<li>
<label>Background image:</label>
<input type="text" name="backgroundImage" onblur="backgroundImageInterface(event)" value="<?=htmlspecialchars($_POST['backgroundImage'])?>" />
</li>
</ul>
</li>
<li>
<label>Border color:</label>
#<input type="text" name="borderColor" onblur="myInterface(event)" style="width: 6em;" maxlength="6" value="<?=htmlspecialchars($_POST['borderColor'])?>" />
</li>
<li>
<label>Drop shadow:</label>
<input type="checkbox" name="dropShadow" checked="checked" onchange="myInterface(event);" />
</ul>
<h3>Header & Footer</h3>
<ul>
<li>
<label>Header & footer background color:</label>
#<input type="text" name="headerColor" onblur="myInterface(event)" style="width: 6em;" maxlength="6" value="<?=htmlspecialchars($_POST['headerColor'])?>" />
<ul>
<li>
<label>Opacity:</label>
<input type="text" name="headerAlpha" onblur="myInterface(event)" style="width: 2em;" value="<?=htmlspecialchars($_POST['headerAlpha'])?>" /> (decimal between 0.0 and 1.0)
</li>
</ul>
</li>
<li>
<label>Header & footer border color:</label>
#<input type="text" name="headerBorderColor" onblur="myInterface(event)" style="width: 6em;" maxlength="6" value="<?=htmlspecialchars($_POST['headerBorderColor'])?>" />
</li>
</ul>
<h2>Headline text</h2>
<ul>
<li>
<label>First Headline</label>
<input type="text" name="headline1" onblur="myInterface(event);" value="<?=htmlspecialchars($_POST['headline1'])?>" />
<label>Color:</label>
#<input type="text" name="headline1Color" onblur="myInterface(event);" style="width: 6em;" maxlength="6" value="<?=htmlspecialchars($_POST['headline1Color'])?>" />
</li>
<li>
<label>Second Headline</label>
<input type="text" name="headline2" onblur="myInterface(event);" value="<?=htmlspecialchars($_POST['headline2'])?>" />
<label>Color:</label>
#<input type="text" name="headline2Color" onblur="myInterface(event);" style="width: 6em;" maxlength="6" value="<?=htmlspecialchars($_POST['headline2Color'])?>" />
</li>
</ul>
<h2>Attribution</h2>
<ul>
<li>
<label>Click URL:</label>
<input type="text" name="clickURL" onblur="myInterface(event);" value="<?=htmlspecialchars($_POST['clickURL'])?>" />
<label>Link color:</label>
#<input type="text" name="wikiURLColor" onblur="myInterface(event);" style="width: 6em;" maxlength="6" value="<?=htmlspecialchars($_POST['wikiURLColor'])?>" />
</li>
<li>
<label>Wikia logo color:</label>
#<input type="text" name="wikiaLogoColor" onblur="myInterface(event);" style="width: 6em;" maxlength="6" value="<?=htmlspecialchars($_POST['wikiaLogoColor'])?>" />
</li>
</ul>
<h2>Images</h2>
<input type="hidden" name="type" value="slideshow" />
<textarea name="slideshowImages" style="height: 100px;"><?=htmlspecialchars(str_replace(",", PHP_EOL, $_POST['slideshowImages']))?></textarea><br />
(One full image url per line) <input type="submit" value="Preview images in the widget"/>
</form>
<h2>Get the code</h2>
<input type="button" value="Generate Code" onclick="generateWidgetCode();" /><br />
<textarea id="codearea" style="width: 600px; height: 150px;"></textarea>
|
felixonmars/app
|
extensions/wikia/WikiaWidget/templates/main.tmpl.php
|
PHP
|
gpl-2.0
| 9,463
|
class TopicRetriever
def initialize(embed_url, opts=nil)
@embed_url = embed_url
@author_username = opts[:author_username]
@opts = opts || {}
end
def retrieve
perform_retrieve unless (invalid_host? || retrieved_recently?)
end
private
def invalid_host?
SiteSetting.allows_embeddable_host?(@embed_url)
end
def retrieved_recently?
# We can disable the throttle for some users, such as staff
return false if @opts[:no_throttle]
# Throttle other users to once every 60 seconds
retrieved_key = "retrieved:#{@embed_url}"
if $redis.setnx(retrieved_key, "1")
$redis.expire(retrieved_key, 60)
return false
end
true
end
def perform_retrieve
# It's possible another process or job found the embed already. So if that happened bail out.
return if TopicEmbed.where(embed_url: @embed_url).exists?
# First check RSS if that is enabled
if SiteSetting.feed_polling_enabled?
Jobs::PollFeed.new.execute({})
return if TopicEmbed.where(embed_url: @embed_url).exists?
end
fetch_http
end
def fetch_http
if @author_username.nil?
username = SiteSetting.embed_by_username.downcase
else
username = @author_username
end
user = User.where(username_lower: username.downcase).first
return if user.blank?
TopicEmbed.import_remote(user, @embed_url)
end
end
|
idnet/discourse
|
lib/topic_retriever.rb
|
Ruby
|
gpl-2.0
| 1,462
|
<?php
/**
* @package EasySocial
* @copyright Copyright (C) 2010 - 2014 Stack Ideas Sdn Bhd. All rights reserved.
* @license GNU/GPL, see LICENSE.php
* EasySocial is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
defined( '_JEXEC' ) or die( 'Unauthorized Access' );
/**
* Helper for currency
*
* @since 1.0
* @author Jason Rey <jasonrey@stackideas.com>
*/
class SocialFieldsUserCurrencyHelper
{
/**
* Get label for currency.
*
* @since 1.0
* @access public
* @param JRegistry The parameter object.
* @param string The type of string to lookup for.
* @return string
*/
public static function getLabel( &$params , $type )
{
// Get the currency to use.
$text = 'PLG_FIELDS_CURRENCY_' . strtoupper( $params->get( 'format' ) ) . '_' . strtoupper( $type );
return JText::_( $text );
}
}
|
cuongnd/banhangonline88_joomla
|
media/com_easysocial/apps/fields/user/currency/helper.php
|
PHP
|
gpl-2.0
| 1,080
|
-- TDB 910.21081 auth
UPDATE `updates` SET `state`='ARCHIVED',`speed`=0;
REPLACE INTO `updates_include` (`path`, `state`) VALUES ('$/sql/old/9.x/auth', 'ARCHIVED');
|
funjoker/TrinityCore
|
sql/old/9.x/auth/21081_2021_10_15/2021_08_18_00_auth.sql
|
SQL
|
gpl-2.0
| 165
|
<?php
/*
Copyright (C) <2011> Vasyl Martyniuk <martyniuk.vasyl@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Role Config Model Class
*
* Role Config Object
*
* @package AAM
* @subpackage Models
* @author Vasyl Martyniuk <martyniuk.vasyl@gmail.com>
* @copyrights Copyright © 2011 Vasyl Martyniuk
* @license GNU General Public License {@link http://www.gnu.org/licenses/}
*/
class mvb_Model_RoleConfig extends mvb_Model_Abstract_Config {
/**
* {@inheritdoc}
*/
protected $type = 'role';
/**
* User Role Name
*
* @access protected
* @var string
*/
protected $name = NULL;
/**
* {@inheritdoc }
*/
public function saveConfig() {
$roles = mvb_Model_API::getRoleList(FALSE);
if (isset($roles[$this->getID()])) {
$roles[$this->getID()]['capabilities'] = $this->getCapabilities();
if (!is_null($this->name)){
$roles[$this->getID()]['name'] = $this->name;
}
mvb_Model_API::updateBlogOption('user_roles', $roles);
}
$options = (object) array(
'menu' => $this->getMenu(),
'metaboxes' => $this->getMetaboxes(),
'menu_order' => $this->getMenuOrder(),
'restrictions' => $this->getRestrictions(),
);
mvb_Model_API::updateBlogOption(WPACCESS_PREFIX . 'config_' . $this->getID(), $options);
mvb_Model_Cache::clearCache();
do_action(WPACCESS_PREFIX . 'do_save');
}
/**
* {@inheritdoc }
*/
protected function getConfig() {
$roles = mvb_Model_API::getRoleList(FALSE); //TODO - Potensially hole
if (isset($roles[$this->getID()]['capabilities'])) {
$config = mvb_Model_API::getBlogOption(WPACCESS_PREFIX . 'config_' . $this->getID());
if ($config) {
$this->setMenu($config->menu);
$this->setMenuOrder($config->menu_order);
$this->setMetaboxes($config->metaboxes);
$this->setRestrictions($config->restrictions);
}
$this->setCapabilities($roles[$this->getID()]['capabilities']);
}
}
public function setName($name){
$this->name = $name;
}
}
?>
|
ciudadanointeligente/legacy-desarrollando-2012
|
wp-content/plugins/advanced-access-manager/model/roleconfig.php
|
PHP
|
gpl-2.0
| 2,910
|
<?php
/**
* Contains ExchangeWebServices.
*/
/**
* Base class of the Exchange Web Services application.
*
* @package php-ews\Client
*/
class ExchangeWebServices
{
/**
* Microsoft Exchange 2007
*
* @var string
*/
const VERSION_2007 = 'Exchange2007';
/**
* Microsoft Exchange 2007 SP1
*
* @var string
*/
const VERSION_2007_SP1 = 'Exchange2007_SP1';
/**
* Microsoft Exchange 2007 SP2
*
* @var string
*/
const VERSION_2007_SP2 = 'Exchange2007_SP2';
/**
* Microsoft Exchange 2007 SP3
*
* @var string
*/
const VERSION_2007_SP3 = 'Exchange2007_SP3';
/**
* Microsoft Exchange 2010
*
* @var string
*/
const VERSION_2010 = 'Exchange2010';
/**
* Microsoft Exchange 2010 SP1
*
* @var string
*/
const VERSION_2010_SP1 = 'Exchange2010_SP1';
/**
* Microsoft Exchange 2010 SP2
*
* @var string
*/
const VERSION_2010_SP2 = 'Exchange2010_SP2';
/**
* Password to use when connecting to the Exchange server.
*
* @var string
*/
protected $password;
/**
* Location of the Exchange server.
*
* @var string
*/
protected $server;
/**
* SOAP client used to make the request
*
* @var NTLMSoapClient_Exchange
*/
protected $soap;
/**
* Username to use when connecting to the Exchange server.
*
* @var string
*/
protected $username;
/**
* Exchange impersonation
*
* @var EWSType_ExchangeImpersonationType
*/
protected $impersonation;
/**
* Miscrosoft Exchange version that we are going to connect to
*
* @var string
*
* @see ExchangeWebServices::VERSION_2007
* @see ExchangeWebServices::VERSION_2007_SP1
* @see ExchangeWebServices::VERSION_2010
* @see ExchangeWebServices::VERSION_2010_SP1
*/
protected $version;
/**
* Constructor for the ExchangeWebServices class
*
* @param string $server
* @param string $username
* @param string $password
* @param string $version one of the ExchangeWebServices::VERSION_* constants
*/
public function __construct(
$server = null,
$username = null,
$password = null,
$version = self::VERSION_2007
) {
// Set the object properties.
$this->setServer($server);
$this->setUsername($username);
$this->setPassword($password);
$this->setVersion($version);
}
/**
* Returns the SOAP Client that may be used to make calls against the server
*
* @return NTLMSoapClient_Exchange
*/
public function getClient()
{
return $this->initializeSoapClient();
}
/**
* Sets the impersonation property.
*
* @param EWSType_ExchangeImpersonationType $impersonation
*/
public function setImpersonation($impersonation)
{
$this->impersonation = $impersonation;
return true;
}
/**
* Sets the password property.
*
* @param string $password
*/
public function setPassword($password)
{
$this->password = $password;
return true;
}
/**
* Sets the server property.
*
* @param string $server
*/
public function setServer($server)
{
$this->server = $server;
return true;
}
/**
* Sets the user name property.
*
* @param string $username
*/
public function setUsername($username)
{
$this->username = $username;
return true;
}
/**
* Sets the version property.
*
* @param string $version
*/
public function setVersion($version)
{
$this->version = $version;
return true;
}
/**
* Adds one or more delegates to a principal's mailbox and sets specific
* access permissions.
*
* @since Exchange 2007 SP1
*
* @param EWSTYpe_AddDelegateType $request
* @return EWSType_AddDelegateResponseMessageType
*/
public function AddDelegate($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Sets a one-time or follow up action on all the items in a conversation.
*
* This operation allows you to categorize, move, copy, delete, and set the
* read state on all items in a conversation. Actions can also be set for
* new messages in a conversation.
*
* @since Exchange 2010 SP1
*
* @param EWSType_ApplyConversationActionType $request
* @return EWSType_ApplyConversationActionResponseType
*/
public function ApplyConversationAction($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Converts item and folder identifiers between formats that are accepted by
* Microsoft Exchange Server.
*
* @since Exchange 2007 SP1
*
* @param EWSType_ConvertIdType $request
* @return EWSType_ConvertIdResponseType
*/
public function ConvertId($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Copies folders in a mailbox.
*
* @since Exchange 2007
*
* @param EWSType_CopyFolderType $request
* @return EWSType_CopyFolderResponseType
*/
public function CopyFolder($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Copies items and puts the items in a different folder.
*
* @since Exchange 2007
*
* @param EWSType_CopyItemType $request
* @return EWSType_CopyItemResponseType
*/
public function CopyItem($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Creates either an item or file attachment and attaches it to the
* specified item.
*
* @since Exchange 2007
*
* @param EWSType_CreateAttachmentType $request
* @return EWSType_CreateAttachmentResponseType
*/
public function CreateAttachment($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Creates folders, calendar folders, contacts folders, tasks folders, and
* search folders.
*
* @since Exchange 2007
*
* @param EWSType_CreateFolderType $request
* @return EWSType_CreateFolderResponseType
*/
public function CreateFolder($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Creates items in the Exchange store.
*
* @since Exchange 2007
*
* @param EWSType_CreateItemType $request
* @return EWSType_CreateItemResponseType
*/
public function CreateItem($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Creates a user configuration object on a folder.
*
* @since Exchange 2010
*
* @param EWSType_CreateUserConfigurationType $request
* @return EWSType_CreateUserConfigurationResponseType
*/
public function CreateUserConfiguration($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Creates a managed folder in the Exchange store.
*
* @since Exchange 2007
*
* @param EWSType_CreateManagedFolderRequestType $request
* @return EWSType_CreateManagedFolderResponseType
*/
public function CreateManagedFolder($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Deletes file and item attachments from an existing item in the Exchange
* store.
*
* @since Exchange 2007
*
* @param EWSType_DeleteAttachmentType $request
* @return EWSType_DeleteAttachmentResponseType
*/
public function DeleteAttachment($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Deletes folders from a mailbox.
*
* @since Exchange 2007
*
* @param EWSType_DeleteFolderType $request
* @return EWSType_DeleteFolderResponseType
*/
public function DeleteFolder($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Deletes items in the Exchange store.
*
* @since Exchange 2007
*
* @param EWSType_DeleteItemType $request
* @return EWSType_DeleteItemResponseType
*/
public function DeleteItem($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Deletes a user configuration object on a folder.
*
* @since Exchange 2010
*
* @param EWSType_DeleteUserConfigurationType $request
* @return EWSType_DeleteUserConfigurationResponseType
*/
public function DeleteUserConfiguration($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Terminates the telephone call.
*
* @since Exchange 2010
*
* @param EWSType_DisconnectPhoneCallType $request
* @return EWSType_DisconnectPhoneCallResponseMessageType
*/
public function DisconnectPhoneCall($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Empties folders in a mailbox.
*
* Optionally, this operation enables you to delete the subfolders of the
* specified folder. When a subfolder is deleted, the subfolder and the
* messages within the subfolder are deleted.
*
* @since Exchange 2010
*
* @param EWSType_EmptyFolderType $request
* @return EWSType_EmptyFolderResponseType
*/
public function EmptyFolder($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Exposes the full membership of distribution lists.
*
* @since Exchange 2007
*
* @param EWSType_ExpandDLType $request
* @return EWSType_ExpandDLResponseType
*/
public function ExpandDL($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Exports items out of a mailbox.
*
* @since Exchange 2010 SP1
*
* @param EWSType_ExportItemsType $request
* @return EWSType_ExportItemsResponseType
*/
public function ExportItems($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Enumerates a list of conversations in a folder.
*
* @since Exchange 2010 SP1
*
* @param EWSType_FindConversationType $request
* @return EWSType_FindConversationResponseMessageType
*/
public function FindConversation($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Uses Exchange Web Services to find subfolders of an identified folder and
* returns a set of properties that describe the set of subfolders.
*
* @since Exchange 2007
*
* @param EWSType_FindFolderType $request
* @return EWSType_FindFolderResponseType
*/
public function FindFolder($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Identifies items that are located in a specified folder.
*
* @since Exchange 2007
*
* @param EWSType_FindItemType $request
* @return EWSType_FindItemResponseType
*/
public function FindItem($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Finds messages that meet the specified criteria.
*
* @since Exchange 2010
*
* @param EWSType_FindMessageTrackingReportRequestType $request
* @return EWSType_FindMessageTrackingReportResponseMessageType
*/
public function FindMessageTrackingReport($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Retrieves existing attachments on items in the Exchange store.
*
* @since Exchange 2007
*
* @param EWSType_GetAttachmentType $request
* @return EWSType_GetAttachmentResponseType
*/
public function GetAttachment($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Retrieves the delegate settings for a specified mailbox.
*
* @since Exchange 2007 SP1
*
* @param EWSType_GetDelegateType $request
* @return EWSType_GetDelegateResponseMessageType
*/
public function GetDelegate($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Pulls subscription clients to request notifications from the Client
* Access server.
*
* @since Exchange 2007
*
* @param EWSType_GetEventsType $request
* @return EWSType_GetEventsResponseType
*/
public function GetEvents($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Gets folders from the Exchange store.
*
* @since Exchange 2007
*
* @param EWSType_GetFolderType $request
* @return EWSType_GetFolderResponseType
*/
public function GetFolder($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Retrieve Inbox rules in the identified user's mailbox.
*
* @since Exchange 2010 SP1
*
* @param EWSType_GetInboxRulesRequestType $request
* @return EWSType_GetInboxRulesResponseType
*/
public function GetInboxRules($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Gets items from the Exchange store.
*
* @since Exchange 2007
*
* @param EWSType_GetItemType $request
* @return EWSType_GetItemResponseType
*/
public function GetItem($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Gets the mail tips information for the specified mailbox.
*
* @since Exchange 2010
*
* @param EWSType_GetMailTipsType $request
* @return EWSType_GetMailTipsResponseMessageType
*/
public function GetMailTips($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Gets tracking information about the specified messages.
*
* @since Exchange 2010
*
* @param EWSType_GetMessageTrackingReportRequestType $request
* @return EWSType_GetMessageTrackingReportResponseMessageType
*/
public function GetMessageTrackingReport($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Retrieve the timezones supported by the server.
*
* @since Exchange 2010 SP1
*
* @param EWSType_GetPasswordExpirationDateType $request
* @return EWSType_GetPasswordExpirationDateResponseMessageType
*/
public function GetPasswordExpirationDate($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Returns information about the specified telephone call.
*
* @since Exchange 2010
*
* @param EWSType_GetPhoneCallInformationType $request
* @return EWSType_GetPhoneCallInformationResponseMessageType
*/
public function GetPhoneCallInformation($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Gets the room lists that are available within the Exchange organization.
*
* @since Exchange 2010 SP1
*
* @param EWSType_GetRoomListsType $request
* @return EWSType_GetRoomListsResponseMessageType
*/
public function GetRoomLists($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Gets the rooms within the specified room list.
*
* @since Exchange 2010 SP1
*
* @param EWSType_GetRoomsType $request
* @return EWSType_GetRoomsResponseMessageType
*/
public function GetRooms($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Returns information from time zone definitions that are available on an
* Exchange server.
*
* @since Exchange 2010
*
* @param EWSType_GetServerTimeZonesType $request
* @return EWSType_GetServerTimeZonesResponseType
*/
public function GetServerTimeZones($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Gets configuration information for the specified type of service.
*
* @since Exchange 2010
*
* @param EWSType_GetServiceConfigurationType $request
* @return EWSType_GetServiceConfigurationResponseMessageType
*/
public function GetServiceConfiguration($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Gets the local folder identifier of a specified shared folder.
*
* @since Exchange 2010
*
* @param EWSType_GetSharingFolderType $request
* @return EWSType_GetSharingFolderResponseMessageType
*/
public function GetSharingFolder($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Gets an opaque authentication token that identifies a sharing invitation.
*
* @since Exchange 2010
*
* @param EWSType_GetSharingMetadataType $request
* @return EWSType_GetSharingMetadataResponseMessageType
*/
public function GetSharingMetadata($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Request subscription notifications from the Client Access server.
*
* @since Exchange 2010 SP1
*
* @param EWSType_GetStreamingEventsType $request
* @return EWSType_GetStreamingEventsResponseType
*/
public function GetStreamingEvents($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Provides detailed information about the availability of a set of users,
* rooms, and resources within a specified time period.
*
* @since Exchange 2007
*
* @param EWSType_GetUserAvailabilityRequestType $request
* @return EWSType_GetUserAvailabilityResponseType
*/
public function GetUserAvailability($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Gets a user configuration object from a folder.
*
* @since Exchange 2010
*
* @param EWSType_GetUserConfigurationType $request
* @return EWSType_GetUserConfigurationResponseType
*/
public function GetUserConfiguration($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Gets a mailbox user's Out of Office (OOF) settings and messages.
*
* @since Exchange 2007
*
* @param EWSType_GetUserOofSettingsRequest $request
* @return EWSType_GetUserOofSettingsResponse
*/
public function GetUserOofSettings($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Moves folders from a specified folder and puts them in another folder.
*
* @since Exchange 2007
*
* @param EWSType_MoveFolderType $request
* @return EWSType_MoveFolderResponseType
*/
public function MoveFolder($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Moves one or more items to a single destination folder.
*
* @since Exchange 2007
*
* @param EWSType_MoveItemType $request
* @return EWSType_MoveItemResponseType
*/
public function MoveItem($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Initiates an outbound call and plays a message over the telephone.
*
* @since Exchange 2010
*
* @param EWSType_PlayOnPhoneType $request
* @return EWSType_PlayOnPhoneResponseMessageType
*/
public function PlayOnPhone($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Refreshes the specified local folder with the latest data from the folder
* that is being shared.
*
* @since Exchange 2010
*
* @param EWSType_RefreshSharingFolderType $request
* @return EWSType_RefreshSharingFolderResponseMessageType
*/
public function RefreshSharingFolder($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Removes one or more delegates from a user's mailbox.
*
* @since Exchange 2007 SP1
*
* @param EWSType_RemoveDelegateType $request
* @return EWSType_RemoveDelegateResponseMessageType
*/
public function RemoveDelegate($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Resolves ambiguous email addresses and display names.
*
* @since Exchange 2007
*
* @param EWSType_ResolveNamesType $request
* @return EWSType_ResolveNamesResponseType
*/
public function ResolveNames($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Sends e-mail messages that are located in the Exchange store.
*
* @since Exchange 2007
*
* @param EWSType_SendItemType $request
* @return EWSType_SendItemResponseType
*/
public function SendItem($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Sets a mailbox user's Out of Office (OOF) settings and message.
*
* @since Exchange 2007
*
* @param EWSType_SetUserOofSettingsRequest $request
* @return EWSType_SetUserOofSettingsResponse
*/
public function SetUserOofSettings($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Subscribes to either push or pull notifications.
*
* @since Exchange 2007
*
* @param EWSType_SubscribeType $request
* @return EWSType_SubscribeResponseType
*/
public function Subscribe($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Synchronizes folders between the computer that is running Microsoft
* Exchange Server and the client.
*
* @since Exchange 2007
*
* @param EWSType_SyncFolderHierarchyType $request
* @return EWSType_SyncFolderHierarchyResponseType
*/
public function SyncFolderHierarchy($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Synchronizes items between the Exchange server and the client.
*
* @since Exchange 2007
*
* @param EWSType_SyncFolderItemsType $request
* @return EWSType_SyncFolderItemsResponseType
*/
public function SyncFolderItems($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Ends a pull notification subscription.
*
* Use this operation rather than letting a subscription timeout.
*
* This operation is only valid for pull notifications.
*
* @since Exchange 2007
*
* @param EWSType_UnsubscribeType $request
* @return EWSType_UnsubscribeResponseType
*/
public function Unsubscribe($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Updates delegate permissions on a principal's mailbox.
*
* @since Exchange 2007 SP1
*
* @param EWSType_UpdateDelegateType $request
* @return EWSType_UpdateDelegateResponseMessageType
*/
public function UpdateDelegate($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Modifies properties of an existing item in the Exchange store.
*
* @since Exchange 2007
*
* @param EWSType_UpdateFolderType $request
* @return EWSType_UpdateFolderResponseType
*/
public function UpdateFolder($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Updates the authenticated user's Inbox rules by applying the specified
* operations.
*
* @since Exchange 2010 SP1
*
* @param EWSType_UpdateInboxRulesRequestType $request
* @return EWSType_UpdateInboxRulesResponseType
*/
public function UpdateInboxRules($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Modifies the properties of an existing item in the Exchange store.
*
* @since Exchange 2007
*
* @param EWSType_UpdateItemType $request
* @return EWSType_UpdateItemResponseType
*/
public function UpdateItem($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Updates a user configuration object on a folder.
*
* @since Exchange 2010
*
* @param EWSType_UpdateUserConfigurationType $request
* @return EWSType_UpdateUserConfigurationResponseType
*/
public function UpdateUserConfiguration($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Uploads a stream of items into an Exchange mailbox.
*
* @since Exchange 2010 SP1
*
* @param EWSType_UploadItemsType $request
* @return EWSType_UploadItemsResponseType
*/
public function UploadItems($request)
{
$this->initializeSoapClient();
$response = $this->soap->{__FUNCTION__}($request);
return $this->processResponse($response);
}
/**
* Initializes the SoapClient object to make a request
*
* @return NTLMSoapClient_Exchange
*/
protected function initializeSoapClient()
{
$this->soap = new NTLMSoapClient_Exchange(
dirname(__FILE__).'/wsdl/services.wsdl',
array(
'user' => $this->username,
'password' => $this->password,
'version' => $this->version,
'location' => 'https://'.$this->server.'/EWS/Exchange.asmx',
'impersonation' => $this->impersonation,
)
);
return $this->soap;
}
/**
* Process a response to verify that it succeeded and take the appropriate
* action
*
* @throws EWS_Exception
*
* @param stdClass $response
* @return EWSType
*
* @todo Map the response to a real object.
*/
protected function processResponse($response)
{
// If the soap call failed then we need to thow an exception.
$code = $this->soap->getResponseCode();
if ($code != 200) {
throw new EWS_Exception('SOAP client returned status of '.$code, $code);
}
return $response;
}
}
|
andrewwippler/rpi-wayfinding
|
php-ews/ExchangeWebServices.php
|
PHP
|
gpl-2.0
| 32,065
|
/* Definitions of target machine for GNU compiler. PowerPC VxworksAE version.
Copyright (C) 2005-2021 Free Software Foundation, Inc.
Contributed by CodeSourcery, LLC.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.
GCC is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
/* This platform supports the probing method of stack checking and
requires 4K of space for executing a possible last chance handler. */
#undef STACK_CHECK_PROTECT
#define STACK_CHECK_PROTECT 4096
|
Gurgel100/gcc
|
gcc/config/rs6000/vxworksae.h
|
C
|
gpl-2.0
| 1,000
|
/* Copyright (C) 2000-2017 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This comes from the Linux kernel header. */
#define OPEN_MAX 256
#include <sysdeps/posix/getdtsz.c>
|
NicoleRobin/glibc
|
sysdeps/unix/sysv/linux/getdtsz.c
|
C
|
gpl-2.0
| 895
|
module.exports = function (grunt) {
// Load in legacy config
require('./grunt')(grunt);
// Configure nodeunit as test
var testConfig = grunt.config.get('test');
grunt.config.set('nodeunit', testConfig);
// Load in nodeunit
process.chdir('..');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
process.chdir(__dirname);
// Override default task
grunt.registerTask('default', ['sprite', 'nodeunit']);
};
|
ibevamp/ourbrand
|
sites/all/themes/ourbrand/grunt/node_modules/grunt-spritesmith/src-test/Gruntfile.js
|
JavaScript
|
gpl-2.0
| 423
|
<?php
namespace Drupal\Tests\conditional_fields\FunctionalJavascript;
use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Tests\conditional_fields\FunctionalJavascript\TestCases\ConditionalFieldCheckedUncheckedInterface;
use Drupal\Tests\conditional_fields\FunctionalJavascript\TestCases\ConditionalFieldValueInterface;
/**
* Test Conditional Fields States.
*
* @group conditional_fields
*/
class ConditionalFieldRadiosTest extends ConditionalFieldTestBase implements
ConditionalFieldValueInterface,
ConditionalFieldCheckedUncheckedInterface {
use EntityReferenceTestTrait;
/**
* {@inheritdoc}
*/
protected $screenshotPath = 'sites/simpletest/conditional_fields/radios/';
/**
* The name and vid of vocabulary, created for testing.
*
* @var string
*/
protected $taxonomyName;
/**
* The amount of generated terms in created vocabulary.
*
* @var int
*/
protected $termsCount;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Create a vocabulary with random name.
$this->taxonomyName = $this->getRandomGenerator()->word(8);
$vocabulary = Vocabulary::create([
'name' => $this->taxonomyName,
'vid' => $this->taxonomyName,
]);
$vocabulary->save();
// Create a random taxonomy terms for vocabulary.
$this->termsCount = mt_rand(3, 5);
for ($i = 1; $i <= $this->termsCount; $i++) {
$termName = $this->getRandomGenerator()->word(8);
Term::create([
'parent' => [],
'name' => $termName,
'vid' => $this->taxonomyName,
])->save();
}
// Add a custom field with taxonomy terms to 'Article'.
// The field label is a machine name of created vocabulary.
$handler_settings = [
'target_bundles' => [
$vocabulary->id() => $vocabulary->id(),
],
];
$this->createEntityReferenceField('node', 'article', 'field_' . $this->taxonomyName, $this->taxonomyName, 'taxonomy_term', 'default', $handler_settings);
EntityFormDisplay::load('node.article.default')
->setComponent('field_' . $this->taxonomyName, ['type' => 'options_buttons'])
->save();
}
/**
* {@inheritdoc}
*/
public function testVisibleValueWidget() {
// TODO: Implement testVisibleValueWidget() method.
$this->markTestIncomplete();
}
/**
* {@inheritdoc}
*/
public function testVisibleValueRegExp() {
// TODO: Implement testVisibleValueRegExp() method.
$this->markTestIncomplete();
}
/**
* {@inheritdoc}
*/
public function testVisibleValueAnd() {
$this->baseTestSteps();
// Visit a ConditionalFields configuration page for `Article` Content type.
$this->createCondition('body', 'field_' . $this->taxonomyName, 'visible', 'value');
// Change a condition's values set and the value.
$this->changeField('#edit-values-set', CONDITIONAL_FIELDS_DEPENDENCY_VALUES_AND);
// Random term id to check necessary value.
$term_id = mt_rand(1, $this->termsCount);
$this->changeField('#edit-values', $term_id);
// Submit the form.
$this->getSession()
->executeScript("jQuery('#conditional-field-edit-form').submit();");
$this->assertSession()->statusCodeEquals(200);
// Check if that configuration is saved.
$this->drupalGet('admin/structure/conditional_fields/node/article');
$this->assertSession()
->pageTextContains('body field_' . $this->taxonomyName . ' visible value');
// Visit Article Add form to check that conditions are applied.
$this->drupalGet('node/add/article');
$this->assertSession()->statusCodeEquals(200);
// Check that the field Body is not visible.
$this->waitUntilHidden('.field--name-body', 0, 'Article Body field is visible');
// Change a select value set to show the body.
$this->changeSelect('#edit-field-' . $this->taxonomyName . '-' . $term_id, $term_id);
$this->waitUntilVisible('.field--name-body', 50, 'Article Body field is not visible');
// $this->createScreenshot('sites/simpletest/scr1BodyVisTerm.jpg');
// Change a select value set to hide the body again.
$this->changeSelect('#edit-field-' . $this->taxonomyName . '-' . $term_id);
$this->waitUntilHidden('.field--name-body', 50, 'Article Body field is visible');
// $this->createScreenshot('sites/simpletest/scr2BodyHid.jpg');
}
/**
* {@inheritdoc}
*/
public function testVisibleValueOr() {
$this->baseTestSteps();
// Visit a ConditionalFields configuration page for `Article` Content type.
$this->createCondition('body', 'field_' . $this->taxonomyName, 'visible', 'value');
// Change a condition's values set and the value.
$this->changeField('#edit-values-set', CONDITIONAL_FIELDS_DEPENDENCY_VALUES_OR);
// Random term id to check necessary value.
$term_id_1 = mt_rand(1, $this->termsCount);
do {
$term_id_2 = mt_rand(1, $this->termsCount);
} while ($term_id_2 == $term_id_1);
$values = $term_id_1 . '\r\n' . $term_id_2;
$this->changeField('#edit-values', $values);
// Submit the form.
$this->getSession()
->executeScript("jQuery('#conditional-field-edit-form').submit();");
$this->assertSession()->statusCodeEquals(200);
// Check if that configuration is saved.
$this->drupalGet('admin/structure/conditional_fields/node/article');
$this->assertSession()
->pageTextContains('body field_' . $this->taxonomyName . ' visible value');
// Visit Article Add form to check that conditions are applied.
$this->drupalGet('node/add/article');
$this->assertSession()->statusCodeEquals(200);
// Check that the field Body is not visible.
$this->waitUntilHidden('.field--name-body', 0, 'Article Body field is visible');
// Change a select value set to show the body.
$this->changeSelect('#edit-field-' . $this->taxonomyName . '-' . $term_id_1, $term_id_1);
$this->waitUntilVisible('.field--name-body', 50, 'Article Body field is not visible');
// Change a select value set to hide the body again.
$this->changeSelect('#edit-field-' . $this->taxonomyName . '-' . $term_id_1);
$this->waitUntilHidden('.field--name-body', 50, 'Article Body field is visible');
$this->changeSelect('#edit-field-' . $this->taxonomyName . '-' . $term_id_2, $term_id_2);
$this->waitUntilVisible('.field--name-body', 50, 'Article Body field is not visible');
// Change a select value set to hide the body again.
$this->changeSelect('#edit-field-' . $this->taxonomyName . '-' . $term_id_2);
$this->waitUntilHidden('.field--name-body', 50, 'Article Body field is visible');
}
/**
* {@inheritdoc}
*/
public function testVisibleValueNot() {
// TODO: Implement testVisibleValueNot() method.
$this->markTestIncomplete();
}
/**
* {@inheritdoc}
*/
public function testVisibleValueXor() {
// TODO: Implement testVisibleValueXor() method.
$this->markTestIncomplete();
}
/**
* {@inheritdoc}
*/
public function testVisibleChecked() {
$this->baseTestSteps();
// Visit a ConditionalFields configuration page for `Article` Content type.
$this->createCondition('body', 'field_' . $this->taxonomyName, 'visible', 'checked');
// Check if that configuration is saved.
$this->drupalGet('admin/structure/conditional_fields/node/article');
$this->assertSession()
->pageTextContains('body field_' . $this->taxonomyName . ' visible checked');
// Visit Article Add form to check that conditions are applied.
$this->drupalGet('node/add/article');
$this->assertSession()->statusCodeEquals(200);
// Check that the field Body is not visible.
$this->waitUntilHidden('.field--name-body', 0, 'Article Body field is visible');
for ($term_id = 1; $term_id < $this->termsCount; $term_id++) {
// Change a select value set to show the body.
$this->changeSelect('#edit-field-' . $this->taxonomyName . '-' . $term_id, $term_id);
$this->waitUntilVisible('.field--name-body', 50, 'Article Body field is not visible');
// $this->createScreenshot('sites/simpletest/scr1BodyVisTerm'.$term_id.'.jpg');
}
}
/**
* {@inheritdoc}
*/
public function testVisibleUnchecked() {
$this->baseTestSteps();
// Visit a ConditionalFields configuration page for `Article` Content type.
$this->createCondition('body', 'field_' . $this->taxonomyName, 'visible', '!checked');
// Check if that configuration is saved.
$this->drupalGet('admin/structure/conditional_fields/node/article');
$this->assertSession()
->pageTextContains('body field_' . $this->taxonomyName . ' visible !checked');
// Visit Article Add form to check that conditions are applied.
$this->drupalGet('node/add/article');
$this->assertSession()->statusCodeEquals(200);
// Check that the field Body is visible.
$this->waitUntilVisible('.field--name-body', 50, 'Article Body field is not visible');
for ($term_id = 1; $term_id < $this->termsCount; $term_id++) {
// Change a select value set to hide the body.
$this->changeSelect('#edit-field-' . $this->taxonomyName . '-' . $term_id, $term_id);
$this->waitUntilHidden('.field--name-body', 50, 'Article Body field is visible');
}
}
/**
* {@inheritdoc}
*/
public function testInvisibleUnchecked() {
// TODO: Implement testInvisibleUnchecked() method.
$this->markTestIncomplete();
}
}
|
AfrikaBurn/Main
|
web/modules/contrib/conditional_fields/tests/src/FunctionalJavascript/ConditionalFieldRadiosTest.php
|
PHP
|
gpl-2.0
| 9,587
|
/*
* The input core
*
* Copyright (c) 1999-2002 Vojtech Pavlik
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*/
#define pr_fmt(fmt) KBUILD_BASENAME ": " fmt
#include <linux/init.h>
#include <linux/types.h>
#include <linux/input/mt.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/random.h>
#include <linux/major.h>
#include <linux/proc_fs.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <linux/poll.h>
#include <linux/device.h>
#include <linux/mutex.h>
#include <linux/rcupdate.h>
#include "input-compat.h"
MODULE_AUTHOR("Vojtech Pavlik <vojtech@suse.cz>");
MODULE_DESCRIPTION("Input core");
MODULE_LICENSE("GPL");
#define INPUT_DEVICES 256
static LIST_HEAD(input_dev_list);
static LIST_HEAD(input_handler_list);
/*
* input_mutex protects access to both input_dev_list and input_handler_list.
* This also causes input_[un]register_device and input_[un]register_handler
* be mutually exclusive which simplifies locking in drivers implementing
* input handlers.
*/
static DEFINE_MUTEX(input_mutex);
static struct input_handler *input_table[8];
static const struct input_value input_value_sync = { EV_SYN, SYN_REPORT, 1 };
static inline int is_event_supported(unsigned int code,
unsigned long *bm, unsigned int max)
{
return code <= max && test_bit(code, bm);
}
static int input_defuzz_abs_event(int value, int old_val, int fuzz)
{
if (fuzz) {
if (value > old_val - fuzz / 2 && value < old_val + fuzz / 2)
return old_val;
if (value > old_val - fuzz && value < old_val + fuzz)
return (old_val * 3 + value) / 4;
if (value > old_val - fuzz * 2 && value < old_val + fuzz * 2)
return (old_val + value) / 2;
}
return value;
}
static void input_start_autorepeat(struct input_dev *dev, int code)
{
if (test_bit(EV_REP, dev->evbit) &&
dev->rep[REP_PERIOD] && dev->rep[REP_DELAY] &&
dev->timer.data) {
dev->repeat_key = code;
mod_timer(&dev->timer,
jiffies + msecs_to_jiffies(dev->rep[REP_DELAY]));
}
}
static void input_stop_autorepeat(struct input_dev *dev)
{
del_timer(&dev->timer);
}
/*
* Pass event first through all filters and then, if event has not been
* filtered out, through all open handles. This function is called with
* dev->event_lock held and interrupts disabled.
*/
static unsigned int input_to_handler(struct input_handle *handle,
struct input_value *vals, unsigned int count)
{
struct input_handler *handler = handle->handler;
struct input_value *end = vals;
struct input_value *v;
for (v = vals; v != vals + count; v++) {
if (handler->filter &&
handler->filter(handle, v->type, v->code, v->value))
continue;
if (end != v)
*end = *v;
end++;
}
count = end - vals;
if (!count)
return 0;
if (handler->events)
handler->events(handle, vals, count);
else if (handler->event)
for (v = vals; v != end; v++)
handler->event(handle, v->type, v->code, v->value);
return count;
}
/*
* Pass values first through all filters and then, if event has not been
* filtered out, through all open handles. This function is called with
* dev->event_lock held and interrupts disabled.
*/
static void input_pass_values(struct input_dev *dev,
struct input_value *vals, unsigned int count)
{
struct input_handle *handle;
struct input_value *v;
if (!count)
return;
rcu_read_lock();
handle = rcu_dereference(dev->grab);
if (handle) {
count = input_to_handler(handle, vals, count);
} else {
list_for_each_entry_rcu(handle, &dev->h_list, d_node)
if (handle->open)
count = input_to_handler(handle, vals, count);
}
rcu_read_unlock();
add_input_randomness(vals->type, vals->code, vals->value);
/* trigger auto repeat for key events */
for (v = vals; v != vals + count; v++) {
if (v->type == EV_KEY && v->value != 2) {
if (v->value)
input_start_autorepeat(dev, v->code);
else
input_stop_autorepeat(dev);
}
}
}
static void input_pass_event(struct input_dev *dev,
unsigned int type, unsigned int code, int value)
{
struct input_value vals[] = { { type, code, value } };
input_pass_values(dev, vals, ARRAY_SIZE(vals));
}
/*
* Generate software autorepeat event. Note that we take
* dev->event_lock here to avoid racing with input_event
* which may cause keys get "stuck".
*/
static void input_repeat_key(unsigned long data)
{
struct input_dev *dev = (void *) data;
unsigned long flags;
spin_lock_irqsave(&dev->event_lock, flags);
if (test_bit(dev->repeat_key, dev->key) &&
is_event_supported(dev->repeat_key, dev->keybit, KEY_MAX)) {
struct input_value vals[] = {
{ EV_KEY, dev->repeat_key, 2 },
input_value_sync
};
input_pass_values(dev, vals, ARRAY_SIZE(vals));
if (dev->rep[REP_PERIOD])
mod_timer(&dev->timer, jiffies +
msecs_to_jiffies(dev->rep[REP_PERIOD]));
}
spin_unlock_irqrestore(&dev->event_lock, flags);
}
#define INPUT_IGNORE_EVENT 0
#define INPUT_PASS_TO_HANDLERS 1
#define INPUT_PASS_TO_DEVICE 2
#define INPUT_SLOT 4
#define INPUT_FLUSH 8
#define INPUT_PASS_TO_ALL (INPUT_PASS_TO_HANDLERS | INPUT_PASS_TO_DEVICE)
static int input_handle_abs_event(struct input_dev *dev,
unsigned int code, int *pval)
{
bool is_mt_event;
int *pold;
if (code == ABS_MT_SLOT) {
/*
* "Stage" the event; we'll flush it later, when we
* get actual touch data.
*/
if (*pval >= 0 && *pval < dev->mtsize)
dev->slot = *pval;
return INPUT_IGNORE_EVENT;
}
is_mt_event = input_is_mt_value(code);
if (!is_mt_event) {
pold = &dev->absinfo[code].value;
} else if (dev->mt) {
struct input_mt_slot *mtslot = &dev->mt[dev->slot];
pold = &mtslot->abs[code - ABS_MT_FIRST];
} else {
/*
* Bypass filtering for multi-touch events when
* not employing slots.
*/
pold = NULL;
}
if (pold) {
*pval = input_defuzz_abs_event(*pval, *pold,
dev->absinfo[code].fuzz);
if (*pold == *pval)
return INPUT_IGNORE_EVENT;
*pold = *pval;
}
/* Flush pending "slot" event */
if (is_mt_event && dev->slot != input_abs_get_val(dev, ABS_MT_SLOT)) {
input_abs_set_val(dev, ABS_MT_SLOT, dev->slot);
return INPUT_PASS_TO_HANDLERS | INPUT_SLOT;
}
return INPUT_PASS_TO_HANDLERS;
}
static int input_get_disposition(struct input_dev *dev,
unsigned int type, unsigned int code, int value)
{
int disposition = INPUT_IGNORE_EVENT;
switch (type) {
case EV_SYN:
switch (code) {
case SYN_CONFIG:
case SYN_TIME_SEC:
case SYN_TIME_NSEC:
disposition = INPUT_PASS_TO_ALL;
break;
case SYN_REPORT:
disposition = INPUT_PASS_TO_HANDLERS | INPUT_FLUSH;
break;
case SYN_MT_REPORT:
disposition = INPUT_PASS_TO_HANDLERS;
break;
}
break;
case EV_KEY:
if (is_event_supported(code, dev->keybit, KEY_MAX) &&
!!test_bit(code, dev->key) != value) {
if (value != 2) {
__change_bit(code, dev->key);
if (value)
input_start_autorepeat(dev, code);
else
input_stop_autorepeat(dev);
}
disposition = INPUT_PASS_TO_HANDLERS;
}
break;
case EV_SW:
if (is_event_supported(code, dev->swbit, SW_MAX) &&
!!test_bit(code, dev->sw) != value) {
__change_bit(code, dev->sw);
disposition = INPUT_PASS_TO_HANDLERS;
}
break;
case EV_ABS:
if (is_event_supported(code, dev->absbit, ABS_MAX))
disposition = input_handle_abs_event(dev, code, &value);
break;
case EV_REL:
if (is_event_supported(code, dev->relbit, REL_MAX) && value)
disposition = INPUT_PASS_TO_HANDLERS;
break;
case EV_MSC:
if (is_event_supported(code, dev->mscbit, MSC_MAX))
disposition = INPUT_PASS_TO_ALL;
break;
case EV_LED:
if (is_event_supported(code, dev->ledbit, LED_MAX) &&
!!test_bit(code, dev->led) != value) {
__change_bit(code, dev->led);
disposition = INPUT_PASS_TO_ALL;
}
break;
case EV_SND:
if (is_event_supported(code, dev->sndbit, SND_MAX)) {
if (!!test_bit(code, dev->snd) != !!value)
__change_bit(code, dev->snd);
disposition = INPUT_PASS_TO_ALL;
}
break;
case EV_REP:
if (code <= REP_MAX && value >= 0 && dev->rep[code] != value) {
dev->rep[code] = value;
disposition = INPUT_PASS_TO_ALL;
}
break;
case EV_FF:
if (value >= 0)
disposition = INPUT_PASS_TO_ALL;
break;
case EV_PWR:
disposition = INPUT_PASS_TO_ALL;
break;
}
return disposition;
}
static void input_handle_event(struct input_dev *dev,
unsigned int type, unsigned int code, int value)
{
int disposition;
disposition = input_get_disposition(dev, type, code, value);
if ((disposition & INPUT_PASS_TO_DEVICE) && dev->event)
dev->event(dev, type, code, value);
if (!dev->vals)
return;
if (disposition & INPUT_PASS_TO_HANDLERS) {
struct input_value *v;
if (disposition & INPUT_SLOT) {
v = &dev->vals[dev->num_vals++];
v->type = EV_ABS;
v->code = ABS_MT_SLOT;
v->value = dev->slot;
}
v = &dev->vals[dev->num_vals++];
v->type = type;
v->code = code;
v->value = value;
}
if (disposition & INPUT_FLUSH) {
if (dev->num_vals >= 2)
input_pass_values(dev, dev->vals, dev->num_vals);
dev->num_vals = 0;
} else if (dev->num_vals >= dev->max_vals - 2) {
dev->vals[dev->num_vals++] = input_value_sync;
input_pass_values(dev, dev->vals, dev->num_vals);
dev->num_vals = 0;
}
}
/**
* input_event() - report new input event
* @dev: device that generated the event
* @type: type of the event
* @code: event code
* @value: value of the event
*
* This function should be used by drivers implementing various input
* devices to report input events. See also input_inject_event().
*
* NOTE: input_event() may be safely used right after input device was
* allocated with input_allocate_device(), even before it is registered
* with input_register_device(), but the event will not reach any of the
* input handlers. Such early invocation of input_event() may be used
* to 'seed' initial state of a switch or initial position of absolute
* axis, etc.
*/
void input_event(struct input_dev *dev,
unsigned int type, unsigned int code, int value)
{
unsigned long flags;
if (is_event_supported(type, dev->evbit, EV_MAX)) {
spin_lock_irqsave(&dev->event_lock, flags);
input_handle_event(dev, type, code, value);
spin_unlock_irqrestore(&dev->event_lock, flags);
}
}
EXPORT_SYMBOL(input_event);
/**
* input_inject_event() - send input event from input handler
* @handle: input handle to send event through
* @type: type of the event
* @code: event code
* @value: value of the event
*
* Similar to input_event() but will ignore event if device is
* "grabbed" and handle injecting event is not the one that owns
* the device.
*/
void input_inject_event(struct input_handle *handle,
unsigned int type, unsigned int code, int value)
{
struct input_dev *dev = handle->dev;
struct input_handle *grab;
unsigned long flags;
if (is_event_supported(type, dev->evbit, EV_MAX)) {
spin_lock_irqsave(&dev->event_lock, flags);
rcu_read_lock();
grab = rcu_dereference(dev->grab);
if (!grab || grab == handle)
input_handle_event(dev, type, code, value);
rcu_read_unlock();
spin_unlock_irqrestore(&dev->event_lock, flags);
}
}
EXPORT_SYMBOL(input_inject_event);
/**
* input_alloc_absinfo - allocates array of input_absinfo structs
* @dev: the input device emitting absolute events
*
* If the absinfo struct the caller asked for is already allocated, this
* functions will not do anything.
*/
void input_alloc_absinfo(struct input_dev *dev)
{
if (!dev->absinfo)
dev->absinfo = kcalloc(ABS_CNT, sizeof(struct input_absinfo),
GFP_KERNEL);
WARN(!dev->absinfo, "%s(): kcalloc() failed?\n", __func__);
}
EXPORT_SYMBOL(input_alloc_absinfo);
void input_set_abs_params(struct input_dev *dev, unsigned int axis,
int min, int max, int fuzz, int flat)
{
struct input_absinfo *absinfo;
input_alloc_absinfo(dev);
if (!dev->absinfo)
return;
absinfo = &dev->absinfo[axis];
absinfo->minimum = min;
absinfo->maximum = max;
absinfo->fuzz = fuzz;
absinfo->flat = flat;
dev->absbit[BIT_WORD(axis)] |= BIT_MASK(axis);
}
EXPORT_SYMBOL(input_set_abs_params);
/**
* input_grab_device - grabs device for exclusive use
* @handle: input handle that wants to own the device
*
* When a device is grabbed by an input handle all events generated by
* the device are delivered only to this handle. Also events injected
* by other input handles are ignored while device is grabbed.
*/
int input_grab_device(struct input_handle *handle)
{
struct input_dev *dev = handle->dev;
int retval;
retval = mutex_lock_interruptible(&dev->mutex);
if (retval)
return retval;
if (dev->grab) {
retval = -EBUSY;
goto out;
}
rcu_assign_pointer(dev->grab, handle);
out:
mutex_unlock(&dev->mutex);
return retval;
}
EXPORT_SYMBOL(input_grab_device);
static void __input_release_device(struct input_handle *handle)
{
struct input_dev *dev = handle->dev;
if (dev->grab == handle) {
rcu_assign_pointer(dev->grab, NULL);
/* Make sure input_pass_event() notices that grab is gone */
synchronize_rcu();
list_for_each_entry(handle, &dev->h_list, d_node)
if (handle->open && handle->handler->start)
handle->handler->start(handle);
}
}
/**
* input_release_device - release previously grabbed device
* @handle: input handle that owns the device
*
* Releases previously grabbed device so that other input handles can
* start receiving input events. Upon release all handlers attached
* to the device have their start() method called so they have a change
* to synchronize device state with the rest of the system.
*/
void input_release_device(struct input_handle *handle)
{
struct input_dev *dev = handle->dev;
mutex_lock(&dev->mutex);
__input_release_device(handle);
mutex_unlock(&dev->mutex);
}
EXPORT_SYMBOL(input_release_device);
/**
* input_open_device - open input device
* @handle: handle through which device is being accessed
*
* This function should be called by input handlers when they
* want to start receive events from given input device.
*/
int input_open_device(struct input_handle *handle)
{
struct input_dev *dev = handle->dev;
int retval;
retval = mutex_lock_interruptible(&dev->mutex);
if (retval)
return retval;
if (dev->going_away) {
retval = -ENODEV;
goto out;
}
handle->open++;
dev->users_private++;
if (!dev->disabled && !dev->users++ && dev->open)
retval = dev->open(dev);
if (retval) {
dev->users_private--;
if (!dev->disabled)
dev->users--;
if (!--handle->open) {
/*
* Make sure we are not delivering any more events
* through this handle
*/
synchronize_rcu();
}
}
out:
mutex_unlock(&dev->mutex);
return retval;
}
EXPORT_SYMBOL(input_open_device);
int input_flush_device(struct input_handle *handle, struct file *file)
{
struct input_dev *dev = handle->dev;
int retval;
retval = mutex_lock_interruptible(&dev->mutex);
if (retval)
return retval;
if (dev->flush)
retval = dev->flush(dev, file);
mutex_unlock(&dev->mutex);
return retval;
}
EXPORT_SYMBOL(input_flush_device);
/**
* input_close_device - close input device
* @handle: handle through which device is being accessed
*
* This function should be called by input handlers when they
* want to stop receive events from given input device.
*/
void input_close_device(struct input_handle *handle)
{
struct input_dev *dev = handle->dev;
mutex_lock(&dev->mutex);
__input_release_device(handle);
--dev->users_private;
if (!dev->disabled && !--dev->users && dev->close)
dev->close(dev);
if (!--handle->open) {
/*
* synchronize_rcu() makes sure that input_pass_event()
* completed and that no more input events are delivered
* through this handle
*/
synchronize_rcu();
}
mutex_unlock(&dev->mutex);
}
EXPORT_SYMBOL(input_close_device);
static int input_enable_device(struct input_dev *dev)
{
int retval;
retval = mutex_lock_interruptible(&dev->mutex);
if (retval)
return retval;
if (!dev->disabled)
goto out;
if (dev->users_private && dev->open) {
retval = dev->open(dev);
if (retval)
goto out;
}
dev->users = dev->users_private;
dev->disabled = false;
out:
mutex_unlock(&dev->mutex);
return retval;
}
static int input_disable_device(struct input_dev *dev)
{
int retval;
retval = mutex_lock_interruptible(&dev->mutex);
if (retval)
return retval;
if (!dev->disabled) {
dev->disabled = true;
if (dev->users && dev->close)
dev->close(dev);
dev->users = 0;
}
mutex_unlock(&dev->mutex);
return 0;
}
/*
* Simulate keyup events for all keys that are marked as pressed.
* The function must be called with dev->event_lock held.
*/
static void input_dev_release_keys(struct input_dev *dev)
{
int code;
if (is_event_supported(EV_KEY, dev->evbit, EV_MAX)) {
for (code = 0; code <= KEY_MAX; code++) {
if (is_event_supported(code, dev->keybit, KEY_MAX) &&
__test_and_clear_bit(code, dev->key)) {
input_pass_event(dev, EV_KEY, code, 0);
}
}
input_pass_event(dev, EV_SYN, SYN_REPORT, 1);
}
}
/*
* Prepare device for unregistering
*/
static void input_disconnect_device(struct input_dev *dev)
{
struct input_handle *handle;
/*
* Mark device as going away. Note that we take dev->mutex here
* not to protect access to dev->going_away but rather to ensure
* that there are no threads in the middle of input_open_device()
*/
mutex_lock(&dev->mutex);
dev->going_away = true;
mutex_unlock(&dev->mutex);
spin_lock_irq(&dev->event_lock);
/*
* Simulate keyup events for all pressed keys so that handlers
* are not left with "stuck" keys. The driver may continue
* generate events even after we done here but they will not
* reach any handlers.
*/
input_dev_release_keys(dev);
list_for_each_entry(handle, &dev->h_list, d_node)
handle->open = 0;
spin_unlock_irq(&dev->event_lock);
}
/**
* input_scancode_to_scalar() - converts scancode in &struct input_keymap_entry
* @ke: keymap entry containing scancode to be converted.
* @scancode: pointer to the location where converted scancode should
* be stored.
*
* This function is used to convert scancode stored in &struct keymap_entry
* into scalar form understood by legacy keymap handling methods. These
* methods expect scancodes to be represented as 'unsigned int'.
*/
int input_scancode_to_scalar(const struct input_keymap_entry *ke,
unsigned int *scancode)
{
switch (ke->len) {
case 1:
*scancode = *((u8 *)ke->scancode);
break;
case 2:
*scancode = *((u16 *)ke->scancode);
break;
case 4:
*scancode = *((u32 *)ke->scancode);
break;
default:
return -EINVAL;
}
return 0;
}
EXPORT_SYMBOL(input_scancode_to_scalar);
/*
* Those routines handle the default case where no [gs]etkeycode() is
* defined. In this case, an array indexed by the scancode is used.
*/
static unsigned int input_fetch_keycode(struct input_dev *dev,
unsigned int index)
{
switch (dev->keycodesize) {
case 1:
return ((u8 *)dev->keycode)[index];
case 2:
return ((u16 *)dev->keycode)[index];
default:
return ((u32 *)dev->keycode)[index];
}
}
static int input_default_getkeycode(struct input_dev *dev,
struct input_keymap_entry *ke)
{
unsigned int index;
int error;
if (!dev->keycodesize)
return -EINVAL;
if (ke->flags & INPUT_KEYMAP_BY_INDEX)
index = ke->index;
else {
error = input_scancode_to_scalar(ke, &index);
if (error)
return error;
}
if (index >= dev->keycodemax)
return -EINVAL;
ke->keycode = input_fetch_keycode(dev, index);
ke->index = index;
ke->len = sizeof(index);
memcpy(ke->scancode, &index, sizeof(index));
return 0;
}
static int input_default_setkeycode(struct input_dev *dev,
const struct input_keymap_entry *ke,
unsigned int *old_keycode)
{
unsigned int index;
int error;
int i;
if (!dev->keycodesize)
return -EINVAL;
if (ke->flags & INPUT_KEYMAP_BY_INDEX) {
index = ke->index;
} else {
error = input_scancode_to_scalar(ke, &index);
if (error)
return error;
}
if (index >= dev->keycodemax)
return -EINVAL;
if (dev->keycodesize < sizeof(ke->keycode) &&
(ke->keycode >> (dev->keycodesize * 8)))
return -EINVAL;
switch (dev->keycodesize) {
case 1: {
u8 *k = (u8 *)dev->keycode;
*old_keycode = k[index];
k[index] = ke->keycode;
break;
}
case 2: {
u16 *k = (u16 *)dev->keycode;
*old_keycode = k[index];
k[index] = ke->keycode;
break;
}
default: {
u32 *k = (u32 *)dev->keycode;
*old_keycode = k[index];
k[index] = ke->keycode;
break;
}
}
__clear_bit(*old_keycode, dev->keybit);
__set_bit(ke->keycode, dev->keybit);
for (i = 0; i < dev->keycodemax; i++) {
if (input_fetch_keycode(dev, i) == *old_keycode) {
__set_bit(*old_keycode, dev->keybit);
break; /* Setting the bit twice is useless, so break */
}
}
return 0;
}
/**
* input_get_keycode - retrieve keycode currently mapped to a given scancode
* @dev: input device which keymap is being queried
* @ke: keymap entry
*
* This function should be called by anyone interested in retrieving current
* keymap. Presently evdev handlers use it.
*/
int input_get_keycode(struct input_dev *dev, struct input_keymap_entry *ke)
{
unsigned long flags;
int retval;
spin_lock_irqsave(&dev->event_lock, flags);
retval = dev->getkeycode(dev, ke);
spin_unlock_irqrestore(&dev->event_lock, flags);
return retval;
}
EXPORT_SYMBOL(input_get_keycode);
/**
* input_set_keycode - attribute a keycode to a given scancode
* @dev: input device which keymap is being updated
* @ke: new keymap entry
*
* This function should be called by anyone needing to update current
* keymap. Presently keyboard and evdev handlers use it.
*/
int input_set_keycode(struct input_dev *dev,
const struct input_keymap_entry *ke)
{
unsigned long flags;
unsigned int old_keycode;
int retval;
if (ke->keycode > KEY_MAX)
return -EINVAL;
spin_lock_irqsave(&dev->event_lock, flags);
retval = dev->setkeycode(dev, ke, &old_keycode);
if (retval)
goto out;
/* Make sure KEY_RESERVED did not get enabled. */
__clear_bit(KEY_RESERVED, dev->keybit);
/*
* Simulate keyup event if keycode is not present
* in the keymap anymore
*/
if (test_bit(EV_KEY, dev->evbit) &&
!is_event_supported(old_keycode, dev->keybit, KEY_MAX) &&
__test_and_clear_bit(old_keycode, dev->key)) {
struct input_value vals[] = {
{ EV_KEY, old_keycode, 0 },
input_value_sync
};
input_pass_values(dev, vals, ARRAY_SIZE(vals));
}
out:
spin_unlock_irqrestore(&dev->event_lock, flags);
return retval;
}
EXPORT_SYMBOL(input_set_keycode);
#define MATCH_BIT(bit, max) \
for (i = 0; i < BITS_TO_LONGS(max); i++) \
if ((id->bit[i] & dev->bit[i]) != id->bit[i]) \
break; \
if (i != BITS_TO_LONGS(max)) \
continue;
static const struct input_device_id *input_match_device(struct input_handler *handler,
struct input_dev *dev)
{
const struct input_device_id *id;
int i;
for (id = handler->id_table; id->flags || id->driver_info; id++) {
if (id->flags & INPUT_DEVICE_ID_MATCH_BUS)
if (id->bustype != dev->id.bustype)
continue;
if (id->flags & INPUT_DEVICE_ID_MATCH_VENDOR)
if (id->vendor != dev->id.vendor)
continue;
if (id->flags & INPUT_DEVICE_ID_MATCH_PRODUCT)
if (id->product != dev->id.product)
continue;
if (id->flags & INPUT_DEVICE_ID_MATCH_VERSION)
if (id->version != dev->id.version)
continue;
MATCH_BIT(evbit, EV_MAX);
MATCH_BIT(keybit, KEY_MAX);
MATCH_BIT(relbit, REL_MAX);
MATCH_BIT(absbit, ABS_MAX);
MATCH_BIT(mscbit, MSC_MAX);
MATCH_BIT(ledbit, LED_MAX);
MATCH_BIT(sndbit, SND_MAX);
MATCH_BIT(ffbit, FF_MAX);
MATCH_BIT(swbit, SW_MAX);
if (!handler->match || handler->match(handler, dev))
return id;
}
return NULL;
}
static int input_attach_handler(struct input_dev *dev, struct input_handler *handler)
{
const struct input_device_id *id;
int error;
id = input_match_device(handler, dev);
if (!id)
return -ENODEV;
error = handler->connect(handler, dev, id);
if (error && error != -ENODEV)
pr_err("failed to attach handler %s to device %s, error: %d\n",
handler->name, kobject_name(&dev->dev.kobj), error);
return error;
}
#ifdef CONFIG_COMPAT
static int input_bits_to_string(char *buf, int buf_size,
unsigned long bits, bool skip_empty)
{
int len = 0;
if (INPUT_COMPAT_TEST) {
u32 dword = bits >> 32;
if (dword || !skip_empty)
len += snprintf(buf, buf_size, "%x ", dword);
dword = bits & 0xffffffffUL;
if (dword || !skip_empty || len)
len += snprintf(buf + len, max(buf_size - len, 0),
"%x", dword);
} else {
if (bits || !skip_empty)
len += snprintf(buf, buf_size, "%lx", bits);
}
return len;
}
#else /* !CONFIG_COMPAT */
static int input_bits_to_string(char *buf, int buf_size,
unsigned long bits, bool skip_empty)
{
return bits || !skip_empty ?
snprintf(buf, buf_size, "%lx", bits) : 0;
}
#endif
#ifdef CONFIG_PROC_FS
static struct proc_dir_entry *proc_bus_input_dir;
static DECLARE_WAIT_QUEUE_HEAD(input_devices_poll_wait);
static int input_devices_state;
static inline void input_wakeup_procfs_readers(void)
{
input_devices_state++;
wake_up(&input_devices_poll_wait);
}
static unsigned int input_proc_devices_poll(struct file *file, poll_table *wait)
{
poll_wait(file, &input_devices_poll_wait, wait);
if (file->f_version != input_devices_state) {
file->f_version = input_devices_state;
return POLLIN | POLLRDNORM;
}
return 0;
}
union input_seq_state {
struct {
unsigned short pos;
bool mutex_acquired;
};
void *p;
};
static void *input_devices_seq_start(struct seq_file *seq, loff_t *pos)
{
union input_seq_state *state = (union input_seq_state *)&seq->private;
int error;
/* We need to fit into seq->private pointer */
BUILD_BUG_ON(sizeof(union input_seq_state) != sizeof(seq->private));
error = mutex_lock_interruptible(&input_mutex);
if (error) {
state->mutex_acquired = false;
return ERR_PTR(error);
}
state->mutex_acquired = true;
return seq_list_start(&input_dev_list, *pos);
}
static void *input_devices_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
return seq_list_next(v, &input_dev_list, pos);
}
static void input_seq_stop(struct seq_file *seq, void *v)
{
union input_seq_state *state = (union input_seq_state *)&seq->private;
if (state->mutex_acquired)
mutex_unlock(&input_mutex);
}
static void input_seq_print_bitmap(struct seq_file *seq, const char *name,
unsigned long *bitmap, int max)
{
int i;
bool skip_empty = true;
char buf[18];
seq_printf(seq, "B: %s=", name);
for (i = BITS_TO_LONGS(max) - 1; i >= 0; i--) {
if (input_bits_to_string(buf, sizeof(buf),
bitmap[i], skip_empty)) {
skip_empty = false;
seq_printf(seq, "%s%s", buf, i > 0 ? " " : "");
}
}
/*
* If no output was produced print a single 0.
*/
if (skip_empty)
seq_puts(seq, "0");
seq_putc(seq, '\n');
}
static int input_devices_seq_show(struct seq_file *seq, void *v)
{
struct input_dev *dev = container_of(v, struct input_dev, node);
const char *path = kobject_get_path(&dev->dev.kobj, GFP_KERNEL);
struct input_handle *handle;
seq_printf(seq, "I: Bus=%04x Vendor=%04x Product=%04x Version=%04x\n",
dev->id.bustype, dev->id.vendor, dev->id.product, dev->id.version);
seq_printf(seq, "N: Name=\"%s\"\n", dev->name ? dev->name : "");
seq_printf(seq, "P: Phys=%s\n", dev->phys ? dev->phys : "");
seq_printf(seq, "S: Sysfs=%s\n", path ? path : "");
seq_printf(seq, "U: Uniq=%s\n", dev->uniq ? dev->uniq : "");
seq_printf(seq, "H: Handlers=");
list_for_each_entry(handle, &dev->h_list, d_node)
seq_printf(seq, "%s ", handle->name);
seq_putc(seq, '\n');
input_seq_print_bitmap(seq, "PROP", dev->propbit, INPUT_PROP_MAX);
input_seq_print_bitmap(seq, "EV", dev->evbit, EV_MAX);
if (test_bit(EV_KEY, dev->evbit))
input_seq_print_bitmap(seq, "KEY", dev->keybit, KEY_MAX);
if (test_bit(EV_REL, dev->evbit))
input_seq_print_bitmap(seq, "REL", dev->relbit, REL_MAX);
if (test_bit(EV_ABS, dev->evbit))
input_seq_print_bitmap(seq, "ABS", dev->absbit, ABS_MAX);
if (test_bit(EV_MSC, dev->evbit))
input_seq_print_bitmap(seq, "MSC", dev->mscbit, MSC_MAX);
if (test_bit(EV_LED, dev->evbit))
input_seq_print_bitmap(seq, "LED", dev->ledbit, LED_MAX);
if (test_bit(EV_SND, dev->evbit))
input_seq_print_bitmap(seq, "SND", dev->sndbit, SND_MAX);
if (test_bit(EV_FF, dev->evbit))
input_seq_print_bitmap(seq, "FF", dev->ffbit, FF_MAX);
if (test_bit(EV_SW, dev->evbit))
input_seq_print_bitmap(seq, "SW", dev->swbit, SW_MAX);
seq_putc(seq, '\n');
kfree(path);
return 0;
}
static const struct seq_operations input_devices_seq_ops = {
.start = input_devices_seq_start,
.next = input_devices_seq_next,
.stop = input_seq_stop,
.show = input_devices_seq_show,
};
static int input_proc_devices_open(struct inode *inode, struct file *file)
{
return seq_open(file, &input_devices_seq_ops);
}
static const struct file_operations input_devices_fileops = {
.owner = THIS_MODULE,
.open = input_proc_devices_open,
.poll = input_proc_devices_poll,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static void *input_handlers_seq_start(struct seq_file *seq, loff_t *pos)
{
union input_seq_state *state = (union input_seq_state *)&seq->private;
int error;
/* We need to fit into seq->private pointer */
BUILD_BUG_ON(sizeof(union input_seq_state) != sizeof(seq->private));
error = mutex_lock_interruptible(&input_mutex);
if (error) {
state->mutex_acquired = false;
return ERR_PTR(error);
}
state->mutex_acquired = true;
state->pos = *pos;
return seq_list_start(&input_handler_list, *pos);
}
static void *input_handlers_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
union input_seq_state *state = (union input_seq_state *)&seq->private;
state->pos = *pos + 1;
return seq_list_next(v, &input_handler_list, pos);
}
static int input_handlers_seq_show(struct seq_file *seq, void *v)
{
struct input_handler *handler = container_of(v, struct input_handler, node);
union input_seq_state *state = (union input_seq_state *)&seq->private;
seq_printf(seq, "N: Number=%u Name=%s", state->pos, handler->name);
if (handler->filter)
seq_puts(seq, " (filter)");
if (handler->fops)
seq_printf(seq, " Minor=%d", handler->minor);
seq_putc(seq, '\n');
return 0;
}
static const struct seq_operations input_handlers_seq_ops = {
.start = input_handlers_seq_start,
.next = input_handlers_seq_next,
.stop = input_seq_stop,
.show = input_handlers_seq_show,
};
static int input_proc_handlers_open(struct inode *inode, struct file *file)
{
return seq_open(file, &input_handlers_seq_ops);
}
static const struct file_operations input_handlers_fileops = {
.owner = THIS_MODULE,
.open = input_proc_handlers_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static int __init input_proc_init(void)
{
struct proc_dir_entry *entry;
proc_bus_input_dir = proc_mkdir("bus/input", NULL);
if (!proc_bus_input_dir)
return -ENOMEM;
entry = proc_create("devices", 0, proc_bus_input_dir,
&input_devices_fileops);
if (!entry)
goto fail1;
entry = proc_create("handlers", 0, proc_bus_input_dir,
&input_handlers_fileops);
if (!entry)
goto fail2;
return 0;
fail2: remove_proc_entry("devices", proc_bus_input_dir);
fail1: remove_proc_entry("bus/input", NULL);
return -ENOMEM;
}
static void input_proc_exit(void)
{
remove_proc_entry("devices", proc_bus_input_dir);
remove_proc_entry("handlers", proc_bus_input_dir);
remove_proc_entry("bus/input", NULL);
}
#else /* !CONFIG_PROC_FS */
static inline void input_wakeup_procfs_readers(void) { }
static inline int input_proc_init(void) { return 0; }
static inline void input_proc_exit(void) { }
#endif
#define INPUT_DEV_STRING_ATTR_SHOW(name) \
static ssize_t input_dev_show_##name(struct device *dev, \
struct device_attribute *attr, \
char *buf) \
{ \
struct input_dev *input_dev = to_input_dev(dev); \
\
return scnprintf(buf, PAGE_SIZE, "%s\n", \
input_dev->name ? input_dev->name : ""); \
} \
static DEVICE_ATTR(name, S_IRUGO, input_dev_show_##name, NULL)
INPUT_DEV_STRING_ATTR_SHOW(name);
INPUT_DEV_STRING_ATTR_SHOW(phys);
INPUT_DEV_STRING_ATTR_SHOW(uniq);
static int input_print_modalias_bits(char *buf, int size,
char name, unsigned long *bm,
unsigned int min_bit, unsigned int max_bit)
{
int len = 0, i;
len += snprintf(buf, max(size, 0), "%c", name);
for (i = min_bit; i < max_bit; i++)
if (bm[BIT_WORD(i)] & BIT_MASK(i))
len += snprintf(buf + len, max(size - len, 0), "%X,", i);
return len;
}
static int input_print_modalias(char *buf, int size, struct input_dev *id,
int add_cr)
{
int len;
len = snprintf(buf, max(size, 0),
"input:b%04Xv%04Xp%04Xe%04X-",
id->id.bustype, id->id.vendor,
id->id.product, id->id.version);
len += input_print_modalias_bits(buf + len, size - len,
'e', id->evbit, 0, EV_MAX);
len += input_print_modalias_bits(buf + len, size - len,
'k', id->keybit, KEY_MIN_INTERESTING, KEY_MAX);
len += input_print_modalias_bits(buf + len, size - len,
'r', id->relbit, 0, REL_MAX);
len += input_print_modalias_bits(buf + len, size - len,
'a', id->absbit, 0, ABS_MAX);
len += input_print_modalias_bits(buf + len, size - len,
'm', id->mscbit, 0, MSC_MAX);
len += input_print_modalias_bits(buf + len, size - len,
'l', id->ledbit, 0, LED_MAX);
len += input_print_modalias_bits(buf + len, size - len,
's', id->sndbit, 0, SND_MAX);
len += input_print_modalias_bits(buf + len, size - len,
'f', id->ffbit, 0, FF_MAX);
len += input_print_modalias_bits(buf + len, size - len,
'w', id->swbit, 0, SW_MAX);
if (add_cr)
len += snprintf(buf + len, max(size - len, 0), "\n");
return len;
}
static ssize_t input_dev_show_modalias(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct input_dev *id = to_input_dev(dev);
ssize_t len;
len = input_print_modalias(buf, PAGE_SIZE, id, 1);
return min_t(int, len, PAGE_SIZE);
}
static DEVICE_ATTR(modalias, S_IRUGO, input_dev_show_modalias, NULL);
static int input_print_bitmap(char *buf, int buf_size, unsigned long *bitmap,
int max, int add_cr);
static ssize_t input_dev_show_properties(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct input_dev *input_dev = to_input_dev(dev);
int len = input_print_bitmap(buf, PAGE_SIZE, input_dev->propbit,
INPUT_PROP_MAX, true);
return min_t(int, len, PAGE_SIZE);
}
static DEVICE_ATTR(properties, S_IRUGO, input_dev_show_properties, NULL);
static ssize_t input_dev_show_enabled(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct input_dev *input_dev = to_input_dev(dev);
return scnprintf(buf, PAGE_SIZE, "%d\n", !input_dev->disabled);
}
static ssize_t input_dev_store_enabled(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
int ret;
bool enable;
struct input_dev *input_dev = to_input_dev(dev);
ret = strtobool(buf, &enable);
if (ret)
return ret;
if (enable)
ret = input_enable_device(input_dev);
else
ret = input_disable_device(input_dev);
if (ret)
return ret;
return size;
}
static DEVICE_ATTR(enabled, S_IRUGO | S_IWUSR,
input_dev_show_enabled, input_dev_store_enabled);
static struct attribute *input_dev_attrs[] = {
&dev_attr_name.attr,
&dev_attr_phys.attr,
&dev_attr_uniq.attr,
&dev_attr_modalias.attr,
&dev_attr_properties.attr,
&dev_attr_enabled.attr,
NULL
};
static struct attribute_group input_dev_attr_group = {
.attrs = input_dev_attrs,
};
#define INPUT_DEV_ID_ATTR(name) \
static ssize_t input_dev_show_id_##name(struct device *dev, \
struct device_attribute *attr, \
char *buf) \
{ \
struct input_dev *input_dev = to_input_dev(dev); \
return scnprintf(buf, PAGE_SIZE, "%04x\n", input_dev->id.name); \
} \
static DEVICE_ATTR(name, S_IRUGO, input_dev_show_id_##name, NULL)
INPUT_DEV_ID_ATTR(bustype);
INPUT_DEV_ID_ATTR(vendor);
INPUT_DEV_ID_ATTR(product);
INPUT_DEV_ID_ATTR(version);
static struct attribute *input_dev_id_attrs[] = {
&dev_attr_bustype.attr,
&dev_attr_vendor.attr,
&dev_attr_product.attr,
&dev_attr_version.attr,
NULL
};
static struct attribute_group input_dev_id_attr_group = {
.name = "id",
.attrs = input_dev_id_attrs,
};
static int input_print_bitmap(char *buf, int buf_size, unsigned long *bitmap,
int max, int add_cr)
{
int i;
int len = 0;
bool skip_empty = true;
for (i = BITS_TO_LONGS(max) - 1; i >= 0; i--) {
len += input_bits_to_string(buf + len, max(buf_size - len, 0),
bitmap[i], skip_empty);
if (len) {
skip_empty = false;
if (i > 0)
len += snprintf(buf + len, max(buf_size - len, 0), " ");
}
}
/*
* If no output was produced print a single 0.
*/
if (len == 0)
len = snprintf(buf, buf_size, "%d", 0);
if (add_cr)
len += snprintf(buf + len, max(buf_size - len, 0), "\n");
return len;
}
#define INPUT_DEV_CAP_ATTR(ev, bm) \
static ssize_t input_dev_show_cap_##bm(struct device *dev, \
struct device_attribute *attr, \
char *buf) \
{ \
struct input_dev *input_dev = to_input_dev(dev); \
int len = input_print_bitmap(buf, PAGE_SIZE, \
input_dev->bm##bit, ev##_MAX, \
true); \
return min_t(int, len, PAGE_SIZE); \
} \
static DEVICE_ATTR(bm, S_IRUGO, input_dev_show_cap_##bm, NULL)
INPUT_DEV_CAP_ATTR(EV, ev);
INPUT_DEV_CAP_ATTR(KEY, key);
INPUT_DEV_CAP_ATTR(REL, rel);
INPUT_DEV_CAP_ATTR(ABS, abs);
INPUT_DEV_CAP_ATTR(MSC, msc);
INPUT_DEV_CAP_ATTR(LED, led);
INPUT_DEV_CAP_ATTR(SND, snd);
INPUT_DEV_CAP_ATTR(FF, ff);
INPUT_DEV_CAP_ATTR(SW, sw);
static struct attribute *input_dev_caps_attrs[] = {
&dev_attr_ev.attr,
&dev_attr_key.attr,
&dev_attr_rel.attr,
&dev_attr_abs.attr,
&dev_attr_msc.attr,
&dev_attr_led.attr,
&dev_attr_snd.attr,
&dev_attr_ff.attr,
&dev_attr_sw.attr,
NULL
};
static struct attribute_group input_dev_caps_attr_group = {
.name = "capabilities",
.attrs = input_dev_caps_attrs,
};
static const struct attribute_group *input_dev_attr_groups[] = {
&input_dev_attr_group,
&input_dev_id_attr_group,
&input_dev_caps_attr_group,
NULL
};
static void input_dev_release(struct device *device)
{
struct input_dev *dev = to_input_dev(device);
input_ff_destroy(dev);
input_mt_destroy_slots(dev);
kfree(dev->absinfo);
kfree(dev->vals);
kfree(dev);
module_put(THIS_MODULE);
}
/*
* Input uevent interface - loading event handlers based on
* device bitfields.
*/
static int input_add_uevent_bm_var(struct kobj_uevent_env *env,
const char *name, unsigned long *bitmap, int max)
{
int len;
if (add_uevent_var(env, "%s", name))
return -ENOMEM;
len = input_print_bitmap(&env->buf[env->buflen - 1],
sizeof(env->buf) - env->buflen,
bitmap, max, false);
if (len >= (sizeof(env->buf) - env->buflen))
return -ENOMEM;
env->buflen += len;
return 0;
}
static int input_add_uevent_modalias_var(struct kobj_uevent_env *env,
struct input_dev *dev)
{
int len;
if (add_uevent_var(env, "MODALIAS="))
return -ENOMEM;
len = input_print_modalias(&env->buf[env->buflen - 1],
sizeof(env->buf) - env->buflen,
dev, 0);
if (len >= (sizeof(env->buf) - env->buflen))
return -ENOMEM;
env->buflen += len;
return 0;
}
#define INPUT_ADD_HOTPLUG_VAR(fmt, val...) \
do { \
int err = add_uevent_var(env, fmt, val); \
if (err) \
return err; \
} while (0)
#define INPUT_ADD_HOTPLUG_BM_VAR(name, bm, max) \
do { \
int err = input_add_uevent_bm_var(env, name, bm, max); \
if (err) \
return err; \
} while (0)
#define INPUT_ADD_HOTPLUG_MODALIAS_VAR(dev) \
do { \
int err = input_add_uevent_modalias_var(env, dev); \
if (err) \
return err; \
} while (0)
static int input_dev_uevent(struct device *device, struct kobj_uevent_env *env)
{
struct input_dev *dev = to_input_dev(device);
INPUT_ADD_HOTPLUG_VAR("PRODUCT=%x/%x/%x/%x",
dev->id.bustype, dev->id.vendor,
dev->id.product, dev->id.version);
if (dev->name)
INPUT_ADD_HOTPLUG_VAR("NAME=\"%s\"", dev->name);
if (dev->phys)
INPUT_ADD_HOTPLUG_VAR("PHYS=\"%s\"", dev->phys);
if (dev->uniq)
INPUT_ADD_HOTPLUG_VAR("UNIQ=\"%s\"", dev->uniq);
INPUT_ADD_HOTPLUG_BM_VAR("PROP=", dev->propbit, INPUT_PROP_MAX);
INPUT_ADD_HOTPLUG_BM_VAR("EV=", dev->evbit, EV_MAX);
if (test_bit(EV_KEY, dev->evbit))
INPUT_ADD_HOTPLUG_BM_VAR("KEY=", dev->keybit, KEY_MAX);
if (test_bit(EV_REL, dev->evbit))
INPUT_ADD_HOTPLUG_BM_VAR("REL=", dev->relbit, REL_MAX);
if (test_bit(EV_ABS, dev->evbit))
INPUT_ADD_HOTPLUG_BM_VAR("ABS=", dev->absbit, ABS_MAX);
if (test_bit(EV_MSC, dev->evbit))
INPUT_ADD_HOTPLUG_BM_VAR("MSC=", dev->mscbit, MSC_MAX);
if (test_bit(EV_LED, dev->evbit))
INPUT_ADD_HOTPLUG_BM_VAR("LED=", dev->ledbit, LED_MAX);
if (test_bit(EV_SND, dev->evbit))
INPUT_ADD_HOTPLUG_BM_VAR("SND=", dev->sndbit, SND_MAX);
if (test_bit(EV_FF, dev->evbit))
INPUT_ADD_HOTPLUG_BM_VAR("FF=", dev->ffbit, FF_MAX);
if (test_bit(EV_SW, dev->evbit))
INPUT_ADD_HOTPLUG_BM_VAR("SW=", dev->swbit, SW_MAX);
INPUT_ADD_HOTPLUG_MODALIAS_VAR(dev);
return 0;
}
#define INPUT_DO_TOGGLE(dev, type, bits, on) \
do { \
int i; \
bool active; \
\
if (!test_bit(EV_##type, dev->evbit)) \
break; \
\
for (i = 0; i < type##_MAX; i++) { \
if (!test_bit(i, dev->bits##bit)) \
continue; \
\
active = test_bit(i, dev->bits); \
if (!active && !on) \
continue; \
\
dev->event(dev, EV_##type, i, on ? active : 0); \
} \
} while (0)
static void input_dev_toggle(struct input_dev *dev, bool activate)
{
if (!dev->event)
return;
INPUT_DO_TOGGLE(dev, LED, led, activate);
INPUT_DO_TOGGLE(dev, SND, snd, activate);
if (activate && test_bit(EV_REP, dev->evbit)) {
dev->event(dev, EV_REP, REP_PERIOD, dev->rep[REP_PERIOD]);
dev->event(dev, EV_REP, REP_DELAY, dev->rep[REP_DELAY]);
}
}
/**
* input_reset_device() - reset/restore the state of input device
* @dev: input device whose state needs to be reset
*
* This function tries to reset the state of an opened input device and
* bring internal state and state if the hardware in sync with each other.
* We mark all keys as released, restore LED state, repeat rate, etc.
*/
void input_reset_device(struct input_dev *dev)
{
mutex_lock(&dev->mutex);
if (dev->users) {
input_dev_toggle(dev, true);
/*
* Keys that have been pressed at suspend time are unlikely
* to be still pressed when we resume.
*/
/* LGE_CHANGE
* During Suspend & Resume Do not release keys for Power Long Key press.
* If some devices want to release pressed keys on Suspend,
* Add the routine on each devices.
* fred.cho@lge.com, 2012-03-19
*/
/* spin_lock_irq(&dev->event_lock);
input_dev_release_keys(dev);
spin_unlock_irq(&dev->event_lock);
*/
}
mutex_unlock(&dev->mutex);
}
EXPORT_SYMBOL(input_reset_device);
#ifdef CONFIG_PM
static int input_dev_suspend(struct device *dev)
{
struct input_dev *input_dev = to_input_dev(dev);
mutex_lock(&input_dev->mutex);
if (input_dev->users)
input_dev_toggle(input_dev, false);
mutex_unlock(&input_dev->mutex);
return 0;
}
static int input_dev_resume(struct device *dev)
{
struct input_dev *input_dev = to_input_dev(dev);
input_reset_device(input_dev);
return 0;
}
static const struct dev_pm_ops input_dev_pm_ops = {
.suspend = input_dev_suspend,
.resume = input_dev_resume,
.poweroff = input_dev_suspend,
.restore = input_dev_resume,
};
#endif /* CONFIG_PM */
static struct device_type input_dev_type = {
.groups = input_dev_attr_groups,
.release = input_dev_release,
.uevent = input_dev_uevent,
#ifdef CONFIG_PM
.pm = &input_dev_pm_ops,
#endif
};
static char *input_devnode(struct device *dev, umode_t *mode)
{
return kasprintf(GFP_KERNEL, "input/%s", dev_name(dev));
}
struct class input_class = {
.name = "input",
.devnode = input_devnode,
};
EXPORT_SYMBOL_GPL(input_class);
/**
* input_allocate_device - allocate memory for new input device
*
* Returns prepared struct input_dev or NULL.
*
* NOTE: Use input_free_device() to free devices that have not been
* registered; input_unregister_device() should be used for already
* registered devices.
*/
struct input_dev *input_allocate_device(void)
{
struct input_dev *dev;
dev = kzalloc(sizeof(struct input_dev), GFP_KERNEL);
if (dev) {
dev->dev.type = &input_dev_type;
dev->dev.class = &input_class;
device_initialize(&dev->dev);
mutex_init(&dev->mutex);
spin_lock_init(&dev->event_lock);
INIT_LIST_HEAD(&dev->h_list);
INIT_LIST_HEAD(&dev->node);
__module_get(THIS_MODULE);
}
return dev;
}
EXPORT_SYMBOL(input_allocate_device);
/**
* input_free_device - free memory occupied by input_dev structure
* @dev: input device to free
*
* This function should only be used if input_register_device()
* was not called yet or if it failed. Once device was registered
* use input_unregister_device() and memory will be freed once last
* reference to the device is dropped.
*
* Device should be allocated by input_allocate_device().
*
* NOTE: If there are references to the input device then memory
* will not be freed until last reference is dropped.
*/
void input_free_device(struct input_dev *dev)
{
if (dev)
input_put_device(dev);
}
EXPORT_SYMBOL(input_free_device);
/**
* input_set_capability - mark device as capable of a certain event
* @dev: device that is capable of emitting or accepting event
* @type: type of the event (EV_KEY, EV_REL, etc...)
* @code: event code
*
* In addition to setting up corresponding bit in appropriate capability
* bitmap the function also adjusts dev->evbit.
*/
void input_set_capability(struct input_dev *dev, unsigned int type, unsigned int code)
{
switch (type) {
case EV_KEY:
__set_bit(code, dev->keybit);
break;
case EV_REL:
__set_bit(code, dev->relbit);
break;
case EV_ABS:
input_alloc_absinfo(dev);
if (!dev->absinfo)
return;
__set_bit(code, dev->absbit);
break;
case EV_MSC:
__set_bit(code, dev->mscbit);
break;
case EV_SW:
__set_bit(code, dev->swbit);
break;
case EV_LED:
__set_bit(code, dev->ledbit);
break;
case EV_SND:
__set_bit(code, dev->sndbit);
break;
case EV_FF:
__set_bit(code, dev->ffbit);
break;
case EV_PWR:
/* do nothing */
break;
default:
pr_err("input_set_capability: unknown type %u (code %u)\n",
type, code);
dump_stack();
return;
}
__set_bit(type, dev->evbit);
}
EXPORT_SYMBOL(input_set_capability);
static unsigned int input_estimate_events_per_packet(struct input_dev *dev)
{
int mt_slots;
int i;
unsigned int events;
if (dev->mtsize) {
mt_slots = dev->mtsize;
} else if (test_bit(ABS_MT_TRACKING_ID, dev->absbit)) {
mt_slots = dev->absinfo[ABS_MT_TRACKING_ID].maximum -
dev->absinfo[ABS_MT_TRACKING_ID].minimum + 1,
mt_slots = clamp(mt_slots, 2, 32);
} else if (test_bit(ABS_MT_POSITION_X, dev->absbit)) {
mt_slots = 2;
} else {
mt_slots = 0;
}
events = mt_slots + 1; /* count SYN_MT_REPORT and SYN_REPORT */
for (i = 0; i < ABS_CNT; i++) {
if (test_bit(i, dev->absbit)) {
if (input_is_mt_axis(i))
events += mt_slots;
else
events++;
}
}
for (i = 0; i < REL_CNT; i++)
if (test_bit(i, dev->relbit))
events++;
/* Make room for KEY and MSC events */
events += 7;
return events;
}
#define INPUT_CLEANSE_BITMASK(dev, type, bits) \
do { \
if (!test_bit(EV_##type, dev->evbit)) \
memset(dev->bits##bit, 0, \
sizeof(dev->bits##bit)); \
} while (0)
static void input_cleanse_bitmasks(struct input_dev *dev)
{
INPUT_CLEANSE_BITMASK(dev, KEY, key);
INPUT_CLEANSE_BITMASK(dev, REL, rel);
INPUT_CLEANSE_BITMASK(dev, ABS, abs);
INPUT_CLEANSE_BITMASK(dev, MSC, msc);
INPUT_CLEANSE_BITMASK(dev, LED, led);
INPUT_CLEANSE_BITMASK(dev, SND, snd);
INPUT_CLEANSE_BITMASK(dev, FF, ff);
INPUT_CLEANSE_BITMASK(dev, SW, sw);
}
/**
* input_register_device - register device with input core
* @dev: device to be registered
*
* This function registers device with input core. The device must be
* allocated with input_allocate_device() and all it's capabilities
* set up before registering.
* If function fails the device must be freed with input_free_device().
* Once device has been successfully registered it can be unregistered
* with input_unregister_device(); input_free_device() should not be
* called in this case.
*/
int input_register_device(struct input_dev *dev)
{
static atomic_t input_no = ATOMIC_INIT(0);
struct input_handler *handler;
unsigned int packet_size;
const char *path;
int error;
/* Every input device generates EV_SYN/SYN_REPORT events. */
__set_bit(EV_SYN, dev->evbit);
/* KEY_RESERVED is not supposed to be transmitted to userspace. */
__clear_bit(KEY_RESERVED, dev->keybit);
/* Make sure that bitmasks not mentioned in dev->evbit are clean. */
input_cleanse_bitmasks(dev);
packet_size = input_estimate_events_per_packet(dev);
if (dev->hint_events_per_packet < packet_size)
dev->hint_events_per_packet = packet_size;
dev->max_vals = max(dev->hint_events_per_packet, packet_size) + 2;
dev->vals = kcalloc(dev->max_vals, sizeof(*dev->vals), GFP_KERNEL);
if (!dev->vals)
return -ENOMEM;
/*
* If delay and period are pre-set by the driver, then autorepeating
* is handled by the driver itself and we don't do it in input.c.
*/
init_timer(&dev->timer);
if (!dev->rep[REP_DELAY] && !dev->rep[REP_PERIOD]) {
dev->timer.data = (long) dev;
dev->timer.function = input_repeat_key;
dev->rep[REP_DELAY] = 250;
dev->rep[REP_PERIOD] = 33;
}
if (!dev->getkeycode)
dev->getkeycode = input_default_getkeycode;
if (!dev->setkeycode)
dev->setkeycode = input_default_setkeycode;
dev_set_name(&dev->dev, "input%ld",
(unsigned long) atomic_inc_return(&input_no) - 1);
error = device_add(&dev->dev);
if (error)
return error;
path = kobject_get_path(&dev->dev.kobj, GFP_KERNEL);
pr_info("%s as %s\n",
dev->name ? dev->name : "Unspecified device",
path ? path : "N/A");
kfree(path);
error = mutex_lock_interruptible(&input_mutex);
if (error) {
device_del(&dev->dev);
return error;
}
list_add_tail(&dev->node, &input_dev_list);
list_for_each_entry(handler, &input_handler_list, node)
input_attach_handler(dev, handler);
input_wakeup_procfs_readers();
mutex_unlock(&input_mutex);
return 0;
}
EXPORT_SYMBOL(input_register_device);
/**
* input_unregister_device - unregister previously registered device
* @dev: device to be unregistered
*
* This function unregisters an input device. Once device is unregistered
* the caller should not try to access it as it may get freed at any moment.
*/
void input_unregister_device(struct input_dev *dev)
{
struct input_handle *handle, *next;
input_disconnect_device(dev);
mutex_lock(&input_mutex);
list_for_each_entry_safe(handle, next, &dev->h_list, d_node)
handle->handler->disconnect(handle);
WARN_ON(!list_empty(&dev->h_list));
del_timer_sync(&dev->timer);
list_del_init(&dev->node);
input_wakeup_procfs_readers();
mutex_unlock(&input_mutex);
device_unregister(&dev->dev);
}
EXPORT_SYMBOL(input_unregister_device);
/**
* input_register_handler - register a new input handler
* @handler: handler to be registered
*
* This function registers a new input handler (interface) for input
* devices in the system and attaches it to all input devices that
* are compatible with the handler.
*/
int input_register_handler(struct input_handler *handler)
{
struct input_dev *dev;
int retval;
retval = mutex_lock_interruptible(&input_mutex);
if (retval)
return retval;
INIT_LIST_HEAD(&handler->h_list);
if (handler->fops != NULL) {
if (input_table[handler->minor >> 5]) {
retval = -EBUSY;
goto out;
}
input_table[handler->minor >> 5] = handler;
}
list_add_tail(&handler->node, &input_handler_list);
list_for_each_entry(dev, &input_dev_list, node)
input_attach_handler(dev, handler);
input_wakeup_procfs_readers();
out:
mutex_unlock(&input_mutex);
return retval;
}
EXPORT_SYMBOL(input_register_handler);
/**
* input_unregister_handler - unregisters an input handler
* @handler: handler to be unregistered
*
* This function disconnects a handler from its input devices and
* removes it from lists of known handlers.
*/
void input_unregister_handler(struct input_handler *handler)
{
struct input_handle *handle, *next;
mutex_lock(&input_mutex);
list_for_each_entry_safe(handle, next, &handler->h_list, h_node)
handler->disconnect(handle);
WARN_ON(!list_empty(&handler->h_list));
list_del_init(&handler->node);
if (handler->fops != NULL)
input_table[handler->minor >> 5] = NULL;
input_wakeup_procfs_readers();
mutex_unlock(&input_mutex);
}
EXPORT_SYMBOL(input_unregister_handler);
/**
* input_handler_for_each_handle - handle iterator
* @handler: input handler to iterate
* @data: data for the callback
* @fn: function to be called for each handle
*
* Iterate over @bus's list of devices, and call @fn for each, passing
* it @data and stop when @fn returns a non-zero value. The function is
* using RCU to traverse the list and therefore may be usind in atonic
* contexts. The @fn callback is invoked from RCU critical section and
* thus must not sleep.
*/
int input_handler_for_each_handle(struct input_handler *handler, void *data,
int (*fn)(struct input_handle *, void *))
{
struct input_handle *handle;
int retval = 0;
rcu_read_lock();
list_for_each_entry_rcu(handle, &handler->h_list, h_node) {
retval = fn(handle, data);
if (retval)
break;
}
rcu_read_unlock();
return retval;
}
EXPORT_SYMBOL(input_handler_for_each_handle);
/**
* input_register_handle - register a new input handle
* @handle: handle to register
*
* This function puts a new input handle onto device's
* and handler's lists so that events can flow through
* it once it is opened using input_open_device().
*
* This function is supposed to be called from handler's
* connect() method.
*/
int input_register_handle(struct input_handle *handle)
{
struct input_handler *handler = handle->handler;
struct input_dev *dev = handle->dev;
int error;
/*
* We take dev->mutex here to prevent race with
* input_release_device().
*/
error = mutex_lock_interruptible(&dev->mutex);
if (error)
return error;
/*
* Filters go to the head of the list, normal handlers
* to the tail.
*/
if (handler->filter)
list_add_rcu(&handle->d_node, &dev->h_list);
else
list_add_tail_rcu(&handle->d_node, &dev->h_list);
mutex_unlock(&dev->mutex);
/*
* Since we are supposed to be called from ->connect()
* which is mutually exclusive with ->disconnect()
* we can't be racing with input_unregister_handle()
* and so separate lock is not needed here.
*/
list_add_tail_rcu(&handle->h_node, &handler->h_list);
if (handler->start)
handler->start(handle);
return 0;
}
EXPORT_SYMBOL(input_register_handle);
/**
* input_unregister_handle - unregister an input handle
* @handle: handle to unregister
*
* This function removes input handle from device's
* and handler's lists.
*
* This function is supposed to be called from handler's
* disconnect() method.
*/
void input_unregister_handle(struct input_handle *handle)
{
struct input_dev *dev = handle->dev;
list_del_rcu(&handle->h_node);
/*
* Take dev->mutex to prevent race with input_release_device().
*/
mutex_lock(&dev->mutex);
list_del_rcu(&handle->d_node);
mutex_unlock(&dev->mutex);
synchronize_rcu();
}
EXPORT_SYMBOL(input_unregister_handle);
static int input_open_file(struct inode *inode, struct file *file)
{
struct input_handler *handler;
const struct file_operations *old_fops, *new_fops = NULL;
int err;
err = mutex_lock_interruptible(&input_mutex);
if (err)
return err;
/* No load-on-demand here? */
handler = input_table[iminor(inode) >> 5];
if (handler)
new_fops = fops_get(handler->fops);
mutex_unlock(&input_mutex);
/*
* That's _really_ odd. Usually NULL ->open means "nothing special",
* not "no device". Oh, well...
*/
if (!new_fops || !new_fops->open) {
fops_put(new_fops);
err = -ENODEV;
goto out;
}
old_fops = file->f_op;
file->f_op = new_fops;
err = new_fops->open(inode, file);
if (err) {
fops_put(file->f_op);
file->f_op = fops_get(old_fops);
}
fops_put(old_fops);
out:
return err;
}
static const struct file_operations input_fops = {
.owner = THIS_MODULE,
.open = input_open_file,
.llseek = noop_llseek,
};
static int __init input_init(void)
{
int err;
err = class_register(&input_class);
if (err) {
pr_err("unable to register input_dev class\n");
return err;
}
err = input_proc_init();
if (err)
goto fail1;
err = register_chrdev(INPUT_MAJOR, "input", &input_fops);
if (err) {
pr_err("unable to register char major %d", INPUT_MAJOR);
goto fail2;
}
return 0;
fail2: input_proc_exit();
fail1: class_unregister(&input_class);
return err;
}
static void __exit input_exit(void)
{
input_proc_exit();
unregister_chrdev(INPUT_MAJOR, "input");
class_unregister(&input_class);
}
subsys_initcall(input_init);
module_exit(input_exit);
|
AOSPA-legacy/android_kernel_lge_msm8974
|
drivers/input/input.c
|
C
|
gpl-2.0
| 57,518
|
<?php
session_start();
if (!array_key_exists("la_logusr",$_SESSION))
{
print "<script language=JavaScript>";
print "close();";
print "opener.document.form1.submit();";
print "</script>";
}
$la_empresa = $_SESSION["la_empresa"];
$li_estmodest = $la_empresa["estmodest"];
$li_loncodestpro1 = $la_empresa["loncodestpro1"];
$li_loncodestpro2 = $la_empresa["loncodestpro2"];
$li_size1 = $li_loncodestpro1+10;
$li_size2 = $li_loncodestpro2+10;
require_once("../shared/class_folder/sigesp_include.php");
require_once("../shared/class_folder/class_sql.php");
require_once("../shared/class_folder/class_funciones.php");
$io_include = new sigesp_include();
$ls_conect = $io_include->uf_conectar();
$io_msg = new class_mensajes();
$io_sql = new class_sql($ls_conect);
if (array_key_exists("operacion",$_POST))
{
$ls_operacion = $_POST["operacion"];
$ls_codestpro1 = $_POST["codestpro1"];
$ls_denestpro1 = $_POST["denestpro1"];
$ls_codestpro2 = $_POST["codestprog2"];
$ls_denestpro2 = $_POST["denominacion"];
$ls_estcla = $_POST["hidestcla"];
}
else
{
$ls_operacion = "BUSCAR";
$ls_codestpro1 = $_GET["codestpro1"];
$ls_denestpro1 = $_GET["denestpro1"];
$ls_estcla = $_GET["hidestcla"];
$ls_codestpro2 = "";
$ls_denestpro2 = "";
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Catálogo de <?php print $la_empresa["nomestpro2"] ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
a:link {
color: #006699;
}
a:visited {
color: #006699;
}
a:active {
color: #006699;
}
-->
</style>
<link href="../shared/css/ventanas.css" rel="stylesheet" type="text/css">
<link href="../shared/css/general.css" rel="stylesheet" type="text/css">
<link href="../shared/css/tablas.css" rel="stylesheet" type="text/css">
</head>
<body>
<form name="form1" method="post" action="">
<p align="center"> </p>
<table width="550" border="0" cellpadding="0" cellspacing="0" class="formato-blanco" align="center">
<tr class="titulo-celda">
<td height="21" colspan="2"><input name="hidestcla" type="hidden" id="hidestcla" value="<?php print $ls_estcla ?>">
<input name="operacion" type="hidden" id="operacion">
Catálogo <?php print $la_empresa["nomestpro2"] ?></td>
</tr>
<tr>
<td height="13"> </td>
<td height="13"> </td>
</tr>
<tr>
<td width="137" height="21"><div align="right"><?php print $la_empresa["nomestpro1"]?></div></td>
<td width="461" height="21"><div align="left">
<input name="codestpro1" type="text" id="codestpro1" value="<?php print $ls_codestpro1 ?>" size="22" maxlength="20" readonly style="text-align:center">
<input name="denestpro1" type="text" class="sin-borde" id="denestpro1" size="50" value="<?php print $ls_denestpro1 ?>" readonly>
</div></td>
</tr>
<tr>
<td height="21" style="text-align:right">Código</td>
<td height="21" style="text-align:left"><input name="codestprog2" type="text" id="codestprog2" size="<?php print $li_size2 ?>" maxlength="<?php print $li_loncodestpro2 ?>" style="text-align:center">
</td>
</tr>
<tr>
<td height="21" style="text-align:right">Denominación</td>
<td height="21" style="text-align:left"><input name="denominacion" type="text" id="denominacion" size="72" maxlength="100" style="text-align:left">
</td>
</tr>
<tr>
<td height="21"> </td>
<td height="21"><div align="right"><a href="javascript: ue_search();"><img src="../shared/imagebank/tools20/buscar.gif" alt="Buscar" width="20" height="20" border="0"> Buscar</a></div></td>
</tr>
</table>
<div align="center"><br>
<?php
print "<table width=600 border=0 cellpadding=1 cellspacing=1 class=fondo-tabla align=center>";
print "<tr class=titulo-celda>";
print "<td width=160 style=text-align:center>".$la_empresa["nomestpro1"]."</td>";
print "<td width=160 style=text-align:center>Código</td>";
print "<td width=350 style=text-align:center>Denominación</td>";
print "<td width=40 style=text-align:center>Tipo</td>";
print "</tr>";
if ($ls_operacion=="BUSCAR")
{
$ls_codestpro1 = str_pad($ls_codestpro1,25,0,0);
if (!empty($ls_codestpro2))
{
$ls_codestpro2 = str_pad($ls_codestpro2,25,0,0);
}
$ls_sql = "SELECT codestpro1,codestpro2,denestpro2,estcla
FROM spg_ep2
WHERE codemp='".$la_empresa["codemp"]."'
AND codestpro1 = '".$ls_codestpro1."'
AND codestpro2 like '%".$ls_codestpro2."%'
AND denestpro2 like '%".$ls_denestpro2."%'
AND estcla='".$ls_estcla."'
AND codestpro2<>'-------------------------'
AND codestpro1||codestpro2||estcla IN (SELECT SUBSTR(codintper,1,50)||SUBSTR(codintper,126,1) FROM sss_permisos_internos WHERE codusu='".$_SESSION["la_logusr"]."' UNION SELECT SUBSTR(codintper,1,50)||SUBSTR(codintper,126,1) FROM sss_permisos_internos_grupo,sss_usuarios_en_grupos WHERE codusu='".$_SESSION["la_logusr"]."' AND sss_permisos_internos_grupo.codgru=sss_usuarios_en_grupos.codgru)
ORDER BY codestpro1, codestpro2 ASC";
$rs_data = $io_sql->select($ls_sql);
if ($rs_data===false)
{
$io_msg->message("Error en Consulta, Contacte al Administrador del Sistema !!!");
}
else
{
$li_numrows = $io_sql->num_rows($rs_data);
if ($li_numrows>0)
{
while ($row=$io_sql->fetch_row($rs_data))
{
print "<tr class=celdas-blancas>";
$ls_codestpro1 = trim(substr($row["codestpro1"],-$li_loncodestpro1));
$ls_codestpro2 = trim(substr($row["codestpro2"],-$li_loncodestpro2));
$ls_denestpro2 = $row["denestpro2"];
$ls_estcla = $row["estcla"];
if ($ls_estcla=='P')
{
$ls_denestcla='Proyecto';
}
elseif($ls_estcla=='A')
{
$ls_denestcla='Actividad';
}
print "<td width=160 style=text-align:center><a href=\"javascript: aceptar('$ls_codestpro2','$ls_denestpro2');\">".$ls_codestpro1."</a></td>";
print "<td width=160 style=text-align:center><a href=\"javascript: aceptar('$ls_codestpro2','$ls_denestpro2');\">".$ls_codestpro2."</a></td>";
print "<td width=350 style=text-align:left title='".$ls_denestpro2."'>".$ls_denestpro2."</td>";
print "<td width=40 style=text-align:center>".$ls_denestcla."</td>";
print "</tr>";
}
}
else
{
$io_msg->message("No se han definido registros !!!");
}
}
}
print "</table>";
?>
</div>
</form>
<p> </p>
<p> </p>
</body>
<script language="JavaScript">
function aceptar(ls_codestpro2,ls_denestpro2)
{
opener.document.form1.denestpro2.value=ls_denestpro2;
opener.document.form1.codestpro2.value=ls_codestpro2;
opener.document.form1.denestpro3.value="";
opener.document.form1.codestpro3.value="";
if("<?php print $li_estmodest;?>"==2)
{
opener.document.form1.codestpro4.value="";
opener.document.form1.denestpro4.value="";
opener.document.form1.codestpro5.value="";
opener.document.form1.denestpro5.value="";
}
close();
}
function ue_search()
{
f=document.form1;
f.operacion.value="BUSCAR";
f.action="sigesp_cat_public_estpro2.php";
f.submit();
}
</script>
</html>
|
omerta/huayra
|
scb/sigesp_cat_public_estpro2.php
|
PHP
|
gpl-2.0
| 7,691
|
<?php
/**
* Copyright (c) 2011 Sardar Madumarov
* All rights reserved.
* ATTENTION: This commercial software is intended for use with Oxwall Free Community Software http://www.oxwall.org/
* and is licensed under Oxwall Store Commercial License.
* Full text of this license can be found at http://www.oxwall.org/store/oscl
*/
/**
* @author Sardar Madumarov <madumarov@gmail.com>
* @package oaseo.controllers
*/
class OASEO_CTRL_Admin extends ADMIN_CTRL_Abstract
{
/**
* @var OASEO_BOL_Service
*/
private $service;
/**
* @var BASE_CMP_ContentMenu
*/
private $menu;
/**
* Constructor.
*/
public function __construct()
{
parent::__construct();
$this->service = OASEO_BOL_Service::getInstance();
if ( !OW::getRequest()->isAjax() )
{
$language = OW::getLanguage();
$this->setPageHeading(OW::getLanguage()->text('oaseo', 'admin_index_heading'));
$this->setPageHeadingIconClass('ow_ic_gear_wheel');
OW::getNavigation()->activateMenuItem('admin_plugins', 'admin', 'sidebar_menu_plugins_installed');
$menuItem = new BASE_MenuItem();
$menuItem->setKey('index');
$menuItem->setLabel($language->text('oaseo', 'admin_tab_index_label'));
$menuItem->setUrl(OW::getRouter()->urlForRoute('oaseo.admin_index'));
$menuItem->setIconClass('ow_ic_files');
$menuItem->setOrder(1);
$menuItem1 = new BASE_MenuItem();
$menuItem1->setKey('advanced');
$menuItem1->setLabel($language->text('oaseo', 'admin_tab_advanced_label'));
$menuItem1->setUrl(OW::getRouter()->urlForRoute('oaseo.admin_advanced'));
$menuItem1->setOrder(2);
$menuItem2 = new BASE_MenuItem();
$menuItem2->setKey('slugs');
$menuItem2->setLabel($language->text('oaseo', 'admin_tab_slugs_label'));
$menuItem2->setUrl(OW::getRouter()->urlForRoute('oaseo.admin_slugs'));
$menuItem2->setIconClass('ow_ic_script');
$menuItem2->setOrder(3);
$menuItem3 = new BASE_MenuItem();
$menuItem3->setKey('robots');
$menuItem3->setLabel($language->text('oaseo', 'admin_tab_robots_label'));
$menuItem3->setUrl(OW::getRouter()->urlForRoute('oaseo.admin_robots'));
$menuItem3->setIconClass('ow_ic_lens');
$menuItem3->setOrder(4);
$menuItem4 = new BASE_MenuItem();
$menuItem4->setKey('sitemap');
$menuItem4->setLabel($language->text('oaseo', 'admin_tab_sitemap_label'));
$menuItem4->setUrl(OW::getRouter()->urlForRoute('oaseo.admin_sitemap'));
$menuItem4->setIconClass('ow_ic_plugin');
$menuItem4->setOrder(5);
$menuItem5 = new BASE_MenuItem();
$menuItem5->setKey('sitemap_info');
$menuItem5->setLabel($language->text('oaseo', 'admin_tab_sitemap_info_label'));
$menuItem5->setUrl(OW::getRouter()->urlForRoute('oaseo.admin_sitemap_info'));
$menuItem5->setIconClass('ow_ic_info');
$menuItem5->setOrder(6);
$this->menu = new BASE_CMP_ContentMenu(array($menuItem, $menuItem1, $menuItem2, $menuItem3, $menuItem4, $menuItem5));
$this->assign('oaseoImageUrl', 'http://oxart.net/' . str_replace('.', '', OW::getConfig()->getValue('base', 'soft_version')) . '/oaseo/' . OW::getPluginManager()->getPlugin('oaseo')->getDto()->getBuild() . '/oa-post-it-note.jpg');
$this->addComponent('contentMenu', $this->menu);
}
}
public function index()
{
$language = OW::getLanguage();
if ( OW::getRequest()->isAjax() && OW::getRequest()->isPost() )
{
$langService = BOL_LanguageService::getInstance(false);
if ( isset($_POST['title']) )
{
$titleLangVal = $langService->getValue($langService->getCurrent()->getId(), 'oaseo', 'page_default_title');
if ( $titleLangVal === null )
{
$key = $langService->findKey('oaseo', 'page_default_title');
$titleLangVal = new BOL_LanguageValue();
$titleLangVal->setKeyId($key->getId());
$titleLangVal->setLanguageId($langService->getCurrent()->getId());
}
$titleLangVal->setValue(trim($_POST['title']));
$langService->saveValue($titleLangVal);
}
if ( isset($_POST['desc']) )
{
$titleLangVal = $langService->getValue($langService->getCurrent()->getId(), 'oaseo', 'page_default_desc');
if ( $titleLangVal === null )
{
$key = $langService->findKey('oaseo', 'page_default_desc');
$titleLangVal = new BOL_LanguageValue();
$titleLangVal->setKeyId($key->getId());
$titleLangVal->setLanguageId($langService->getCurrent()->getId());
}
$titleLangVal->setValue(trim($_POST['desc']));
$langService->saveValue($titleLangVal);
}
if ( isset($_POST['keywords']) )
{
$titleLangVal = $langService->getValue($langService->getCurrent()->getId(), 'oaseo', 'page_default_keywords');
if ( $titleLangVal === null )
{
$key = $langService->findKey('oaseo', 'page_default_keywords');
$titleLangVal = new BOL_LanguageValue();
$titleLangVal->setKeyId($key->getId());
$titleLangVal->setLanguageId($langService->getCurrent()->getId());
}
$titleLangVal->setValue(trim($_POST['keywords']));
$langService->saveValue($titleLangVal);
}
exit(json_encode(array('message' => $language->text('oaseo', 'general_meta_submit_message'))));
}
$form = new Form('global_meta_form');
$form->setAjax();
$form->setAjaxResetOnSuccess(false);
$form->bindJsFunction(Form::BIND_SUCCESS, "function(data){OW.info(data.message);}");
$title = new TextField('title');
$title->setLabel($language->text('oaseo', 'title_label'));
$title->setDescription($language->text('oaseo', 'meta_edit_form_title_desc'));
$title->setValue($language->text('oaseo', 'page_default_title'));
$form->addElement($title);
$desc = new Textarea('desc');
$desc->setLabel($language->text('oaseo', 'desc_label'));
$desc->setDescription($language->text('oaseo', 'meta_edit_form_desc_desc'));
$desc->setValue($language->text('oaseo', 'page_default_desc'));
$form->addElement($desc);
$kewords = new TextField('keywords');
$kewords->setLabel($language->text('oaseo', 'keywords_label'));
$kewords->setDescription($language->text('oaseo', 'meta_edit_form_keyword_desc'));
$kewords->setValue($language->text('oaseo', 'page_default_keywords'));
$form->addElement($kewords);
$submit = new Submit('submit');
$submit->setValue(OW::getLanguage()->text('admin', 'save_btn_label'));
$form->addElement($submit);
$this->addForm($form);
}
public function advanced()
{
$language = OW::getLanguage();
$defaultMetaInfo = array(
'title' => $language->text('oaseo', 'page_default_title', array('defaultTitle' => $language->text('nav', 'page_default_title'))),
'desc' => $language->text('oaseo', 'page_default_desc', array('defaultDesc' => $language->text('nav', 'page_default_description'))),
'keywords' => $language->text('oaseo', 'page_default_keywords', array('defaultKeywords' => $language->text('nav', 'page_default_keywords')))
);
$script = "$('#oaseo_add_meta_button').click(
function(){
window.oaseoFB = OA_AjaxFloatBox('OASEO_CMP_MetaEdit', [" . json_encode($defaultMetaInfo) . ", $('#oaseo_add_meta_url_input').val(), false], {width:900, iconClass: 'ow_ic_gear', title: '" . $language->text('oaseo', 'meta_edit_form_cmp_title') . "'})
}
);
";
OW::getDocument()->addOnloadScript($script);
}
public function slugs()
{
$language = OW::getLanguage();
if ( OW::getRequest()->isAjax() && OW::getRequest()->isPost() )
{
if ( isset($_POST['plugins']) && is_array($_POST['plugins']) )
{
OW::getConfig()->saveConfig('oaseo', OASEO_BOL_Service::CNF_SLUG_PLUGINS, json_encode($_POST['plugins']));
}
if ( isset($_POST['redirect']) )
{
OW::getConfig()->saveConfig('oaseo', OASEO_BOL_Service::CNF_SLUG_OLD_URLS_ENABLE, (bool) $_POST['redirect']);
}
if ( isset($_POST['words']) )
{
OW::getConfig()->saveConfig('oaseo', OASEO_BOL_Service::CNF_SLUG_FILTER_COMMON_WORDS, json_encode(array_map('mb_strtolower', array_map('trim', explode(',', $_POST['words'])))));
}
exit(json_encode(array('message' => $language->text('oaseo', 'slugs_submit_message'))));
}
$data = $this->service->getSlugData();
$pluginKeys = array_keys($data);
$event = new BASE_CLASS_EventCollector('admin.add_auth_labels');
OW::getEventManager()->trigger($event);
$labelData = $event->getData();
$dataLabels = empty($labelData) ? array() : call_user_func_array('array_merge', $labelData);
$finalData = array();
foreach ( $dataLabels as $pluginKey => $pluginInfo )
{
if ( in_array($pluginKey, $pluginKeys) )
{
$finalData[$pluginKey] = $pluginInfo['label'];
}
}
$form = new Form('slugs_form');
$form->setAjax();
$form->setAjaxResetOnSuccess(false);
$form->bindJsFunction(Form::BIND_SUCCESS, "function(data){OW.info(data.message);}");
$plugins = new CheckboxGroup('plugins');
$plugins->setLabel($language->text('oaseo', 'slug_plugins_label'));
$plugins->setDescription($language->text('oaseo', 'slug_plugins_desc'));
$plugins->setOptions($finalData);
$plugins->setValue(json_decode(OW::getConfig()->getValue('oaseo', OASEO_BOL_Service::CNF_SLUG_PLUGINS), true));
$form->addElement($plugins);
$redirect = new CheckboxField('redirect');
$redirect->setLabel($language->text('oaseo', 'slug_redirect_label'));
$redirect->setDescription($language->text('oaseo', 'slug_redirect_desc'));
$redirect->setValue(OW::getConfig()->getValue('oaseo', OASEO_BOL_Service::CNF_SLUG_OLD_URLS_ENABLE));
$form->addElement($redirect);
$words = new Textarea('words');
$words->setLabel($language->text('oaseo', 'slug_words_label'));
$words->setDescription($language->text('oaseo', 'slug_words_desc'));
$wordsList = json_decode(OW::getConfig()->getValue('oaseo', OASEO_BOL_Service::CNF_SLUG_FILTER_COMMON_WORDS));
if( is_array($wordsList) )
{
$valString = implode(', ', $wordsList);
}
else
{
$valString = '';
}
$words->setValue($valString);
$form->addElement($words);
$submit = new Submit('submit');
$submit->setValue(OW::getLanguage()->text('admin', 'save_btn_label'));
$form->addElement($submit);
$this->addForm($form);
}
public function robots()
{
if ( OW::getRequest()->isPost() )
{
$contents = trim($_POST['robots']);
OW::getConfig()->saveConfig('oaseo', OASEO_BOL_Service::CNF_ROBOTS_CONTENTS, $contents);
OW::getFeedback()->info(OW::getLanguage()->text('oaseo', 'admin_saved_msg'));
$this->redirect();
}
$form = new Form('robots');
$textarea = new Textarea('robots');
$textarea->setValue(OW::getConfig()->getValue('oaseo', OASEO_BOL_Service::CNF_ROBOTS_CONTENTS));
$form->addElement($textarea);
$submit = new Submit('submit');
$form->addElement($submit);
$this->addForm($form);
}
public function sitemap()
{
$language = OW::getLanguage();
$config = OW::getConfig();
$form = new Form('sitemap_form');
$sitemapUrl = new TextField('sitemap_url');
$sitemapUrl->setLabel($language->text('oaseo', 'sitemap_url_label'));
$sitemapUrl->setDescription($language->text('oaseo', 'sitemap_url_desc'));
$sitemapUrl->setValue(OW_URL_HOME . $config->getValue('oaseo', 'sitemap_url'));
$form->addElement($sitemapUrl);
// $rorUrl = new TextField('ror_url');
// $rorUrl->setLabel($language->text('oaseo', 'ror_url_label'));
// $rorUrl->setDescription($language->text('oaseo', 'ror_url_desc'));
// $rorUrl->setValue(OW_URL_HOME . $config->getValue('oaseo', 'ror_url'));
// $form->addElement($rorUrl);
$imageUrl = new TextField('imagemap_url');
$imageUrl->setLabel($language->text('oaseo', 'imagemap_url_label'));
$imageUrl->setDescription($language->text('oaseo', 'imagemap_url_desc'));
$imageUrl->setValue(OW_URL_HOME . $config->getValue('oaseo', 'imagemap_url'));
$form->addElement($imageUrl);
$undateFreq = new Selectbox('update_freq');
$options = array('86400' => 'Daily', '604800' => 'Weekly', '2419200' => 'Monthly');
$undateFreq->setHasInvitation(false);
$undateFreq->addOptions($options);
$undateFreq->setLabel($language->text('oaseo', 'update_freq_label'));
$undateFreq->setDescription($language->text('oaseo', 'update_freq_desc'));
$form->addElement($undateFreq);
$undateFreq->setValue($config->getValue('oaseo', 'update_freq'));
// $prio = new CheckboxField('prio');
// $prio->setLabel($language->text('oaseo', 'prio_label'));
// $prio->setDescription($language->text('oaseo', 'prio_desc'));
// $form->addElement($prio);
// $email = new TextField('email');
// $email->setLabel($language->text('oaseo', 'email_label'));
// $email->setDescription($language->text('oaseo', 'email_desc'));
// $form->addElement($email);
$inform = new CheckboxGroup('inform');
$inform->setLabel($language->text('oaseo', 'inform_label'));
$inform->setDescription($language->text('oaseo', 'inform_desc'));
$inform->setOptions(array( 'google' => 'Google', 'bing' => 'Bing', 'yahoo' => 'Yahoo', 'ask' => 'Ask' ));
$form->addElement($inform);
$inform->setValue(json_decode($config->getValue('oaseo', 'inform')));
// $extlink = new CheckboxField('extlink');
// $extlink->setLabel($language->text('oaseo', 'extlink_label'));
// $extlink->setDescription($language->text('oaseo', 'extlink_desc'));
// $form->addElement($extlink);
//
// $brock = new CheckboxField('brock_link');
// $brock->setLabel($language->text('oaseo', 'brock_link_label'));
// $brock->setDescription($language->text('oaseo', 'brock_link_desc'));
// $form->addElement($brock);
$submit = new Submit('submit');
$submit->setValue(OW::getLanguage()->text('admin', 'save_btn_label'));
$form->addElement($submit);
$this->addForm($form);
if( OW::getRequest()->isPost() && $form->isValid($_POST) )
{
$data = $form->getValues();
$config->saveConfig('oaseo', 'sitemap_url', str_replace(OW_URL_HOME, '', $data['sitemap_url']));
$config->saveConfig('oaseo', 'imagemap_url', str_replace(OW_URL_HOME, '', $data['imagemap_url']));
$config->saveConfig('oaseo', 'update_freq', (int)$data['update_freq']);
$config->saveConfig('oaseo', 'inform', json_encode( $data['inform'] ? $data['inform'] : array() ));
}
}
public function sitemapInfo()
{
$config = OW::getConfig();
if( !(bool)$config->getValue('oaseo', 'sitemap_init') )
{
$this->assign('init', false);
return;
}
if( $this->service->getToProcessPagesCount() > 0 )
{
$this->assign('in_process_message', OW::getLanguage()->text('oaseo', 'in_progress_label'));
$this->assign('url', $this->service->getNextUrlToProcess());
$this->assign('processed', $this->service->getProcessedPagesCount());
$this->assign('to_process', $this->service->getToProcessPagesCount());
return;
}
$page = !empty($_GET['page']) && (int)$_GET['page'] > 0 ? (int)$_GET['page'] : 1;
$numOnPage = 25;
$first = $numOnPage*($page-1);
$count = $numOnPage;
$itemsCountArr = array(
'pages' => $this->service->findAllPagesCount(),
'broken_links' => $this->service->findBrokenPagesCount(),
'images' => $this->service->findItemsCount(OASEO_BOL_Service::ITEM_VAL_IMAGE),
'broken_images' => $this->service->findItemsCount(OASEO_BOL_Service::ITEM_VAL_BROKEN_IMAGE),
'ext_links' => $this->service->findItemsCount(OASEO_BOL_Service::ITEM_VAL_EXT_LINK),
'brok_ext_links' => $this->service->findItemsCount(OASEO_BOL_Service::ITEM_VAL_BROKEN_EXT_LINK)
);
$router = OW::getRouter();
$urlArr = array(
'pages' => $router->urlFor('OASEO_CTRL_Admin', 'sitemapInfo'),
'broken' => $router->urlFor('OASEO_CTRL_Admin', 'sitemapInfo').'?list=broken',
'images' => $router->urlFor('OASEO_CTRL_Admin', 'sitemapInfo').'?list=images',
'broken_images' => $router->urlFor('OASEO_CTRL_Admin', 'sitemapInfo').'?list=broken_images',
'ext_links' => $router->urlFor('OASEO_CTRL_Admin', 'sitemapInfo').'?list=ext_links',
'broken_ext_links' => $router->urlFor('OASEO_CTRL_Admin', 'sitemapInfo').'?list=broken_ext_links'
);
$this->assign('urlArray', $urlArr);
$this->assign('counts', $itemsCountArr);
$list = empty($_GET['list']) ? 'std' : trim($_GET['list']);
$finalArray = array();
switch ( $list )
{
case 'broken':
$items = $this->service->findPages($first, $count, true);
$itemsCount = $itemsCountArr['broken_links'];
foreach ( $items as $item )
{
if( !isset($finalArray[$item['burl']]) )
{
$finalArray[$item['burl']] = array();
}
$finalArray[$item['burl']][] = $item['url'];
}
break;
case 'images':
$items = $this->service->findItems(OASEO_BOL_Service::ITEM_VAL_IMAGE, $first, $count);
$itemsCount = $itemsCountArr['images'];
$list = 'images';
$finalArray = $this->processPageItems($items);
break;
case 'broken_images':
$items = $this->service->findItems(OASEO_BOL_Service::ITEM_VAL_BROKEN_IMAGE, $first, $count);
$itemsCount = $itemsCountArr['broken_images'];
$list = 'broken_images';
$finalArray = $this->processPageItems($items);
break;
case 'ext_links':
$items = $this->service->findItems(OASEO_BOL_Service::ITEM_VAL_EXT_LINK, $first, $count);
$itemsCount = $itemsCountArr['ext_links'];
$list = 'ext_links';
$finalArray = $this->processPageItems($items);
break;
case 'broken_ext_links':
$items = $this->service->findItems(OASEO_BOL_Service::ITEM_VAL_BROKEN_EXT_LINK, $first, $count);
$itemsCount = $itemsCountArr['brok_ext_links'];
$list = 'broken_ext_links';
$finalArray = $this->processPageItems($items);
break;
default:
$items = $this->service->findPages($first, $count);
$itemsCount = $itemsCountArr['pages'];
$list = 'pages';
foreach ( $items as $item )
{
$metaInfo = json_decode($item['meta'], true);
$keywords = empty($metaInfo['keywords']) ? '<span style="color:red;">_NO_KEYWORDS_</span>' : $metaInfo['keywords'];
$desc = empty($metaInfo['description']) ? '<span style="color:red;">_NO_DESCRIPTION_</span>' : $metaInfo['description'];
$finalArray[] = array( 'keywords' => $keywords, 'desc' => $desc, 'url' => urldecode($item['url']), 'title' => empty($item['title']) ? '<span style="color:red;">_NO_TITLE_</span>' : $item['title'] );
}
}
$this->assign('list', $list);
$this->assign('items', $finalArray);
$this->addComponent('paging', new BASE_CMP_Paging($page, ceil($itemsCount / $numOnPage), 5));
}
private function processPageItems( $items )
{
$finalArray = array();
foreach ( $items as $item )
{
if( !isset($finalArray[$item['value']]) )
{
$finalArray[$item['value']] = array();
}
if( !in_array($item['url'], $finalArray[$item['value']]) )
{
if( sizeof($finalArray[$item['value']]) < 11 )
{
$finalArray[$item['value']][] = $item['url'];
}
}
}
return $finalArray;
}
}
|
seret/oxtebafu
|
ow_plugins/oaseo98/controllers/admin.php
|
PHP
|
gpl-2.0
| 22,064
|
/*********************************************************************************************************/
/**
* fileicon plugin for CKEditor 3.x (Author: Lajox ; Email: lajox@19www.com)
* version: 1.0
* Released: On 2009-12-11
* Download: http://code.google.com/p/lajox
*/
/*********************************************************************************************************/
CKEDITOR.dialog.add('fileicon', function (a) {
var b = a.config,
c = b.fileicon_images,
d = 8,
e, f, g = function (k) {
var l = k.data.getTarget(),
m = l.getName();
if (m == 'td') l = l.getChild([0, 0]);
else if (m == 'a') l = l.getChild(0);
else if (m != 'img') return;
var n = l.getAttribute('cke_src'),
o = l.getAttribute('title'),
p = a.document.createElement('img', {
attributes: {
src: n,
_cke_saved_src: n,
title: o,
alt: o
}
});
a.insertElement(p);
f.hide();
},
h = CKEDITOR.tools.addFunction(function (k, l) {
k = new CKEDITOR.dom.event(k);
l = new CKEDITOR.dom.element(l);
var m, n, o = k.getKeystroke();
switch (o) {
case 39:
if (m = l.getParent().getNext()) {
n = m.getChild(0);
n.focus();
}
k.preventDefault();
break;
case 37:
if (m = l.getParent().getPrevious()) {
n = m.getChild(0);
n.focus();
}
k.preventDefault();
break;
case 38:
if (m = l.getParent().getParent().getPrevious()) {
n = m.getChild([l.getParent().getIndex(), 0]);
n.focus();
}
k.preventDefault();
break;
case 40:
if (m = l.getParent().getParent().getNext()) {
n = m.getChild([l.getParent().getIndex(), 0]);
if (n) n.focus();
}
k.preventDefault();
break;
case 32:
g({
data: k
});
k.preventDefault();
break;
case 9:
if (m = l.getParent().getNext()) {
n = m.getChild(0);
n.focus();
k.preventDefault(true);
} else if (m = l.getParent().getParent().getNext()) {
n = m.getChild([0, 0]);
if (n) n.focus();
k.preventDefault(true);
}
break;
case CKEDITOR.SHIFT + 9:
if (m = l.getParent().getPrevious()) {
n = m.getChild(0);
n.focus();
k.preventDefault(true);
} else if (m = l.getParent().getParent().getPrevious()) {
n = m.getLast().getChild(0);
n.focus();
k.preventDefault(true);
}
break;
default:
return;
}
}),
i = ['<table cellspacing="2" cellpadding="2"', CKEDITOR.env.ie && CKEDITOR.env.quirks ? ' style="position:absolute;"' : '', '><tbody>'];
for (e = 0; e < c.length; e++) {
if (e % d === 0) i.push('<tr>');
i.push('<td class="cke_dark_background cke_hand cke_centered" style="vertical-align: middle;"><a href="javascript:void(0)" class="cke_smile" tabindex="-1" onkeydown="CKEDITOR.tools.callFunction( ', h, ', event, this );">', '<img class="hand" title="', b.fileicon_descriptions[e], '" cke_src="', CKEDITOR.tools.htmlEncode(b.fileicon_path + c[e]), '" alt="', b.fileicon_descriptions[e], '"', ' src="', CKEDITOR.tools.htmlEncode(b.fileicon_path + c[e]), '"', CKEDITOR.env.ie ? " onload=\"this.setAttribute('width', 2); this.removeAttribute('width');\" " : '', '></a>', '</td>');
if (e % d == d - 1) i.push('</tr>');
}
if (e < d - 1) {
for (; e < d - 1; e++) i.push('<td></td>');
i.push('</tr>');
}
i.push('</tbody></table>');
var j = {
type: 'html',
html: i.join(''),
onLoad: function (k) {
f = k.sender;
},
focus: function () {
var k = this.getElement().getChild([0, 0, 0, 0]);
k.focus();
},
onClick: g,
style: 'width: 100%; height: 100%; border-collapse: separate;'
};
return {
title: a.lang.fileicon.title,
minWidth: 280,
minHeight: 150,
contents: [{
id: 'tab1',
label: '',
title: '',
expand: true,
padding: 0,
elements: [j]
}],
buttons: [CKEDITOR.dialog.cancelButton]
};
});
|
bundocba/unitedworld
|
plugins/editors/jckeditor/plugins/fileicon/dialogs/fileicon.js
|
JavaScript
|
gpl-2.0
| 5,136
|
/**
* @file
* Appearance settings.
*/
(function ($, Drupal) {
Drupal.behaviors.atCoreLayoutVisualization = {
attach: function () {
$('#edit-layout-select select[id*="edit-settings-page-"]').change(function(){
$('#' + $(this).attr('id')).parent().next().children().removeClass().addClass(this.value);
});
}
};
}(jQuery, Drupal));
|
raidho93/buildrace
|
themes/adaptivetheme/at_core/scripts/at.appearance.js
|
JavaScript
|
gpl-2.0
| 364
|
/*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/xr19rel/WINNT_5.2_Depend/mozilla/netwerk/base/public/nsIIOService.idl
*/
#ifndef __gen_nsIIOService_h__
#define __gen_nsIIOService_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIProtocolHandler; /* forward declaration */
class nsIChannel; /* forward declaration */
class nsIURI; /* forward declaration */
class nsIFile; /* forward declaration */
/* starting interface: nsIIOService */
#define NS_IIOSERVICE_IID_STR "bddeda3f-9020-4d12-8c70-984ee9f7935e"
#define NS_IIOSERVICE_IID \
{0xbddeda3f, 0x9020, 0x4d12, \
{ 0x8c, 0x70, 0x98, 0x4e, 0xe9, 0xf7, 0x93, 0x5e }}
/**
* nsIIOService provides a set of network utility functions. This interface
* duplicates many of the nsIProtocolHandler methods in a protocol handler
* independent way (e.g., NewURI inspects the scheme in order to delegate
* creation of the new URI to the appropriate protocol handler). nsIIOService
* also provides a set of URL parsing utility functions. These are provided
* as a convenience to the programmer and in some cases to improve performance
* by eliminating intermediate data structures and interfaces.
*
* @status FROZEN
*/
class NS_NO_VTABLE NS_SCRIPTABLE nsIIOService : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IIOSERVICE_IID)
/**
* Returns a protocol handler for a given URI scheme.
*
* @param aScheme the URI scheme
* @return reference to corresponding nsIProtocolHandler
*/
/* nsIProtocolHandler getProtocolHandler (in string aScheme); */
NS_SCRIPTABLE NS_IMETHOD GetProtocolHandler(const char *aScheme, nsIProtocolHandler **_retval) = 0;
/**
* Returns the protocol flags for a given scheme.
*
* @param aScheme the URI scheme
* @return value of corresponding nsIProtocolHandler::protocolFlags
*/
/* unsigned long getProtocolFlags (in string aScheme); */
NS_SCRIPTABLE NS_IMETHOD GetProtocolFlags(const char *aScheme, PRUint32 *_retval) = 0;
/**
* This method constructs a new URI by determining the scheme of the
* URI spec, and then delegating the construction of the URI to the
* protocol handler for that scheme. QueryInterface can be used on
* the resulting URI object to obtain a more specific type of URI.
*
* @see nsIProtocolHandler::newURI
*/
/* nsIURI newURI (in AUTF8String aSpec, in string aOriginCharset, in nsIURI aBaseURI); */
NS_SCRIPTABLE NS_IMETHOD NewURI(const nsACString & aSpec, const char *aOriginCharset, nsIURI *aBaseURI, nsIURI **_retval) = 0;
/**
* This method constructs a new URI from a nsIFile.
*
* @param aFile specifies the file path
* @return reference to a new nsIURI object
*/
/* nsIURI newFileURI (in nsIFile aFile); */
NS_SCRIPTABLE NS_IMETHOD NewFileURI(nsIFile *aFile, nsIURI **_retval) = 0;
/**
* Creates a channel for a given URI.
*
* @param aURI nsIURI from which to make a channel
* @return reference to the new nsIChannel object
*/
/* nsIChannel newChannelFromURI (in nsIURI aURI); */
NS_SCRIPTABLE NS_IMETHOD NewChannelFromURI(nsIURI *aURI, nsIChannel **_retval) = 0;
/**
* Equivalent to newChannelFromURI(newURI(...))
*/
/* nsIChannel newChannel (in AUTF8String aSpec, in string aOriginCharset, in nsIURI aBaseURI); */
NS_SCRIPTABLE NS_IMETHOD NewChannel(const nsACString & aSpec, const char *aOriginCharset, nsIURI *aBaseURI, nsIChannel **_retval) = 0;
/**
* Returns true if networking is in "offline" mode. When in offline mode,
* attempts to access the network will fail (although this does not
* necessarily correlate with whether there is actually a network
* available -- that's hard to detect without causing the dialer to
* come up).
*
* Changing this fires observer notifications ... see below.
*/
/* attribute boolean offline; */
NS_SCRIPTABLE NS_IMETHOD GetOffline(PRBool *aOffline) = 0;
NS_SCRIPTABLE NS_IMETHOD SetOffline(PRBool aOffline) = 0;
/**
* Checks if a port number is banned. This involves consulting a list of
* unsafe ports, corresponding to network services that may be easily
* exploitable. If the given port is considered unsafe, then the protocol
* handler (corresponding to aScheme) will be asked whether it wishes to
* override the IO service's decision to block the port. This gives the
* protocol handler ultimate control over its own security policy while
* ensuring reasonable, default protection.
*
* @see nsIProtocolHandler::allowPort
*/
/* boolean allowPort (in long aPort, in string aScheme); */
NS_SCRIPTABLE NS_IMETHOD AllowPort(PRInt32 aPort, const char *aScheme, PRBool *_retval) = 0;
/**
* Utility to extract the scheme from a URL string, consistently and
* according to spec (see RFC 2396).
*
* NOTE: Most URL parsing is done via nsIURI, and in fact the scheme
* can also be extracted from a URL string via nsIURI. This method
* is provided purely as an optimization.
*
* @param aSpec the URL string to parse
* @return URL scheme
*
* @throws NS_ERROR_MALFORMED_URI if URL string is not of the right form.
*/
/* ACString extractScheme (in AUTF8String urlString); */
NS_SCRIPTABLE NS_IMETHOD ExtractScheme(const nsACString & urlString, nsACString & _retval) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIIOService, NS_IIOSERVICE_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIIOSERVICE \
NS_SCRIPTABLE NS_IMETHOD GetProtocolHandler(const char *aScheme, nsIProtocolHandler **_retval); \
NS_SCRIPTABLE NS_IMETHOD GetProtocolFlags(const char *aScheme, PRUint32 *_retval); \
NS_SCRIPTABLE NS_IMETHOD NewURI(const nsACString & aSpec, const char *aOriginCharset, nsIURI *aBaseURI, nsIURI **_retval); \
NS_SCRIPTABLE NS_IMETHOD NewFileURI(nsIFile *aFile, nsIURI **_retval); \
NS_SCRIPTABLE NS_IMETHOD NewChannelFromURI(nsIURI *aURI, nsIChannel **_retval); \
NS_SCRIPTABLE NS_IMETHOD NewChannel(const nsACString & aSpec, const char *aOriginCharset, nsIURI *aBaseURI, nsIChannel **_retval); \
NS_SCRIPTABLE NS_IMETHOD GetOffline(PRBool *aOffline); \
NS_SCRIPTABLE NS_IMETHOD SetOffline(PRBool aOffline); \
NS_SCRIPTABLE NS_IMETHOD AllowPort(PRInt32 aPort, const char *aScheme, PRBool *_retval); \
NS_SCRIPTABLE NS_IMETHOD ExtractScheme(const nsACString & urlString, nsACString & _retval);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIIOSERVICE(_to) \
NS_SCRIPTABLE NS_IMETHOD GetProtocolHandler(const char *aScheme, nsIProtocolHandler **_retval) { return _to GetProtocolHandler(aScheme, _retval); } \
NS_SCRIPTABLE NS_IMETHOD GetProtocolFlags(const char *aScheme, PRUint32 *_retval) { return _to GetProtocolFlags(aScheme, _retval); } \
NS_SCRIPTABLE NS_IMETHOD NewURI(const nsACString & aSpec, const char *aOriginCharset, nsIURI *aBaseURI, nsIURI **_retval) { return _to NewURI(aSpec, aOriginCharset, aBaseURI, _retval); } \
NS_SCRIPTABLE NS_IMETHOD NewFileURI(nsIFile *aFile, nsIURI **_retval) { return _to NewFileURI(aFile, _retval); } \
NS_SCRIPTABLE NS_IMETHOD NewChannelFromURI(nsIURI *aURI, nsIChannel **_retval) { return _to NewChannelFromURI(aURI, _retval); } \
NS_SCRIPTABLE NS_IMETHOD NewChannel(const nsACString & aSpec, const char *aOriginCharset, nsIURI *aBaseURI, nsIChannel **_retval) { return _to NewChannel(aSpec, aOriginCharset, aBaseURI, _retval); } \
NS_SCRIPTABLE NS_IMETHOD GetOffline(PRBool *aOffline) { return _to GetOffline(aOffline); } \
NS_SCRIPTABLE NS_IMETHOD SetOffline(PRBool aOffline) { return _to SetOffline(aOffline); } \
NS_SCRIPTABLE NS_IMETHOD AllowPort(PRInt32 aPort, const char *aScheme, PRBool *_retval) { return _to AllowPort(aPort, aScheme, _retval); } \
NS_SCRIPTABLE NS_IMETHOD ExtractScheme(const nsACString & urlString, nsACString & _retval) { return _to ExtractScheme(urlString, _retval); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIIOSERVICE(_to) \
NS_SCRIPTABLE NS_IMETHOD GetProtocolHandler(const char *aScheme, nsIProtocolHandler **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetProtocolHandler(aScheme, _retval); } \
NS_SCRIPTABLE NS_IMETHOD GetProtocolFlags(const char *aScheme, PRUint32 *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetProtocolFlags(aScheme, _retval); } \
NS_SCRIPTABLE NS_IMETHOD NewURI(const nsACString & aSpec, const char *aOriginCharset, nsIURI *aBaseURI, nsIURI **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->NewURI(aSpec, aOriginCharset, aBaseURI, _retval); } \
NS_SCRIPTABLE NS_IMETHOD NewFileURI(nsIFile *aFile, nsIURI **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->NewFileURI(aFile, _retval); } \
NS_SCRIPTABLE NS_IMETHOD NewChannelFromURI(nsIURI *aURI, nsIChannel **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->NewChannelFromURI(aURI, _retval); } \
NS_SCRIPTABLE NS_IMETHOD NewChannel(const nsACString & aSpec, const char *aOriginCharset, nsIURI *aBaseURI, nsIChannel **_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->NewChannel(aSpec, aOriginCharset, aBaseURI, _retval); } \
NS_SCRIPTABLE NS_IMETHOD GetOffline(PRBool *aOffline) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetOffline(aOffline); } \
NS_SCRIPTABLE NS_IMETHOD SetOffline(PRBool aOffline) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetOffline(aOffline); } \
NS_SCRIPTABLE NS_IMETHOD AllowPort(PRInt32 aPort, const char *aScheme, PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->AllowPort(aPort, aScheme, _retval); } \
NS_SCRIPTABLE NS_IMETHOD ExtractScheme(const nsACString & urlString, nsACString & _retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->ExtractScheme(urlString, _retval); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsIOService : public nsIIOService
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIIOSERVICE
nsIOService();
private:
~nsIOService();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsIOService, nsIIOService)
nsIOService::nsIOService()
{
/* member initializers and constructor code */
}
nsIOService::~nsIOService()
{
/* destructor code */
}
/* nsIProtocolHandler getProtocolHandler (in string aScheme); */
NS_IMETHODIMP nsIOService::GetProtocolHandler(const char *aScheme, nsIProtocolHandler **_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* unsigned long getProtocolFlags (in string aScheme); */
NS_IMETHODIMP nsIOService::GetProtocolFlags(const char *aScheme, PRUint32 *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIURI newURI (in AUTF8String aSpec, in string aOriginCharset, in nsIURI aBaseURI); */
NS_IMETHODIMP nsIOService::NewURI(const nsACString & aSpec, const char *aOriginCharset, nsIURI *aBaseURI, nsIURI **_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIURI newFileURI (in nsIFile aFile); */
NS_IMETHODIMP nsIOService::NewFileURI(nsIFile *aFile, nsIURI **_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIChannel newChannelFromURI (in nsIURI aURI); */
NS_IMETHODIMP nsIOService::NewChannelFromURI(nsIURI *aURI, nsIChannel **_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIChannel newChannel (in AUTF8String aSpec, in string aOriginCharset, in nsIURI aBaseURI); */
NS_IMETHODIMP nsIOService::NewChannel(const nsACString & aSpec, const char *aOriginCharset, nsIURI *aBaseURI, nsIChannel **_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute boolean offline; */
NS_IMETHODIMP nsIOService::GetOffline(PRBool *aOffline)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsIOService::SetOffline(PRBool aOffline)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* boolean allowPort (in long aPort, in string aScheme); */
NS_IMETHODIMP nsIOService::AllowPort(PRInt32 aPort, const char *aScheme, PRBool *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* ACString extractScheme (in AUTF8String urlString); */
NS_IMETHODIMP nsIOService::ExtractScheme(const nsACString & urlString, nsACString & _retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
/**
* We send notifications through nsIObserverService with topic
* NS_IOSERVICE_GOING_OFFLINE_TOPIC and data NS_IOSERVICE_OFFLINE
* when 'offline' has changed from false to true, and we are about
* to shut down network services such as DNS. When those
* services have been shut down, we send a notification with
* topic NS_IOSERVICE_OFFLINE_STATUS_TOPIC and data
* NS_IOSERVICE_OFFLINE.
*
* When 'offline' changes from true to false, then after
* network services have been restarted, we send a notification
* with topic NS_IOSERVICE_OFFLINE_STATUS_TOPIC and data
* NS_IOSERVICE_ONLINE.
*/
#define NS_IOSERVICE_GOING_OFFLINE_TOPIC "network:offline-about-to-go-offline"
#define NS_IOSERVICE_OFFLINE_STATUS_TOPIC "network:offline-status-changed"
#define NS_IOSERVICE_OFFLINE "offline"
#define NS_IOSERVICE_ONLINE "online"
#endif /* __gen_nsIIOService_h__ */
|
nikgoodley-ibboost/forklabs-javaxpcom
|
tools/xulrunner-1.9.0.13-sdk/sdk/include/nsIIOService.h
|
C
|
gpl-2.0
| 13,706
|
/* Definition for thread-local data handling. NPTL/SH version.
Copyright (C) 2003-2017 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#ifndef _TLS_H
#define _TLS_H
# include <dl-sysdep.h>
#ifndef __ASSEMBLER__
# include <stdbool.h>
# include <stddef.h>
# include <stdint.h>
# include <stdlib.h>
# include <list.h>
# include <sysdep.h>
# include <dl-dtv.h>
typedef struct
{
dtv_t *dtv;
uintptr_t pointer_guard;
} tcbhead_t;
# define TLS_MULTIPLE_THREADS_IN_TCB 1
#else /* __ASSEMBLER__ */
# include <tcb-offsets.h>
#endif /* __ASSEMBLER__ */
#ifndef __ASSEMBLER__
/* Get system call information. */
# include <sysdep.h>
/* This is the size of the initial TCB. */
# define TLS_INIT_TCB_SIZE sizeof (tcbhead_t)
/* Alignment requirements for the initial TCB. */
# define TLS_INIT_TCB_ALIGN __alignof__ (tcbhead_t)
/* This is the size of the TCB. */
# define TLS_TCB_SIZE sizeof (tcbhead_t)
/* This is the size we need before TCB. */
# define TLS_PRE_TCB_SIZE sizeof (struct pthread)
/* Alignment requirements for the TCB. */
# define TLS_TCB_ALIGN __alignof__ (struct pthread)
/* The TLS blocks start right after the TCB. */
# define TLS_DTV_AT_TP 1
# define TLS_TCB_AT_TP 0
/* Get the thread descriptor definition. */
# include <nptl/descr.h>
/* Install the dtv pointer. The pointer passed is to the element with
index -1 which contain the length. */
# define INSTALL_DTV(tcbp, dtvp) \
((tcbhead_t *) (tcbp))->dtv = (dtvp) + 1
/* Install new dtv for current thread. */
# define INSTALL_NEW_DTV(dtv) \
({ tcbhead_t *__tcbp; \
__asm __volatile ("stc gbr,%0" : "=r" (__tcbp)); \
__tcbp->dtv = (dtv);})
/* Return dtv of given thread descriptor. */
# define GET_DTV(tcbp) \
(((tcbhead_t *) (tcbp))->dtv)
/* Code to initially initialize the thread pointer. This might need
special attention since 'errno' is not yet available and if the
operation can cause a failure 'errno' must not be touched. */
# define TLS_INIT_TP(tcbp) \
({ __asm __volatile ("ldc %0,gbr" : : "r" (tcbp)); NULL; })
# define TLS_DEFINE_INIT_TP(tp, pd) void *tp = (pd) + 1
/* Return the address of the dtv for the current thread. */
# define THREAD_DTV() \
({ tcbhead_t *__tcbp; \
__asm __volatile ("stc gbr,%0" : "=r" (__tcbp)); \
__tcbp->dtv;})
/* Return the thread descriptor for the current thread.
The contained asm must *not* be marked volatile since otherwise
assignments like
struct pthread *self = thread_self();
do not get optimized away. */
# define THREAD_SELF \
({ struct pthread *__self; \
__asm ("stc gbr,%0" : "=r" (__self)); \
__self - 1;})
/* Magic for libthread_db to know how to do THREAD_SELF. */
# define DB_THREAD_SELF \
REGISTER (32, 32, REG_GBR * 4, -sizeof (struct pthread))
/* Read member of the thread descriptor directly. */
# define THREAD_GETMEM(descr, member) (descr->member)
/* Same as THREAD_GETMEM, but the member offset can be non-constant. */
# define THREAD_GETMEM_NC(descr, member, idx) (descr->member[idx])
/* Set member of the thread descriptor directly. */
# define THREAD_SETMEM(descr, member, value) \
descr->member = (value)
/* Same as THREAD_SETMEM, but the member offset can be non-constant. */
# define THREAD_SETMEM_NC(descr, member, idx, value) \
descr->member[idx] = (value)
#define THREAD_GET_POINTER_GUARD() \
({ tcbhead_t *__tcbp; \
__asm __volatile ("stc gbr,%0" : "=r" (__tcbp)); \
__tcbp->pointer_guard;})
#define THREAD_SET_POINTER_GUARD(value) \
({ tcbhead_t *__tcbp; \
__asm __volatile ("stc gbr,%0" : "=r" (__tcbp)); \
__tcbp->pointer_guard = (value);})
#define THREAD_COPY_POINTER_GUARD(descr) \
({ tcbhead_t *__tcbp; \
__asm __volatile ("stc gbr,%0" : "=r" (__tcbp)); \
((tcbhead_t *) (descr + 1))->pointer_guard = __tcbp->pointer_guard;})
/* Get and set the global scope generation counter in struct pthread. */
#define THREAD_GSCOPE_FLAG_UNUSED 0
#define THREAD_GSCOPE_FLAG_USED 1
#define THREAD_GSCOPE_FLAG_WAIT 2
#define THREAD_GSCOPE_RESET_FLAG() \
do \
{ int __res \
= atomic_exchange_rel (&THREAD_SELF->header.gscope_flag, \
THREAD_GSCOPE_FLAG_UNUSED); \
if (__res == THREAD_GSCOPE_FLAG_WAIT) \
lll_futex_wake (&THREAD_SELF->header.gscope_flag, 1, LLL_PRIVATE); \
} \
while (0)
#define THREAD_GSCOPE_SET_FLAG() \
do \
{ \
THREAD_SELF->header.gscope_flag = THREAD_GSCOPE_FLAG_USED; \
atomic_write_barrier (); \
} \
while (0)
#define THREAD_GSCOPE_WAIT() \
GL(dl_wait_lookup_done) ()
#endif /* __ASSEMBLER__ */
#endif /* tls.h */
|
NicoleRobin/glibc
|
sysdeps/sh/nptl/tls.h
|
C
|
gpl-2.0
| 5,537
|
/* -*- c++ -*- ----------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
https://www.lammps.org/, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#ifdef DIHEDRAL_CLASS
// clang-format off
DihedralStyle(quadratic,DihedralQuadratic);
// clang-format on
#else
#ifndef LMP_DIHEDRAL_QUADRATIC_H
#define LMP_DIHEDRAL_QUADRATIC_H
#include "dihedral.h"
namespace LAMMPS_NS {
class DihedralQuadratic : public Dihedral {
public:
DihedralQuadratic(class LAMMPS *);
~DihedralQuadratic() override;
void compute(int, int) override;
void coeff(int, char **) override;
void write_restart(FILE *) override;
void read_restart(FILE *) override;
void write_data(FILE *) override;
protected:
double *k, *phi0;
int *sign, *multiplicity;
void allocate();
};
} // namespace LAMMPS_NS
#endif
#endif
|
akohlmey/lammps
|
src/EXTRA-MOLECULE/dihedral_quadratic.h
|
C
|
gpl-2.0
| 1,288
|
<?php
/**
*
* NOTICE OF LICENSE
*
* This source file is subject to the GNU General Public License (GPL 3)
* that is bundled with this package in the file LICENSE.txt
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Payone to newer
* versions in the future. If you wish to customize Payone for your
* needs please refer to http://www.payone.de for more information.
*
* @category Payone
* @package Payone_ClientApi
* @subpackage Service
* @copyright Copyright (c) 2012 <info@noovias.com> - www.noovias.com
* @author Matthias Walter <info@noovias.com>
* @license <http://www.gnu.org/licenses/> GNU General Public License (GPL 3)
* @link http://www.noovias.com
*/
/**
*
* @category Payone
* @package Payone_ClientApi
* @subpackage Service
* @copyright Copyright (c) 2012 <info@noovias.com> - www.noovias.com
* @license <http://www.gnu.org/licenses/> GNU General Public License (GPL 3)
* @link http://www.noovias.com
*/
class Payone_ClientApi_Service_GenerateHash
{
protected $hashParameters = array(
'mid',
'amount',
'productid',
'aid',
'currency',
'accessname',
'portalid',
'due_time',
'accesscode',
'mode',
'storecarddata',
'access_expiretime',
'request',
'checktype',
'access_canceltime',
'responsetype',
'addresschecktype',
'access_starttime',
'reference',
'consumerscoretype',
'access_period',
'userid',
'invoiceid',
'access_aboperiod',
'customerid',
'invoiceappendix',
'access_price',
'param',
'invoice_deliverymode',
'access_aboprice',
'narrative_text',
'eci',
'access_vat',
'successurl',
'settleperiod',
'errorurl',
'settletime',
'backurl',
'vaccountname',
'exiturl',
'vreference',
'clearingtype',
'encoding',
// @todo Item parameters not supported
// 'id[x]', 'pr[x]', 'no[x]', 'de[x]', 'ti[x]', 'va[x]',
// 'id', 'pr', 'no', 'de', 'ti', 'va',
);
/**
* @param Payone_ClientApi_Request_Interface $request All parameters of the request
* @param string $securityKey Payone security key
*
* @return string The hash
* @throws Payone_ClientApi_Exception_InvalidParameters
*/
public function generate(Payone_ClientApi_Request_Interface $request, $securityKey)
{
$requestData = $request->toArray();
sort($this->hashParameters);
$hashString = '';
foreach ($this->hashParameters as $key) {
if (!array_key_exists($key, $requestData)) {
continue;
}
$hashString .= $requestData[$key];
}
$hashString .= $securityKey;
$hash = md5($hashString);
return $hash;
}
}
|
dsiekiera/modified-bs4
|
includes/external/payone/php/Payone/ClientApi/Service/GenerateHash.php
|
PHP
|
gpl-2.0
| 3,048
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <sys/utsname.h>
#include "architecture.h"
#include "macro.h"
#include "string-table.h"
#include "string-util.h"
int uname_architecture(void) {
/* Return a sanitized enum identifying the architecture we are
* running on. This is based on uname(), and the user may
* hence control what this returns by using
* personality(). This puts the user in control on systems
* that can run binaries of multiple architectures.
*
* We do not translate the string returned by uname()
* 1:1. Instead we try to clean it up and break down the
* confusion on x86 and arm in particular.
*
* We do not try to distinguish CPUs not CPU features, but
* actual architectures, i.e. that have genuinely different
* code. */
static const struct {
const char *machine;
int arch;
} arch_map[] = {
#if defined(__x86_64__) || defined(__i386__)
{ "x86_64", ARCHITECTURE_X86_64 },
{ "i686", ARCHITECTURE_X86 },
{ "i586", ARCHITECTURE_X86 },
{ "i486", ARCHITECTURE_X86 },
{ "i386", ARCHITECTURE_X86 },
#elif defined(__powerpc__) || defined(__powerpc64__)
{ "ppc64", ARCHITECTURE_PPC64 },
{ "ppc64le", ARCHITECTURE_PPC64_LE },
{ "ppc", ARCHITECTURE_PPC },
{ "ppcle", ARCHITECTURE_PPC_LE },
#elif defined(__ia64__)
{ "ia64", ARCHITECTURE_IA64 },
#elif defined(__hppa__) || defined(__hppa64__)
{ "parisc64", ARCHITECTURE_PARISC64 },
{ "parisc", ARCHITECTURE_PARISC },
#elif defined(__s390__) || defined(__s390x__)
{ "s390x", ARCHITECTURE_S390X },
{ "s390", ARCHITECTURE_S390 },
#elif defined(__sparc__)
{ "sparc64", ARCHITECTURE_SPARC64 },
{ "sparc", ARCHITECTURE_SPARC },
#elif defined(__mips__) || defined(__mips64__)
{ "mips64", ARCHITECTURE_MIPS64 },
{ "mips", ARCHITECTURE_MIPS },
#elif defined(__alpha__)
{ "alpha" , ARCHITECTURE_ALPHA },
#elif defined(__arm__) || defined(__aarch64__)
{ "aarch64", ARCHITECTURE_ARM64 },
{ "aarch64_be", ARCHITECTURE_ARM64_BE },
{ "armv4l", ARCHITECTURE_ARM },
{ "armv4b", ARCHITECTURE_ARM_BE },
{ "armv4tl", ARCHITECTURE_ARM },
{ "armv4tb", ARCHITECTURE_ARM_BE },
{ "armv5tl", ARCHITECTURE_ARM },
{ "armv5tb", ARCHITECTURE_ARM_BE },
{ "armv5tel", ARCHITECTURE_ARM },
{ "armv5teb" , ARCHITECTURE_ARM_BE },
{ "armv5tejl", ARCHITECTURE_ARM },
{ "armv5tejb", ARCHITECTURE_ARM_BE },
{ "armv6l", ARCHITECTURE_ARM },
{ "armv6b", ARCHITECTURE_ARM_BE },
{ "armv7l", ARCHITECTURE_ARM },
{ "armv7b", ARCHITECTURE_ARM_BE },
{ "armv7ml", ARCHITECTURE_ARM },
{ "armv7mb", ARCHITECTURE_ARM_BE },
{ "armv4l", ARCHITECTURE_ARM },
{ "armv4b", ARCHITECTURE_ARM_BE },
{ "armv4tl", ARCHITECTURE_ARM },
{ "armv4tb", ARCHITECTURE_ARM_BE },
{ "armv5tl", ARCHITECTURE_ARM },
{ "armv5tb", ARCHITECTURE_ARM_BE },
{ "armv5tel", ARCHITECTURE_ARM },
{ "armv5teb", ARCHITECTURE_ARM_BE },
{ "armv5tejl", ARCHITECTURE_ARM },
{ "armv5tejb", ARCHITECTURE_ARM_BE },
{ "armv6l", ARCHITECTURE_ARM },
{ "armv6b", ARCHITECTURE_ARM_BE },
{ "armv7l", ARCHITECTURE_ARM },
{ "armv7b", ARCHITECTURE_ARM_BE },
{ "armv7ml", ARCHITECTURE_ARM },
{ "armv7mb", ARCHITECTURE_ARM_BE },
{ "armv8l", ARCHITECTURE_ARM },
{ "armv8b", ARCHITECTURE_ARM_BE },
#elif defined(__sh__) || defined(__sh64__)
{ "sh5", ARCHITECTURE_SH64 },
{ "sh2", ARCHITECTURE_SH },
{ "sh2a", ARCHITECTURE_SH },
{ "sh3", ARCHITECTURE_SH },
{ "sh4", ARCHITECTURE_SH },
{ "sh4a", ARCHITECTURE_SH },
#elif defined(__m68k__)
{ "m68k", ARCHITECTURE_M68K },
#elif defined(__tilegx__)
{ "tilegx", ARCHITECTURE_TILEGX },
#elif defined(__cris__)
{ "crisv32", ARCHITECTURE_CRIS },
#elif defined(__nios2__)
{ "nios2", ARCHITECTURE_NIOS2 },
#elif defined(__riscv__) || defined(__riscv)
/* __riscv__ is obsolete, remove in 2018 */
{ "riscv32", ARCHITECTURE_RISCV32 },
{ "riscv64", ARCHITECTURE_RISCV64 },
# if __SIZEOF_POINTER__ == 4
{ "riscv", ARCHITECTURE_RISCV32 },
# elif __SIZEOF_POINTER__ == 8
{ "riscv", ARCHITECTURE_RISCV64 },
# endif
#elif defined(__arc__)
{ "arc", ARCHITECTURE_ARC },
{ "arceb", ARCHITECTURE_ARC_BE },
#else
#error "Please register your architecture here!"
#endif
};
static int cached = _ARCHITECTURE_INVALID;
struct utsname u;
unsigned i;
if (cached != _ARCHITECTURE_INVALID)
return cached;
assert_se(uname(&u) >= 0);
for (i = 0; i < ELEMENTSOF(arch_map); i++)
if (streq(arch_map[i].machine, u.machine))
return cached = arch_map[i].arch;
assert_not_reached("Couldn't identify architecture. You need to patch systemd.");
return _ARCHITECTURE_INVALID;
}
static const char *const architecture_table[_ARCHITECTURE_MAX] = {
[ARCHITECTURE_X86] = "x86",
[ARCHITECTURE_X86_64] = "x86-64",
[ARCHITECTURE_PPC] = "ppc",
[ARCHITECTURE_PPC_LE] = "ppc-le",
[ARCHITECTURE_PPC64] = "ppc64",
[ARCHITECTURE_PPC64_LE] = "ppc64-le",
[ARCHITECTURE_IA64] = "ia64",
[ARCHITECTURE_PARISC] = "parisc",
[ARCHITECTURE_PARISC64] = "parisc64",
[ARCHITECTURE_S390] = "s390",
[ARCHITECTURE_S390X] = "s390x",
[ARCHITECTURE_SPARC] = "sparc",
[ARCHITECTURE_SPARC64] = "sparc64",
[ARCHITECTURE_MIPS] = "mips",
[ARCHITECTURE_MIPS_LE] = "mips-le",
[ARCHITECTURE_MIPS64] = "mips64",
[ARCHITECTURE_MIPS64_LE] = "mips64-le",
[ARCHITECTURE_ALPHA] = "alpha",
[ARCHITECTURE_ARM] = "arm",
[ARCHITECTURE_ARM_BE] = "arm-be",
[ARCHITECTURE_ARM64] = "arm64",
[ARCHITECTURE_ARM64_BE] = "arm64-be",
[ARCHITECTURE_SH] = "sh",
[ARCHITECTURE_SH64] = "sh64",
[ARCHITECTURE_M68K] = "m68k",
[ARCHITECTURE_TILEGX] = "tilegx",
[ARCHITECTURE_CRIS] = "cris",
[ARCHITECTURE_NIOS2] = "nios2",
[ARCHITECTURE_RISCV32] = "riscv32",
[ARCHITECTURE_RISCV64] = "riscv64",
[ARCHITECTURE_ARC] = "arc",
[ARCHITECTURE_ARC_BE] = "arc-be",
};
DEFINE_STRING_TABLE_LOOKUP(architecture, int);
|
phomes/systemd
|
src/basic/architecture.c
|
C
|
gpl-2.0
| 7,739
|
!
! Copyright (C) 2001-2013 Quantum ESPRESSO group
! This file is distributed under the terms of the
! GNU General Public License. See the file `License'
! in the root directory of the present distribution,
! or http://www.gnu.org/copyleft/gpl.txt .
!
!
!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
! this routine initializes some variables for DFT+U
! calculation, in particular atomic wfc
!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
!-----------------------------------------------------------------------
SUBROUTINE orthoUwfc_k(ik)
!-----------------------------------------------------------------------
!
! This routine is meant to orthogonalize all the atomic wfcs. This is
! useful when we want to compute the occupation of the atomic orbitals
! in order to make lda+U calculations
!
USE kinds, ONLY : DP
USE io_global, ONLY : stdout
USE io_files, ONLY : iunhub, nwordwfcU, diropn
USE ions_base, ONLY : nat
USE basis, ONLY : natomwfc, swfcatom
USE klist, ONLY : nks, xk, ngk
USE ldaU, ONLY : U_projection, wfcU, nwfcU, copy_U_wfc
USE wvfct, ONLY : npwx, npw, igk
USE uspp, ONLY : nkb, vkb
USE becmod, ONLY : allocate_bec_type, deallocate_bec_type, becp, calbec
USE control_flags, ONLY : gamma_only
USE noncollin_module, ONLY : noncolin, npol
!
IMPLICIT NONE
!
INTEGER :: ik, ibnd, info, i, j, k, na, nb, nt, isym, n, ntemp, m, &
l, lm, ltot, ntot, ipol
! the k point under consideration
! counter on bands
LOGICAL :: orthogonalize_wfc, normalize_only
COMPLEX(DP) , ALLOCATABLE :: wfcatom (:,:)
LOGICAL :: exst
ALLOCATE (wfcatom( npwx*npol, natomwfc),swfcatom(npwx*npol, natomwfc))
IF ( U_projection == "pseudo" ) THEN
WRITE(stdout,'(8x,a)') &
'! Beta functions used for LDA+U Projector'
RETURN
ELSE IF (U_projection=="file") THEN
WRITE(stdout,'(8x,a)') &
'! LDA+U Projector read from file '
RETURN
ELSE IF (U_projection=="atomic") THEN
orthogonalize_wfc = .FALSE.
normalize_only = .FALSE.
WRITE(stdout,'(8x,a)') &
'! Atomic wfc used for LDA+U Projector are NOT orthogonalized'
ELSE IF (U_projection=="ortho-atomic") THEN
orthogonalize_wfc = .TRUE.
normalize_only = .FALSE.
WRITE(stdout,'(8x,a)') &
'! Atomic wfc used for LDA+U Projector are orthogonalized'
IF (gamma_only) CALL errore('orthoatwfc', &
'Gamma-only calculation for this case not implemented', 1 )
ELSE IF (U_projection=="norm-atomic") THEN
orthogonalize_wfc = .TRUE.
normalize_only = .TRUE.
WRITE(stdout,'(8x,a)') &
'! Atomic wfc used for LDA+U Projector are normalized but NOT orthogonalized'
IF (gamma_only) CALL errore('orthoatwfc', &
'Gamma-only calculation for this case not implemented', 1 )
ELSE
WRITE(stdout,'(8x,a)') &
"! U_projection_type =", U_projection
CALL errore ("orthoatwfc"," this U_projection_type is not valid",1)
END IF
CALL allocate_bec_type (nkb,natomwfc, becp)
! Allocate the array becp = <beta|wfcatom>
CALL atomic_wfc (ik, wfcatom)
call init_us_2(npw, igk, xk (1, ik), vkb)
CALL calbec (npw, vkb, wfcatom, becp)
CALL s_psi (npwx, npw, natomwfc, wfcatom, swfcatom)
IF (orthogonalize_wfc) &
CALL ortho_swfc ( normalize_only, natomwfc, wfcatom, swfcatom )
!
CALL copy_U_wfc (swfcatom)
!
DEALLOCATE (wfcatom)
DEALLOCATE (swfcatom)
CALL deallocate_bec_type (becp )
!
RETURN
END SUBROUTINE orthoUwfc_k
|
maxhutch/quantum-espresso
|
XSpectra/src/orthoUatwfc_k.f90
|
FORTRAN
|
gpl-2.0
| 3,548
|
#include <ulib.h>
#include <stdio.h>
#include <dir.h>
#define printf(...) fprintf(1, __VA_ARGS__)
void
usage(void) {
printf("usage: unlink dir [...]\n");
}
int
main(int argc, char **argv) {
if (argc == 1) {
usage();
return -1;
}
else {
int i, ret;
for (i = 1; i < argc; i ++) {
if ((ret = unlink(argv[i])) != 0) {
return ret;
}
}
}
return 0;
}
|
spinlock/ucore
|
x86_64/lab6_filesystem/proj19/user/unlink.c
|
C
|
gpl-2.0
| 472
|
import { Component, ChangeDetectionStrategy, Input, Output, EventEmitter, TemplateRef, ContentChild, forwardRef, ChangeDetectorRef } from '@angular/core';
import { NgbRatingConfig } from './rating-config';
import { toString, getValueInRange } from '../util/util';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
var Key;
(function (Key) {
Key[Key["End"] = 35] = "End";
Key[Key["Home"] = 36] = "Home";
Key[Key["ArrowLeft"] = 37] = "ArrowLeft";
Key[Key["ArrowUp"] = 38] = "ArrowUp";
Key[Key["ArrowRight"] = 39] = "ArrowRight";
Key[Key["ArrowDown"] = 40] = "ArrowDown";
})(Key || (Key = {}));
var NGB_RATING_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(function () { return NgbRating; }),
multi: true
};
/**
* Rating directive that will take care of visualising a star rating bar.
*/
export var NgbRating = (function () {
function NgbRating(config, _changeDetectorRef) {
this._changeDetectorRef = _changeDetectorRef;
this.range = [];
/**
* An event fired when a user is hovering over a given rating.
* Event's payload equals to the rating being hovered over.
*/
this.hover = new EventEmitter();
/**
* An event fired when a user stops hovering over a given rating.
* Event's payload equals to the rating of the last item being hovered over.
*/
this.leave = new EventEmitter();
/**
* An event fired when a user selects a new rating.
* Event's payload equals to the newly selected rating.
*/
this.rateChange = new EventEmitter(true);
this.onChange = function (_) { };
this.onTouched = function () { };
this.max = config.max;
this.readonly = config.readonly;
}
NgbRating.prototype.ariaValueText = function () { return this.rate + " out of " + this.max; };
NgbRating.prototype.enter = function (value) {
if (!this.readonly) {
this.rate = value;
}
this.hover.emit(value);
};
NgbRating.prototype.handleKeyDown = function (event) {
if (Key[toString(event.which)]) {
event.preventDefault();
switch (event.which) {
case Key.ArrowDown:
case Key.ArrowLeft:
this.update(this.rate - 1);
break;
case Key.ArrowUp:
case Key.ArrowRight:
this.update(this.rate + 1);
break;
case Key.Home:
this.update(0);
break;
case Key.End:
this.update(this.max);
break;
}
}
};
NgbRating.prototype.getFillValue = function (index) {
var diff = this.rate - index;
if (diff >= 1) {
return 100;
}
if (diff < 1 && diff > 0) {
return Number.parseInt((diff * 100).toFixed(2));
}
return 0;
};
NgbRating.prototype.ngOnChanges = function (changes) {
if (changes['rate']) {
this.update(this.rate);
this._oldRate = this.rate;
}
};
NgbRating.prototype.ngOnInit = function () { this.range = Array.from({ length: this.max }, function (v, k) { return k + 1; }); };
NgbRating.prototype.registerOnChange = function (fn) { this.onChange = fn; };
NgbRating.prototype.registerOnTouched = function (fn) { this.onTouched = fn; };
NgbRating.prototype.reset = function () {
this.leave.emit(this.rate);
this.rate = this._oldRate;
};
NgbRating.prototype.update = function (value, internalChange) {
if (internalChange === void 0) { internalChange = true; }
if (!this.readonly) {
var newRate = value ? getValueInRange(value, this.max, 0) : 0;
if (this._oldRate !== newRate) {
this._oldRate = newRate;
this.rate = newRate;
this.rateChange.emit(newRate);
if (internalChange) {
this.onChange(this.rate);
}
}
}
};
NgbRating.prototype.writeValue = function (value) {
this.update(value, false);
this._changeDetectorRef.markForCheck();
};
NgbRating.decorators = [
{ type: Component, args: [{
selector: 'ngb-rating',
changeDetection: ChangeDetectionStrategy.OnPush,
host: { '(keydown)': 'handleKeyDown($event)' },
template: "\n <template #t let-fill=\"fill\">{{ fill === 100 ? '★' : '☆' }}</template>\n <span tabindex=\"0\" (mouseleave)=\"reset()\" role=\"slider\" aria-valuemin=\"0\"\n [attr.aria-valuemax]=\"max\" [attr.aria-valuenow]=\"rate\" [attr.aria-valuetext]=\"ariaValueText()\">\n <template ngFor [ngForOf]=\"range\" let-index=\"index\">\n <span class=\"sr-only\">({{ index < rate ? '*' : ' ' }})</span>\n <span (mouseenter)=\"enter(index + 1)\" (click)=\"update(index + 1)\" \n [style.cursor]=\"readonly ? 'default' : 'pointer'\">\n <template [ngTemplateOutlet]=\"starTemplate || t\" [ngOutletContext]=\"{fill: getFillValue(index)}\"></template>\n </span>\n </template>\n </span>\n ",
providers: [NGB_RATING_VALUE_ACCESSOR]
},] },
];
/** @nocollapse */
NgbRating.ctorParameters = [
{ type: NgbRatingConfig, },
{ type: ChangeDetectorRef, },
];
NgbRating.propDecorators = {
'max': [{ type: Input },],
'rate': [{ type: Input },],
'readonly': [{ type: Input },],
'starTemplate': [{ type: Input }, { type: ContentChild, args: [TemplateRef,] },],
'hover': [{ type: Output },],
'leave': [{ type: Output },],
'rateChange': [{ type: Output },],
};
return NgbRating;
}());
//# sourceMappingURL=rating.js.map
|
Planigle/planigle
|
node_modules/@ng-bootstrap/ng-bootstrap/rating/rating.js
|
JavaScript
|
gpl-2.0
| 6,008
|
//
// Copyright (C) 2007, 2009 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include <exception>
#include <stdexcept>
#include <cstdlib>
#include <cstdio>
namespace __gnu_test
{
struct counter_error : public std::exception { };
struct counter
{
std::size_t _M_count;
bool _M_throw;
counter() : _M_count(0), _M_throw(true) { }
~counter()
{
if (_M_throw && _M_count != 0)
throw counter_error();
}
static void
increment() { get()._M_count++; }
static void
decrement() { get()._M_count--; }
static counter&
get()
{
static counter g;
return g;
}
static std::size_t
count() { return get()._M_count; }
static void
exceptions(bool __b) { get()._M_throw = __b; }
};
template<typename Alloc, bool uses_global_new>
bool
check_new(Alloc a = Alloc())
{
__gnu_test::counter::exceptions(false);
a.allocate(10);
const bool __b((__gnu_test::counter::count() > 0) == uses_global_new);
if (!__b)
throw std::logic_error("counter not incremented");
return __b;
}
template<typename Alloc, bool uses_global_delete>
bool
check_delete(Alloc a = Alloc())
{
__gnu_test::counter::exceptions(false);
typename Alloc::pointer p = a.allocate(10);
const std::size_t count1 = __gnu_test::counter::count();
a.deallocate(p, 10);
const std::size_t count2 = __gnu_test::counter::count();
const bool __b((count2 < count1) == uses_global_delete);
if (!__b)
throw std::logic_error("counter not decremented");
return __b;
}
} // namespace __gnu_test
void* operator new(std::size_t size) throw(std::bad_alloc)
{
std::printf("operator new is called \n");
void* p = std::malloc(size);
if (p == NULL)
throw std::bad_alloc();
__gnu_test::counter::increment();
return p;
}
void operator delete(void* p) throw()
{
std::printf("operator delete is called \n");
if (p != NULL)
{
std::free(p);
__gnu_test::counter::decrement();
std::size_t count = __gnu_test::counter::count();
if (count == 0)
std::printf("All memory released \n");
else
std::printf("%lu allocations to be released \n", count);
}
}
|
intervigilium/cs259-or32-gcc
|
libstdc++-v3/testsuite/util/replacement_memory_operators.h
|
C
|
gpl-2.0
| 2,940
|
#pragma once
/*
* Copyright (C) 2005-2014 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "windowing/VideoSync.h"
#include "system_gl.h"
#include <X11/X.h>
#include <X11/Xlib.h>
#include <GL/glx.h>
#include "guilib/DispResource.h"
#include "threads/Event.h"
class CVideoSyncGLX : public CVideoSync, IDispResource
{
public:
CVideoSyncGLX(void *clock) : CVideoSync(clock) {};
bool Setup(PUPDATECLOCK func) override;
void Run(CEvent& stopEvent) override;
void Cleanup() override;
float GetFps() override;
void OnLostDisplay() override;
void OnResetDisplay() override;
private:
int (*m_glXWaitVideoSyncSGI) (int, int, unsigned int*);
int (*m_glXGetVideoSyncSGI) (unsigned int*);
static Display* m_Dpy;
XVisualInfo *m_vInfo;
Window m_Window;
GLXContext m_Context;
volatile bool m_displayLost;
volatile bool m_displayReset;
CEvent m_lostEvent;
};
|
popcornmix/xbmc
|
xbmc/windowing/X11/VideoSyncGLX.h
|
C
|
gpl-2.0
| 1,557
|
---
title: Syntax highlighting
tags: [formatting]
keywords: rouge, pygments, prettify, color coding,
last_updated: August 12, 2015
summary: "You can apply syntax highlighting to your code. This theme uses pygments and applies color coding based on the lexer you specify."
---
## About syntax highlighting
For syntax highlighting, use fenced code blocks optionally followed by the language syntax you want:
<pre>
```ruby
def foo
puts 'foo'
end
```
</pre>
This looks as follows:
```ruby
def foo
puts 'foo'
end
```
Fenced code blocks require a blank line before and after.
If you're using an HTML file, you can also use the `highlight` command with Liquid markup:
<pre>
{% raw %}{% highlight ruby %}
def foo
puts 'foo'
end
{% endhighlight %}{% endraw %}
</pre>
It renders the same:
{% highlight ruby %}
def foo
puts 'foo'
end
{% endhighlight %}
The theme has syntax highlighting specified in the configuration file as follows:
```
highlighter: pygments
```
You can use another highlighter such as `rouge`.
The syntax highlighting is done via the css/syntax.css file.
## Available Pygments lexers
The keywords you must add to specify the highlighting (in the previous example, `ruby`) are called "lexers." You can search for "pygments lexers" or go directly to [Available lexers](http://pygments.org/docs/lexers/) to see what values you can use. Here are some common ones I use:
* js
* html
* yaml
* css
* json
* php
* java
* cpp
* dotnet
* xml
* http
|
npateman/documentation-theme-jekyll
|
doc_syntax_highlighting.md
|
Markdown
|
gpl-2.0
| 1,524
|
<?php
/**
*
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Reports\Controller\Adminhtml\Report\Sales;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
class ExportCouponsExcel extends \Magento\Reports\Controller\Adminhtml\Report\Sales
{
/**
* Export coupons report grid to Excel XML format
*
* @return ResponseInterface
*/
public function execute()
{
$fileName = 'coupons.xml';
$grid = $this->_view->getLayout()->createBlock('Magento\Reports\Block\Adminhtml\Sales\Coupons\Grid');
$this->_initReportAction($grid);
return $this->_fileFactory->create($fileName, $grid->getExcelFile($fileName), DirectoryList::VAR_DIR);
}
}
|
FPLD/project0
|
vendor/magento/module-reports/Controller/Adminhtml/Report/Sales/ExportCouponsExcel.php
|
PHP
|
gpl-2.0
| 805
|
/*
* arch/arm/mach-sun7i/cpu-freq/cpu-freq.c
*
* Copyright (c) 2012 Allwinner.
* kevin.z.m (kevin@allwinnertech.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/cpufreq.h>
#include <linux/cpu.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <mach/sys_config.h>
#include <linux/cpu.h>
#include <asm/cpu.h>
#include "cpu-freq.h"
#include <linux/pm.h>
#include <linux/regulator/consumer.h>
#include <mach/includes.h>
#define AHB_APB_CLK_ASYNC
static struct sunxi_cpu_freq_t cpu_cur; /* current cpu frequency configuration */
static unsigned int last_target = ~0; /* backup last target frequency */
static struct clk *clk_pll; /* pll clock handler */
static struct clk *clk_cpu; /* cpu clock handler */
static struct clk *clk_axi; /* axi clock handler */
static struct clk *clk_ahb; /* ahb clock handler */
static struct clk *clk_apb; /* apb clock handler */
#ifdef AHB_APB_CLK_ASYNC
static struct clk *clk_sata_pll; /* apb clock handler */
#endif
static DEFINE_MUTEX(sunxi_cpu_lock);
static unsigned int cpu_freq_max = SUNXI_CPUFREQ_MAX / 1000;
static unsigned int cpu_freq_min = SUNXI_CPUFREQ_MIN / 1000;
#ifdef CONFIG_SMP
static struct cpumask sunxi_cpumask;
static int cpus_initialized;
#endif
int setgetfreq_debug = 0;
#ifdef CONFIG_CPU_FREQ_SETFREQ_DEBUG
unsigned long long setfreq_time_usecs = 0;
unsigned long long getfreq_time_usecs = 0;
#endif
#ifdef CONFIG_CPU_FREQ_DVFS
#define TABLE_LENGTH (16)
struct cpufreq_dvfs {
unsigned int freq; /* cpu frequency */
unsigned int volt; /* voltage for the frequency */
};
static struct cpufreq_dvfs dvfs_table[] = {
{.freq = 1008000000, .volt = 1450}, /* core vdd is 1.40v if cpu frequency is (912Mhz, 1008Mhz] */
{.freq = 912000000, .volt = 1400}, /* core vdd is 1.40v if cpu frequency is (864Mhz, 912Mhz] */
{.freq = 864000000, .volt = 1300}, /* core vdd is 1.30v if cpu frequency is (720Mhz, 864Mhz] */
{.freq = 720000000, .volt = 1200}, /* core vdd is 1.20v if cpu frequency is (528Mhz, 720Mhz] */
{.freq = 528000000, .volt = 1100}, /* core vdd is 1.10v if cpu frequency is (336Mhz, 528Mhz] */
{.freq = 312000000, .volt = 1000}, /* core vdd is 1.00v if cpu frequency is (144Mhz, 312Mhz] */
{.freq = 144000000, .volt = 900}, /* core vdd is 0.90v if cpu frequency is ( 0Mhz, 144Mhz] */
{.freq = 0, .volt = 900}, /* end of cpu dvfs table */
};
static struct cpufreq_dvfs dvfs_table_syscfg[TABLE_LENGTH];
static unsigned int table_length_syscfg = 0;
static int use_default_table = 0;
static struct regulator *corevdd;
static unsigned int last_vdd = 1400; /* backup last target voltage, default is 1.4v */
#endif
/*
*check if the cpu frequency policy is valid;
*/
static int sunxi_cpufreq_verify(struct cpufreq_policy *policy)
{
return 0;
}
/*
*show cpu frequency information;
*/
static void sunxi_cpufreq_show(const char *pfx, struct sunxi_cpu_freq_t *cfg)
{
#ifndef AHB_APB_CLK_ASYNC
CPUFREQ_DBG("%s: pll=%u, cpudiv=%u, axidiv=%u, ahbdiv=%u, apb=%u\n",
pfx, cfg->pll, cfg->div.cpu_div, cfg->div.axi_div, cfg->div.ahb_div, cfg->div.apb_div);
#else
CPUFREQ_DBG("%s: pll=%u, cpudiv=%u, axidiv=%u\n", pfx, cfg->pll, cfg->div.cpu_div, cfg->div.axi_div);
#endif
}
#ifdef CONFIG_CPU_FREQ_DVFS
/*
*********************************************************************************************************
* __init_vftable_syscfg
*
*Description: init vftable from sysconfig.
*
*Arguments : none;
*
*Return : result, 0 - init vftable successed, !0 - init vftable failed;
*
*Notes : LV1: core vdd is 1.50v if cpu frequency is (1008Mhz, 1056Mhz]
* LV2: core vdd is 1.40v if cpu frequency is (912Mhz, 1008Mhz]
* LV3: core vdd is 1.35v if cpu frequency is (864Mhz, 912Mhz]
* LV4: core vdd is 1.30v if cpu frequency is (624Mhz, 864Mhz]
* LV5: core vdd is 1.25v if cpu frequency is (60Mhz, 624Mhz]
*
*********************************************************************************************************
*/
static int __init_vftable_syscfg(void)
{
int ret = 0;
char name[16] = {0};
script_item_u level_freq, level_volt, level_count;
script_item_value_type_e type;
int i;
type = script_get_item("dvfs_table", "LV_count", &level_count);
if (SCIRPT_ITEM_VALUE_TYPE_INT != type) {
CPUFREQ_ERR("get LV_count from sysconfig failed\n");
use_default_table = 1;
ret = -1;
goto fail;
}
table_length_syscfg = level_count.val;
/* table_length_syscfg must be < TABLE_LENGTH */
if(table_length_syscfg >= TABLE_LENGTH){
CPUFREQ_ERR("LV_count from sysconfig is out of bounder\n");
use_default_table = 1;
ret = -1;
goto fail;
}
for (i = 1; i <= table_length_syscfg; i++){
sprintf(name, "LV%d_freq", i);
type = script_get_item("dvfs_table", name, &level_freq);
if (SCIRPT_ITEM_VALUE_TYPE_INT != type) {
CPUFREQ_ERR("get LV%d_freq from sysconfig failed\n", i);
use_default_table = 1;
ret = -1;
goto fail;
}
sprintf(name, "LV%d_volt", i);
type = script_get_item("dvfs_table", name, &level_volt);
if (SCIRPT_ITEM_VALUE_TYPE_INT != type) {
CPUFREQ_ERR("get LV%d_volt from sysconfig failed\n", i);
use_default_table = 1;
ret = -1;
goto fail;
}
dvfs_table_syscfg[i-1].freq = level_freq.val;
dvfs_table_syscfg[i-1].volt = level_volt.val;
}
/* end of cpu dvfs table */
dvfs_table_syscfg[table_length_syscfg].freq = 0;
dvfs_table_syscfg[table_length_syscfg].volt = 1000;
fail:
return ret;
}
/*
*********************************************************************************************************
* __vftable_show
*
*Description: show vftable information
*
*Arguments : none;
*
*Return : none;
*
*Notes :
*
*********************************************************************************************************
*/
static void __vftable_show(void)
{
int i;
CPUFREQ_INF("-------------------V-F Table-------------------\n");
if(use_default_table){
for(i = 0; i < sizeof(dvfs_table)/sizeof(dvfs_table[0]); i++){
CPUFREQ_INF("\tvoltage = %4dmv \tfrequency = %4dMHz\n", dvfs_table[i].volt,
dvfs_table[i].freq/1000000);
}
}
else{
for(i = 0; i <= table_length_syscfg; i++){
CPUFREQ_INF("\tvoltage = %4dmv \tfrequency = %4dMHz\n", dvfs_table_syscfg[i].volt,
dvfs_table_syscfg[i].freq/1000000);
}
}
CPUFREQ_INF("-----------------------------------------------\n");
}
/*
*********************************************************************************************************
* __get_vdd_value
*
*Description: get vdd with cpu frequency.
*
*Arguments : freq cpu frequency;
*
*Return : vdd value;
*
*Notes :
*
*********************************************************************************************************
*/
static inline unsigned int __get_vdd_value(unsigned int freq)
{
struct cpufreq_dvfs *dvfs_inf = NULL;
if(use_default_table)
dvfs_inf = &dvfs_table[0];
else
dvfs_inf = &dvfs_table_syscfg[0];
while((dvfs_inf+1)->freq >= freq) dvfs_inf++;
return dvfs_inf->volt;
}
#endif
/*
*********************************************************************************************************
* __set_cpufreq_hw
*
*Description: set cpu frequency configuration to hardware.
*
*Arguments : freq frequency configuration;
*
*Return : result
*
*Notes :
*
*********************************************************************************************************
*/
static inline int __set_cpufreq_hw(struct sunxi_cpu_freq_t *freq)
{
int ret;
unsigned int frequency;
/* try to adjust pll frequency */
ret = clk_set_rate(clk_pll, freq->pll);
/* try to adjust cpu frequency */
frequency = freq->pll / freq->div.cpu_div;
ret |= clk_set_rate(clk_cpu, frequency);
/* try to adjuxt axi frequency */
frequency /= freq->div.axi_div;
ret |= clk_set_rate(clk_axi, frequency);
#ifndef AHB_APB_CLK_ASYNC
/* try to adjust ahb frequency */
frequency /= freq->div.ahb_div;
ret |= clk_set_rate(clk_ahb, frequency);
/* try to adjust apb frequency */
frequency /= freq->div.apb_div;
ret |= clk_set_rate(clk_apb, frequency);
#endif
return ret;
}
/*
*********************************************************************************************************
* __set_cpufreq_target
*
*Description: set target frequency, the frequency limitation of axi is 450Mhz, the frequency
* limitation of ahb is 250Mhz, and the limitation of apb is 150Mhz. for usb connecting,
* the frequency of ahb must not lower than 60Mhz.
*
*Arguments : old cpu/axi/ahb/apb frequency old configuration.
* new cpu/axi/ahb/apb frequency new configuration.
*
*Return : result, 0 - set frequency successed, !0 - set frequency failed;
*
*Notes : we check two frequency point: 204Mhz, 408Mhz, 816Mhz and 1200Mhz.
* if increase cpu frequency, the flow should be:
* low(1:1:1:2) -> 204Mhz(1:1:1:2) -> 204Mhz(1:1:2:2) -> 408Mhz(1:1:2:2)
* -> 408Mhz(1:2:2:2) -> 816Mhz(1:2:2:2) -> 816Mhz(1:3:2:2) -> 1200Mhz(1:3:2:2)
* -> 1200Mhz(1:4:2:2) -> target(1:4:2:2) -> target(x:x:x:x)
* if decrease cpu frequency, the flow should be:
* high(x:x:x:x) -> target(1:4:2:2) -> 1200Mhz(1:4:2:2) -> 1200Mhz(1:3:2:2)
* -> 816Mhz(1:3:2:2) -> 816Mhz(1:2:2:2) -> 408Mhz(1:2:2:2) -> 408Mhz(1:1:2:2)
* -> 204Mhz(1:1:2:2) -> 204Mhz(1:1:1:2) -> target(1:1:1:2)
*********************************************************************************************************
*/
static int __set_cpufreq_target(struct sunxi_cpu_freq_t *old, struct sunxi_cpu_freq_t *new)
{
int ret = 0;
struct sunxi_cpu_freq_t old_freq, new_freq;
if(!old || !new) {
return -EINVAL;
}
old_freq = *old;
new_freq = *new;
CPUFREQ_INF("cpu: %dMhz->%dMhz\n", old_freq.pll/1000000, new_freq.pll/1000000);
if(new_freq.pll > old_freq.pll) {
if((old_freq.pll <= 204000000) && (new_freq.pll >= 204000000)) {
/* set to 204Mhz (1:1:1:2) */
old_freq.pll = 204000000;
old_freq.div.cpu_div = 1;
old_freq.div.axi_div = 1;
#ifndef AHB_APB_CLK_ASYNC
old_freq.div.ahb_div = 1;
old_freq.div.apb_div = 2;
#endif
ret |= __set_cpufreq_hw(&old_freq);
#ifndef AHB_APB_CLK_ASYNC
/* set to 204Mhz (1:1:2:2) */
old_freq.div.ahb_div = 2;
ret |= __set_cpufreq_hw(&old_freq);
#endif
}
if((old_freq.pll <= 408000000) && (new_freq.pll >= 408000000)) {
/* set to 408Mhz (1:1:2:2) */
old_freq.pll = 408000000;
old_freq.div.cpu_div = 1;
old_freq.div.axi_div = 1;
#ifndef AHB_APB_CLK_ASYNC
old_freq.div.ahb_div = 2;
old_freq.div.apb_div = 2;
#endif
ret |= __set_cpufreq_hw(&old_freq);
/* set to 408Mhz (1:2:2:2) */
old_freq.div.axi_div = 2;
ret |= __set_cpufreq_hw(&old_freq);
}
if((old_freq.pll <= 816000000) && (new_freq.pll >= 816000000)) {
/* set to 816Mhz (1:2:2:2) */
old_freq.pll = 816000000;
old_freq.div.cpu_div = 1;
old_freq.div.axi_div = 2;
#ifndef AHB_APB_CLK_ASYNC
old_freq.div.ahb_div = 2;
old_freq.div.apb_div = 2;
#endif
ret |= __set_cpufreq_hw(&old_freq);
/* set to 816Mhz (1:3:2:2) */
old_freq.div.axi_div = 3;
ret |= __set_cpufreq_hw(&old_freq);
}
if((old_freq.pll <= 1200000000) && (new_freq.pll >= 1200000000)) {
/* set to 1200Mhz (1:3:2:2) */
old_freq.pll = 1200000000;
old_freq.div.cpu_div = 1;
old_freq.div.axi_div = 3;
#ifndef AHB_APB_CLK_ASYNC
old_freq.div.ahb_div = 2;
old_freq.div.apb_div = 2;
#endif
ret |= __set_cpufreq_hw(&old_freq);
/* set to 1200Mhz (1:4:2:2) */
old_freq.div.axi_div = 4;
ret |= __set_cpufreq_hw(&old_freq);
}
/* adjust to target frequency */
ret |= __set_cpufreq_hw(&new_freq);
}
else if(new_freq.pll < old_freq.pll) {
if((old_freq.pll > 1200000000) && (new_freq.pll <= 1200000000)) {
/* set to 1200Mhz (1:3:2:2) */
old_freq.pll = 1200000000;
old_freq.div.cpu_div = 1;
old_freq.div.axi_div = 3;
#ifndef AHB_APB_CLK_ASYNC
old_freq.div.ahb_div = 2;
old_freq.div.apb_div = 2;
#endif
ret |= __set_cpufreq_hw(&old_freq);
}
if((old_freq.pll > 816000000) && (new_freq.pll <= 816000000)) {
/* set to 816Mhz (1:3:2:2) */
old_freq.pll = 816000000;
old_freq.div.cpu_div = 1;
old_freq.div.axi_div = 3;
#ifndef AHB_APB_CLK_ASYNC
old_freq.div.ahb_div = 2;
old_freq.div.apb_div = 2;
#endif
ret |= __set_cpufreq_hw(&old_freq);
/* set to 816Mhz (1:2:2:2) */
old_freq.div.axi_div = 2;
ret |= __set_cpufreq_hw(&old_freq);
}
if((old_freq.pll > 408000000) && (new_freq.pll <= 408000000)) {
/* set to 408Mhz (1:2:2:2) */
old_freq.pll = 408000000;
old_freq.div.cpu_div = 1;
old_freq.div.axi_div = 2;
#ifndef AHB_APB_CLK_ASYNC
old_freq.div.ahb_div = 2;
old_freq.div.apb_div = 2;
#endif
ret |= __set_cpufreq_hw(&old_freq);
/* set to 816Mhz (1:1:2:2) */
old_freq.div.axi_div = 1;
ret |= __set_cpufreq_hw(&old_freq);
}
if((old_freq.pll > 204000000) && (new_freq.pll <= 204000000)) {
/* set to 204Mhz (1:1:2:2) */
old_freq.pll = 204000000;
old_freq.div.cpu_div = 1;
old_freq.div.axi_div = 1;
#ifndef AHB_APB_CLK_ASYNC
old_freq.div.ahb_div = 2;
old_freq.div.apb_div = 2;
#endif
ret |= __set_cpufreq_hw(&old_freq);
/* set to 204Mhz (1:1:1:2) */
#ifndef AHB_APB_CLK_ASYNC
old_freq.div.ahb_div = 1;
ret |= __set_cpufreq_hw(&old_freq);
#endif
}
/* adjust to target frequency */
ret |= __set_cpufreq_hw(&new_freq);
}
if(ret) {
unsigned int frequency;
CPUFREQ_ERR("try to set target frequency failed!\n");
/* try to restore frequency configuration */
frequency = clk_get_rate(clk_cpu);
frequency /= 4;
clk_set_rate(clk_axi, frequency);
#ifndef AHB_APB_CLK_ASYNC
frequency /= 2;
clk_set_rate(clk_ahb, frequency);
frequency /= 2;
clk_set_rate(clk_apb, frequency);
#endif
clk_set_rate(clk_pll, old->pll);
frequency = old->pll / old->div.cpu_div;
clk_set_rate(clk_cpu, frequency);
frequency /= old->div.axi_div;
clk_set_rate(clk_axi, frequency);
#ifndef AHB_APB_CLK_ASYNC
frequency /= old->div.ahb_div;
clk_set_rate(clk_ahb, frequency);
frequency /= old->div.apb_div;
clk_set_rate(clk_apb, frequency);
#endif
CPUFREQ_ERR(KERN_ERR "no compatible settings cpu freq for %d\n", new_freq.pll);
return -1;
}
return 0;
}
/*
*********************************************************************************************************
* sunxi_cpufreq_settarget
*
*Description: adjust cpu frequency;
*
*Arguments : policy cpu frequency policy, to mark if need notify;
* cpu_freq new cpu frequency configuration;
*
*Return : return 0 if set successed, otherwise, return -EINVAL
*
*Notes :
*
*********************************************************************************************************
*/
static int sunxi_cpufreq_settarget(struct cpufreq_policy *policy, struct sunxi_cpu_freq_t *cpu_freq)
{
struct cpufreq_freqs freqs;
struct sunxi_cpu_freq_t cpu_new;
int i;
#ifdef CONFIG_CPU_FREQ_DVFS
unsigned int new_vdd;
#endif
/* show current cpu frequency configuration, just for debug */
sunxi_cpufreq_show("cur", &cpu_cur);
/* get new cpu frequency configuration */
cpu_new = *cpu_freq;
sunxi_cpufreq_show("new", &cpu_new);
/* notify that cpu clock will be adjust if needed */
if (policy) {
freqs.cpu = policy->cpu;
freqs.old = cpu_cur.pll / 1000;
freqs.new = cpu_new.pll / 1000;
#ifdef CONFIG_SMP
/* notifiers */
for_each_cpu(i, policy->cpus) {
freqs.cpu = i;
cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE);
}
#else
cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE);
#endif
}
#ifdef CONFIG_CPU_FREQ_DVFS
/* get vdd value for new frequency */
new_vdd = __get_vdd_value(cpu_new.pll);
if(corevdd && (new_vdd > last_vdd)) {
CPUFREQ_INF("set core vdd to %d\n", new_vdd);
if(regulator_set_voltage(corevdd, new_vdd*1000, new_vdd*1000)) {
CPUFREQ_INF("try to set voltage failed!\n");
/* notify everyone that clock transition finish */
if (policy) {
freqs.cpu = policy->cpu;
freqs.old = freqs.new;
freqs.new = cpu_cur.pll / 1000;
cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
}
return -EINVAL;
}
}
#endif
if(__set_cpufreq_target(&cpu_cur, &cpu_new)){
/* try to set cpu frequency failed */
#ifdef CONFIG_CPU_FREQ_DVFS
if(corevdd && (new_vdd > last_vdd)) {
CPUFREQ_INF("set core vdd to %d\n", last_vdd);
if(regulator_set_voltage(corevdd, last_vdd*1000, last_vdd*1000)){
CPUFREQ_INF("try to set voltage failed!\n");
last_vdd = new_vdd;
}
}
#endif
/* notify everyone that clock transition finish */
if (policy) {
freqs.cpu = policy->cpu;
freqs.old = freqs.new;
freqs.new = cpu_cur.pll / 1000;
#ifdef CONFIG_SMP
/* notifiers */
for_each_cpu(i, policy->cpus) {
freqs.cpu = i;
cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
}
#else
cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
#endif
}
return -EINVAL;
}
#ifdef CONFIG_CPU_FREQ_DVFS
if(corevdd && (new_vdd < last_vdd)) {
CPUFREQ_INF("set core vdd to %d\n", new_vdd);
if(regulator_set_voltage(corevdd, new_vdd*1000, new_vdd*1000)) {
CPUFREQ_INF("try to set voltage failed!\n");
new_vdd = last_vdd;
}
}
last_vdd = new_vdd;
#endif
/* update our current settings */
cpu_cur = cpu_new;
/* notify everyone we've done this */
if (policy) {
#ifdef CONFIG_SMP
/*
* Note that loops_per_jiffy is not updated on SMP systems in
* cpufreq driver. So, update the per-CPU loops_per_jiffy value
* on frequency transition. We need to update all dependent cpus
*/
for_each_cpu(i, policy->cpus) {
per_cpu(cpu_data, i).loops_per_jiffy =
cpufreq_scale(per_cpu(cpu_data, i).loops_per_jiffy, freqs.old, freqs.new);
freqs.cpu = i;
cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
}
#else
cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
#endif
}
CPUFREQ_DBG("%s: finished\n", __func__);
return 0;
}
/*
* adjust the frequency that cpu is currently running;
* policy: cpu frequency policy;
* freq: target frequency to be set, based on khz;
* relation: method for selecting the target requency;
* return: result, return 0 if set target frequency successed, else, return -EINVAL;
* notes: this function is called by the cpufreq core;
*/
static int sunxi_cpufreq_target(struct cpufreq_policy *policy, __u32 freq, __u32 relation)
{
int ret = 0;
unsigned int index;
struct sunxi_cpu_freq_t freq_cfg;
#ifdef CONFIG_CPU_FREQ_SETFREQ_DEBUG
ktime_t calltime = ktime_set(0, 0), delta, rettime;
if (unlikely(setgetfreq_debug)) {
calltime = ktime_get();
}
#endif
mutex_lock(&sunxi_cpu_lock);
#ifdef CONFIG_SMP
/* Wait untill all CPU's are initialized */
if (unlikely(cpus_initialized < num_online_cpus())) {
ret = -EINVAL;
goto out;
}
#endif
/* avoid repeated calls which cause a needless amout of duplicated
* logging output (and CPU time as the calculation process is
* done) */
if (freq == last_target) {
goto out;
}
/* try to look for a valid frequency value from cpu frequency table */
if (cpufreq_frequency_table_target(policy, sunxi_freq_tbl, freq, relation, &index)) {
CPUFREQ_ERR("try to look for a valid frequency for %u failed!\n", freq);
ret = -EINVAL;
goto out;
}
/* frequency is same as the value last set, need not adjust */
if (sunxi_freq_tbl[index].frequency == last_target) {
goto out;
}
freq = sunxi_freq_tbl[index].frequency;
/* update the target frequency */
freq_cfg.pll = sunxi_freq_tbl[index].frequency * 1000;
freq_cfg.div = *(struct sunxi_clk_div_t *)&sunxi_freq_tbl[index].index;
CPUFREQ_DBG("target frequency find is %u, entry %u\n", freq_cfg.pll, index);
/* try to set target frequency */
ret = sunxi_cpufreq_settarget(policy, &freq_cfg);
if(!ret) {
last_target = freq;
}
out:
#ifdef CONFIG_CPU_FREQ_SETFREQ_DEBUG
if (unlikely(setgetfreq_debug)) {
rettime = ktime_get();
delta = ktime_sub(rettime, calltime);
setfreq_time_usecs = ktime_to_ns(delta) >> 10;
printk("[setfreq]: %Ld usecs\n", setfreq_time_usecs);
}
#endif
mutex_unlock(&sunxi_cpu_lock);
return ret;
}
/*
* get the frequency that cpu currently is running;
* cpu: cpu number, all cpus use the same clock;
* return: cpu frequency, based on khz;
*/
static unsigned int sunxi_cpufreq_get(unsigned int cpu)
{
unsigned int current_freq = 0;
#ifdef CONFIG_CPU_FREQ_SETFREQ_DEBUG
ktime_t calltime = ktime_set(0, 0), delta, rettime;
if (unlikely(setgetfreq_debug)) {
calltime = ktime_get();
}
#endif
current_freq = clk_get_rate(clk_cpu) / 1000;
#ifdef CONFIG_CPU_FREQ_SETFREQ_DEBUG
if (unlikely(setgetfreq_debug)) {
rettime = ktime_get();
delta = ktime_sub(rettime, calltime);
getfreq_time_usecs = ktime_to_ns(delta) >> 10;
printk("[getfreq]: %Ld usecs\n", getfreq_time_usecs);
}
#endif
return current_freq;
}
/*
* get the frequency that cpu average is running;
* cpu: cpu number, all cpus use the same clock;
* return: cpu frequency, based on khz;
*/
static unsigned int sunxi_cpufreq_getavg(struct cpufreq_policy *policy, unsigned int cpu)
{
return clk_get_rate(clk_cpu) / 1000;
}
/*
* get a valid frequency from cpu frequency table;
* target_freq: target frequency to be judge, based on KHz;
* return: cpu frequency, based on khz;
*/
static unsigned int __get_valid_freq(unsigned int target_freq)
{
struct cpufreq_frequency_table *tmp = &sunxi_freq_tbl[0];
while(tmp->frequency != CPUFREQ_TABLE_END){
if((tmp+1)->frequency <= target_freq)
tmp++;
else
break;
}
return tmp->frequency;
}
/*
* init cpu max/min frequency from sysconfig;
* return: 0 - init cpu max/min successed, !0 - init cpu max/min failed;
*/
static int __init_freq_syscfg(void)
{
int ret = 0;
#if 1
script_item_u max, min;
script_item_value_type_e type;
type = script_get_item("dvfs_table", "max_freq", &max);
if (SCIRPT_ITEM_VALUE_TYPE_INT != type) {
CPUFREQ_ERR("get cpu max frequency from sysconfig failed\n");
ret = -1;
goto fail;
}
cpu_freq_max = max.val;
type = script_get_item("dvfs_table", "min_freq", &min);
if (SCIRPT_ITEM_VALUE_TYPE_INT != type) {
CPUFREQ_ERR("get cpu min frequency from sysconfig failed\n");
ret = -1;
goto fail;
}
cpu_freq_min = min.val;
if(cpu_freq_max > SUNXI_CPUFREQ_MAX || cpu_freq_max < SUNXI_CPUFREQ_MIN
|| cpu_freq_min < SUNXI_CPUFREQ_MIN || cpu_freq_min > SUNXI_CPUFREQ_MAX){
CPUFREQ_ERR("cpu max or min frequency from sysconfig is more than range\n");
ret = -1;
goto fail;
}
if(cpu_freq_min > cpu_freq_max){
CPUFREQ_ERR("cpu min frequency can not be more than cpu max frequency\n");
ret = -1;
goto fail;
}
/* get valid max/min frequency from cpu frequency table */
cpu_freq_max = __get_valid_freq(cpu_freq_max / 1000);
cpu_freq_min = __get_valid_freq(cpu_freq_min / 1000);
return 0;
fail:
/* use default cpu max/min frequency */
cpu_freq_max = SUNXI_CPUFREQ_MAX / 1000;
cpu_freq_min = SUNXI_CPUFREQ_MIN / 1000;
#endif
return ret;
}
/*
* cpu frequency initialise a policy;
* policy: cpu frequency policy;
* result: return 0 if init ok, else, return -EINVAL;
*/
static int sunxi_cpufreq_init(struct cpufreq_policy *policy)
{
policy->cur = sunxi_cpufreq_get(0);
policy->min = policy->cpuinfo.min_freq = cpu_freq_min;
policy->max = policy->cpuinfo.max_freq = cpu_freq_max;
policy->cpuinfo.max_freq = SUNXI_CPUFREQ_MAX / 1000;
policy->cpuinfo.min_freq = SUNXI_CPUFREQ_MIN / 1000;
policy->governor = CPUFREQ_DEFAULT_GOVERNOR;
/* feed the latency information from the cpu driver */
policy->cpuinfo.transition_latency = SUNXI_FREQTRANS_LATENCY;
cpufreq_frequency_table_get_attr(sunxi_freq_tbl, policy->cpu);
#ifdef CONFIG_SMP
/*
* both processors share the same voltage and the same clock,
* but have dedicated power domains. So both cores needs to be
* scaled together and hence needs software co-ordination.
* Use cpufreq affected_cpus interface to handle this scenario.
*/
policy->shared_type = CPUFREQ_SHARED_TYPE_ANY;
cpumask_or(&sunxi_cpumask, cpumask_of(policy->cpu), &sunxi_cpumask);
cpumask_copy(policy->cpus, &sunxi_cpumask);
cpus_initialized++;
#endif
return 0;
}
/*
* get current cpu frequency configuration;
* cfg: cpu frequency cofniguration;
* return: result;
*/
static int sunxi_cpufreq_getcur(struct sunxi_cpu_freq_t *cfg)
{
unsigned int freq, freq0;
if(!cfg) {
return -EINVAL;
}
cfg->pll = clk_get_rate(clk_pll);
freq = clk_get_rate(clk_cpu);
cfg->div.cpu_div = cfg->pll / freq;
freq0 = clk_get_rate(clk_axi);
cfg->div.axi_div = freq / freq0;
#ifndef AHB_APB_CLK_ASYNC
freq = clk_get_rate(clk_ahb);
cfg->div.ahb_div = freq0 / freq;
freq0 = clk_get_rate(clk_apb);
cfg->div.apb_div = freq /freq0;
#endif
return 0;
}
#ifdef CONFIG_PM
/*
* cpu frequency configuration suspend;
*/
static int sunxi_cpufreq_suspend(struct cpufreq_policy *policy)
{
CPUFREQ_DBG("%s\n", __func__);
return 0;
}
/*
* cpu frequency configuration resume;
*/
static int sunxi_cpufreq_resume(struct cpufreq_policy *policy)
{
/* invalidate last_target setting */
last_target = ~0;
CPUFREQ_DBG("%s\n", __func__);
return 0;
}
#else /* #ifdef CONFIG_PM */
#define sunxi_cpufreq_suspend NULL
#define sunxi_cpufreq_resume NULL
#endif /* #ifdef CONFIG_PM */
static ssize_t show_debug_mask(struct cpufreq_policy *policy, char *buf)
{
return sprintf(buf, "%u\n", setgetfreq_debug);
}
static ssize_t store_debug_mask (struct cpufreq_policy *policy, const char *buf, size_t count)
{
unsigned int ret = -EINVAL;
int debug_mask = 0;
ret = sscanf(buf, "%u", &debug_mask);
if (ret != 1)
return -EINVAL;
setgetfreq_debug = debug_mask;
return ret ? ret : count;
}
cpufreq_freq_attr_rw(debug_mask);
static struct freq_attr *platform_attrs[] = {
&debug_mask,
NULL
};
static struct cpufreq_driver sunxi_cpufreq_driver = {
.name = "sunxi",
.flags = CPUFREQ_STICKY,
.init = sunxi_cpufreq_init,
.verify = sunxi_cpufreq_verify,
.target = sunxi_cpufreq_target,
.get = sunxi_cpufreq_get,
.getavg = sunxi_cpufreq_getavg,
.suspend = sunxi_cpufreq_suspend,
.resume = sunxi_cpufreq_resume,
.attr = platform_attrs,
};
/*
* cpu frequency driver init
*/
static int __init sunxi_cpufreq_initcall(void)
{
int ret = 0;
clk_pll = clk_get(NULL, "core_pll");
clk_cpu = clk_get(NULL, "cpu");
clk_axi = clk_get(NULL, "axi");
clk_ahb = clk_get(NULL, "ahb");
clk_apb = clk_get(NULL, "apb");
if (IS_ERR(clk_pll) || IS_ERR(clk_cpu) || IS_ERR(clk_axi) ||
IS_ERR(clk_ahb) || IS_ERR(clk_apb)) {
CPUFREQ_INF(KERN_ERR "%s: could not get clock(s)\n", __func__);
return -ENOENT;
}
#ifdef AHB_APB_CLK_ASYNC
CPUFREQ_INF("set ahb apb clock async\n");
clk_sata_pll = clk_get(NULL, "sata_pll");
if (IS_ERR(clk_sata_pll)) {
CPUFREQ_INF(KERN_ERR "%s: could not get clock(s)\n", __func__);
return -ENOENT;
}
clk_set_parent(clk_ahb, clk_sata_pll);
clk_set_rate(clk_ahb, 150000000);
clk_set_rate(clk_apb, 75000000);
#endif
CPUFREQ_INF("%s: clocks pll=%lu,cpu=%lu,axi=%lu,ahp=%lu,apb=%lu\n", __func__,
clk_get_rate(clk_pll), clk_get_rate(clk_cpu), clk_get_rate(clk_axi),
clk_get_rate(clk_ahb), clk_get_rate(clk_apb));
#ifdef CONFIG_CPU_FREQ_DVFS
#if defined (CONFIG_AW_AXP15)
corevdd = regulator_get(NULL, "axp15_core");
#endif
#if defined (CONFIG_AW_AXP20)
corevdd = regulator_get(NULL, "axp20_core");
#endif
if(IS_ERR(corevdd)) {
CPUFREQ_INF("try to get regulator failed, core vdd will not changed!\n");
corevdd = NULL;
}
else {
CPUFREQ_INF("try to get regulator(0x%x) successed.\n", (__u32)corevdd);
last_vdd = regulator_get_voltage(corevdd) / 1000;
}
ret = __init_vftable_syscfg();
if(ret) {
CPUFREQ_ERR("use default V-F Table\n");
}
__vftable_show();
#endif
/* init cpu frequency from sysconfig */
if(__init_freq_syscfg()) {
CPUFREQ_ERR("%s, use default cpu max/min frequency, max freq: %uMHz, min freq: %uMHz\n",
__func__, cpu_freq_max/1000, cpu_freq_min/1000);
}else{
CPUFREQ_INF("%s, get cpu frequency from sysconfig, max freq: %uMHz, min freq: %uMHz\n",
__func__, cpu_freq_max/1000, cpu_freq_min/1000);
}
/* initialise current frequency configuration */
sunxi_cpufreq_getcur(&cpu_cur);
sunxi_cpufreq_show("cur", &cpu_cur);
/* register cpu frequency driver */
ret = cpufreq_register_driver(&sunxi_cpufreq_driver);
return ret;
}
/*
* cpu frequency driver exit
*/
static void __exit sunxi_cpufreq_exitcall(void)
{
clk_put(clk_pll);
clk_put(clk_cpu);
clk_put(clk_axi);
clk_put(clk_ahb);
clk_put(clk_apb);
#ifdef AHB_APB_CLK_ASYNC
clk_put(clk_sata_pll);
#endif
#ifdef CONFIG_CPU_FREQ_DVFS
if(corevdd == NULL) {
regulator_put(corevdd);
corevdd = NULL;
}
#endif
cpufreq_unregister_driver(&sunxi_cpufreq_driver);
}
MODULE_DESCRIPTION("cpufreq driver for sunxi SOCs");
MODULE_LICENSE("GPL");
module_init(sunxi_cpufreq_initcall);
module_exit(sunxi_cpufreq_exitcall);
|
LuckJC/cubie-linux
|
arch/arm/mach-sun7i/cpu-freq/cpu-freq.c
|
C
|
gpl-2.0
| 32,340
|
<?php
/**
* Abstract cover background layer
*
* PHP version 7
*
* Copyright (C) Villanova University 2018.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Cover_Generator
* @author Demian Katz <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:hierarchy_components Wiki
*/
namespace VuFind\Cover\Layer;
/**
* Abstract cover background layer
*
* @category VuFind
* @package Cover_Generator
* @author Demian Katz <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:hierarchy_components Wiki
*/
abstract class AbstractBackgroundLayer extends AbstractLayer
{
/**
* Generates a dynamic cover image from elements of the book
*
* @param string $title Title of the book
* @param string $callnumber Callnumber of the book
*
* @return int unique number for this record
*/
protected function createSeed($title, $callnumber)
{
// Turn callnumber into number
if (null == $callnumber) {
$callnumber = $title;
}
if (null !== $callnumber) {
$cv = 0;
for ($i = 0;$i < strlen($callnumber);$i++) {
$cv += ord($callnumber[$i]);
}
return $cv;
} else {
// If no callnumber, random
return ceil(rand(2 ** 4, 2 ** 32));
}
}
/**
* Generate an accent color from a seed value.
*
* @param resource $im Active image resource
* @param int $seed Seed value
* @param object $settings Generator settings object
*
* @return int
*/
protected function getAccentColor($im, $seed, $settings)
{
// Number to color, hsb to control saturation and lightness
return $settings->accentColor == 'random'
? $this->getHSBColor(
$im,
$seed % 256,
$settings->saturation,
$settings->lightness
) : $this->getColor($im, $settings->accentColor);
}
}
|
vufind-org/vufind
|
module/VuFind/src/VuFind/Cover/Layer/AbstractBackgroundLayer.php
|
PHP
|
gpl-2.0
| 2,874
|
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4773013
* @summary When hunting subpackages, silently ignore any directory name that
* can't be part of a subpackage.
*/
import com.sun.javadoc.*;
public class SubpackageIgnore extends Doclet {
public static void main(String[] args) {
if (com.sun.tools.javadoc.Main.execute(
"javadoc",
"SubpackageIgnore",
SubpackageIgnore.class.getClassLoader(),
new String[] {"-Xwerror",
"-sourcepath",
System.getProperty("test.src", "."),
"-subpackages",
"pkg1"}) != 0)
throw new Error("Javadoc encountered warnings or errors.");
}
/*
* The world's simplest doclet.
*/
public static boolean start(RootDoc root) {
return true;
}
}
|
lucasicf/metricgenerator-jdk-compiler
|
test/tools/javadoc/subpackageIgnore/SubpackageIgnore.java
|
Java
|
gpl-2.0
| 1,946
|
/*
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/** \file
\ingroup u2w
*/
#include "WorldSocket.h" // must be first to make ACE happy with ACE includes in it
#include "Common.h"
#include "Database/DatabaseEnv.h"
#include "Log.h"
#include "Opcodes.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "Player.h"
#include "ObjectMgr.h"
#include "Group.h"
#include "Guild.h"
#include "World.h"
#include "ObjectAccessor.h"
#include "BattleGroundMgr.h"
#include "SocialMgr.h"
/// WorldSession constructor
WorldSession::WorldSession(uint32 id, WorldSocket *sock, uint32 sec, uint8 expansion, time_t mute_time, LocaleConstant locale) :
LookingForGroup_auto_join(false), LookingForGroup_auto_add(false), m_muteTime(mute_time),
_player(NULL), m_Socket(sock),_security(sec), _accountId(id), m_expansion(expansion),
m_sessionDbcLocale(sWorld.GetAvailableDbcLocale(locale)), m_sessionDbLocaleIndex(objmgr.GetIndexForLocale(locale)),
_logoutTime(0), m_inQueue(false), m_playerLoading(false), m_playerLogout(false), m_playerRecentlyLogout(false), m_latency(0)
{
if (sock)
{
m_Address = sock->GetRemoteAddress ();
sock->AddReference ();
}
}
/// WorldSession destructor
WorldSession::~WorldSession()
{
///- unload player if not unloaded
if (_player)
LogoutPlayer (true);
/// - If have unclosed socket, close it
if (m_Socket)
{
m_Socket->CloseSocket ();
m_Socket->RemoveReference ();
m_Socket = NULL;
}
///- empty incoming packet queue
while(!_recvQueue.empty())
{
WorldPacket *packet = _recvQueue.next ();
delete packet;
}
}
void WorldSession::SizeError(WorldPacket const& packet, uint32 size) const
{
sLog.outError("Client (account %u) send packet %s (%u) with size %u but expected %u (attempt crash server?), skipped",
GetAccountId(),LookupOpcodeName(packet.GetOpcode()),packet.GetOpcode(),packet.size(),size);
}
/// Get the player name
char const* WorldSession::GetPlayerName() const
{
return GetPlayer() ? GetPlayer()->GetName() : "<none>";
}
/// Send a packet to the client
void WorldSession::SendPacket(WorldPacket const* packet)
{
if (!m_Socket)
return;
#ifdef MANGOS_DEBUG
// Code for network use statistic
static uint64 sendPacketCount = 0;
static uint64 sendPacketBytes = 0;
static time_t firstTime = time(NULL);
static time_t lastTime = firstTime; // next 60 secs start time
static uint64 sendLastPacketCount = 0;
static uint64 sendLastPacketBytes = 0;
time_t cur_time = time(NULL);
if((cur_time - lastTime) < 60)
{
sendPacketCount+=1;
sendPacketBytes+=packet->size();
sendLastPacketCount+=1;
sendLastPacketBytes+=packet->size();
}
else
{
uint64 minTime = uint64(cur_time - lastTime);
uint64 fullTime = uint64(lastTime - firstTime);
sLog.outDetail("Send all time packets count: " I64FMTD " bytes: " I64FMTD " avr.count/sec: %f avr.bytes/sec: %f time: %u",sendPacketCount,sendPacketBytes,float(sendPacketCount)/fullTime,float(sendPacketBytes)/fullTime,uint32(fullTime));
sLog.outDetail("Send last min packets count: " I64FMTD " bytes: " I64FMTD " avr.count/sec: %f avr.bytes/sec: %f",sendLastPacketCount,sendLastPacketBytes,float(sendLastPacketCount)/minTime,float(sendLastPacketBytes)/minTime);
lastTime = cur_time;
sendLastPacketCount = 1;
sendLastPacketBytes = packet->wpos(); // wpos is real written size
}
#endif // !MANGOS_DEBUG
if (m_Socket->SendPacket (*packet) == -1)
m_Socket->CloseSocket ();
}
/// Add an incoming packet to the queue
void WorldSession::QueuePacket(WorldPacket* new_packet)
{
_recvQueue.add(new_packet);
}
/// Logging helper for unexpected opcodes
void WorldSession::logUnexpectedOpcode(WorldPacket* packet, const char *reason)
{
sLog.outError( "SESSION: received unexpected opcode %s (0x%.4X) %s",
LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode(),
reason);
}
/// Update the WorldSession (triggered by World update)
bool WorldSession::Update(uint32 /*diff*/)
{
///- Retrieve packets from the receive queue and call the appropriate handlers
/// not proccess packets if socket already closed
while (!_recvQueue.empty() && m_Socket && !m_Socket->IsClosed ())
{
WorldPacket *packet = _recvQueue.next();
/*#if 1
sLog.outError( "MOEP: %s (0x%.4X)",
LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode());
#endif*/
if(packet->GetOpcode() >= NUM_MSG_TYPES)
{
sLog.outError( "SESSION: received non-existed opcode %s (0x%.4X)",
LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode());
}
else
{
OpcodeHandler& opHandle = opcodeTable[packet->GetOpcode()];
switch (opHandle.status)
{
case STATUS_LOGGEDIN:
if(!_player)
{
// skip STATUS_LOGGEDIN opcode unexpected errors if player logout sometime ago - this can be network lag delayed packets
if(!m_playerRecentlyLogout)
logUnexpectedOpcode(packet, "the player has not logged in yet");
}
else if(_player->IsInWorld())
(this->*opHandle.handler)(*packet);
// lag can cause STATUS_LOGGEDIN opcodes to arrive after the player started a transfer
break;
case STATUS_TRANSFER_PENDING:
if(!_player)
logUnexpectedOpcode(packet, "the player has not logged in yet");
else if(_player->IsInWorld())
logUnexpectedOpcode(packet, "the player is still in world");
else
(this->*opHandle.handler)(*packet);
break;
case STATUS_AUTHED:
// prevent cheating with skip queue wait
if(m_inQueue)
{
logUnexpectedOpcode(packet, "the player not pass queue yet");
break;
}
m_playerRecentlyLogout = false;
(this->*opHandle.handler)(*packet);
break;
case STATUS_NEVER:
sLog.outError( "SESSION: received not allowed opcode %s (0x%.4X)",
LookupOpcodeName(packet->GetOpcode()),
packet->GetOpcode());
break;
}
}
delete packet;
}
///- Cleanup socket pointer if need
if (m_Socket && m_Socket->IsClosed ())
{
m_Socket->RemoveReference ();
m_Socket = NULL;
}
///- If necessary, log the player out
time_t currTime = time(NULL);
if (!m_Socket || (ShouldLogOut(currTime) && !m_playerLoading))
LogoutPlayer(true);
if (!m_Socket)
return false; //Will remove this session from the world session map
return true;
}
/// %Log the player out
void WorldSession::LogoutPlayer(bool Save)
{
// finish pending transfers before starting the logout
while(_player && _player->IsBeingTeleported())
HandleMoveWorldportAckOpcode();
m_playerLogout = true;
if (_player)
{
if (uint64 lguid = GetPlayer()->GetLootGUID())
DoLootRelease(lguid);
///- If the player just died before logging out, make him appear as a ghost
//FIXME: logout must be delayed in case lost connection with client in time of combat
if (_player->GetDeathTimer())
{
_player->getHostilRefManager().deleteReferences();
_player->BuildPlayerRepop();
_player->RepopAtGraveyard();
}
else if (!_player->getAttackers().empty())
{
_player->CombatStop();
_player->getHostilRefManager().setOnlineOfflineState(false);
_player->RemoveAllAurasOnDeath();
// build set of player who attack _player or who have pet attacking of _player
std::set<Player*> aset;
for(Unit::AttackerSet::const_iterator itr = _player->getAttackers().begin(); itr != _player->getAttackers().end(); ++itr)
{
Unit* owner = (*itr)->GetOwner(); // including player controlled case
if(owner)
{
if(owner->GetTypeId()==TYPEID_PLAYER)
aset.insert((Player*)owner);
}
else
if((*itr)->GetTypeId()==TYPEID_PLAYER)
aset.insert((Player*)(*itr));
}
_player->SetPvPDeath(!aset.empty());
_player->KillPlayer();
_player->BuildPlayerRepop();
_player->RepopAtGraveyard();
// give honor to all attackers from set like group case
for(std::set<Player*>::const_iterator itr = aset.begin(); itr != aset.end(); ++itr)
(*itr)->RewardHonor(_player,aset.size());
// give bg rewards and update counters like kill by first from attackers
// this can't be called for all attackers.
if(!aset.empty())
if(BattleGround *bg = _player->GetBattleGround())
bg->HandleKillPlayer(_player,*aset.begin());
}
else if(_player->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION))
{
// this will kill character by SPELL_AURA_SPIRIT_OF_REDEMPTION
_player->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT);
//_player->SetDeathPvP(*); set at SPELL_AURA_SPIRIT_OF_REDEMPTION apply time
_player->KillPlayer();
_player->BuildPlayerRepop();
_player->RepopAtGraveyard();
}
//drop a flag if player is carrying it
if(BattleGround *bg = _player->GetBattleGround())
bg->EventPlayerLoggedOut(_player);
///- Teleport to home if the player is in an invalid instance
if(!_player->m_InstanceValid && !_player->isGameMaster())
_player->TeleportTo(_player->m_homebindMapId, _player->m_homebindX, _player->m_homebindY, _player->m_homebindZ, _player->GetOrientation());
for (int i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; i++)
{
if(BattleGroundQueueTypeId bgQueueTypeId = _player->GetBattleGroundQueueTypeId(i))
{
_player->RemoveBattleGroundQueueId(bgQueueTypeId);
sBattleGroundMgr.m_BattleGroundQueues[ bgQueueTypeId ].RemovePlayer(_player->GetGUID(), true);
}
}
///- Reset the online field in the account table
// no point resetting online in character table here as Player::SaveToDB() will set it to 1 since player has not been removed from world at this stage
//No SQL injection as AccountID is uint32
loginDatabase.PExecute("UPDATE account SET online = 0 WHERE id = '%u'", GetAccountId());
///- If the player is in a guild, update the guild roster and broadcast a logout message to other guild members
Guild *guild = objmgr.GetGuildById(_player->GetGuildId());
if(guild)
{
guild->LoadPlayerStatsByGuid(_player->GetGUID());
guild->UpdateLogoutTime(_player->GetGUID());
WorldPacket data(SMSG_GUILD_EVENT, (1+1+12+8)); // name limited to 12 in character table.
data<<(uint8)GE_SIGNED_OFF;
data<<(uint8)1;
data<<_player->GetName();
data<<_player->GetGUID();
guild->BroadcastPacket(&data);
}
///- Remove pet
_player->RemovePet(NULL,PET_SAVE_AS_CURRENT, true);
///- empty buyback items and save the player in the database
// some save parts only correctly work in case player present in map/player_lists (pets, etc)
if(Save)
{
uint32 eslot;
for(int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; j++)
{
eslot = j - BUYBACK_SLOT_START;
_player->SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1+eslot*2,0);
_player->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1+eslot,0);
_player->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1+eslot,0);
}
_player->SaveToDB();
}
///- Leave all channels before player delete...
_player->CleanupChannels();
///- If the player is in a group (or invited), remove him. If the group if then only 1 person, disband the group.
_player->UninviteFromGroup();
// remove player from the group if he is:
// a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected)
if(_player->GetGroup() && !_player->GetGroup()->isRaidGroup() && m_Socket)
_player->RemoveFromGroup();
///- Remove the player from the world
// the player may not be in the world when logging out
// e.g if he got disconnected during a transfer to another map
// calls to GetMap in this case may cause crashes
if(_player->IsInWorld()) _player->GetMap()->Remove(_player, false);
// RemoveFromWorld does cleanup that requires the player to be in the accessor
ObjectAccessor::Instance().RemoveObject(_player);
///- Send update to group
if(_player->GetGroup())
_player->GetGroup()->SendUpdate();
///- Broadcast a logout message to the player's friends
sSocialMgr.SendFriendStatus(_player, FRIEND_OFFLINE, _player->GetGUIDLow(), true);
///- Delete the player object
_player->CleanupsBeforeDelete(); // do some cleanup before deleting to prevent crash at crossreferences to already deleted data
sSocialMgr.RemovePlayerSocial (_player->GetGUIDLow ());
delete _player;
_player = NULL;
///- Send the 'logout complete' packet to the client
WorldPacket data( SMSG_LOGOUT_COMPLETE, 0 );
SendPacket( &data );
///- Since each account can only have one online character at any given time, ensure all characters for active account are marked as offline
//No SQL injection as AccountId is uint32
CharacterDatabase.PExecute("UPDATE characters SET online = 0 WHERE account = '%u'",
GetAccountId());
sLog.outDebug( "SESSION: Sent SMSG_LOGOUT_COMPLETE Message" );
}
m_playerLogout = false;
m_playerRecentlyLogout = true;
LogoutRequest(0);
}
/// Kick a player out of the World
void WorldSession::KickPlayer()
{
if (m_Socket)
m_Socket->CloseSocket ();
}
/// Cancel channeling handler
void WorldSession::SendAreaTriggerMessage(const char* Text, ...)
{
va_list ap;
char szStr [1024];
szStr[0] = '\0';
va_start(ap, Text);
vsnprintf( szStr, 1024, Text, ap );
va_end(ap);
uint32 length = strlen(szStr)+1;
WorldPacket data(SMSG_AREA_TRIGGER_MESSAGE, 4+length);
data << length;
data << szStr;
SendPacket(&data);
}
void WorldSession::SendNotification(const char *format,...)
{
if(format)
{
va_list ap;
char szStr [1024];
szStr[0] = '\0';
va_start(ap, format);
vsnprintf( szStr, 1024, format, ap );
va_end(ap);
WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
data << szStr;
SendPacket(&data);
}
}
void WorldSession::SendNotification(int32 string_id,...)
{
char const* format = GetMangosString(string_id);
if(format)
{
va_list ap;
char szStr [1024];
szStr[0] = '\0';
va_start(ap, string_id);
vsnprintf( szStr, 1024, format, ap );
va_end(ap);
WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
data << szStr;
SendPacket(&data);
}
}
void WorldSession::SendSetPhaseShift(uint32 PhaseShift)
{
WorldPacket data(SMSG_SET_PHASE_SHIFT, 4);
data << uint32(PhaseShift);
SendPacket(&data);
}
const char * WorldSession::GetMangosString( int32 entry ) const
{
return objmgr.GetMangosString(entry,GetSessionDbLocaleIndex());
}
void WorldSession::Handle_NULL( WorldPacket& recvPacket )
{
sLog.outError( "SESSION: received unhandled opcode %s (0x%.4X)",
LookupOpcodeName(recvPacket.GetOpcode()),
recvPacket.GetOpcode());
}
void WorldSession::Handle_EarlyProccess( WorldPacket& recvPacket )
{
sLog.outError( "SESSION: received opcode %s (0x%.4X) that must be processed in WorldSocket::OnRead",
LookupOpcodeName(recvPacket.GetOpcode()),
recvPacket.GetOpcode());
}
void WorldSession::Handle_ServerSide( WorldPacket& recvPacket )
{
sLog.outError( "SESSION: received server-side opcode %s (0x%.4X)",
LookupOpcodeName(recvPacket.GetOpcode()),
recvPacket.GetOpcode());
}
void WorldSession::Handle_Deprecated( WorldPacket& recvPacket )
{
sLog.outError( "SESSION: received deprecated opcode %s (0x%.4X)",
LookupOpcodeName(recvPacket.GetOpcode()),
recvPacket.GetOpcode());
}
void WorldSession::SendAuthWaitQue(uint32 position)
{
if(position == 0)
{
WorldPacket packet( SMSG_AUTH_RESPONSE, 1 );
packet << uint8( AUTH_OK );
SendPacket(&packet);
}
else
{
WorldPacket packet( SMSG_AUTH_RESPONSE, 5 );
packet << uint8( AUTH_WAIT_QUEUE );
packet << uint32 (position);
SendPacket(&packet);
}
}
void WorldSession::LoadAccountData()
{
for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i)
{
AccountData data;
m_accountData[i] = data;
}
QueryResult *result = CharacterDatabase.PQuery("SELECT type, time, data FROM account_data WHERE account='%u'", GetAccountId());
if(!result)
return;
do
{
Field *fields = result->Fetch();
uint32 type = fields[0].GetUInt32();
if(type < NUM_ACCOUNT_DATA_TYPES)
{
m_accountData[type].Time = fields[1].GetUInt32();
m_accountData[type].Data = fields[2].GetCppString();
}
} while (result->NextRow());
delete result;
}
void WorldSession::SetAccountData(uint32 type, time_t time_, std::string data)
{
m_accountData[type].Time = time_;
m_accountData[type].Data = data;
uint32 acc = GetAccountId();
CharacterDatabase.BeginTransaction ();
CharacterDatabase.PExecute("DELETE FROM account_data WHERE account='%u' AND type='%u'", acc, type);
CharacterDatabase.escape_string(data);
CharacterDatabase.PExecute("INSERT INTO account_data VALUES ('%u','%u','%u','%s')", acc, type, (uint32)time_, data.c_str());
CharacterDatabase.CommitTransaction ();
}
void WorldSession::ReadMovementInfo(WorldPacket &data, MovementInfo *mi)
{
CHECK_PACKET_SIZE(data, data.rpos()+4+2+4+4+4+4+4);
data >> mi->flags;
data >> mi->unk1;
data >> mi->time;
data >> mi->x;
data >> mi->y;
data >> mi->z;
data >> mi->o;
if(mi->flags & MOVEMENTFLAG_ONTRANSPORT)
{
CHECK_PACKET_SIZE(data, data.rpos()+8+4+4+4+4+4+1);
data >> mi->t_guid;
data >> mi->t_x;
data >> mi->t_y;
data >> mi->t_z;
data >> mi->t_o;
data >> mi->t_time;
data >> mi->t_seat;
}
if((mi->flags & (MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING2)) || (mi->unk1 & 0x20))
{
CHECK_PACKET_SIZE(data, data.rpos()+4);
data >> mi->s_pitch;
}
CHECK_PACKET_SIZE(data, data.rpos()+4);
data >> mi->fallTime;
if(mi->flags & MOVEMENTFLAG_JUMPING)
{
CHECK_PACKET_SIZE(data, data.rpos()+4+4+4+4);
data >> mi->j_unk;
data >> mi->j_sinAngle;
data >> mi->j_cosAngle;
data >> mi->j_xyspeed;
}
if(mi->flags & MOVEMENTFLAG_SPLINE)
{
CHECK_PACKET_SIZE(data, data.rpos()+4);
data >> mi->u_unk1;
}
}
|
katsumy186/mangos
|
src/game/WorldSession.cpp
|
C++
|
gpl-2.0
| 21,073
|
package teammates.test.cases.action;
import java.util.Date;
import java.util.Map;
import org.testng.annotations.Test;
import teammates.common.datatransfer.attributes.FeedbackSessionAttributes;
import teammates.common.exception.NullPostParameterException;
import teammates.common.util.Const;
import teammates.common.util.Const.ParamsNames;
import teammates.common.util.TaskWrapper;
import teammates.common.util.TimeHelper;
import teammates.storage.api.FeedbackSessionsDb;
import teammates.ui.controller.InstructorFeedbackPublishAction;
import teammates.ui.controller.RedirectResult;
/**
* SUT: {@link InstructorFeedbackPublishAction}.
*/
public class InstructorFeedbackPublishActionTest extends BaseActionTest {
@Override
protected String getActionUri() {
return Const.ActionURIs.INSTRUCTOR_FEEDBACK_PUBLISH;
}
@Override
@Test
public void testExecuteAndPostProcess() throws Exception {
gaeSimulation.loginAsInstructor(dataBundle.instructors.get("instructor1OfCourse1").googleId);
FeedbackSessionAttributes session = dataBundle.feedbackSessions.get("session2InCourse1");
String[] paramsNormal = {
Const.ParamsNames.COURSE_ID, session.getCourseId(),
Const.ParamsNames.FEEDBACK_SESSION_NAME,
session.getFeedbackSessionName()
};
String[] paramsWithNullCourseId = {
Const.ParamsNames.FEEDBACK_SESSION_NAME,
session.getFeedbackSessionName()
};
String[] paramsWithNullFeedbackSessionName = {
Const.ParamsNames.COURSE_ID,
session.getCourseId()
};
______TS("Typical successful case: session publishable");
makeFeedbackSessionUnpublished(session);
InstructorFeedbackPublishAction publishAction = getAction(paramsNormal);
RedirectResult result = getRedirectResult(publishAction);
String expectedDestination = getPageResultDestination(
Const.ActionURIs.INSTRUCTOR_FEEDBACK_SESSIONS_PAGE, false, "idOfInstructor1OfCourse1");
assertEquals(expectedDestination, result.getDestinationWithParams());
assertEquals(Const.StatusMessages.FEEDBACK_SESSION_PUBLISHED, result.getStatusMessage());
assertFalse(result.isError);
verifySpecifiedTasksAdded(publishAction, Const.TaskQueue.FEEDBACK_SESSION_PUBLISHED_EMAIL_QUEUE_NAME, 1);
TaskWrapper taskAdded = publishAction.getTaskQueuer().getTasksAdded().get(0);
Map<String, String[]> paramMap = taskAdded.getParamMap();
assertEquals(session.getCourseId(), paramMap.get(ParamsNames.EMAIL_COURSE)[0]);
assertEquals(session.getSessionName(), paramMap.get(ParamsNames.EMAIL_FEEDBACK)[0]);
______TS("Unsuccessful case 1: params with null course id");
String errorMessage = "";
publishAction = getAction(paramsWithNullCourseId);
try {
publishAction.executeAndPostProcess();
signalFailureToDetectException("NullPostParameterException expected");
} catch (NullPostParameterException e) {
errorMessage = e.getMessage();
}
assertEquals(
String.format(Const.StatusCodes.NULL_POST_PARAMETER, Const.ParamsNames.COURSE_ID),
errorMessage);
______TS("Unsuccessful case 2: params with null feedback session name");
errorMessage = "";
publishAction = getAction(paramsWithNullFeedbackSessionName);
try {
publishAction.executeAndPostProcess();
signalFailureToDetectException("NullPostParameterException expected");
} catch (NullPostParameterException e) {
errorMessage = e.getMessage();
}
assertEquals(
String.format(Const.StatusCodes.NULL_POST_PARAMETER, Const.ParamsNames.FEEDBACK_SESSION_NAME),
errorMessage);
______TS("Unsuccessful case 3: trying to publish a session not currently unpublished");
makeFeedbackSessionPublished(session);
publishAction = getAction(paramsNormal);
result = getRedirectResult(publishAction);
expectedDestination = getPageResultDestination(
Const.ActionURIs.INSTRUCTOR_FEEDBACK_SESSIONS_PAGE, true, "idOfInstructor1OfCourse1");
assertEquals(expectedDestination, result.getDestinationWithParams());
assertEquals("Error publishing feedback session: Session has already been published.",
result.getStatusMessage());
assertTrue(result.isError);
verifyNoTasksAdded(publishAction);
makeFeedbackSessionUnpublished(session);
}
private void modifyFeedbackSessionPublishState(FeedbackSessionAttributes session, boolean isPublished) throws Exception {
// startTime < endTime <= resultsVisibleFromTime
Date startTime = TimeHelper.getDateOffsetToCurrentTime(-2);
Date endTime = TimeHelper.getDateOffsetToCurrentTime(-1);
Date resultsVisibleFromTimeForPublishedSession = TimeHelper.getDateOffsetToCurrentTime(-1);
session.setStartTime(startTime);
session.setEndTime(endTime);
if (isPublished) {
session.setResultsVisibleFromTime(resultsVisibleFromTimeForPublishedSession);
assertTrue(session.isPublished());
} else {
session.setResultsVisibleFromTime(Const.TIME_REPRESENTS_LATER);
assertFalse(session.isPublished());
}
session.setSentPublishedEmail(false);
new FeedbackSessionsDb().updateFeedbackSession(session);
}
private void makeFeedbackSessionUnpublished(FeedbackSessionAttributes session) throws Exception {
modifyFeedbackSessionPublishState(session, false);
}
private void makeFeedbackSessionPublished(FeedbackSessionAttributes session) throws Exception {
modifyFeedbackSessionPublishState(session, true);
}
@Override
protected InstructorFeedbackPublishAction getAction(String... params) {
return (InstructorFeedbackPublishAction) gaeSimulation.getActionObject(getActionUri(), params);
}
@Override
@Test
protected void testAccessControl() throws Exception {
FeedbackSessionAttributes session = dataBundle.feedbackSessions.get("session1InCourse1");
makeFeedbackSessionUnpublished(session); //we have to revert to the closed state
String[] submissionParams = new String[]{
Const.ParamsNames.COURSE_ID, session.getCourseId(),
Const.ParamsNames.FEEDBACK_SESSION_NAME, session.getFeedbackSessionName()
};
verifyUnaccessibleWithoutLogin(submissionParams);
verifyUnaccessibleForUnregisteredUsers(submissionParams);
verifyUnaccessibleForStudents(submissionParams);
verifyUnaccessibleForInstructorsOfOtherCourses(submissionParams);
verifyUnaccessibleWithoutModifySessionPrivilege(submissionParams);
verifyAccessibleForInstructorsOfTheSameCourse(submissionParams);
makeFeedbackSessionUnpublished(session); //we have to revert to the closed state
verifyAccessibleForAdminToMasqueradeAsInstructor(submissionParams);
}
}
|
BrianCoveney/teammates
|
src/test/java/teammates/test/cases/action/InstructorFeedbackPublishActionTest.java
|
Java
|
gpl-2.0
| 7,215
|
# This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
from contextlib import contextmanager
import sqlalchemy as sa
from sqlalchemy.ext import compiler
from sqlalchemy.sql.expression import ClauseElement
from sqlalchemy.sql.expression import Executable
# from http:
# //www.sqlalchemy.org/docs/core/compiler.html#compiling-sub-elements-of-a-custom-expression-construct # noqa pylint: disable=line-too-long
# _execution_options per
# http://docs.sqlalchemy.org/en/rel_0_7/core/compiler.html#enabling-compiled-autocommit
# (UpdateBase requires sqlalchemy 0.7.0)
class InsertFromSelect(Executable, ClauseElement):
_execution_options = \
Executable._execution_options.union({'autocommit': True})
def __init__(self, table, select):
self.table = table
self.select = select
@compiler.compiles(InsertFromSelect)
def _visit_insert_from_select(element, compiler, **kw):
return "INSERT INTO {} {}".format(compiler.process(element.table, asfrom=True),
compiler.process(element.select))
def sa_version():
if hasattr(sa, '__version__'):
def tryint(s):
try:
return int(s)
except (ValueError, TypeError):
return -1
return tuple(map(tryint, sa.__version__.split('.')))
return (0, 0, 0) # "it's old"
def Table(*args, **kwargs):
"""Wrap table creation to add any necessary dialect-specific options"""
# work around the case where a database was created for us with
# a non-utf8 character set (mysql's default)
kwargs['mysql_character_set'] = 'utf8'
return sa.Table(*args, **kwargs)
@contextmanager
def withoutSqliteForeignKeys(engine, connection=None):
conn = connection
if engine.dialect.name == 'sqlite':
if conn is None:
conn = engine.connect()
# This context is not re-entrant. Ensure it.
assert not getattr(engine, 'fk_disabled', False)
engine.fk_disabled = True
conn.execute('pragma foreign_keys=OFF')
try:
yield
finally:
if engine.dialect.name == 'sqlite':
engine.fk_disabled = False
conn.execute('pragma foreign_keys=ON')
if connection is None:
conn.close()
|
anish/buildbot
|
master/buildbot/util/sautils.py
|
Python
|
gpl-2.0
| 2,925
|
/***************************************************************************
* (C) Copyright 2017 - Stendhal *
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
package games.stendhal.server.maps.ados.city;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import games.stendhal.server.core.config.ZoneConfigurator;
import games.stendhal.server.core.engine.StendhalRPZone;
import games.stendhal.server.core.pathfinder.FixedPath;
import games.stendhal.server.core.pathfinder.Node;
import games.stendhal.server.entity.npc.SpeakerNPC;
/**
* Soldiers on the wall
*
* @author snowflake
* @author hendrik
*/
public class WallSoldier1NPC implements ZoneConfigurator {
/**
* Configure a zone.
*
* @param zone The zone to be configured.
* @param attributes Configuration attributes.
*/
@Override
public void configureZone(final StendhalRPZone zone, final Map<String, String> attributes) {
buildAdosWallSoldier(zone);
}
/**
* Creatures a soldier on the city wall
*
* @param zone StendhalRPZone
*/
private void buildAdosWallSoldier(final StendhalRPZone zone) {
final SpeakerNPC npc = new SpeakerNPC("Helius") {
@Override
protected void createPath() {
final List<Node> path = new LinkedList<Node>();
path.add(new Node(26, 73));
path.add(new Node(48, 73));
path.add(new Node(48, 70));
path.add(new Node(26, 70));
setPath(new FixedPath(path, true));
}
@Override
protected void createDialog() {
addGreeting("Hi, welcome to Ados City!");
addJob("A job? Are you blind? I'm a guard! Isn't this obvious? Please move along, citizen.");
addHelp("I don't have time for chatting. If you need help, better ask Julius. He's located at the main entrance of the city.");
addGoodbye("Goodbye.");
}
};
npc.setEntityClass("youngsoldiernpc");
npc.setPosition(26, 73);
npc.initHP(100);
npc.setDescription("You see Helius, a soldier who guards the city wall of Ados.");
zone.add(npc);
}
}
|
AntumDeluge/arianne-stendhal
|
src/games/stendhal/server/maps/ados/city/WallSoldier1NPC.java
|
Java
|
gpl-2.0
| 2,680
|
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Copyright (C) 2008 Sun Microsystems, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#pragma once
#include <drizzled/item/ref.h>
#include <drizzled/item/direct_ref.h>
#include <drizzled/item/field.h>
/*
Class for outer fields.
An object of this class is created when the select where the outer field was
resolved is a grouping one. After it has been fixed the ref field will point
to either an Item_ref or an Item_direct_ref object which will be used to
access the field.
See also comments for the fix_inner_refs() and the
Item_field::fix_outer_field() functions.
*/
namespace drizzled {
class Item_outer_ref : public Item_direct_ref
{
public:
Item *outer_ref;
/* The aggregate function under which this outer ref is used, if any. */
Item_sum *in_sum_func;
/*
true <=> that the outer_ref is already present in the select list
of the outer select.
*/
bool found_in_select_list;
Item_outer_ref(Name_resolution_context *context_arg,
Item_field *outer_field_arg)
:Item_direct_ref(context_arg, 0, outer_field_arg->table_name,
outer_field_arg->field_name),
outer_ref(outer_field_arg), in_sum_func(0),
found_in_select_list(0)
{
ref= &outer_ref;
set_properties();
fixed= 0;
}
Item_outer_ref(Name_resolution_context *context_arg, Item **item,
const char *table_name_arg, const char *field_name_arg,
bool alias_name_used_arg)
:Item_direct_ref(context_arg, item, table_name_arg, field_name_arg,
alias_name_used_arg),
outer_ref(0), in_sum_func(0), found_in_select_list(1)
{}
void save_in_result_field(bool)
{
outer_ref->save_org_in_field(result_field);
}
bool fix_fields(Session *, Item **);
void fix_after_pullout(Select_Lex *new_parent, Item **ref);
table_map used_tables() const
{
return (*ref)->const_item() ? 0 : OUTER_REF_TABLE_BIT;
}
virtual Ref_Type ref_type() { return OUTER_REF; }
};
} /* namespace drizzled */
|
0xffea/drizzle
|
drizzled/item/outer_ref.h
|
C
|
gpl-2.0
| 2,772
|
include ../Makefile.include
ifneq ($(shell test -f $(PREFIX)/share/config.site && echo 1),1)
$(error Error: $(PREFIX)/share/config.site is missing. Please reconfigure depends to generate it)
endif
DEPENDS = \
pcre expat gettext sqlite3 libgpg-error \
libgcrypt bzip2 liblzo2 libzip freetype2 fontconfig \
openssl gmp nettle gnutls libssh2 curl \
libjpeg-turbo tiff jasper libpng \
libogg libvorbis libflac fribidi libmpeg2 \
libass libsquish \
libmodplug librtmp libxml2 yajl libmicrohttpd mysql libffi \
python26 libshairplay \
libplist libcec libbluray boost tinyxml dummy-libxbmc \
libamplayer libssh taglib libusb libnfs libmp3lame \
pythonmodule-pil libxslt ffmpeg platform crossguid libdcadec
FFMPEG_DEPENDS = gnutls libdcadec
ifeq ($(ENABLE_GPLV3),yes)
DEPENDS+=samba-gplv3 libcdio-gplv3
else
DEPENDS+=samba libcdio
endif
ifeq ($(OS),ios)
DEPENDS += Backrow
EXCLUDED_DEPENDS = libcec libusb
endif
ifeq ($(OS),osx)
DEPENDS += libGLEW libsdl
EXCLUDED_DEPENDS = libusb
endif
ifeq ($(OS),android)
DEPENDS += mdnsresponder android-sources-ics google-breakpad
endif
DEPENDS := $(filter-out $(EXCLUDED_DEPENDS),$(DEPENDS))
ZLIB=
ifneq ($(HAS_ZLIB),1)
DEPENDS += zlib
ZLIB = zlib
endif
ICONV=
ifeq ($(NEED_LIBICONV),1)
DEPENDS += libiconv
ICONV = libiconv
endif
ALSA_LIB=
LINUX_SYSTEM_LIBS=
ifeq ($(OS),linux)
DEPENDS += libuuid
#not for raspberry pi
ifneq ($(TARGET_PLATFORM),raspberry-pi)
DEPENDS += libsdl2 linux-system-libs
LINUX_SYSTEM_LIBS = linux-system-libs
endif
DEPENDS += alsa-lib
ALSA_LIB = alsa-lib
endif
.PHONY: $(DEPENDS)
all: .installed-$(PLATFORM)
gettext: $(ICONV)
libgcrypt: libgpg-error
fontconfig: freetype2 expat $(ICONV)
libssh2: libgcrypt openssl
curl: openssl libssh2
tiff: libjpeg-turbo
jasper: libjpeg-turbo
libvorbis: libogg
libflac: libogg gettext
libass: fontconfig libpng freetype2 expat $(ICONV)
librtmp: openssl
libmicrohttpd: gnutls libgcrypt libgpg-error
python26: expat gettext libxml2 sqlite3 openssl libffi
libcdio: $(ICONV)
libplist: libxml2 $(ZLIB)
libbluray: $(ICONV) libxml2
libssh: openssl
mysql: openssl
libzip: $(ZLIB)
libmp3lame: $(ICONV)
libpng: $(ZLIB)
openssl: $(ZLIB)
gnutls: nettle $(ZLIB)
nettle: gmp
pythonmodule-pil: $(ZLIB) libjpeg-turbo libpng freetype2 python26
libsdl2: $(LINUX_SYSTEM_LIBS)
libxslt: libgcrypt
ffmpeg: $(ICONV) $(ZLIB) bzip2 libvorbis $(FFMPEG_DEPENDS)
libcec: platform
ifeq ($(OS),linux)
crossguid: libuuid
endif
.installed-$(PLATFORM): $(DEPENDS)
touch $@
@echo "Dependencies built successfully."
$(DEPENDS):
$(MAKE) -C $@
clean:
for d in $(DEPENDS); do $(MAKE) -C $$d clean; done
# Debug target, this will DELETE all data in staging!
test-dependencies:
( for d in $(DEPENDS); do \
rm -rf $(PREFIX); \
mkdir -p $(PREFIX)/include $(PREFIX)/share $(PREFIX)/bin; \
cp -f config.site Toolchain.cmake $(PREFIX)/share/; \
$(MAKE) distclean; \
$(MAKE) $$d; done ) && echo "$@ built successfully"
distclean::
for d in $(DEPENDS); do $(MAKE) -C $$d distclean; done
linux-system-libs:
[ -f $(PREFIX)/lib/pkgconfig/x11.pc ] || ln -s /usr/lib/$(HOST)/pkgconfig/x11.pc $(PREFIX)/lib/pkgconfig/x11.pc
[ -f $(PREFIX)/lib/pkgconfig/xproto.pc ] || ln -s /usr/share/pkgconfig/xproto.pc $(PREFIX)/lib/pkgconfig/xproto.pc
[ -f $(PREFIX)/lib/pkgconfig/kbproto.pc ] || ln -s /usr/share/pkgconfig/kbproto.pc $(PREFIX)/lib/pkgconfig/kbproto.pc
[ -f $(PREFIX)/lib/pkgconfig/xcb.pc ] || ln -s /usr/lib/$(HOST)/pkgconfig/xcb.pc $(PREFIX)/lib/pkgconfig/xcb.pc
[ -f $(PREFIX)/lib/pkgconfig/pthread-stubs.pc ] || ln -s /usr/lib/$(HOST)/pkgconfig/pthread-stubs.pc $(PREFIX)/lib/pkgconfig/pthread-stubs.pc
[ -f $(PREFIX)/lib/pkgconfig/xau.pc ] || ln -s /usr/lib/$(HOST)/pkgconfig/xau.pc $(PREFIX)/lib/pkgconfig/xau.pc
[ -f $(PREFIX)/lib/pkgconfig/xdmcp.pc ] || ln -s /usr/lib/$(HOST)/pkgconfig/xdmcp.pc $(PREFIX)/lib/pkgconfig/xdmcp.pc
[ -f $(PREFIX)/lib/pkgconfig/xext.pc ] || ln -s /usr/lib/$(HOST)/pkgconfig/xext.pc $(PREFIX)/lib/pkgconfig/xext.pc
[ -f $(PREFIX)/lib/pkgconfig/xextproto.pc ] || ln -s /usr/share/pkgconfig/xextproto.pc $(PREFIX)/lib/pkgconfig/xextproto.pc
[ -f $(PREFIX)/lib/pkgconfig/xrandr.pc ] || ln -s /usr/lib/$(HOST)/pkgconfig/xrandr.pc $(PREFIX)/lib/pkgconfig/xrandr.pc
[ -f $(PREFIX)/lib/pkgconfig/xrender.pc ] || ln -s /usr/lib/$(HOST)/pkgconfig/xrender.pc $(PREFIX)/lib/pkgconfig/xrender.pc
[ -f $(PREFIX)/lib/pkgconfig/randrproto.pc ] || ln -s /usr/share/pkgconfig/randrproto.pc $(PREFIX)/lib/pkgconfig/randrproto.pc
[ -f $(PREFIX)/lib/pkgconfig/renderproto.pc ] || ln -s /usr/share/pkgconfig/renderproto.pc $(PREFIX)/lib/pkgconfig/renderproto.pc
[ -f $(PREFIX)/lib/pkgconfig/xt.pc ] || ln -s /usr/lib/$(HOST)/pkgconfig/xt.pc $(PREFIX)/lib/pkgconfig/xt.pc
[ -f $(PREFIX)/lib/pkgconfig/ice.pc ] || ln -s /usr/lib/$(HOST)/pkgconfig/ice.pc $(PREFIX)/lib/pkgconfig/ice.pc
[ -f $(PREFIX)/lib/pkgconfig/sm.pc ] || ln -s /usr/lib/$(HOST)/pkgconfig/sm.pc $(PREFIX)/lib/pkgconfig/sm.pc
[ -f $(PREFIX)/lib/pkgconfig/xmu.pc ] || ln -s /usr/lib/$(HOST)/pkgconfig/xmu.pc $(PREFIX)/lib/pkgconfig/xmu.pc
[ -f $(PREFIX)/lib/pkgconfig/libdrm.pc ] || ln -s /usr/lib/$(HOST)/pkgconfig/libdrm.pc $(PREFIX)/lib/pkgconfig/libdrm.pc
|
zidootech/zidoo-kodi-15.1
|
tools/depends/target/Makefile
|
Makefile
|
gpl-2.0
| 5,189
|
/* $Id: tif_dirinfo.c,v 1.28 2009/09/06 13:11:27 drolon Exp $ */
/*
* Copyright (c) 1988-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
/*
* TIFF Library.
*
* Core Directory Tag Support.
*/
#include "tiffiop.h"
#include <stdlib.h>
/*
* NB: NB: THIS ARRAY IS ASSUMED TO BE SORTED BY TAG.
* If a tag can have both LONG and SHORT types then the LONG must be
* placed before the SHORT for writing to work properly.
*
* NOTE: The second field (field_readcount) and third field (field_writecount)
* sometimes use the values TIFF_VARIABLE (-1), TIFF_VARIABLE2 (-3)
* and TIFFTAG_SPP (-2). The macros should be used but would throw off
* the formatting of the code, so please interprete the -1, -2 and -3
* values accordingly.
*/
static const TIFFFieldInfo
tiffFieldInfo[] = {
{ TIFFTAG_SUBFILETYPE, 1, 1, TIFF_LONG, FIELD_SUBFILETYPE,
1, 0, "SubfileType" },
/* XXX SHORT for compatibility w/ old versions of the library */
{ TIFFTAG_SUBFILETYPE, 1, 1, TIFF_SHORT, FIELD_SUBFILETYPE,
1, 0, "SubfileType" },
{ TIFFTAG_OSUBFILETYPE, 1, 1, TIFF_SHORT, FIELD_SUBFILETYPE,
1, 0, "OldSubfileType" },
{ TIFFTAG_IMAGEWIDTH, 1, 1, TIFF_LONG, FIELD_IMAGEDIMENSIONS,
0, 0, "ImageWidth" },
{ TIFFTAG_IMAGEWIDTH, 1, 1, TIFF_SHORT, FIELD_IMAGEDIMENSIONS,
0, 0, "ImageWidth" },
{ TIFFTAG_IMAGELENGTH, 1, 1, TIFF_LONG, FIELD_IMAGEDIMENSIONS,
1, 0, "ImageLength" },
{ TIFFTAG_IMAGELENGTH, 1, 1, TIFF_SHORT, FIELD_IMAGEDIMENSIONS,
1, 0, "ImageLength" },
{ TIFFTAG_BITSPERSAMPLE, -1,-1, TIFF_SHORT, FIELD_BITSPERSAMPLE,
0, 0, "BitsPerSample" },
/* XXX LONG for compatibility with some broken TIFF writers */
{ TIFFTAG_BITSPERSAMPLE, -1,-1, TIFF_LONG, FIELD_BITSPERSAMPLE,
0, 0, "BitsPerSample" },
{ TIFFTAG_COMPRESSION, -1, 1, TIFF_SHORT, FIELD_COMPRESSION,
0, 0, "Compression" },
/* XXX LONG for compatibility with some broken TIFF writers */
{ TIFFTAG_COMPRESSION, -1, 1, TIFF_LONG, FIELD_COMPRESSION,
0, 0, "Compression" },
{ TIFFTAG_PHOTOMETRIC, 1, 1, TIFF_SHORT, FIELD_PHOTOMETRIC,
0, 0, "PhotometricInterpretation" },
/* XXX LONG for compatibility with some broken TIFF writers */
{ TIFFTAG_PHOTOMETRIC, 1, 1, TIFF_LONG, FIELD_PHOTOMETRIC,
0, 0, "PhotometricInterpretation" },
{ TIFFTAG_THRESHHOLDING, 1, 1, TIFF_SHORT, FIELD_THRESHHOLDING,
1, 0, "Threshholding" },
{ TIFFTAG_CELLWIDTH, 1, 1, TIFF_SHORT, FIELD_IGNORE,
1, 0, "CellWidth" },
{ TIFFTAG_CELLLENGTH, 1, 1, TIFF_SHORT, FIELD_IGNORE,
1, 0, "CellLength" },
{ TIFFTAG_FILLORDER, 1, 1, TIFF_SHORT, FIELD_FILLORDER,
0, 0, "FillOrder" },
{ TIFFTAG_DOCUMENTNAME, -1,-1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "DocumentName" },
{ TIFFTAG_IMAGEDESCRIPTION, -1,-1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "ImageDescription" },
{ TIFFTAG_MAKE, -1,-1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "Make" },
{ TIFFTAG_MODEL, -1,-1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "Model" },
{ TIFFTAG_STRIPOFFSETS, -1,-1, TIFF_LONG, FIELD_STRIPOFFSETS,
0, 0, "StripOffsets" },
{ TIFFTAG_STRIPOFFSETS, -1,-1, TIFF_SHORT, FIELD_STRIPOFFSETS,
0, 0, "StripOffsets" },
{ TIFFTAG_ORIENTATION, 1, 1, TIFF_SHORT, FIELD_ORIENTATION,
0, 0, "Orientation" },
{ TIFFTAG_SAMPLESPERPIXEL, 1, 1, TIFF_SHORT, FIELD_SAMPLESPERPIXEL,
0, 0, "SamplesPerPixel" },
{ TIFFTAG_ROWSPERSTRIP, 1, 1, TIFF_LONG, FIELD_ROWSPERSTRIP,
0, 0, "RowsPerStrip" },
{ TIFFTAG_ROWSPERSTRIP, 1, 1, TIFF_SHORT, FIELD_ROWSPERSTRIP,
0, 0, "RowsPerStrip" },
{ TIFFTAG_STRIPBYTECOUNTS, -1,-1, TIFF_LONG, FIELD_STRIPBYTECOUNTS,
0, 0, "StripByteCounts" },
{ TIFFTAG_STRIPBYTECOUNTS, -1,-1, TIFF_SHORT, FIELD_STRIPBYTECOUNTS,
0, 0, "StripByteCounts" },
{ TIFFTAG_MINSAMPLEVALUE, -2,-1, TIFF_SHORT, FIELD_MINSAMPLEVALUE,
1, 0, "MinSampleValue" },
{ TIFFTAG_MAXSAMPLEVALUE, -2,-1, TIFF_SHORT, FIELD_MAXSAMPLEVALUE,
1, 0, "MaxSampleValue" },
{ TIFFTAG_XRESOLUTION, 1, 1, TIFF_RATIONAL, FIELD_RESOLUTION,
1, 0, "XResolution" },
{ TIFFTAG_YRESOLUTION, 1, 1, TIFF_RATIONAL, FIELD_RESOLUTION,
1, 0, "YResolution" },
{ TIFFTAG_PLANARCONFIG, 1, 1, TIFF_SHORT, FIELD_PLANARCONFIG,
0, 0, "PlanarConfiguration" },
{ TIFFTAG_PAGENAME, -1,-1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "PageName" },
{ TIFFTAG_XPOSITION, 1, 1, TIFF_RATIONAL, FIELD_POSITION,
1, 0, "XPosition" },
{ TIFFTAG_YPOSITION, 1, 1, TIFF_RATIONAL, FIELD_POSITION,
1, 0, "YPosition" },
{ TIFFTAG_FREEOFFSETS, -1,-1, TIFF_LONG, FIELD_IGNORE,
0, 0, "FreeOffsets" },
{ TIFFTAG_FREEBYTECOUNTS, -1,-1, TIFF_LONG, FIELD_IGNORE,
0, 0, "FreeByteCounts" },
{ TIFFTAG_GRAYRESPONSEUNIT, 1, 1, TIFF_SHORT, FIELD_IGNORE,
1, 0, "GrayResponseUnit" },
{ TIFFTAG_GRAYRESPONSECURVE,-1,-1, TIFF_SHORT, FIELD_IGNORE,
1, 0, "GrayResponseCurve" },
{ TIFFTAG_RESOLUTIONUNIT, 1, 1, TIFF_SHORT, FIELD_RESOLUTIONUNIT,
1, 0, "ResolutionUnit" },
{ TIFFTAG_PAGENUMBER, 2, 2, TIFF_SHORT, FIELD_PAGENUMBER,
1, 0, "PageNumber" },
{ TIFFTAG_COLORRESPONSEUNIT, 1, 1, TIFF_SHORT, FIELD_IGNORE,
1, 0, "ColorResponseUnit" },
{ TIFFTAG_TRANSFERFUNCTION, -1,-1, TIFF_SHORT, FIELD_TRANSFERFUNCTION,
1, 0, "TransferFunction" },
{ TIFFTAG_SOFTWARE, -1,-1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "Software" },
{ TIFFTAG_DATETIME, 20,20, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "DateTime" },
{ TIFFTAG_ARTIST, -1,-1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "Artist" },
{ TIFFTAG_HOSTCOMPUTER, -1,-1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "HostComputer" },
{ TIFFTAG_WHITEPOINT, 2, 2, TIFF_RATIONAL, FIELD_CUSTOM,
1, 0, "WhitePoint" },
{ TIFFTAG_PRIMARYCHROMATICITIES,6,6,TIFF_RATIONAL, FIELD_CUSTOM,
1, 0, "PrimaryChromaticities" },
{ TIFFTAG_COLORMAP, -1,-1, TIFF_SHORT, FIELD_COLORMAP,
1, 0, "ColorMap" },
{ TIFFTAG_HALFTONEHINTS, 2, 2, TIFF_SHORT, FIELD_HALFTONEHINTS,
1, 0, "HalftoneHints" },
{ TIFFTAG_TILEWIDTH, 1, 1, TIFF_LONG, FIELD_TILEDIMENSIONS,
0, 0, "TileWidth" },
{ TIFFTAG_TILEWIDTH, 1, 1, TIFF_SHORT, FIELD_TILEDIMENSIONS,
0, 0, "TileWidth" },
{ TIFFTAG_TILELENGTH, 1, 1, TIFF_LONG, FIELD_TILEDIMENSIONS,
0, 0, "TileLength" },
{ TIFFTAG_TILELENGTH, 1, 1, TIFF_SHORT, FIELD_TILEDIMENSIONS,
0, 0, "TileLength" },
{ TIFFTAG_TILEOFFSETS, -1, 1, TIFF_LONG, FIELD_STRIPOFFSETS,
0, 0, "TileOffsets" },
{ TIFFTAG_TILEBYTECOUNTS, -1, 1, TIFF_LONG, FIELD_STRIPBYTECOUNTS,
0, 0, "TileByteCounts" },
{ TIFFTAG_TILEBYTECOUNTS, -1, 1, TIFF_SHORT, FIELD_STRIPBYTECOUNTS,
0, 0, "TileByteCounts" },
{ TIFFTAG_SUBIFD, -1,-1, TIFF_IFD, FIELD_SUBIFD,
1, 1, "SubIFD" },
{ TIFFTAG_SUBIFD, -1,-1, TIFF_LONG, FIELD_SUBIFD,
1, 1, "SubIFD" },
{ TIFFTAG_INKSET, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
0, 0, "InkSet" },
{ TIFFTAG_INKNAMES, -1,-1, TIFF_ASCII, FIELD_INKNAMES,
1, 1, "InkNames" },
{ TIFFTAG_NUMBEROFINKS, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "NumberOfInks" },
{ TIFFTAG_DOTRANGE, 2, 2, TIFF_SHORT, FIELD_CUSTOM,
0, 0, "DotRange" },
{ TIFFTAG_DOTRANGE, 2, 2, TIFF_BYTE, FIELD_CUSTOM,
0, 0, "DotRange" },
{ TIFFTAG_TARGETPRINTER, -1,-1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "TargetPrinter" },
{ TIFFTAG_EXTRASAMPLES, -1,-1, TIFF_SHORT, FIELD_EXTRASAMPLES,
0, 1, "ExtraSamples" },
/* XXX for bogus Adobe Photoshop v2.5 files */
{ TIFFTAG_EXTRASAMPLES, -1,-1, TIFF_BYTE, FIELD_EXTRASAMPLES,
0, 1, "ExtraSamples" },
{ TIFFTAG_SAMPLEFORMAT, -1,-1, TIFF_SHORT, FIELD_SAMPLEFORMAT,
0, 0, "SampleFormat" },
{ TIFFTAG_SMINSAMPLEVALUE, -2,-1, TIFF_ANY, FIELD_SMINSAMPLEVALUE,
1, 0, "SMinSampleValue" },
{ TIFFTAG_SMAXSAMPLEVALUE, -2,-1, TIFF_ANY, FIELD_SMAXSAMPLEVALUE,
1, 0, "SMaxSampleValue" },
{ TIFFTAG_CLIPPATH, -1, -3, TIFF_BYTE, FIELD_CUSTOM,
0, 1, "ClipPath" },
{ TIFFTAG_XCLIPPATHUNITS, 1, 1, TIFF_SLONG, FIELD_CUSTOM,
0, 0, "XClipPathUnits" },
{ TIFFTAG_XCLIPPATHUNITS, 1, 1, TIFF_SSHORT, FIELD_CUSTOM,
0, 0, "XClipPathUnits" },
{ TIFFTAG_XCLIPPATHUNITS, 1, 1, TIFF_SBYTE, FIELD_CUSTOM,
0, 0, "XClipPathUnits" },
{ TIFFTAG_YCLIPPATHUNITS, 1, 1, TIFF_SLONG, FIELD_CUSTOM,
0, 0, "YClipPathUnits" },
{ TIFFTAG_YCLIPPATHUNITS, 1, 1, TIFF_SSHORT, FIELD_CUSTOM,
0, 0, "YClipPathUnits" },
{ TIFFTAG_YCLIPPATHUNITS, 1, 1, TIFF_SBYTE, FIELD_CUSTOM,
0, 0, "YClipPathUnits" },
{ TIFFTAG_YCBCRCOEFFICIENTS, 3, 3, TIFF_RATIONAL, FIELD_CUSTOM,
0, 0, "YCbCrCoefficients" },
{ TIFFTAG_YCBCRSUBSAMPLING, 2, 2, TIFF_SHORT, FIELD_YCBCRSUBSAMPLING,
0, 0, "YCbCrSubsampling" },
{ TIFFTAG_YCBCRPOSITIONING, 1, 1, TIFF_SHORT, FIELD_YCBCRPOSITIONING,
0, 0, "YCbCrPositioning" },
{ TIFFTAG_REFERENCEBLACKWHITE, 6, 6, TIFF_RATIONAL, FIELD_CUSTOM,
1, 0, "ReferenceBlackWhite" },
/* XXX temporarily accept LONG for backwards compatibility */
{ TIFFTAG_REFERENCEBLACKWHITE, 6, 6, TIFF_LONG, FIELD_CUSTOM,
1, 0, "ReferenceBlackWhite" },
{ TIFFTAG_XMLPACKET, -3,-3, TIFF_BYTE, FIELD_CUSTOM,
0, 1, "XMLPacket" },
/* begin SGI tags */
{ TIFFTAG_MATTEING, 1, 1, TIFF_SHORT, FIELD_EXTRASAMPLES,
0, 0, "Matteing" },
{ TIFFTAG_DATATYPE, -2,-1, TIFF_SHORT, FIELD_SAMPLEFORMAT,
0, 0, "DataType" },
{ TIFFTAG_IMAGEDEPTH, 1, 1, TIFF_LONG, FIELD_IMAGEDEPTH,
0, 0, "ImageDepth" },
{ TIFFTAG_IMAGEDEPTH, 1, 1, TIFF_SHORT, FIELD_IMAGEDEPTH,
0, 0, "ImageDepth" },
{ TIFFTAG_TILEDEPTH, 1, 1, TIFF_LONG, FIELD_TILEDEPTH,
0, 0, "TileDepth" },
{ TIFFTAG_TILEDEPTH, 1, 1, TIFF_SHORT, FIELD_TILEDEPTH,
0, 0, "TileDepth" },
/* end SGI tags */
/* begin Pixar tags */
{ TIFFTAG_PIXAR_IMAGEFULLWIDTH, 1, 1, TIFF_LONG, FIELD_CUSTOM,
1, 0, "ImageFullWidth" },
{ TIFFTAG_PIXAR_IMAGEFULLLENGTH, 1, 1, TIFF_LONG, FIELD_CUSTOM,
1, 0, "ImageFullLength" },
{ TIFFTAG_PIXAR_TEXTUREFORMAT, -1, -1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "TextureFormat" },
{ TIFFTAG_PIXAR_WRAPMODES, -1, -1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "TextureWrapModes" },
{ TIFFTAG_PIXAR_FOVCOT, 1, 1, TIFF_FLOAT, FIELD_CUSTOM,
1, 0, "FieldOfViewCotangent" },
{ TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN, 16,16, TIFF_FLOAT,
FIELD_CUSTOM, 1, 0, "MatrixWorldToScreen" },
{ TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA, 16,16, TIFF_FLOAT,
FIELD_CUSTOM, 1, 0, "MatrixWorldToCamera" },
{ TIFFTAG_COPYRIGHT, -1, -1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "Copyright" },
/* end Pixar tags */
{ TIFFTAG_RICHTIFFIPTC, -3, -3, TIFF_LONG, FIELD_CUSTOM,
0, 1, "RichTIFFIPTC" },
{ TIFFTAG_PHOTOSHOP, -3, -3, TIFF_BYTE, FIELD_CUSTOM,
0, 1, "Photoshop" },
{ TIFFTAG_EXIFIFD, 1, 1, TIFF_LONG, FIELD_CUSTOM,
0, 0, "EXIFIFDOffset" },
{ TIFFTAG_ICCPROFILE, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM,
0, 1, "ICC Profile" },
{ TIFFTAG_GPSIFD, 1, 1, TIFF_LONG, FIELD_CUSTOM,
0, 0, "GPSIFDOffset" },
{ TIFFTAG_STONITS, 1, 1, TIFF_DOUBLE, FIELD_CUSTOM,
0, 0, "StoNits" },
{ TIFFTAG_INTEROPERABILITYIFD, 1, 1, TIFF_LONG, FIELD_CUSTOM,
0, 0, "InteroperabilityIFDOffset" },
/* begin DNG tags */
{ TIFFTAG_DNGVERSION, 4, 4, TIFF_BYTE, FIELD_CUSTOM,
0, 0, "DNGVersion" },
{ TIFFTAG_DNGBACKWARDVERSION, 4, 4, TIFF_BYTE, FIELD_CUSTOM,
0, 0, "DNGBackwardVersion" },
{ TIFFTAG_UNIQUECAMERAMODEL, -1, -1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "UniqueCameraModel" },
{ TIFFTAG_LOCALIZEDCAMERAMODEL, -1, -1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "LocalizedCameraModel" },
{ TIFFTAG_LOCALIZEDCAMERAMODEL, -1, -1, TIFF_BYTE, FIELD_CUSTOM,
1, 1, "LocalizedCameraModel" },
{ TIFFTAG_CFAPLANECOLOR, -1, -1, TIFF_BYTE, FIELD_CUSTOM,
0, 1, "CFAPlaneColor" },
{ TIFFTAG_CFALAYOUT, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
0, 0, "CFALayout" },
{ TIFFTAG_LINEARIZATIONTABLE, -1, -1, TIFF_SHORT, FIELD_CUSTOM,
0, 1, "LinearizationTable" },
{ TIFFTAG_BLACKLEVELREPEATDIM, 2, 2, TIFF_SHORT, FIELD_CUSTOM,
0, 0, "BlackLevelRepeatDim" },
{ TIFFTAG_BLACKLEVEL, -1, -1, TIFF_LONG, FIELD_CUSTOM,
0, 1, "BlackLevel" },
{ TIFFTAG_BLACKLEVEL, -1, -1, TIFF_SHORT, FIELD_CUSTOM,
0, 1, "BlackLevel" },
{ TIFFTAG_BLACKLEVEL, -1, -1, TIFF_RATIONAL, FIELD_CUSTOM,
0, 1, "BlackLevel" },
{ TIFFTAG_BLACKLEVELDELTAH, -1, -1, TIFF_SRATIONAL, FIELD_CUSTOM,
0, 1, "BlackLevelDeltaH" },
{ TIFFTAG_BLACKLEVELDELTAV, -1, -1, TIFF_SRATIONAL, FIELD_CUSTOM,
0, 1, "BlackLevelDeltaV" },
{ TIFFTAG_WHITELEVEL, -2, -2, TIFF_LONG, FIELD_CUSTOM,
0, 0, "WhiteLevel" },
{ TIFFTAG_WHITELEVEL, -2, -2, TIFF_SHORT, FIELD_CUSTOM,
0, 0, "WhiteLevel" },
{ TIFFTAG_DEFAULTSCALE, 2, 2, TIFF_RATIONAL, FIELD_CUSTOM,
0, 0, "DefaultScale" },
{ TIFFTAG_BESTQUALITYSCALE, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
0, 0, "BestQualityScale" },
{ TIFFTAG_DEFAULTCROPORIGIN, 2, 2, TIFF_LONG, FIELD_CUSTOM,
0, 0, "DefaultCropOrigin" },
{ TIFFTAG_DEFAULTCROPORIGIN, 2, 2, TIFF_SHORT, FIELD_CUSTOM,
0, 0, "DefaultCropOrigin" },
{ TIFFTAG_DEFAULTCROPORIGIN, 2, 2, TIFF_RATIONAL, FIELD_CUSTOM,
0, 0, "DefaultCropOrigin" },
{ TIFFTAG_DEFAULTCROPSIZE, 2, 2, TIFF_LONG, FIELD_CUSTOM,
0, 0, "DefaultCropSize" },
{ TIFFTAG_DEFAULTCROPSIZE, 2, 2, TIFF_SHORT, FIELD_CUSTOM,
0, 0, "DefaultCropSize" },
{ TIFFTAG_DEFAULTCROPSIZE, 2, 2, TIFF_RATIONAL, FIELD_CUSTOM,
0, 0, "DefaultCropSize" },
{ TIFFTAG_COLORMATRIX1, -1, -1, TIFF_SRATIONAL, FIELD_CUSTOM,
0, 1, "ColorMatrix1" },
{ TIFFTAG_COLORMATRIX2, -1, -1, TIFF_SRATIONAL, FIELD_CUSTOM,
0, 1, "ColorMatrix2" },
{ TIFFTAG_CAMERACALIBRATION1, -1, -1, TIFF_SRATIONAL, FIELD_CUSTOM,
0, 1, "CameraCalibration1" },
{ TIFFTAG_CAMERACALIBRATION2, -1, -1, TIFF_SRATIONAL, FIELD_CUSTOM,
0, 1, "CameraCalibration2" },
{ TIFFTAG_REDUCTIONMATRIX1, -1, -1, TIFF_SRATIONAL, FIELD_CUSTOM,
0, 1, "ReductionMatrix1" },
{ TIFFTAG_REDUCTIONMATRIX2, -1, -1, TIFF_SRATIONAL, FIELD_CUSTOM,
0, 1, "ReductionMatrix2" },
{ TIFFTAG_ANALOGBALANCE, -1, -1, TIFF_RATIONAL, FIELD_CUSTOM,
0, 1, "AnalogBalance" },
{ TIFFTAG_ASSHOTNEUTRAL, -1, -1, TIFF_SHORT, FIELD_CUSTOM,
0, 1, "AsShotNeutral" },
{ TIFFTAG_ASSHOTNEUTRAL, -1, -1, TIFF_RATIONAL, FIELD_CUSTOM,
0, 1, "AsShotNeutral" },
{ TIFFTAG_ASSHOTWHITEXY, 2, 2, TIFF_RATIONAL, FIELD_CUSTOM,
0, 0, "AsShotWhiteXY" },
{ TIFFTAG_BASELINEEXPOSURE, 1, 1, TIFF_SRATIONAL, FIELD_CUSTOM,
0, 0, "BaselineExposure" },
{ TIFFTAG_BASELINENOISE, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
0, 0, "BaselineNoise" },
{ TIFFTAG_BASELINESHARPNESS, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
0, 0, "BaselineSharpness" },
{ TIFFTAG_BAYERGREENSPLIT, 1, 1, TIFF_LONG, FIELD_CUSTOM,
0, 0, "BayerGreenSplit" },
{ TIFFTAG_LINEARRESPONSELIMIT, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
0, 0, "LinearResponseLimit" },
{ TIFFTAG_CAMERASERIALNUMBER, -1, -1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "CameraSerialNumber" },
{ TIFFTAG_LENSINFO, 4, 4, TIFF_RATIONAL, FIELD_CUSTOM,
0, 0, "LensInfo" },
{ TIFFTAG_CHROMABLURRADIUS, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
0, 0, "ChromaBlurRadius" },
{ TIFFTAG_ANTIALIASSTRENGTH, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
0, 0, "AntiAliasStrength" },
{ TIFFTAG_SHADOWSCALE, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
0, 0, "ShadowScale" },
{ TIFFTAG_DNGPRIVATEDATA, -1, -1, TIFF_BYTE, FIELD_CUSTOM,
0, 1, "DNGPrivateData" },
{ TIFFTAG_MAKERNOTESAFETY, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
0, 0, "MakerNoteSafety" },
{ TIFFTAG_CALIBRATIONILLUMINANT1, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
0, 0, "CalibrationIlluminant1" },
{ TIFFTAG_CALIBRATIONILLUMINANT2, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
0, 0, "CalibrationIlluminant2" },
{ TIFFTAG_RAWDATAUNIQUEID, 16, 16, TIFF_BYTE, FIELD_CUSTOM,
0, 0, "RawDataUniqueID" },
{ TIFFTAG_ORIGINALRAWFILENAME, -1, -1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "OriginalRawFileName" },
{ TIFFTAG_ORIGINALRAWFILENAME, -1, -1, TIFF_BYTE, FIELD_CUSTOM,
1, 1, "OriginalRawFileName" },
{ TIFFTAG_ORIGINALRAWFILEDATA, -1, -1, TIFF_UNDEFINED, FIELD_CUSTOM,
0, 1, "OriginalRawFileData" },
{ TIFFTAG_ACTIVEAREA, 4, 4, TIFF_LONG, FIELD_CUSTOM,
0, 0, "ActiveArea" },
{ TIFFTAG_ACTIVEAREA, 4, 4, TIFF_SHORT, FIELD_CUSTOM,
0, 0, "ActiveArea" },
{ TIFFTAG_MASKEDAREAS, -1, -1, TIFF_LONG, FIELD_CUSTOM,
0, 1, "MaskedAreas" },
{ TIFFTAG_ASSHOTICCPROFILE, -1, -1, TIFF_UNDEFINED, FIELD_CUSTOM,
0, 1, "AsShotICCProfile" },
{ TIFFTAG_ASSHOTPREPROFILEMATRIX, -1, -1, TIFF_SRATIONAL, FIELD_CUSTOM,
0, 1, "AsShotPreProfileMatrix" },
{ TIFFTAG_CURRENTICCPROFILE, -1, -1, TIFF_UNDEFINED, FIELD_CUSTOM,
0, 1, "CurrentICCProfile" },
{ TIFFTAG_CURRENTPREPROFILEMATRIX, -1, -1, TIFF_SRATIONAL, FIELD_CUSTOM,
0, 1, "CurrentPreProfileMatrix" },
/* end DNG tags */
};
static const TIFFFieldInfo
exifFieldInfo[] = {
{ EXIFTAG_EXPOSURETIME, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
1, 0, "ExposureTime" },
{ EXIFTAG_FNUMBER, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
1, 0, "FNumber" },
{ EXIFTAG_EXPOSUREPROGRAM, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "ExposureProgram" },
{ EXIFTAG_SPECTRALSENSITIVITY, -1, -1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "SpectralSensitivity" },
{ EXIFTAG_ISOSPEEDRATINGS, -1, -1, TIFF_SHORT, FIELD_CUSTOM,
1, 1, "ISOSpeedRatings" },
{ EXIFTAG_OECF, -1, -1, TIFF_UNDEFINED, FIELD_CUSTOM,
1, 1, "OptoelectricConversionFactor" },
{ EXIFTAG_EXIFVERSION, 4, 4, TIFF_UNDEFINED, FIELD_CUSTOM,
1, 0, "ExifVersion" },
{ EXIFTAG_DATETIMEORIGINAL, 20, 20, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "DateTimeOriginal" },
{ EXIFTAG_DATETIMEDIGITIZED, 20, 20, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "DateTimeDigitized" },
{ EXIFTAG_COMPONENTSCONFIGURATION, 4, 4, TIFF_UNDEFINED, FIELD_CUSTOM,
1, 0, "ComponentsConfiguration" },
{ EXIFTAG_COMPRESSEDBITSPERPIXEL, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
1, 0, "CompressedBitsPerPixel" },
{ EXIFTAG_SHUTTERSPEEDVALUE, 1, 1, TIFF_SRATIONAL, FIELD_CUSTOM,
1, 0, "ShutterSpeedValue" },
{ EXIFTAG_APERTUREVALUE, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
1, 0, "ApertureValue" },
{ EXIFTAG_BRIGHTNESSVALUE, 1, 1, TIFF_SRATIONAL, FIELD_CUSTOM,
1, 0, "BrightnessValue" },
{ EXIFTAG_EXPOSUREBIASVALUE, 1, 1, TIFF_SRATIONAL, FIELD_CUSTOM,
1, 0, "ExposureBiasValue" },
{ EXIFTAG_MAXAPERTUREVALUE, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
1, 0, "MaxApertureValue" },
{ EXIFTAG_SUBJECTDISTANCE, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
1, 0, "SubjectDistance" },
{ EXIFTAG_METERINGMODE, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "MeteringMode" },
{ EXIFTAG_LIGHTSOURCE, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "LightSource" },
{ EXIFTAG_FLASH, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "Flash" },
{ EXIFTAG_FOCALLENGTH, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
1, 0, "FocalLength" },
{ EXIFTAG_SUBJECTAREA, -1, -1, TIFF_SHORT, FIELD_CUSTOM,
1, 1, "SubjectArea" },
{ EXIFTAG_MAKERNOTE, -1, -1, TIFF_UNDEFINED, FIELD_CUSTOM,
1, 1, "MakerNote" },
{ EXIFTAG_USERCOMMENT, -1, -1, TIFF_UNDEFINED, FIELD_CUSTOM,
1, 1, "UserComment" },
{ EXIFTAG_SUBSECTIME, -1, -1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "SubSecTime" },
{ EXIFTAG_SUBSECTIMEORIGINAL, -1, -1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "SubSecTimeOriginal" },
{ EXIFTAG_SUBSECTIMEDIGITIZED,-1, -1, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "SubSecTimeDigitized" },
{ EXIFTAG_FLASHPIXVERSION, 4, 4, TIFF_UNDEFINED, FIELD_CUSTOM,
1, 0, "FlashpixVersion" },
{ EXIFTAG_COLORSPACE, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "ColorSpace" },
{ EXIFTAG_PIXELXDIMENSION, 1, 1, TIFF_LONG, FIELD_CUSTOM,
1, 0, "PixelXDimension" },
{ EXIFTAG_PIXELXDIMENSION, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "PixelXDimension" },
{ EXIFTAG_PIXELYDIMENSION, 1, 1, TIFF_LONG, FIELD_CUSTOM,
1, 0, "PixelYDimension" },
{ EXIFTAG_PIXELYDIMENSION, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "PixelYDimension" },
{ EXIFTAG_RELATEDSOUNDFILE, 13, 13, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "RelatedSoundFile" },
{ EXIFTAG_FLASHENERGY, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
1, 0, "FlashEnergy" },
{ EXIFTAG_SPATIALFREQUENCYRESPONSE, -1, -1, TIFF_UNDEFINED, FIELD_CUSTOM,
1, 1, "SpatialFrequencyResponse" },
{ EXIFTAG_FOCALPLANEXRESOLUTION, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
1, 0, "FocalPlaneXResolution" },
{ EXIFTAG_FOCALPLANEYRESOLUTION, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
1, 0, "FocalPlaneYResolution" },
{ EXIFTAG_FOCALPLANERESOLUTIONUNIT, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "FocalPlaneResolutionUnit" },
{ EXIFTAG_SUBJECTLOCATION, 2, 2, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "SubjectLocation" },
{ EXIFTAG_EXPOSUREINDEX, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
1, 0, "ExposureIndex" },
{ EXIFTAG_SENSINGMETHOD, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "SensingMethod" },
{ EXIFTAG_FILESOURCE, 1, 1, TIFF_UNDEFINED, FIELD_CUSTOM,
1, 0, "FileSource" },
{ EXIFTAG_SCENETYPE, 1, 1, TIFF_UNDEFINED, FIELD_CUSTOM,
1, 0, "SceneType" },
{ EXIFTAG_CFAPATTERN, -1, -1, TIFF_UNDEFINED, FIELD_CUSTOM,
1, 1, "CFAPattern" },
{ EXIFTAG_CUSTOMRENDERED, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "CustomRendered" },
{ EXIFTAG_EXPOSUREMODE, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "ExposureMode" },
{ EXIFTAG_WHITEBALANCE, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "WhiteBalance" },
{ EXIFTAG_DIGITALZOOMRATIO, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
1, 0, "DigitalZoomRatio" },
{ EXIFTAG_FOCALLENGTHIN35MMFILM, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "FocalLengthIn35mmFilm" },
{ EXIFTAG_SCENECAPTURETYPE, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "SceneCaptureType" },
{ EXIFTAG_GAINCONTROL, 1, 1, TIFF_RATIONAL, FIELD_CUSTOM,
1, 0, "GainControl" },
{ EXIFTAG_CONTRAST, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "Contrast" },
{ EXIFTAG_SATURATION, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "Saturation" },
{ EXIFTAG_SHARPNESS, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "Sharpness" },
{ EXIFTAG_DEVICESETTINGDESCRIPTION, -1, -1, TIFF_UNDEFINED, FIELD_CUSTOM,
1, 1, "DeviceSettingDescription" },
{ EXIFTAG_SUBJECTDISTANCERANGE, 1, 1, TIFF_SHORT, FIELD_CUSTOM,
1, 0, "SubjectDistanceRange" },
{ EXIFTAG_IMAGEUNIQUEID, 33, 33, TIFF_ASCII, FIELD_CUSTOM,
1, 0, "ImageUniqueID" }
};
const TIFFFieldInfo *
_TIFFGetFieldInfo(size_t *size)
{
*size = TIFFArrayCount(tiffFieldInfo);
return tiffFieldInfo;
}
const TIFFFieldInfo *
_TIFFGetExifFieldInfo(size_t *size)
{
*size = TIFFArrayCount(exifFieldInfo);
return exifFieldInfo;
}
void
_TIFFSetupFieldInfo(TIFF* tif, const TIFFFieldInfo info[], size_t n)
{
if (tif->tif_fieldinfo) {
size_t i;
for (i = 0; i < tif->tif_nfields; i++)
{
TIFFFieldInfo *fld = tif->tif_fieldinfo[i];
if (fld->field_bit == FIELD_CUSTOM &&
strncmp("Tag ", fld->field_name, 4) == 0) {
_TIFFfree(fld->field_name);
_TIFFfree(fld);
}
}
_TIFFfree(tif->tif_fieldinfo);
tif->tif_nfields = 0;
}
if (!_TIFFMergeFieldInfo(tif, info, n))
{
TIFFErrorExt(tif->tif_clientdata, "_TIFFSetupFieldInfo",
"Setting up field info failed");
}
}
static int
tagCompare(const void* a, const void* b)
{
const TIFFFieldInfo* ta = *(const TIFFFieldInfo**) a;
const TIFFFieldInfo* tb = *(const TIFFFieldInfo**) b;
/* NB: be careful of return values for 16-bit platforms */
if (ta->field_tag != tb->field_tag)
return (int)ta->field_tag - (int)tb->field_tag;
else
return (ta->field_type == TIFF_ANY) ?
0 : ((int)tb->field_type - (int)ta->field_type);
}
static int
tagNameCompare(const void* a, const void* b)
{
const TIFFFieldInfo* ta = *(const TIFFFieldInfo**) a;
const TIFFFieldInfo* tb = *(const TIFFFieldInfo**) b;
int ret = strcmp(ta->field_name, tb->field_name);
if (ret)
return ret;
else
return (ta->field_type == TIFF_ANY) ?
0 : ((int)tb->field_type - (int)ta->field_type);
}
void
TIFFMergeFieldInfo(TIFF* tif, const TIFFFieldInfo info[], int n)
{
if (_TIFFMergeFieldInfo(tif, info, n) < 0)
{
TIFFErrorExt(tif->tif_clientdata, "TIFFMergeFieldInfo",
"Merging block of %d fields failed", n);
}
}
int
_TIFFMergeFieldInfo(TIFF* tif, const TIFFFieldInfo info[], int n)
{
static const char module[] = "_TIFFMergeFieldInfo";
static const char reason[] = "for field info array";
TIFFFieldInfo** tp;
int i;
tif->tif_foundfield = NULL;
if (tif->tif_nfields > 0) {
tif->tif_fieldinfo = (TIFFFieldInfo**)
_TIFFCheckRealloc(tif, tif->tif_fieldinfo,
(tif->tif_nfields + n),
sizeof (TIFFFieldInfo*), reason);
} else {
tif->tif_fieldinfo = (TIFFFieldInfo**)
_TIFFCheckMalloc(tif, n, sizeof (TIFFFieldInfo*),
reason);
}
if (!tif->tif_fieldinfo) {
TIFFErrorExt(tif->tif_clientdata, module,
"Failed to allocate field info array");
return 0;
}
tp = tif->tif_fieldinfo + tif->tif_nfields;
for (i = 0; i < n; i++)
{
const TIFFFieldInfo *fip =
_TIFFFindFieldInfo(tif, info[i].field_tag, info[i].field_type);
/* only add definitions that aren't already present */
if (!fip) {
*tp++ = (TIFFFieldInfo*) (info + i);
tif->tif_nfields++;
}
}
/* Sort the field info by tag number */
qsort(tif->tif_fieldinfo, tif->tif_nfields,
sizeof (TIFFFieldInfo*), tagCompare);
return n;
}
void
_TIFFPrintFieldInfo(TIFF* tif, FILE* fd)
{
size_t i;
fprintf(fd, "%s: \n", tif->tif_name);
for (i = 0; i < tif->tif_nfields; i++) {
const TIFFFieldInfo* fip = tif->tif_fieldinfo[i];
fprintf(fd, "field[%2d] %5lu, %2d, %2d, %d, %2d, %5s, %5s, %s\n"
, (int)i
, (unsigned long) fip->field_tag
, fip->field_readcount, fip->field_writecount
, fip->field_type
, fip->field_bit
, fip->field_oktochange ? "TRUE" : "FALSE"
, fip->field_passcount ? "TRUE" : "FALSE"
, fip->field_name
);
}
}
/*
* Return size of TIFFDataType in bytes
*/
int
TIFFDataWidth(TIFFDataType type)
{
switch(type)
{
case 0: /* nothing */
case 1: /* TIFF_BYTE */
case 2: /* TIFF_ASCII */
case 6: /* TIFF_SBYTE */
case 7: /* TIFF_UNDEFINED */
return 1;
case 3: /* TIFF_SHORT */
case 8: /* TIFF_SSHORT */
return 2;
case 4: /* TIFF_LONG */
case 9: /* TIFF_SLONG */
case 11: /* TIFF_FLOAT */
case 13: /* TIFF_IFD */
return 4;
case 5: /* TIFF_RATIONAL */
case 10: /* TIFF_SRATIONAL */
case 12: /* TIFF_DOUBLE */
return 8;
default:
return 0; /* will return 0 for unknown types */
}
}
/*
* Return size of TIFFDataType in bytes.
*
* XXX: We need a separate function to determine the space needed
* to store the value. For TIFF_RATIONAL values TIFFDataWidth() returns 8,
* but we use 4-byte float to represent rationals.
*/
int
_TIFFDataSize(TIFFDataType type)
{
switch (type) {
case TIFF_BYTE:
case TIFF_SBYTE:
case TIFF_ASCII:
case TIFF_UNDEFINED:
return 1;
case TIFF_SHORT:
case TIFF_SSHORT:
return 2;
case TIFF_LONG:
case TIFF_SLONG:
case TIFF_FLOAT:
case TIFF_IFD:
case TIFF_RATIONAL:
case TIFF_SRATIONAL:
return 4;
case TIFF_DOUBLE:
return 8;
default:
return 0;
}
}
/*
* Return nearest TIFFDataType to the sample type of an image.
*/
TIFFDataType
_TIFFSampleToTagType(TIFF* tif)
{
uint32 bps = TIFFhowmany8(tif->tif_dir.td_bitspersample);
switch (tif->tif_dir.td_sampleformat) {
case SAMPLEFORMAT_IEEEFP:
return (bps == 4 ? TIFF_FLOAT : TIFF_DOUBLE);
case SAMPLEFORMAT_INT:
return (bps <= 1 ? TIFF_SBYTE :
bps <= 2 ? TIFF_SSHORT : TIFF_SLONG);
case SAMPLEFORMAT_UINT:
return (bps <= 1 ? TIFF_BYTE :
bps <= 2 ? TIFF_SHORT : TIFF_LONG);
case SAMPLEFORMAT_VOID:
return (TIFF_UNDEFINED);
}
/*NOTREACHED*/
return (TIFF_UNDEFINED);
}
const TIFFFieldInfo*
_TIFFFindFieldInfo(TIFF* tif, ttag_t tag, TIFFDataType dt)
{
TIFFFieldInfo key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0};
TIFFFieldInfo* pkey = &key;
const TIFFFieldInfo **ret;
if (tif->tif_foundfield && tif->tif_foundfield->field_tag == tag &&
(dt == TIFF_ANY || dt == tif->tif_foundfield->field_type))
return tif->tif_foundfield;
/* If we are invoked with no field information, then just return. */
if ( !tif->tif_fieldinfo ) {
return NULL;
}
/* NB: use sorted search (e.g. binary search) */
key.field_tag = tag;
key.field_type = dt;
ret = (const TIFFFieldInfo **) bsearch(&pkey,
tif->tif_fieldinfo,
tif->tif_nfields,
sizeof(TIFFFieldInfo *),
tagCompare);
return tif->tif_foundfield = (ret ? *ret : NULL);
}
const TIFFFieldInfo*
_TIFFFindFieldInfoByName(TIFF* tif, const char *field_name, TIFFDataType dt)
{
TIFFFieldInfo key = {0, 0, 0, TIFF_NOTYPE, 0, 0, 0, 0};
TIFFFieldInfo* pkey = &key;
const TIFFFieldInfo **ret;
if (tif->tif_foundfield
&& streq(tif->tif_foundfield->field_name, field_name)
&& (dt == TIFF_ANY || dt == tif->tif_foundfield->field_type))
return (tif->tif_foundfield);
/* If we are invoked with no field information, then just return. */
if ( !tif->tif_fieldinfo ) {
return NULL;
}
/* NB: use sorted search (e.g. binary search) */
key.field_name = (char *)field_name;
key.field_type = dt;
ret = (const TIFFFieldInfo **) lfind(&pkey,
tif->tif_fieldinfo,
&tif->tif_nfields,
sizeof(TIFFFieldInfo *),
tagNameCompare);
return tif->tif_foundfield = (ret ? *ret : NULL);
}
const TIFFFieldInfo*
_TIFFFieldWithTag(TIFF* tif, ttag_t tag)
{
const TIFFFieldInfo* fip = _TIFFFindFieldInfo(tif, tag, TIFF_ANY);
if (!fip) {
TIFFErrorExt(tif->tif_clientdata, "TIFFFieldWithTag",
"Internal error, unknown tag 0x%x",
(unsigned int) tag);
assert(fip != NULL);
/*NOTREACHED*/
}
return (fip);
}
const TIFFFieldInfo*
_TIFFFieldWithName(TIFF* tif, const char *field_name)
{
const TIFFFieldInfo* fip =
_TIFFFindFieldInfoByName(tif, field_name, TIFF_ANY);
if (!fip) {
TIFFErrorExt(tif->tif_clientdata, "TIFFFieldWithName",
"Internal error, unknown tag %s", field_name);
assert(fip != NULL);
/*NOTREACHED*/
}
return (fip);
}
const TIFFFieldInfo*
_TIFFFindOrRegisterFieldInfo( TIFF *tif, ttag_t tag, TIFFDataType dt )
{
const TIFFFieldInfo *fld;
fld = _TIFFFindFieldInfo( tif, tag, dt );
if( fld == NULL )
{
fld = _TIFFCreateAnonFieldInfo( tif, tag, dt );
if (!_TIFFMergeFieldInfo(tif, fld, 1))
return NULL;
}
return fld;
}
TIFFFieldInfo*
_TIFFCreateAnonFieldInfo(TIFF *tif, ttag_t tag, TIFFDataType field_type)
{
TIFFFieldInfo *fld;
(void) tif;
fld = (TIFFFieldInfo *) _TIFFmalloc(sizeof (TIFFFieldInfo));
if (fld == NULL)
return NULL;
_TIFFmemset( fld, 0, sizeof(TIFFFieldInfo) );
fld->field_tag = tag;
fld->field_readcount = TIFF_VARIABLE2;
fld->field_writecount = TIFF_VARIABLE2;
fld->field_type = field_type;
fld->field_bit = FIELD_CUSTOM;
fld->field_oktochange = TRUE;
fld->field_passcount = TRUE;
fld->field_name = (char *) _TIFFmalloc(32);
if (fld->field_name == NULL) {
_TIFFfree(fld);
return NULL;
}
/*
* note that this name is a special sign to TIFFClose() and
* _TIFFSetupFieldInfo() to free the field
*/
sprintf(fld->field_name, "Tag %d", (int) tag);
return fld;
}
/* vim: set ts=8 sts=8 sw=8 noet: */
|
bhargavkumar040/android-source-browsing.platform--external--free-image
|
Source/LibTIFF/tif_dirinfo.c
|
C
|
gpl-2.0
| 33,305
|
// { dg-options "-std=gnu++11" }
// { dg-require-cstdint "" }
//
// Copyright (C) 2011-2014 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 26.5.8.2.1 Class template bernoulli_distribution [rand.dist.bern.bernoulli]
#include <random>
#include <functional>
#include <testsuite_random.h>
void test01()
{
using namespace __gnu_test;
std::mt19937 eng;
std::bernoulli_distribution bd1(0.25);
auto bbd1 = std::bind(bd1, eng);
testDiscreteDist(bbd1, [](int n) { return bernoulli_pdf(n, 0.25); } );
std::bernoulli_distribution bd2(0.5);
auto bbd2 = std::bind(bd2, eng);
testDiscreteDist(bbd2, [](int n) { return bernoulli_pdf(n, 0.5); } );
std::bernoulli_distribution bd3(0.75);
auto bbd3 = std::bind(bd3, eng);
testDiscreteDist(bbd3, [](int n) { return bernoulli_pdf(n, 0.75); } );
}
int main()
{
test01();
return 0;
}
|
mageec/mageec-gcc
|
libstdc++-v3/testsuite/26_numerics/random/bernoulli_distribution/operators/values.cc
|
C++
|
gpl-2.0
| 1,541
|
#include <utils/Log.h>
#include <fcntl.h>
#include <math.h>
#include "camera_custom_nvram.h"
#include "camera_custom_sensor.h"
#include "image_sensor.h"
#include "kd_imgsensor_define.h"
#include "camera_AE_PLineTable_s5k5e2yamipiraw.h"
#include "camera_info_s5k5e2yamipiraw.h"
#include "camera_custom_AEPlinetable.h"
#include "camera_custom_flicker_para.h"
#include <cutils/xlog.h>
static void get_flicker_para_by_preview(FLICKER_CUST_PARA* para)
{
int i;
int freq[9] = { 70, 100, 120, 140, 160, 170, 190, 210, 230};
FLICKER_CUST_STATISTICS EV50_L50 = {-194, 4721, 381, -766};
FLICKER_CUST_STATISTICS EV50_L60 = {911, 510, 953, -446};
FLICKER_CUST_STATISTICS EV60_L50 = {1086, 537, 1419, -520};
FLICKER_CUST_STATISTICS EV60_L60 = {-162, 2898, 247, -642};
for(i=0;i<9;i++)
{
para->flickerFreq[i]=freq[i];
}
para->flickerGradThreshold=24;
para->flickerSearchRange=20;
para->minPastFrames=3;
para->maxPastFrames=14;
para->EV50_L50=EV50_L50;
para->EV50_L60=EV50_L60;
para->EV60_L50=EV60_L50;
para->EV60_L60=EV60_L60;
para->EV50_thresholds[0]=-30;
para->EV50_thresholds[1]=12;
para->EV60_thresholds[0]=-30;
para->EV60_thresholds[1]=12;
para->freq_feature_index[0]=2;
para->freq_feature_index[1]=1;
}
static void get_flicker_para_by_ZSD(FLICKER_CUST_PARA* para)
{
int i;
int freq[9] = { 70, 80, 90, 100, 120, 130, 140, 160, 170};
FLICKER_CUST_STATISTICS EV50_L50 = {-194, 4721, 381, -766};
FLICKER_CUST_STATISTICS EV50_L60 = {1159, 401, 749, -384};
FLICKER_CUST_STATISTICS EV60_L50 = {1383, 422, 1115, -458};
FLICKER_CUST_STATISTICS EV60_L60 = {-162, 2898, 247, -642};
for(i=0;i<9;i++)
{
para->flickerFreq[i]=freq[i];
}
para->flickerGradThreshold=25;
para->flickerSearchRange=40;
para->minPastFrames=3;
para->maxPastFrames=14;
para->EV50_L50=EV50_L50;
para->EV50_L60=EV50_L60;
para->EV60_L50=EV60_L50;
para->EV60_L60=EV60_L60;
para->EV50_thresholds[0]=-30;
para->EV50_thresholds[1]=12;
para->EV60_thresholds[0]=-30;
para->EV60_thresholds[1]=12;
para->freq_feature_index[0]=4;
para->freq_feature_index[1]=3;
}
typedef NSFeature::RAWSensorInfo<SENSOR_ID> SensorInfoSingleton_T;
namespace NSFeature {
template <>
UINT32
SensorInfoSingleton_T::
impGetFlickerPara(MINT32 sensorMode, MVOID*const pDataBuf) const
{
XLOGD("impGetFlickerPara+ mode=%d", sensorMode);
XLOGD("prv=%d, vdo=%d, cap=%d, zsd=%d",
(int)e_sensorModePreview, (int)e_sensorModeVideoPreview, (int)e_sensorModeCapture, (int)e_sensorModeZsd );
FLICKER_CUST_PARA* para;
para = (FLICKER_CUST_PARA*)pDataBuf;
if(sensorMode==e_sensorModePreview)
get_flicker_para_by_preview(para);
else if(sensorMode==e_sensorModeZsd||
sensorMode==e_sensorModeVideoPreview ||
sensorMode==e_sensorModeCapture)
{
get_flicker_para_by_ZSD(para);
}
else
{
XLOGD("impGetFlickerPara ERROR ln=%d", __LINE__);
return -1;
}
XLOGD("impGetFlickerPara-");
return 0;
}
}
|
rimistri/mediatek
|
mt6732/mediatek/custom/mt6752/hal/imgsensor/s5k5e2ya_mipi_raw/camera_flicker_para_s5k5e2yamipiraw.cpp
|
C++
|
gpl-2.0
| 2,935
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2008 StatPro Italia srl
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#ifndef quantlib_test_cds_option_hpp
#define quantlib_test_cds_option_hpp
#include <boost/test/unit_test.hpp>
/* remember to document new and/or updated tests in the Doxygen
comment block of the corresponding class */
class CdsOptionTest {
public:
static void testCached();
static boost::unit_test_framework::test_suite* suite();
};
#endif
|
EuroPlusFinance/Software
|
Quantum Trading Platforms/QuantLib-1.4/test-suite/cdsoption.hpp
|
C++
|
gpl-2.0
| 1,163
|
/*
* Copyright (C) 2012 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SpeechGrammar_h
#define SpeechGrammar_h
#if ENABLE(SCRIPTED_SPEECH)
#include "URL.h"
#include <wtf/RefCounted.h>
#include <wtf/text/WTFString.h>
namespace WebCore {
class ScriptExecutionContext;
class SpeechGrammar : public RefCounted<SpeechGrammar> {
public:
static PassRefPtr<SpeechGrammar> create(); // FIXME: The spec is not clear on what the constructor should look like.
static PassRefPtr<SpeechGrammar> create(const URL& src, double weight);
const URL& src(ScriptExecutionContext*) const { return m_src; }
const URL& src() const { return m_src; }
void setSrc(ScriptExecutionContext*, const String& src);
double weight() const { return m_weight; }
void setWeight(double weight) { m_weight = weight; }
private:
SpeechGrammar();
SpeechGrammar(const URL& src, double weight);
URL m_src;
double m_weight;
};
} // namespace WebCore
#endif // ENABLE(SCRIPTED_SPEECH)
#endif // SpeechGrammar_h
|
loveyoupeng/rt
|
modules/web/src/main/native/Source/WebCore/Modules/speech/SpeechGrammar.h
|
C
|
gpl-2.0
| 2,310
|
<?php
/**
* File contains: eZ\Publish\Core\Persistence\Legacy\Tests\Content\Type\Gateway\DoctrineDatabaseTest class.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*
* @version //autogentag//
*/
namespace eZ\Publish\Core\Persistence\Legacy\Tests\Content\Gateway;
use eZ\Publish\Core\Persistence\Legacy\Tests\Content\LanguageAwareTestCase;
use eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase;
use eZ\Publish\Core\Persistence\Legacy\Content\StorageFieldValue;
use eZ\Publish\SPI\Persistence\Content;
use eZ\Publish\SPI\Persistence\Content\ContentInfo;
use eZ\Publish\SPI\Persistence\Content\CreateStruct;
use eZ\Publish\SPI\Persistence\Content\UpdateStruct;
use eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct;
use eZ\Publish\SPI\Persistence\Content\Field;
use eZ\Publish\SPI\Persistence\Content\VersionInfo;
use eZ\Publish\API\Repository\Values\Content\Relation as RelationValue;
use eZ\Publish\SPI\Persistence\Content\Relation\CreateStruct as RelationCreateStruct;
/**
* Test case for eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase.
*/
class DoctrineDatabaseTest extends LanguageAwareTestCase
{
/**
* Database gateway to test.
*
* @var \eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase
*/
protected $databaseGateway;
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::__construct
*/
public function testCtor()
{
$handlerMock = $this->getDatabaseHandler();
$gateway = $this->getDatabaseGateway();
$this->assertAttributeSame(
$handlerMock,
'dbHandler',
$gateway
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::insertContentObject
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::generateLanguageMask
*
* @todo Fix not available fields
*/
public function testInsertContentObject()
{
$struct = $this->getCreateStructFixture();
$gateway = $this->getDatabaseGateway();
$gateway->insertContentObject($struct);
$this->assertQueryResult(
array(
array(
'name' => 'Content name',
'contentclass_id' => '23',
'section_id' => '42',
'owner_id' => '13',
'current_version' => '1',
'initial_language_id' => '2',
'remote_id' => 'some_remote_id',
'language_mask' => '3',
'modified' => '0',
'published' => '0',
'status' => ContentInfo::STATUS_DRAFT,
),
),
$this->getDatabaseHandler()
->createSelectQuery()
->select(
array(
'name',
'contentclass_id',
'section_id',
'owner_id',
'current_version',
'initial_language_id',
'remote_id',
'language_mask',
'modified',
'published',
'status',
)
)->from('ezcontentobject')
);
}
/**
* Returns a Content fixture.
*
* @return \eZ\Publish\SPI\Persistence\Content\CreateStruct
*/
protected function getCreateStructFixture()
{
$struct = new CreateStruct();
$struct->typeId = 23;
$struct->sectionId = 42;
$struct->ownerId = 13;
$struct->initialLanguageId = 2;
$struct->remoteId = 'some_remote_id';
$struct->alwaysAvailable = true;
$struct->modified = 456;
$struct->name = array(
'eng-US' => 'Content name',
);
$struct->fields = array(
new Field(array('languageCode' => 'eng-US')),
);
$struct->locations = array();
return $struct;
}
/**
* Returns a Content fixture.
*
* @return \eZ\Publish\SPI\Persistence\Content
*/
protected function getContentFixture()
{
$content = new Content();
$content->versionInfo = new VersionInfo();
$content->versionInfo->names = array(
'eng-US' => 'Content name',
);
$content->versionInfo->status = VersionInfo::STATUS_PENDING;
$content->versionInfo->contentInfo = new ContentInfo();
$content->versionInfo->contentInfo->contentTypeId = 23;
$content->versionInfo->contentInfo->sectionId = 42;
$content->versionInfo->contentInfo->ownerId = 13;
$content->versionInfo->contentInfo->currentVersionNo = 2;
$content->versionInfo->contentInfo->mainLanguageCode = 'eng-US';
$content->versionInfo->contentInfo->remoteId = 'some_remote_id';
$content->versionInfo->contentInfo->alwaysAvailable = true;
$content->versionInfo->contentInfo->publicationDate = 123;
$content->versionInfo->contentInfo->modificationDate = 456;
$content->versionInfo->contentInfo->isPublished = false;
$content->versionInfo->contentInfo->name = 'Content name';
return $content;
}
/**
* Returns a Version fixture.
*
* @return \eZ\Publish\SPI\Persistence\Content\VersionInfo
*/
protected function getVersionFixture()
{
$version = new VersionInfo();
$version->id = null;
$version->versionNo = 1;
$version->creatorId = 13;
$version->status = 0;
$version->creationDate = 1312278322;
$version->modificationDate = 1312278323;
$version->initialLanguageCode = 'eng-GB';
$version->contentInfo = new ContentInfo(
array(
'id' => 2342,
'alwaysAvailable' => true,
)
);
return $version;
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::insertVersion
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::generateLanguageMask
*/
public function testInsertVersion()
{
$version = $this->getVersionFixture();
$gateway = $this->getDatabaseGateway();
$gateway->insertVersion($version, array());
$this->assertQueryResult(
array(
array(
'contentobject_id' => '2342',
'created' => '1312278322',
'creator_id' => '13',
'modified' => '1312278323',
'status' => '0',
'workflow_event_pos' => '0',
'version' => '1',
'language_mask' => '5',
'initial_language_id' => '4',
// Not needed, according to field mapping document
// 'user_id',
),
),
$this->getDatabaseHandler()
->createSelectQuery()
->select(
array(
'contentobject_id',
'created',
'creator_id',
'modified',
'status',
'workflow_event_pos',
'version',
'language_mask',
'initial_language_id',
)
)->from('ezcontentobject_version')
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::setStatus
*/
public function testSetStatus()
{
$gateway = $this->getDatabaseGateway();
// insert content
$struct = $this->getCreateStructFixture();
$contentId = $gateway->insertContentObject($struct);
// insert version
$version = $this->getVersionFixture();
$version->contentInfo->id = $contentId;
$gateway->insertVersion($version, array());
$this->assertTrue(
$gateway->setStatus($version->contentInfo->id, $version->versionNo, VersionInfo::STATUS_PENDING)
);
$this->assertQueryResult(
array(array(VersionInfo::STATUS_PENDING)),
$this->getDatabaseHandler()
->createSelectQuery()
->select('status')
->from('ezcontentobject_version')
);
// check that content status has not been set to published
$this->assertQueryResult(
array(array(VersionInfo::STATUS_DRAFT)),
$this->getDatabaseHandler()
->createSelectQuery()
->select('status')
->from('ezcontentobject')
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::setStatus
*/
public function testSetStatusPublished()
{
$gateway = $this->getDatabaseGateway();
// insert content
$struct = $this->getCreateStructFixture();
$contentId = $gateway->insertContentObject($struct);
// insert version
$version = $this->getVersionFixture();
$version->contentInfo->id = $contentId;
$gateway->insertVersion($version, array());
$this->assertTrue(
$gateway->setStatus($version->contentInfo->id, $version->versionNo, VersionInfo::STATUS_PUBLISHED)
);
$this->assertQueryResult(
array(array(VersionInfo::STATUS_PUBLISHED)),
$this->getDatabaseHandler()
->createSelectQuery()
->select('status')
->from('ezcontentobject_version')
);
// check that content status has been set to published
$this->assertQueryResult(
array(array(ContentInfo::STATUS_PUBLISHED)),
$this->getDatabaseHandler()
->createSelectQuery()
->select('status')
->from('ezcontentobject')
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::setStatus
*/
public function testSetStatusUnknownVersion()
{
$gateway = $this->getDatabaseGateway();
$this->assertFalse(
$gateway->setStatus(23, 42, 2)
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::updateContent
*/
public function testUpdateContent()
{
$gateway = $this->getDatabaseGateway();
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$metadataStruct = $this->getMetadataUpdateStructFixture();
$gateway->updateContent(10, $metadataStruct);
$this->assertQueryResult(
array(
array(
'initial_language_id' => '3',
'modified' => '234567',
'owner_id' => '42',
'published' => '123456',
'remote_id' => 'ghjk1234567890ghjk1234567890',
'name' => 'Thoth',
),
),
$this->getDatabaseHandler()->createSelectQuery()
->select(
'initial_language_id',
'modified',
'owner_id',
'published',
'remote_id',
'name'
)->from('ezcontentobject')
->where('id = 10')
);
}
/**
* Returns an UpdateStruct fixture.
*
* @return \eZ\Publish\SPI\Persistence\Content\UpdateStruct
*/
protected function getUpdateStructFixture()
{
$struct = new UpdateStruct();
$struct->creatorId = 23;
$struct->fields = array();
$struct->modificationDate = 234567;
$struct->initialLanguageId = 2;
return $struct;
}
/**
* Returns a MetadataUpdateStruct fixture.
*
* @return \eZ\Publish\SPI\Persistence\Content\MetadataUpdateStruct
*/
protected function getMetadataUpdateStructFixture()
{
$struct = new MetadataUpdateStruct();
$struct->ownerId = 42;
$struct->publicationDate = 123456;
$struct->mainLanguageId = 3;
$struct->modificationDate = 234567;
$struct->remoteId = 'ghjk1234567890ghjk1234567890';
$struct->name = 'Thoth';
return $struct;
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::updateVersion
*/
public function testUpdateVersion()
{
$gateway = $this->getDatabaseGateway();
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$gateway->updateVersion(10, 2, $this->getUpdateStructFixture());
$query = $this->getDatabaseHandler()->createSelectQuery();
$this->assertQueryResult(
array(
array(
'creator_id' => '23',
'initial_language_id' => '2',
'modified' => '234567',
),
),
$query
->select(
array(
'creator_id',
'initial_language_id',
'modified',
)
)->from('ezcontentobject_version')
->where(
$query->expr->lAnd(
$query->expr->eq('contentobject_id', 10),
$query->expr->eq('version', 2)
)
)
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::insertNewField
*/
public function testInsertNewField()
{
$content = $this->getContentFixture();
$content->versionInfo->contentInfo->id = 2342;
$field = $this->getFieldFixture();
$value = $this->getStorageValueFixture();
$gateway = $this->getDatabaseGateway();
$gateway->insertNewField($content, $field, $value);
$this->assertQueryResult(
array(
array(
'contentclassattribute_id' => '231',
'contentobject_id' => '2342',
'data_float' => '24.42',
'data_int' => '42',
'data_text' => 'Test text',
'data_type_string' => 'ezstring',
'language_code' => 'eng-GB',
'language_id' => '4',
'sort_key_int' => '23',
'sort_key_string' => 'Test',
'version' => '1',
),
),
$this->getDatabaseHandler()
->createSelectQuery()
->select(
array(
'contentclassattribute_id',
'contentobject_id',
'data_float',
'data_int',
'data_text',
'data_type_string',
'language_code',
'language_id',
'sort_key_int',
'sort_key_string',
'version',
)
)->from('ezcontentobject_attribute')
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::insertNewField
*/
public function testInsertNewAlwaysAvailableField()
{
$content = $this->getContentFixture();
$content->versionInfo->contentInfo->id = 2342;
// Set main language to the one used in the field fixture
$content->versionInfo->contentInfo->mainLanguageCode = 'eng-GB';
$field = $this->getFieldFixture();
$value = $this->getStorageValueFixture();
$gateway = $this->getDatabaseGateway();
$gateway->insertNewField($content, $field, $value);
$this->assertQueryResult(
array(
array(
'contentclassattribute_id' => '231',
'contentobject_id' => '2342',
'data_float' => '24.42',
'data_int' => '42',
'data_text' => 'Test text',
'data_type_string' => 'ezstring',
'language_code' => 'eng-GB',
'language_id' => '5',
'sort_key_int' => '23',
'sort_key_string' => 'Test',
'version' => '1',
),
),
$this->getDatabaseHandler()
->createSelectQuery()
->select(
array(
'contentclassattribute_id',
'contentobject_id',
'data_float',
'data_int',
'data_text',
'data_type_string',
'language_code',
'language_id',
'sort_key_int',
'sort_key_string',
'version',
)
)->from('ezcontentobject_attribute')
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::updateField
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::setFieldUpdateValues
*/
public function testUpdateField()
{
$content = $this->getContentFixture();
$content->versionInfo->contentInfo->id = 2342;
$field = $this->getFieldFixture();
$value = $this->getStorageValueFixture();
$gateway = $this->getDatabaseGateway();
$field->id = $gateway->insertNewField($content, $field, $value);
$newValue = new StorageFieldValue(
array(
'dataFloat' => 124.42,
'dataInt' => 142,
'dataText' => 'New text',
'sortKeyInt' => 123,
'sortKeyString' => 'new_text',
)
);
$gateway->updateField($field, $newValue);
$this->assertQueryResult(
array(
array(
'data_float' => '124.42',
'data_int' => '142',
'data_text' => 'New text',
'sort_key_int' => '123',
'sort_key_string' => 'new_text',
),
),
$this->getDatabaseHandler()
->createSelectQuery()
->select(
array(
'data_float',
'data_int',
'data_text',
'sort_key_int',
'sort_key_string',
)
)->from('ezcontentobject_attribute')
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::updateNonTranslatableField
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::setFieldUpdateValues
*/
public function testUpdateNonTranslatableField()
{
$content = $this->getContentFixture();
$content->versionInfo->contentInfo->id = 2342;
$fieldGb = $this->getFieldFixture();
$fieldUs = $this->getOtherLanguageFieldFixture();
$value = $this->getStorageValueFixture();
$gateway = $this->getDatabaseGateway();
$fieldGb->id = $gateway->insertNewField($content, $fieldGb, $value);
$fieldUs->id = $gateway->insertNewField($content, $fieldUs, $value);
$updateStruct = new Content\UpdateStruct();
$newValue = new StorageFieldValue(
array(
'dataFloat' => 124.42,
'dataInt' => 142,
'dataText' => 'New text',
'sortKeyInt' => 123,
'sortKeyString' => 'new_text',
)
);
$gateway->updateNonTranslatableField($fieldGb, $newValue, $content->versionInfo->contentInfo->id);
$this->assertQueryResult(
array(
// Both fields updated
array(
'data_float' => '124.42',
'data_int' => '142',
'data_text' => 'New text',
'sort_key_int' => '123',
'sort_key_string' => 'new_text',
),
array(
'data_float' => '124.42',
'data_int' => '142',
'data_text' => 'New text',
'sort_key_int' => '123',
'sort_key_string' => 'new_text',
),
),
$this->getDatabaseHandler()
->createSelectQuery()
->select(
array(
'data_float',
'data_int',
'data_text',
'sort_key_int',
'sort_key_string',
)
)->from('ezcontentobject_attribute')
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::listVersions
*/
public function testListVersions()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$gateway = $this->getDatabaseGateway();
$res = $gateway->listVersions(226);
$this->assertEquals(
2,
count($res)
);
foreach ($res as $row) {
$this->assertEquals(
22,
count($row)
);
}
$this->assertEquals(
675,
$res[0]['ezcontentobject_version_id']
);
$this->assertEquals(
676,
$res[1]['ezcontentobject_version_id']
);
//$orig = include __DIR__ . '/../_fixtures/restricted_version_rows.php';
/*$this->storeFixture(
__DIR__ . '/../_fixtures/restricted_version_rows.php',
$res
);*/
//$this->assertEquals( $orig, $res, "Fixtures differ between what was previously stored(expected) and what it now generates(actual), this hints either some mistake in impl or that the fixture (../_fixtures/restricted_version_rows.php) and tests needs to be adapted." );
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::listVersionNumbers
*/
public function testListVersionNumbers()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$gateway = $this->getDatabaseGateway();
$res = $gateway->listVersionNumbers(226);
$this->assertEquals(array(1, 2), $res);
}
/**
* @covers \eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::listVersionsForUser
*/
public function testListVersionsForUser()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$gateway = $this->getDatabaseGateway();
$res = $gateway->listVersionsForUser(14);
$this->assertEquals(
2,
count($res)
);
foreach ($res as $row) {
$this->assertEquals(
22,
count($row)
);
}
$this->assertEquals(
677,
$res[0]['ezcontentobject_version_id']
);
$this->assertEquals(
0,
$res[0]['ezcontentobject_version_status']
);
$this->assertEquals(
678,
$res[1]['ezcontentobject_version_id']
);
$this->assertEquals(
0,
$res[1]['ezcontentobject_version_status']
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::load
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase\QueryBuilder
*/
public function testLoadWithAllTranslations()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$gateway = $this->getDatabaseGateway();
$res = $gateway->load(226, 2);
$this->assertValuesInRows(
'ezcontentobject_attribute_language_code',
array('eng-US', 'eng-GB'),
$res
);
$this->assertValuesInRows(
'ezcontentobject_attribute_language_id',
array('2', '4'),
$res
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::load
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase\QueryBuilder
*/
public function testCreateFixtureForMapperExtractContentFromRowsMultipleVersions()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$gateway = $this->getDatabaseGateway();
$resFirst = $gateway->load(11, 1);
$resSecond = $gateway->load(11, 2);
$res = array_merge($resFirst, $resSecond);
$orig = include __DIR__ . '/../_fixtures/extract_content_from_rows_multiple_versions.php';
/*$this->storeFixture(
__DIR__ . '/../_fixtures/extract_content_from_rows_multiple_versions.php',
$res
);*/
$this->assertEquals($orig, $res, 'Fixtures differ between what was previously stored(expected) and what it now generates(actual), this hints either some mistake in impl or that the fixture (../_fixtures/extract_content_from_rows_multiple_versions.php) and tests needs to be adapted.');
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::load
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase\QueryBuilder
*/
public function testCreateFixtureForMapperExtractContentFromRows()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$gateway = $this->getDatabaseGateway();
$res = $gateway->load(226, 2);
$res = array_merge($res);
$orig = include __DIR__ . '/../_fixtures/extract_content_from_rows.php';
/*$this->storeFixture(
__DIR__ . '/../_fixtures/extract_content_from_rows.php',
$res
);*/
$this->assertEquals($orig, $res, 'Fixtures differ between what was previously stored(expected) and what it now generates(actual), this hints either some mistake in impl or that the fixture (../_fixtures/extract_content_from_rows.php) and tests needs to be adapted.');
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::load
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase\QueryBuilder
*/
public function testLoadWithSingleTranslation()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$gateway = $this->getDatabaseGateway();
$res = $gateway->load(226, 2, array('eng-GB'));
$this->assertValuesInRows(
'ezcontentobject_attribute_language_code',
array('eng-GB'),
$res
);
$this->assertValuesInRows(
'ezcontentobject_attribute_language_id',
array('4'),
$res
);
$this->assertEquals(
1,
count($res)
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::load
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase\QueryBuilder
*/
public function testLoadNonExistentTranslation()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$gateway = $this->getDatabaseGateway();
$res = $gateway->load(226, 2, array('de-DE'));
$this->assertEquals(
0,
count($res)
);
}
/**
* Asserts that $columnKey in $actualRows exactly contains $expectedValues.
*
* @param string $columnKey
* @param string[] $expectedValues
* @param string[][] $actualRows
*/
protected function assertValuesInRows($columnKey, array $expectedValues, array $actualRows)
{
$expectedValues = array_fill_keys(
array_values($expectedValues),
true
);
$containedValues = array();
foreach ($actualRows as $row) {
if (isset($row[$columnKey])) {
$containedValues[$row[$columnKey]] = true;
}
}
$this->assertEquals(
$expectedValues,
$containedValues
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::getAllLocationIds
*/
public function testGetAllLocationIds()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$gateway = $this->getDatabaseGateway();
$this->assertEquals(
array(228),
$gateway->getAllLocationIds(226)
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::getFieldIdsByType
*/
public function testGetFieldIdsByType()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$gateway = $this->getDatabaseGateway();
$this->assertEquals(
array(
'ezstring' => array(841),
'ezrichtext' => array(842),
'ezimage' => array(843),
'ezkeyword' => array(844),
),
$gateway->getFieldIdsByType(149)
);
}
/**
* @covers \eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::getFieldIdsByType
*/
public function testGetFieldIdsByTypeWithSecondArgument()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$gateway = $this->getDatabaseGateway();
$this->assertEquals(
array(
'ezstring' => array(4001, 4002),
),
$gateway->getFieldIdsByType(225, 2)
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::deleteRelations
*/
public function testDeleteRelationsTo()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$beforeCount = array(
'all' => $this->countContentRelations(),
'from' => $this->countContentRelations(149),
'to' => $this->countContentRelations(null, 149),
);
$gateway = $this->getDatabaseGateway();
$gateway->deleteRelations(149);
$this->assertEquals(
// yes, relates to itself!
array(
'all' => $beforeCount['all'] - 2,
'from' => $beforeCount['from'] - 1,
'to' => $beforeCount['to'] - 2,
),
array(
'all' => $this->countContentRelations(),
'from' => $this->countContentRelations(149),
'to' => $this->countContentRelations(null, 149),
)
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::deleteRelations
*/
public function testDeleteRelationsFrom()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$beforeCount = array(
'all' => $this->countContentRelations(),
'from' => $this->countContentRelations(75),
'to' => $this->countContentRelations(null, 75),
);
$gateway = $this->getDatabaseGateway();
$gateway->deleteRelations(75);
$this->assertEquals(
array(
'all' => $beforeCount['all'] - 6,
'from' => $beforeCount['from'] - 6,
'to' => $beforeCount['to'],
),
array(
'all' => $this->countContentRelations(),
'from' => $this->countContentRelations(75),
'to' => $this->countContentRelations(null, 75),
)
);
}
/**
* @covers \eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::deleteRelations
*/
public function testDeleteRelationsWithSecondArgument()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$beforeCount = array(
'all' => $this->countContentRelations(),
'from' => $this->countContentRelations(225),
'to' => $this->countContentRelations(null, 225),
);
$gateway = $this->getDatabaseGateway();
$gateway->deleteRelations(225, 2);
$this->assertEquals(
array(
'all' => $beforeCount['all'] - 1,
'from' => $beforeCount['from'] - 1,
'to' => $beforeCount['to'],
),
array(
'all' => $this->countContentRelations(),
'from' => $this->countContentRelations(225),
'to' => $this->countContentRelations(null, 225),
)
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::deleteField
*/
public function testDeleteField()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$beforeCount = $this->countContentFields();
$gateway = $this->getDatabaseGateway();
$gateway->deleteField(22);
$this->assertEquals(
$beforeCount - 2,
$this->countContentFields()
);
$this->assertQueryResult(
array(),
$this->getDatabaseHandler()->createSelectQuery()
->select('*')
->from('ezcontentobject_attribute')
->where('id=22')
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::deleteFields
*/
public function testDeleteFields()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$beforeCount = array(
'all' => $this->countContentFields(),
'this' => $this->countContentFields(4),
);
$gateway = $this->getDatabaseGateway();
$gateway->deleteFields(4);
$this->assertEquals(
array(
'all' => $beforeCount['all'] - 2,
'this' => 0,
),
array(
'all' => $this->countContentFields(),
'this' => $this->countContentFields(4),
)
);
}
/**
* @covers \eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::deleteFields
*/
public function testDeleteFieldsWithSecondArgument()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$beforeCount = array(
'all' => $this->countContentFields(),
'this' => $this->countContentFields(225),
);
$gateway = $this->getDatabaseGateway();
$gateway->deleteFields(225, 2);
$this->assertEquals(
array(
'all' => $beforeCount['all'] - 2,
'this' => $beforeCount['this'] - 2,
),
array(
'all' => $this->countContentFields(),
'this' => $this->countContentFields(225),
)
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::deleteVersions
*/
public function testDeleteVersions()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$beforeCount = array(
'all' => $this->countContentVersions(),
'this' => $this->countContentVersions(14),
);
$gateway = $this->getDatabaseGateway();
$gateway->deleteVersions(14);
$this->assertEquals(
array(
'all' => $beforeCount['all'] - 2,
'this' => 0,
),
array(
'all' => $this->countContentVersions(),
'this' => $this->countContentVersions(14),
)
);
}
/**
* @covers \eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::deleteVersions
*/
public function testDeleteVersionsWithSecondArgument()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$beforeCount = array(
'all' => $this->countContentVersions(),
'this' => $this->countContentVersions(225),
);
$gateway = $this->getDatabaseGateway();
$gateway->deleteVersions(225, 2);
$this->assertEquals(
array(
'all' => $beforeCount['all'] - 1,
'this' => $beforeCount['this'] - 1,
),
array(
'all' => $this->countContentVersions(),
'this' => $this->countContentVersions(225),
)
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::setName
*/
public function testSetName()
{
$beforeCount = array(
'all' => $this->countContentNames(),
'this' => $this->countContentNames(14),
);
$gateway = $this->getDatabaseGateway();
$gateway->setName(14, 2, 'Hello world!', 'eng-GB');
$this->assertQueryResult(
array(array('eng-GB', 2, 14, 4, 'Hello world!', 'eng-GB')),
$this->getDatabaseHandler()
->createSelectQuery()
->select('*')
->from('ezcontentobject_name')
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::deleteNames
*/
public function testDeleteNames()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$beforeCount = array(
'all' => $this->countContentNames(),
'this' => $this->countContentNames(14),
);
$gateway = $this->getDatabaseGateway();
$gateway->deleteNames(14);
$this->assertEquals(
array(
'all' => $beforeCount['all'] - 2,
'this' => 0,
),
array(
'all' => $this->countContentNames(),
'this' => $this->countContentNames(14),
)
);
}
/**
* @covers \eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::deleteNames
*/
public function testDeleteNamesWithSecondArgument()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$beforeCount = array(
'all' => $this->countContentNames(),
'this' => $this->countContentNames(225),
);
$gateway = $this->getDatabaseGateway();
$gateway->deleteNames(225, 2);
$this->assertEquals(
array(
'all' => $beforeCount['all'] - 1,
'this' => $beforeCount['this'] - 1,
),
array(
'all' => $this->countContentNames(),
'this' => $this->countContentNames(225),
)
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::deleteContent
*/
public function testDeleteContent()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$beforeCount = $this->countContent();
$gateway = $this->getDatabaseGateway();
$gateway->deleteContent(14);
$this->assertEquals(
array(
'all' => $beforeCount - 1,
'this' => 0,
),
array(
'all' => $this->countContent(),
'this' => $this->countContent(14),
)
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::loadRelations
*/
public function testLoadRelations()
{
$this->insertRelationFixture();
$gateway = $this->getDatabaseGateway();
$relations = $gateway->loadRelations(57);
$this->assertEquals(3, count($relations));
$this->assertValuesInRows(
'ezcontentobject_link_to_contentobject_id',
array(58, 59, 60),
$relations
);
$this->assertValuesInRows(
'ezcontentobject_link_from_contentobject_id',
array(57),
$relations
);
$this->assertValuesInRows(
'ezcontentobject_link_from_contentobject_version',
array(2),
$relations
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::loadRelations
*/
public function testLoadRelationsByType()
{
$this->insertRelationFixture();
$gateway = $this->getDatabaseGateway();
$relations = $gateway->loadRelations(57, null, \eZ\Publish\API\Repository\Values\Content\Relation::COMMON);
$this->assertEquals(1, count($relations), 'Expecting one relation to be loaded');
$this->assertValuesInRows(
'ezcontentobject_link_relation_type',
array(\eZ\Publish\API\Repository\Values\Content\Relation::COMMON),
$relations
);
$this->assertValuesInRows(
'ezcontentobject_link_to_contentobject_id',
array(58),
$relations
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::loadRelations
*/
public function testLoadRelationsByVersion()
{
$this->insertRelationFixture();
$gateway = $this->getDatabaseGateway();
$relations = $gateway->loadRelations(57, 1);
$this->assertEquals(1, count($relations), 'Expecting one relation to be loaded');
$this->assertValuesInRows(
'ezcontentobject_link_to_contentobject_id',
array(58),
$relations
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::loadRelations
*/
public function testLoadRelationsNoResult()
{
$this->insertRelationFixture();
$gateway = $this->getDatabaseGateway();
$relations = $gateway->loadRelations(57, 1, \eZ\Publish\API\Repository\Values\Content\Relation::EMBED);
$this->assertEquals(0, count($relations), 'Expecting no relation to be loaded');
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::loadReverseRelations
*/
public function testLoadReverseRelations()
{
$this->insertRelationFixture();
$gateway = $this->getDatabaseGateway();
$relations = $gateway->loadReverseRelations(58);
self::assertEquals(2, count($relations));
$this->assertValuesInRows(
'ezcontentobject_link_from_contentobject_id',
array(57, 61),
$relations
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::loadReverseRelations
*/
public function testLoadReverseRelationsWithType()
{
$this->insertRelationFixture();
$gateway = $this->getDatabaseGateway();
$relations = $gateway->loadReverseRelations(58, \eZ\Publish\API\Repository\Values\Content\Relation::COMMON);
self::assertEquals(1, count($relations));
$this->assertValuesInRows(
'ezcontentobject_link_from_contentobject_id',
array(57),
$relations
);
$this->assertValuesInRows(
'ezcontentobject_link_relation_type',
array(\eZ\Publish\API\Repository\Values\Content\Relation::COMMON),
$relations
);
}
/**
* Inserts the relation database fixture from relation_data.php.
*/
protected function insertRelationFixture()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/relations_data.php'
);
}
/*
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::getLastVersionNumber
*
* @return void
*/
public function testGetLastVersionNumber()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$gateway = $this->getDatabaseGateway();
$this->assertEquals(
1,
$gateway->getLastVersionNumber(4)
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::insertRelation
*/
public function testInsertRelation()
{
$struct = $this->getRelationCreateStructFixture();
$gateway = $this->getDatabaseGateway();
$gateway->insertRelation($struct);
$this->assertQueryResult(
array(
array(
'id' => 1,
'from_contentobject_id' => $struct->sourceContentId,
'from_contentobject_version' => $struct->sourceContentVersionNo,
'contentclassattribute_id' => $struct->sourceFieldDefinitionId,
'to_contentobject_id' => $struct->destinationContentId,
'relation_type' => $struct->type,
),
),
$this->getDatabaseHandler()
->createSelectQuery()
->select(
array(
'id',
'from_contentobject_id',
'from_contentobject_version',
'contentclassattribute_id',
'to_contentobject_id',
'relation_type',
)
)->from('ezcontentobject_link')
->where('id = 1')
);
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::deleteRelation
*/
public function testDeleteRelation()
{
$this->insertRelationFixture();
self::assertEquals(4, $this->countContentRelations(57));
$gateway = $this->getDatabaseGateway();
$gateway->deleteRelation(2, RelationValue::COMMON);
self::assertEquals(3, $this->countContentRelations(57));
}
/**
* @covers eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::deleteRelation
*/
public function testDeleteRelationWithCompositeBitmask()
{
$this->insertRelationFixture();
$gateway = $this->getDatabaseGateway();
$gateway->deleteRelation(11, RelationValue::COMMON);
/** @var $query \eZ\Publish\Core\Persistence\Database\SelectQuery */
$query = $this->getDatabaseHandler()->createSelectQuery();
$this->assertQueryResult(
array(array('relation_type' => RelationValue::LINK)),
$query->select(
array('relation_type')
)->from(
'ezcontentobject_link'
)->where(
$query->expr->eq('id', 11)
)
);
}
/**
* Test for the updateAlwaysAvailableFlag() method.
*
* @covers \eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::updateAlwaysAvailableFlag
*/
public function testUpdateAlwaysAvailableFlagRemove()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$gateway = $this->getDatabaseGateway();
$gateway->updateAlwaysAvailableFlag(103, false);
$this->assertQueryResult(
array(array('id' => 2)),
$this->getDatabaseHandler()->createSelectQuery()->select(
array('language_mask')
)->from(
'ezcontentobject'
)->where(
'id = 103'
)
);
$query = $this->getDatabaseHandler()->createSelectQuery();
$this->assertQueryResult(
array(array('language_id' => 2)),
$query->select(
array('language_id')
)->from(
'ezcontentobject_name'
)->where(
$query->expr->lAnd(
$query->expr->eq('contentobject_id', 103),
$query->expr->eq('content_version', 1)
)
)
);
$query = $this->getDatabaseHandler()->createSelectQuery();
$this->assertQueryResult(
array(
array('language_id' => 2),
),
$query->selectDistinct(
array('language_id')
)->from(
'ezcontentobject_attribute'
)->where(
$query->expr->lAnd(
$query->expr->eq('contentobject_id', 103),
$query->expr->eq('version', 1)
)
)
);
}
/**
* Test for the updateAlwaysAvailableFlag() method.
*
* @covers \eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::updateAlwaysAvailableFlag
*/
public function testUpdateAlwaysAvailableFlagAdd()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$gateway = $this->getDatabaseGateway();
$gateway->updateAlwaysAvailableFlag(102, true);
$this->assertQueryResult(
array(array('id' => 3)),
$this->getDatabaseHandler()->createSelectQuery()->select(
array('language_mask')
)->from(
'ezcontentobject'
)->where(
'id = 102'
)
);
$query = $this->getDatabaseHandler()->createSelectQuery();
$this->assertQueryResult(
array(array('language_id' => 3)),
$query->select(
array('language_id')
)->from(
'ezcontentobject_name'
)->where(
$query->expr->lAnd(
$query->expr->eq('contentobject_id', 102),
$query->expr->eq('content_version', 1)
)
)
);
$query = $this->getDatabaseHandler()->createSelectQuery();
$this->assertQueryResult(
array(
array('language_id' => 3),
),
$query->selectDistinct(
array('language_id')
)->from(
'ezcontentobject_attribute'
)->where(
$query->expr->lAnd(
$query->expr->eq('contentobject_id', 102),
$query->expr->eq('version', 1)
)
)
);
}
/**
* Test for the updateAlwaysAvailableFlag() method.
*
* @covers \eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::updateAlwaysAvailableFlag
*/
public function testUpdateContentAddAlwaysAvailableFlagMultilingual()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects_multilingual.php'
);
$gateway = $this->getDatabaseGateway();
$contentMetadataUpdateStruct = new MetadataUpdateStruct(
array(
'mainLanguageId' => 4,
'alwaysAvailable' => true,
)
);
$gateway->updateContent(4, $contentMetadataUpdateStruct);
$this->assertQueryResult(
array(array('id' => 7)),
$this->getDatabaseHandler()->createSelectQuery()->select(
array('language_mask')
)->from(
'ezcontentobject'
)->where(
'id = 4'
)
);
$query = $this->getDatabaseHandler()->createSelectQuery();
$this->assertQueryResult(
array(
array('id' => '7', 'language_id' => 2),
array('id' => '8', 'language_id' => 5),
),
$query->selectDistinct(
array('id', 'language_id')
)->from(
'ezcontentobject_attribute'
)->where(
$query->expr->lAnd(
$query->expr->eq('contentobject_id', 4),
$query->expr->eq('version', 2)
)
)->orderBy('id')
);
$query = $this->getDatabaseHandler()->createSelectQuery();
$this->assertQueryResult(
array(
array('id' => '7', 'language_id' => 2),
array('id' => '8', 'language_id' => 5),
),
$query->selectDistinct(
array('id', 'language_id')
)->from(
'ezcontentobject_attribute'
)->where(
$query->expr->lAnd(
$query->expr->eq('contentobject_id', 4),
$query->expr->eq('version', 1)
)
)->orderBy('id')
);
}
/**
* Test for the updateAlwaysAvailableFlag() method.
*
* @covers \eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase::updateAlwaysAvailableFlag
*/
public function testUpdateContentRemoveAlwaysAvailableFlagMultilingual()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects_multilingual.php'
);
$gateway = $this->getDatabaseGateway();
$contentMetadataUpdateStruct = new MetadataUpdateStruct(
array(
'mainLanguageId' => 4,
'alwaysAvailable' => false,
)
);
$gateway->updateContent(4, $contentMetadataUpdateStruct);
$this->assertQueryResult(
array(array('id' => 6)),
$this->getDatabaseHandler()->createSelectQuery()->select(
array('language_mask')
)->from(
'ezcontentobject'
)->where(
'id = 4'
)
);
$query = $this->getDatabaseHandler()->createSelectQuery();
$this->assertQueryResult(
array(
array('id' => '7', 'language_id' => 2),
array('id' => '8', 'language_id' => 4),
),
$query->selectDistinct(
array('id', 'language_id')
)->from(
'ezcontentobject_attribute'
)->where(
$query->expr->lAnd(
$query->expr->eq('contentobject_id', 4),
$query->expr->eq('version', 2)
)
)->orderBy('id')
);
$query = $this->getDatabaseHandler()->createSelectQuery();
$this->assertQueryResult(
array(
array('id' => '7', 'language_id' => 2),
array('id' => '8', 'language_id' => 5),
),
$query->selectDistinct(
array('id', 'language_id')
)->from(
'ezcontentobject_attribute'
)->where(
$query->expr->lAnd(
$query->expr->eq('contentobject_id', 4),
$query->expr->eq('version', 1)
)
)->orderBy('id')
);
}
public function testLoadVersionInfo()
{
$this->insertDatabaseFixture(
__DIR__ . '/../_fixtures/contentobjects.php'
);
$gateway = $this->getDatabaseGateway();
$resFirst = $gateway->loadVersionInfo(11, 1);
$resSecond = $gateway->loadVersionInfo(11, 2);
$res = array_merge($resFirst, $resSecond);
$orig = include __DIR__ . '/../_fixtures/extract_version_info_from_rows_multiple_versions.php';
/*$this->storeFixture(
__DIR__ . '/../_fixtures/extract_version_info_from_rows_multiple_versions.php',
$res
);*/
$this->assertEquals($orig, $res, 'Fixtures differ between what was previously stored(expected) and what it now generates(actual), this hints either some mistake in impl or that the fixture (../_fixtures/extract_content_from_rows_multiple_versions.php) and tests needs to be adapted.');
}
/**
* Counts the number of relations in the database.
*
* @param int $fromId
* @param int $toId
*
* @return int
*/
protected function countContentRelations($fromId = null, $toId = null)
{
$query = $this->getDatabaseHandler()->createSelectQuery();
$query->select('count(*)')
->from('ezcontentobject_link');
if ($fromId !== null) {
$query->where(
'from_contentobject_id=' . $fromId
);
}
if ($toId !== null) {
$query->where(
'to_contentobject_id=' . $toId
);
}
$statement = $query->prepare();
$statement->execute();
return (int)$statement->fetchColumn();
}
/**
* Counts the number of fields.
*
* @param int $contentId
*
* @return int
*/
protected function countContentFields($contentId = null)
{
$query = $this->getDatabaseHandler()->createSelectQuery();
$query->select('count(*)')
->from('ezcontentobject_attribute');
if ($contentId !== null) {
$query->where(
'contentobject_id=' . $contentId
);
}
$statement = $query->prepare();
$statement->execute();
return (int)$statement->fetchColumn();
}
/**
* Counts the number of versions.
*
* @param int $contentId
*
* @return int
*/
protected function countContentVersions($contentId = null)
{
$query = $this->getDatabaseHandler()->createSelectQuery();
$query->select('count(*)')
->from('ezcontentobject_version');
if ($contentId !== null) {
$query->where(
'contentobject_id=' . $contentId
);
}
$statement = $query->prepare();
$statement->execute();
return (int)$statement->fetchColumn();
}
/**
* Counts the number of content names.
*
* @param int $contentId
*
* @return int
*/
protected function countContentNames($contentId = null)
{
$query = $this->getDatabaseHandler()->createSelectQuery();
$query->select('count(*)')
->from('ezcontentobject_name');
if ($contentId !== null) {
$query->where(
'contentobject_id=' . $contentId
);
}
$statement = $query->prepare();
$statement->execute();
return (int)$statement->fetchColumn();
}
/**
* Counts the number of content objects.
*
* @param int $contentId
*
* @return int
*/
protected function countContent($contentId = null)
{
$query = $this->getDatabaseHandler()->createSelectQuery();
$query->select('count(*)')
->from('ezcontentobject');
if ($contentId !== null) {
$query->where(
'id=' . $contentId
);
}
$statement = $query->prepare();
$statement->execute();
return (int)$statement->fetchColumn();
}
/**
* Stores $fixture in $file to be required as a fixture.
*
* @param string $file
* @param mixed $fixture
*/
protected function storeFixture($file, $fixture)
{
file_put_contents(
$file,
"<?php\n\nreturn " . str_replace(" \n", "\n", var_export($fixture, true)) . ";\n"
);
}
/**
* Returns a Field fixture.
*
* @return Field
*/
protected function getFieldFixture()
{
$field = new Field();
$field->fieldDefinitionId = 231;
$field->type = 'ezstring';
$field->languageCode = 'eng-GB';
$field->versionNo = 1;
return $field;
}
/**
* Returns a Field fixture in a different language.
*
* @return Field
*/
protected function getOtherLanguageFieldFixture()
{
$field = $this->getFieldFixture();
$field->languageCode = 'eng-US';
return $field;
}
/**
* Returns a StorageFieldValue fixture.
*
* @return StorageFieldValue
*/
protected function getStorageValueFixture()
{
$value = new StorageFieldValue();
$value->dataFloat = 24.42;
$value->dataInt = 42;
$value->dataText = 'Test text';
$value->sortKeyInt = 23;
$value->sortKeyString = 'Test';
return $value;
}
/**
* Returns a ready to test DoctrineDatabase gateway.
*
* @return \eZ\Publish\Core\Persistence\Legacy\Content\Gateway\DoctrineDatabase
*/
protected function getDatabaseGateway()
{
if (!isset($this->databaseGateway)) {
$this->databaseGateway = new DoctrineDatabase(
($dbHandler = $this->getDatabaseHandler()),
new DoctrineDatabase\QueryBuilder($dbHandler),
$this->getLanguageHandler(),
$this->getLanguageMaskGenerator()
);
}
return $this->databaseGateway;
}
/**
* DoctrineDatabaseTest::getRelationCreateStructFixture().
*
* @return \eZ\Publish\SPI\Persistence\Content\Relation\CreateStruct
*/
protected function getRelationCreateStructFixture()
{
$struct = new RelationCreateStruct();
$struct->destinationContentId = 1;
$struct->sourceContentId = 1;
$struct->sourceContentVersionNo = 1;
$struct->sourceFieldDefinitionId = 0;
$struct->type = RelationValue::COMMON;
return $struct;
}
}
|
miguelcleverti/ezpublish-kernel
|
eZ/Publish/Core/Persistence/Legacy/Tests/Content/Gateway/DoctrineDatabaseTest.php
|
PHP
|
gpl-2.0
| 63,196
|
/* Copyright (C) 2011 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <drepper@gmail.com>, 2011.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <fenv.h>
#include <math.h>
#include <math_private.h>
/* wrapper log(x) */
double
__log (double x)
{
if (__builtin_expect (x <= 0.0, 0) && _LIB_VERSION != _IEEE_)
{
if (x == 0.0)
{
feraiseexcept (FE_DIVBYZERO);
return __kernel_standard (x, x, 16); /* log(0) */
}
else
{
feraiseexcept (FE_INVALID);
return __kernel_standard (x, x, 17); /* log(x<0) */
}
}
return __ieee754_log (x);
}
weak_alias (__log, log)
#ifdef NO_LONG_DOUBLE
strong_alias (__log, __logl)
weak_alias (__log, logl)
#endif
|
pexip/os-eglibc
|
math/w_log.c
|
C
|
gpl-2.0
| 1,452
|
/* Return the canonical absolute name of a given file.
Copyright (C) 1996-2001, 2002 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Copyright (C) 2002 Red Hat, Inc. (trivial port to GLib)
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <config.h>
#include "canonicalize.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <errno.h>
#include <stddef.h>
/* Return the canonical absolute name of file NAME. A canonical name
does not contain any `.', `..' components nor any repeated path
separators ('/') or symlinks. All path components must exist. If
RESOLVED is null, the result is malloc'd; otherwise, if the
canonical name is PATH_MAX chars or more, returns null with `errno'
set to ENAMETOOLONG; if the name fits in fewer than PATH_MAX chars,
returns the name in RESOLVED. If the name cannot be resolved and
RESOLVED is non-NULL, it contains the path of the first component
that cannot be resolved. If the path can be resolved, RESOLVED
holds the same value as the value returned. */
static char*
menu_realpath (const char *name, char *resolved)
{
char *rpath, *dest, *extra_buf = NULL;
const char *start, *end, *rpath_limit;
long int path_max;
int num_links = 0;
if (name == NULL)
{
/* As per Single Unix Specification V2 we must return an error if
either parameter is a null pointer. We extend this to allow
the RESOLVED parameter to be NULL in case the we are expected to
allocate the room for the return value. */
errno = EINVAL;
return NULL;
}
if (name[0] == '\0')
{
/* As per Single Unix Specification V2 we must return an error if
the name argument points to an empty string. */
errno = ENOENT;
return NULL;
}
#ifdef PATH_MAX
path_max = PATH_MAX;
#else
path_max = pathconf (name, _PC_PATH_MAX);
if (path_max <= 0)
path_max = 1024;
#endif
rpath = resolved ? g_alloca (path_max) : g_malloc (path_max);
rpath_limit = rpath + path_max;
if (name[0] != G_DIR_SEPARATOR)
{
if (!getcwd (rpath, path_max))
{
rpath[0] = '\0';
goto error;
}
dest = strchr (rpath, '\0');
}
else
{
rpath[0] = G_DIR_SEPARATOR;
dest = rpath + 1;
}
for (start = end = name; *start; start = end)
{
struct stat st;
int n;
/* Skip sequence of multiple path-separators. */
while (*start == G_DIR_SEPARATOR)
++start;
/* Find end of path component. */
for (end = start; *end && *end != G_DIR_SEPARATOR; ++end)
/* Nothing. */;
if (end - start == 0)
break;
else if (end - start == 1 && start[0] == '.')
/* nothing */;
else if (end - start == 2 && start[0] == '.' && start[1] == '.')
{
/* Back up to previous component, ignore if at root already. */
if (dest > rpath + 1)
while ((--dest)[-1] != G_DIR_SEPARATOR);
}
else
{
size_t new_size;
if (dest[-1] != G_DIR_SEPARATOR)
*dest++ = G_DIR_SEPARATOR;
if (dest + (end - start) >= rpath_limit)
{
ptrdiff_t dest_offset = dest - rpath;
char *new_rpath;
if (resolved)
{
#ifdef ENAMETOOLONG
errno = ENAMETOOLONG;
#else
/* Uh... just pick something */
errno = EINVAL;
#endif
if (dest > rpath + 1)
dest--;
*dest = '\0';
goto error;
}
new_size = rpath_limit - rpath;
if (end - start + 1 > path_max)
new_size += end - start + 1;
else
new_size += path_max;
new_rpath = (char *) realloc (rpath, new_size);
if (new_rpath == NULL)
goto error;
rpath = new_rpath;
rpath_limit = rpath + new_size;
dest = rpath + dest_offset;
}
memcpy (dest, start, end - start);
dest = dest + (end - start);
*dest = '\0';
if (stat (rpath, &st) < 0)
goto error;
if (S_ISLNK (st.st_mode))
{
char *buf = alloca (path_max);
size_t len;
if (++num_links > MAXSYMLINKS)
{
errno = ELOOP;
goto error;
}
n = readlink (rpath, buf, path_max);
if (n < 0)
goto error;
buf[n] = '\0';
if (!extra_buf)
extra_buf = g_alloca (path_max);
len = strlen (end);
if ((long int) (n + len) >= path_max)
{
#ifdef ENAMETOOLONG
errno = ENAMETOOLONG;
#else
/* Uh... just pick something */
errno = EINVAL;
#endif
goto error;
}
/* Careful here, end may be a pointer into extra_buf... */
g_memmove (&extra_buf[n], end, len + 1);
name = end = memcpy (extra_buf, buf, n);
if (buf[0] == G_DIR_SEPARATOR)
dest = rpath + 1; /* It's an absolute symlink */
else
/* Back up to previous component, ignore if at root already: */
if (dest > rpath + 1)
while ((--dest)[-1] != G_DIR_SEPARATOR);
}
}
}
if (dest > rpath + 1 && dest[-1] == G_DIR_SEPARATOR)
--dest;
*dest = '\0';
return resolved ? memcpy (resolved, rpath, dest - rpath + 1) : rpath;
error:
if (resolved)
strcpy (resolved, rpath);
else
g_free (rpath);
return NULL;
}
char *
menu_canonicalize_file_name (const char *name,
gboolean allow_missing_basename)
{
char *retval;
retval = menu_realpath (name, NULL);
/* We could avoid some system calls by using the second
* argument to realpath() instead of doing realpath
* all over again, but who cares really. we'll see if
* it's ever in a profile.
*/
if (allow_missing_basename && retval == NULL)
{
char *dirname;
char *canonical_dirname;
dirname = g_path_get_dirname (name);
canonical_dirname = menu_realpath (dirname, NULL);
g_free (dirname);
if (canonical_dirname)
{
char *basename;
basename = g_path_get_basename (name);
retval = g_build_filename (canonical_dirname, basename, NULL);
g_free (basename);
g_free (canonical_dirname);
}
}
return retval;
}
|
LStranger/clone-menu-cache-debian-build
|
menu-cache-gen/canonicalize.c
|
C
|
gpl-2.0
| 7,539
|
<?php
/**
* @version $Id: constants.php 203 2011-06-01 19:02:19Z happy_noodle_boy $
* @package JCE
* @copyright Copyright © 2009-2011 Ryan Demmer. All rights reserved.
* @copyright Copyright © 2005 - 2007 Open Source Matters. All rights reserved.
* @license GNU/GPL 2 or later
* This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
*/
// no direct access
defined('_JEXEC') or die('RESTRICTED');
// define Joomla! version
define('WF_JOOMLA15', version_compare(JVERSION, '1.6', '<'));
// define JQuery version
define('WF_JQUERY', '1.6.2');
// define JQuery UI version
define('WF_JQUERYUI', '1.8.13');
// Some shortcuts to make life easier
// JCE Administration Component
define('WF_ADMINISTRATOR', JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_jce');
// JCE Site Component
define('WF_SITE', JPATH_SITE . DS . 'components' . DS . 'com_jce');
// JCE Plugin
if (WF_JOOMLA15) {
define('WF_PLUGIN', JPATH_SITE . DS . 'plugins' . DS . 'editors');
} else {
define('WF_PLUGIN', JPATH_SITE . DS . 'plugins' . DS . 'editors' . DS . 'jce');
}
// JCE Editor
define('WF_EDITOR', WF_SITE . DS . 'editor');
// JCE Editor Plugins
define('WF_EDITOR_PLUGINS', WF_EDITOR . DS . 'tiny_mce' . DS . 'plugins');
// JCE Editor Themes
define('WF_EDITOR_THEMES', WF_EDITOR . DS . 'tiny_mce' . DS . 'themes');
// JCE Editor Libraries
define('WF_EDITOR_LIBRARIES', WF_EDITOR . DS . 'libraries');
// JCE Editor Classes
define('WF_EDITOR_CLASSES', WF_EDITOR_LIBRARIES . DS . 'classes');
// JCE Editor Extensions
define('WF_EDITOR_EXTENSIONS', WF_EDITOR . DS . 'extensions');
?>
|
healthcommcore/lodalab
|
administrator/components/com_jce/includes/constants.php
|
PHP
|
gpl-2.0
| 1,824
|
/*
* ARCH LINUX DJANGO (MAIN SITE)
*
* Stylesheet for printing
*/
/* general styling */
body { font: normal 100% sans-serif; }
#content { font-size: 0.812em; }
#archnavbarmenu, #archdev-navbar, .admin-actions { display: none; }
|
archhurd/archweb
|
sitestatic/archweb-print.css
|
CSS
|
gpl-2.0
| 236
|
/* Touch_synaptics.c
*
* Copyright (C) 2012 LGE.
*
* Author: yehan.ahn@lge.com, hyesung.shin@lge.com
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/err.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/gpio.h>
#include <linux/regulator/machine.h>
#include <linux/async.h>
#if defined(CONFIG_MACH_MSM8974_G3_KDDI_EVB)
#include <linux/input/lge_touch_core_kddi_evb.h>
#include <linux/input/touch_synaptics_kddi_evb.h>
#else
#include <linux/input/lge_touch_core.h>
#include <linux/input/touch_synaptics.h>
#endif
#if defined(CONFIG_MACH_APQ8064_GK_KR) || defined(CONFIG_MACH_APQ8064_GKATT) || defined(CONFIG_MACH_APQ8064_GKGLOBAL)|| defined(CONFIG_MACH_MSM8974_G3_KDDI_EVB)
#include "SynaImage_for_GK.h"
#elif defined(CONFIG_MACH_APQ8064_GVDCM)
#include "SynaImage_for_DCM.h"
#elif defined(CONFIG_MACH_APQ8064_J1D) || defined(CONFIG_MACH_APQ8064_J1KD)
#include "SynaImage_for_GJ.h"
#else
#include "SynaImage.h"
#define G_ONLY
#endif
#include <linux/regulator/machine.h>
/*
*/
#define RMI_DEVICE_CONTROL 0x01
#define TOUCHPAD_SENSORS 0x11
#define CAPACITIVE_BUTTON_SENSORS 0x1A
#define GPIO_LEDS 0x30
#define LEDS 0x31
#define ANALOG_CONTROL 0x54
#define TIMER 0x32
#define FLASH_MEMORY_MANAGEMENT 0x34
#define AUXILIARY_ADC 0x36
/*
*/
/* */
#define MANUFACTURER_ID_REG (ts->common_fc.dsc.query_base) /* */
#define FW_REVISION_REG (ts->common_fc.dsc.query_base+3) /* */
#define PRODUCT_ID_REG (ts->common_fc.dsc.query_base+11) /* */
#define DEVICE_COMMAND_REG (ts->common_fc.dsc.command_base)
#define DEVICE_CONTROL_REG (ts->common_fc.dsc.control_base) /* */
#define DEVICE_CONTROL_NORMAL_OP 0x00 /* */
#define DEVICE_CONTROL_SLEEP 0x01 /* */
#define DEVICE_CONTROL_SPECIFIC 0x02 /* */
#define DEVICE_CONTROL_NOSLEEP 0x04
#define DEVICE_CONTROL_CONFIGURED 0x80
#ifdef CUST_G_TOUCH
#define DEVICE_CHARGER_CONNECTED 0x20
#endif
#define INTERRUPT_ENABLE_REG (ts->common_fc.dsc.control_base+1) /* */
#define DEVICE_STATUS_REG (ts->common_fc.dsc.data_base) /* */
#define DEVICE_FAILURE_MASK 0x03
#define DEVICE_CRC_ERROR_MASK 0x04
#define DEVICE_STATUS_FLASH_PROG 0x40
#define DEVICE_STATUS_UNCONFIGURED 0x80
#define INTERRUPT_STATUS_REG (ts->common_fc.dsc.data_base+1) /* */
#ifdef CUST_G_TOUCH
//
#else
#define INTERRUPT_MASK_FLASH 0x01
#define INTERRUPT_MASK_ABS0 0x04
#define INTERRUPT_MASK_BUTTON 0x10
#endif
/* */
#define FINGER_COMMAND_REG (ts->finger_fc.dsc.command_base)
#define FINGER_STATE_REG (ts->finger_fc.dsc.data_base) /* */
#define FINGER_DATA_REG_START (ts->finger_fc.dsc.data_base+3) /* */
#define FINGER_STATE_MASK 0x03
#define REG_X_POSITION 0
#define REG_Y_POSITION 1
#define REG_YX_POSITION 2
#define REG_WY_WX 3
#define REG_Z 4
#define TWO_D_EXTEND_STATUS (ts->finger_fc.dsc.data_base+53)
#define TWO_D_REPORTING_MODE (ts->finger_fc.dsc.control_base+0) /* */
#ifdef CUST_G_TOUCH
#define REPORT_BEYOND_CLIP 0x80
#endif
#define REPORT_MODE_CONTINUOUS 0x00
#define REPORT_MODE_REDUCED 0x01
#define ABS_FILTER 0x08
#define PALM_DETECT_REG (ts->finger_fc.dsc.control_base+1) /* */
#define DELTA_X_THRESH_REG (ts->finger_fc.dsc.control_base+2) /* */
#define DELTA_Y_THRESH_REG (ts->finger_fc.dsc.control_base+3) /* */
#define SENSOR_MAX_X_POS (ts->finger_fc.dsc.control_base+6) /* */
#define SENSOR_MAX_Y_POS (ts->finger_fc.dsc.control_base+8) /* */
/* */
#define BUTTON_COMMAND_REG (ts->button_fc.dsc.command_base)
#define BUTTON_DATA_REG (ts->button_fc.dsc.data_base) /* */
#define MAX_NUM_OF_BUTTON 4
/* */
#define ANALOG_COMMAND_REG (ts->analog_fc.dsc.command_base)
#define FORCE_UPDATE 0x04
#define ANALOG_CONTROL_REG (ts->analog_fc.dsc.control_base)
#define FORCE_FAST_RELAXATION 0x04
#define FAST_RELAXATION_RATE (ts->analog_fc.dsc.control_base+16)
/* */
#define FLASH_CONFIG_ID_REG (ts->flash_fc.dsc.control_base) /* */
#define FLASH_CONTROL_REG (ts->flash_fc.dsc.data_base+18)
#define FLASH_STATUS_MASK 0xF0
/* */
#define COMMON_PAGE (ts->common_fc.function_page)
#define FINGER_PAGE (ts->finger_fc.function_page)
#define BUTTON_PAGE (ts->button_fc.function_page)
#define ANALOG_PAGE (ts->analog_fc.function_page)
#define FLASH_PAGE (ts->flash_fc.function_page)
#define DEFAULT_PAGE 0x00
/*
*/
#define TS_SNTS_GET_X_POSITION(_high_reg, _low_reg) \
( ((u16)((_high_reg << 4) & 0x0FF0) | (u16)(_low_reg&0x0F)))
#define TS_SNTS_GET_Y_POSITION(_high_reg, _low_reg) \
( ((u16)((_high_reg << 4) & 0x0FF0) | (u16)((_low_reg >> 4) & 0x0F)))
#define TS_SNTS_GET_WIDTH_MAJOR(_width) \
((((_width & 0xF0) >> 4) - (_width & 0x0F)) > 0) ? (_width & 0xF0) >> 4 : _width & 0x0F
#define TS_SNTS_GET_WIDTH_MINOR(_width) \
((((_width & 0xF0) >> 4) - (_width & 0x0F)) > 0) ? _width & 0x0F : (_width & 0xF0) >> 4
#define TS_SNTS_GET_ORIENTATION(_width) \
((((_width & 0xF0) >> 4) - (_width & 0x0F)) > 0) ? 0 : 1
#define TS_SNTS_GET_PRESSURE(_pressure) \
_pressure
/*
*/
#define GET_BIT_MASK(_finger_status_reg) \
(_finger_status_reg[2] & 0x04)<<7 | (_finger_status_reg[2] & 0x01)<<8 | \
(_finger_status_reg[1] & 0x40)<<1 | (_finger_status_reg[1] & 0x10)<<2 | \
(_finger_status_reg[1] & 0x04)<<3 | (_finger_status_reg[1] & 0x01)<<4 | \
(_finger_status_reg[0] & 0x40)>>3 | (_finger_status_reg[0] & 0x10)>>2 | \
(_finger_status_reg[0] & 0x04)>>1 | (_finger_status_reg[0] & 0x01)
#define GET_INDEX_FROM_MASK(_index, _bit_mask, _max_finger) \
for(; !((_bit_mask>>_index)&0x01) && _index <= _max_finger; _index++); \
if (_index <= _max_finger) _bit_mask &= ~(_bit_mask & (1<<(_index)));
#ifdef CUST_G_TOUCH
u8 pressure_zero = 0;
extern int ts_charger_plug;
extern int ts_charger_type;
#if defined (CONFIG_MACH_APQ8064_J1A)
#define CUST_G_TOUCH_FREQ_HOPPING
#endif
#ifdef CUST_G_TOUCH_FREQ_HOPPING
extern int cur_hopping_idx;
int cns_en = 0;
u8 hopping = 0;
#endif
#endif
/*
*/
int synaptics_ts_page_data_read(struct i2c_client *client, u8 page, u8 reg, int size, u8 *data)
{
if (unlikely(touch_i2c_write_byte(client, PAGE_SELECT_REG, page) < 0)) {
TOUCH_ERR_MSG("PAGE_SELECT_REG write fail\n");
return -EIO;
}
if (unlikely(touch_i2c_read(client, reg, size, data) < 0)) {
TOUCH_ERR_MSG("[%dP:%d]register read fail\n", page, reg);
return -EIO;
}
if (unlikely(touch_i2c_write_byte(client, PAGE_SELECT_REG, DEFAULT_PAGE) < 0)) {
TOUCH_ERR_MSG("PAGE_SELECT_REG write fail\n");
return -EIO;
}
return 0;
}
int synaptics_ts_page_data_write(struct i2c_client *client, u8 page, u8 reg, int size, u8 *data)
{
if (unlikely(touch_i2c_write_byte(client, PAGE_SELECT_REG, page) < 0)) {
TOUCH_ERR_MSG("PAGE_SELECT_REG write fail\n");
return -EIO;
}
if (unlikely(touch_i2c_write(client, reg, size, data) < 0)) {
TOUCH_ERR_MSG("[%dP:%d]register read fail\n", page, reg);
return -EIO;
}
if (unlikely(touch_i2c_write_byte(client, PAGE_SELECT_REG, DEFAULT_PAGE) < 0)) {
TOUCH_ERR_MSG("PAGE_SELECT_REG write fail\n");
return -EIO;
}
return 0;
}
int synaptics_ts_page_data_write_byte(struct i2c_client *client, u8 page, u8 reg, u8 data)
{
if (unlikely(touch_i2c_write_byte(client, PAGE_SELECT_REG, page) < 0)) {
TOUCH_ERR_MSG("PAGE_SELECT_REG write fail\n");
return -EIO;
}
if (unlikely(touch_i2c_write_byte(client, reg, data) < 0)) {
TOUCH_ERR_MSG("[%dP:%d]register write fail\n", page, reg);
return -EIO;
}
if (unlikely(touch_i2c_write_byte(client, PAGE_SELECT_REG, DEFAULT_PAGE) < 0)) {
TOUCH_ERR_MSG("PAGE_SELECT_REG write fail\n");
return -EIO;
}
return 0;
}
int synaptics_ts_get_data(struct i2c_client *client, struct touch_data* data)
{
struct synaptics_ts_data* ts =
(struct synaptics_ts_data*)get_touch_handle(client);
u16 touch_finger_bit_mask=0;
u8 finger_index=0;
u8 index=0;
u8 buf=0;
u8 cnt;
u8 buf2=0;
u16 alpha = 0;
u8 cns = 0;
u16 im = 0;
u16 vm = 0;
u16 aim = 0;
data->total_num = 0;
#ifdef CUST_G_TOUCH
pressure_zero = 0;
#ifdef CUST_G_TOUCH_FREQ_HOPPING
hopping = 0;
#endif
#endif
if (unlikely(touch_debug_mask & DEBUG_TRACE))
TOUCH_DEBUG_MSG("\n");
if (unlikely(touch_i2c_read(client, DEVICE_STATUS_REG,
sizeof(ts->ts_data.interrupt_status_reg),
&ts->ts_data.device_status_reg) < 0)) {
TOUCH_ERR_MSG("DEVICE_STATUS_REG read fail\n");
goto err_synaptics_getdata;
}
/* */
if ((ts->ts_data.device_status_reg & DEVICE_FAILURE_MASK)== DEVICE_FAILURE_MASK) {
TOUCH_ERR_MSG("ESD damage occured. Reset Touch IC\n");
goto err_synaptics_device_damage;
}
/* */
if (((ts->ts_data.device_status_reg & DEVICE_STATUS_UNCONFIGURED) >> 7) == 1) {
TOUCH_ERR_MSG("Touch IC resetted internally. Reconfigure register setting\n");
goto err_synaptics_device_damage;
}
if (unlikely(touch_i2c_read(client, INTERRUPT_STATUS_REG,
sizeof(ts->ts_data.interrupt_status_reg),
&ts->ts_data.interrupt_status_reg) < 0)) {
TOUCH_ERR_MSG("INTERRUPT_STATUS_REG read fail\n");
goto err_synaptics_getdata;
}
if (unlikely(touch_debug_mask & DEBUG_GET_DATA))
TOUCH_INFO_MSG("Interrupt_status : 0x%x\n", ts->ts_data.interrupt_status_reg);
#ifdef CUST_G_TOUCH
//
#else
/* */
if (ts->ts_data.interrupt_status_reg == 0) {
TOUCH_ERR_MSG("Interrupt_status reg is 0. Something is wrong in IC\n");
goto err_synaptics_device_damage;
}
#endif
/* */
if (unlikely(ts->ts_data.interrupt_status_reg & ts->interrupt_mask.flash)){
TOUCH_ERR_MSG("Impossible Interrupt\n");
goto err_synaptics_device_damage;
}
#ifdef CUST_G_TOUCH
if ( ts->ts_data.interrupt_status_reg == 0x08 || ts->ts_data.interrupt_status_reg == 0x00 ) {
TOUCH_ERR_MSG("Ignore interrupt. interrupt status reg = 0x%x\n", ts->ts_data.interrupt_status_reg);
goto ignore_interrupt;
}
#endif
/* */
if (likely(ts->ts_data.interrupt_status_reg & ts->interrupt_mask.abs)) {
if (unlikely(touch_i2c_read(client, FINGER_STATE_REG,
sizeof(ts->ts_data.finger.finger_status_reg),
ts->ts_data.finger.finger_status_reg) < 0)) {
TOUCH_ERR_MSG("FINGER_STATE_REG read fail\n");
goto err_synaptics_getdata;
}
touch_finger_bit_mask = GET_BIT_MASK(ts->ts_data.finger.finger_status_reg);
if (unlikely(touch_debug_mask & DEBUG_GET_DATA)) {
TOUCH_INFO_MSG("Finger_status : 0x%x, 0x%x, 0x%x\n", ts->ts_data.finger.finger_status_reg[0],
ts->ts_data.finger.finger_status_reg[1], ts->ts_data.finger.finger_status_reg[2]);
TOUCH_INFO_MSG("Touch_bit_mask: 0x%x\n", touch_finger_bit_mask);
}
while(touch_finger_bit_mask) {
GET_INDEX_FROM_MASK(finger_index, touch_finger_bit_mask, MAX_NUM_OF_FINGERS)
if (unlikely(touch_i2c_read(ts->client,
FINGER_DATA_REG_START + (NUM_OF_EACH_FINGER_DATA_REG * finger_index),
NUM_OF_EACH_FINGER_DATA_REG,
ts->ts_data.finger.finger_reg[finger_index]) < 0)) {
TOUCH_ERR_MSG("FINGER_DATA_REG read fail\n");
goto err_synaptics_getdata;
}
data->curr_data[finger_index].id = finger_index;
data->curr_data[finger_index].x_position =
TS_SNTS_GET_X_POSITION(ts->ts_data.finger.finger_reg[finger_index][REG_X_POSITION],
ts->ts_data.finger.finger_reg[finger_index][REG_YX_POSITION]);
data->curr_data[finger_index].y_position =
TS_SNTS_GET_Y_POSITION(ts->ts_data.finger.finger_reg[finger_index][REG_Y_POSITION],
ts->ts_data.finger.finger_reg[finger_index][REG_YX_POSITION]);
data->curr_data[finger_index].width_major = TS_SNTS_GET_WIDTH_MAJOR(ts->ts_data.finger.finger_reg[finger_index][REG_WY_WX]);
data->curr_data[finger_index].width_minor = TS_SNTS_GET_WIDTH_MINOR(ts->ts_data.finger.finger_reg[finger_index][REG_WY_WX]);
data->curr_data[finger_index].width_orientation = TS_SNTS_GET_ORIENTATION(ts->ts_data.finger.finger_reg[finger_index][REG_WY_WX]);
data->curr_data[finger_index].pressure = TS_SNTS_GET_PRESSURE(ts->ts_data.finger.finger_reg[finger_index][REG_Z]);
data->curr_data[finger_index].status = FINGER_PRESSED;
#ifdef CUST_G_TOUCH
if(ts->pdata->role->ghost_detection_enable) {
if(data->curr_data[finger_index].pressure == 0) pressure_zero = 1;
}
#endif
if (unlikely(touch_debug_mask & DEBUG_GET_DATA))
TOUCH_INFO_MSG("<%d> pos(%4d,%4d) w_m[%2d] w_n[%2d] w_o[%2d] p[%2d]\n",
finger_index, data->curr_data[finger_index].x_position, data->curr_data[finger_index].y_position,
data->curr_data[finger_index].width_major, data->curr_data[finger_index].width_minor,
data->curr_data[finger_index].width_orientation, data->curr_data[finger_index].pressure);
index++;
}
data->total_num = index;
if (unlikely(touch_debug_mask & DEBUG_GET_DATA))
TOUCH_INFO_MSG("Total_num: %d\n", data->total_num);
}
/* */
if (unlikely(ts->button_fc.dsc.id != 0)) {
if (likely(ts->ts_data.interrupt_status_reg & ts->interrupt_mask.button)) {
if (unlikely(synaptics_ts_page_data_read(client, BUTTON_PAGE, BUTTON_DATA_REG,
sizeof(ts->ts_data.button_data_reg), &ts->ts_data.button_data_reg) < 0)) {
TOUCH_ERR_MSG("BUTTON_DATA_REG read fail\n");
goto err_synaptics_getdata;
}
if (unlikely(touch_debug_mask & DEBUG_BUTTON))
TOUCH_DEBUG_MSG("Button register: 0x%x\n", ts->ts_data.button_data_reg);
if (ts->ts_data.button_data_reg) {
/* */
for (cnt = 0; cnt < ts->pdata->caps->number_of_button; cnt++)
{
#ifdef CUST_G_TOUCH
if(ts->ic_panel_type == G_IC3203_G2) {
if ((ts->ts_data.button_data_reg >> (cnt << 1)) & 0x3) {
ts->ts_data.button.key_code = ts->pdata->caps->button_name[cnt];
data->curr_button.key_code = ts->ts_data.button.key_code;
data->curr_button.state = 1;
break;
}
} else {
if ((ts->ts_data.button_data_reg >> cnt) & 0x1) {
ts->ts_data.button.key_code = ts->pdata->caps->button_name[cnt];
data->curr_button.key_code = ts->ts_data.button.key_code;
data->curr_button.state = 1;
break;
}
}
#endif
}
}else {
/* */
data->curr_button.key_code = ts->ts_data.button.key_code;
data->curr_button.state = 0;
}
}
}
/* */
if (unlikely(touch_i2c_read(client, TWO_D_EXTEND_STATUS, 1, &buf) < 0)){
TOUCH_ERR_MSG("TWO_D_EXTEND_STATUS read fail\n");
goto err_synaptics_getdata;
}
data->palm = buf & 0x2;
if( (ts_charger_plug == 1 && (data->prev_total_num != data->total_num)) ||
(touch_debug_mask & DEBUG_NOISE) ) {
if (unlikely(synaptics_ts_page_data_read(client, ANALOG_PAGE, 0x0e, 1, &buf) < 0)) {
TOUCH_ERR_MSG("Alpha REG read fail\n");
goto err_synaptics_getdata;
}
if (unlikely(synaptics_ts_page_data_read(client, ANALOG_PAGE, 0x0f, 1, &buf2) < 0)) {
TOUCH_ERR_MSG("Alpha REG read fail\n");
goto err_synaptics_getdata;
}
alpha = (buf2<<8)|buf;
if (unlikely(synaptics_ts_page_data_read(client, ANALOG_PAGE, 0x0D, 1, &cns) < 0)) {
TOUCH_ERR_MSG("Current Noise State REG read fail\n");
goto err_synaptics_getdata;
}
#ifdef CUST_G_TOUCH_FREQ_HOPPING
if(ts_charger_plug && cns >= 1) {
cns_en = 1;
if(cur_hopping_idx != 4){
buf = 0x84;
synaptics_ts_page_data_write(client, 0x01, 0x04, 1, &buf);
cur_hopping_idx = 4;
hopping = 1;
TOUCH_INFO_MSG("cur_hopping_idx [ %s ] = %x %x \n", __func__, buf, hopping);
} else {
hopping = 0;
}
}
#endif
if (unlikely(synaptics_ts_page_data_read(client, ANALOG_PAGE, 0x05, 1, &buf) < 0)) {
TOUCH_ERR_MSG("Interference Metric REG read fail\n");
goto err_synaptics_getdata;
}
if (unlikely(synaptics_ts_page_data_read(client, ANALOG_PAGE, 0x06, 1, &buf2) < 0)) {
TOUCH_ERR_MSG("Interference Metric REG read fail\n");
goto err_synaptics_getdata;
}
im = (buf2<<8)|buf;
if (unlikely(synaptics_ts_page_data_read(client, ANALOG_PAGE, 0x09, 1, &buf) < 0)) {
TOUCH_ERR_MSG("Variance Metric REG read fail\n");
goto err_synaptics_getdata;
}
if (unlikely(synaptics_ts_page_data_read(client, ANALOG_PAGE, 0x0a, 1, &buf2) < 0)) {
TOUCH_ERR_MSG("Variance Metric REG read fail\n");
goto err_synaptics_getdata;
}
vm = (buf2<<8)|buf;
if (unlikely(synaptics_ts_page_data_read(client, ANALOG_PAGE, 0x0b, 1, &buf) < 0)) {
TOUCH_ERR_MSG("Averaged IM REG read fail\n");
goto err_synaptics_getdata;
}
if (unlikely(synaptics_ts_page_data_read(client, ANALOG_PAGE, 0x0c, 1, &buf2) < 0)) {
TOUCH_ERR_MSG("Averaged IM REG read fail\n");
goto err_synaptics_getdata;
}
aim = (buf2<<8)|buf;
TOUCH_INFO_MSG(" A[%5d] CNS[%d] IM[%5d] VM[%5d] AIM[%5d]\n", alpha, cns, im, vm, aim);
}
return 0;
err_synaptics_device_damage:
err_synaptics_getdata:
return -EIO;
#ifdef CUST_G_TOUCH
ignore_interrupt:
return -IGNORE_INTERRUPT;
#endif
}
static int read_page_description_table(struct i2c_client* client)
{
struct synaptics_ts_data* ts =
(struct synaptics_ts_data*)get_touch_handle(client);
struct function_descriptor buffer;
unsigned short u_address = 0;
unsigned short page_num = 0;
if (touch_debug_mask & DEBUG_TRACE)
TOUCH_DEBUG_MSG("\n");
memset(&buffer, 0x0, sizeof(struct function_descriptor));
memset(&ts->common_fc, 0x0, sizeof(struct ts_ic_function));
memset(&ts->finger_fc, 0x0, sizeof(struct ts_ic_function));
memset(&ts->button_fc, 0x0, sizeof(struct ts_ic_function));
memset(&ts->analog_fc, 0x0, sizeof(struct ts_ic_function));
memset(&ts->flash_fc, 0x0, sizeof(struct ts_ic_function));
for(page_num = 0; page_num < PAGE_MAX_NUM; page_num++) {
if (unlikely(touch_i2c_write_byte(client, PAGE_SELECT_REG, page_num) < 0)) {
TOUCH_ERR_MSG("PAGE_SELECT_REG write fail\n");
return -EIO;
}
for(u_address = DESCRIPTION_TABLE_START; u_address > 10; u_address -= sizeof(struct function_descriptor)) {
if (unlikely(touch_i2c_read(client, u_address, sizeof(buffer), (unsigned char *)&buffer) < 0)) {
TOUCH_ERR_MSG("RMI4 Function Descriptor read fail\n");
return -EIO;
}
if (buffer.id == 0)
break;
switch (buffer.id) {
case RMI_DEVICE_CONTROL:
ts->common_fc.dsc = buffer;
ts->common_fc.function_page = page_num;
break;
case TOUCHPAD_SENSORS:
ts->finger_fc.dsc = buffer;
ts->finger_fc.function_page = page_num;
break;
case CAPACITIVE_BUTTON_SENSORS:
ts->button_fc.dsc = buffer;
ts->button_fc.function_page = page_num;
break;
case ANALOG_CONTROL:
ts->analog_fc.dsc = buffer;
ts->analog_fc.function_page = page_num;
break;
case FLASH_MEMORY_MANAGEMENT:
ts->flash_fc.dsc = buffer;
ts->flash_fc.function_page = page_num;
default:
break;
}
}
}
if (unlikely(touch_i2c_write_byte(client, PAGE_SELECT_REG, 0x00) < 0)) {
TOUCH_ERR_MSG("PAGE_SELECT_REG write fail\n");
return -EIO;
}
/* */
ts->interrupt_mask.flash = 0x1;
ts->interrupt_mask.status = 0x2;
#ifdef CUST_G_TOUCH
ts->interrupt_mask.abs = 0x4;
ts->interrupt_mask.button = 0x20;
#endif
if(ts->common_fc.dsc.id == 0 || ts->finger_fc.dsc.id == 0
|| ts->analog_fc.dsc.id == 0 || ts->flash_fc.dsc.id == 0){
TOUCH_ERR_MSG("common/finger/analog/flash are not initiailized\n");
return -EPERM;
}
if (touch_debug_mask & DEBUG_BASE_INFO)
TOUCH_INFO_MSG("common[%dP:0x%02x] finger[%dP:0x%02x] button[%dP:0x%02x] analog[%dP:0x%02x] flash[%dP:0x%02x]\n",
ts->common_fc.function_page, ts->common_fc.dsc.id,
ts->finger_fc.function_page, ts->finger_fc.dsc.id,
ts->button_fc.function_page, ts->button_fc.dsc.id,
ts->analog_fc.function_page, ts->analog_fc.dsc.id,
ts->flash_fc.function_page, ts->flash_fc.dsc.id);
return 0;
}
int get_ic_info(struct synaptics_ts_data* ts, struct touch_fw_info* fw_info)
{
#if defined(ARRAYED_TOUCH_FW_BIN)
int cnt;
#endif
u8 device_status = 0;
u8 flash_control = 0;
read_page_description_table(ts->client);
memset(&ts->fw_info, 0, sizeof(struct synaptics_ts_fw_info));
if (unlikely(touch_i2c_read(ts->client, FW_REVISION_REG,
sizeof(ts->fw_info.fw_rev), &ts->fw_info.fw_rev) < 0)) {
TOUCH_ERR_MSG("FW_REVISION_REG read fail\n");
return -EIO;
}
if (unlikely(touch_i2c_read(ts->client, MANUFACTURER_ID_REG,
sizeof(ts->fw_info.manufacturer_id), &ts->fw_info.manufacturer_id) < 0)) {
TOUCH_ERR_MSG("MANUFACTURER_ID_REG read fail\n");
return -EIO;
}
/* */
if (unlikely(touch_i2c_read(ts->client, PRODUCT_ID_REG,
sizeof(ts->fw_info.product_id) - 1, ts->fw_info.product_id) < 0)) {
TOUCH_ERR_MSG("PRODUCT_ID_REG read fail\n");
return -EIO;
}
if (unlikely(touch_i2c_read(ts->client, FLASH_CONFIG_ID_REG,
sizeof(ts->fw_info.config_id) - 1, ts->fw_info.config_id) < 0)) {
TOUCH_ERR_MSG("FLASH_CONFIG_ID_REG read fail\n");
return -EIO;
}
snprintf(fw_info->ic_fw_identifier, sizeof(fw_info->ic_fw_identifier),
"%s - %d", ts->fw_info.product_id, ts->fw_info.manufacturer_id);
snprintf(fw_info->ic_fw_version, sizeof(fw_info->ic_fw_version),
"%s", ts->fw_info.config_id);
#ifdef CUST_G_TOUCH
if(!strncmp(ts->fw_info.product_id, "DS4 R3.0", 8)) { //
if(!strncmp(fw_info->ic_fw_version, "0000", 4) || !strncmp(fw_info->ic_fw_version, "S001", 4)) {
ts->ic_panel_type = G_IC7020_GFF;
TOUCH_INFO_MSG("IC is 7020, panel is GFF.");
} else {
if( fw_info->ic_fw_version[0] == 'E' && (int)simple_strtol(&fw_info->ic_fw_version[1], NULL, 10) < 14) {
ts->ic_panel_type = G_IC7020_G2;
TOUCH_INFO_MSG("IC is 7020, panel is G2.");
} else if( (fw_info->ic_fw_version[0] == 'E' &&
(int)simple_strtol(&fw_info->ic_fw_version[1], NULL, 10) >= 14 &&
(int)simple_strtol(&fw_info->ic_fw_version[1], NULL, 10) < 27) ||
fw_info->ic_fw_version[0] == 'T') {
ts->ic_panel_type = G_IC3203_G2;
TOUCH_INFO_MSG("IC is 3203, panel is G2.");
} else {
ts->ic_panel_type = UNKNOWN;
TOUCH_INFO_MSG("UNKNOWN OLD PANEL");
}
}
} else if(!strncmp(ts->fw_info.product_id, "TM2000", 6)) { //
ts->ic_panel_type = G_IC7020_G2_LGIT;
TOUCH_INFO_MSG("IC is 7020, H pattern, panel is G2. LGIT");
if((fw_info->ic_fw_version[0] == 'E') &&
((int)simple_strtol(&fw_info->ic_fw_version[1], NULL, 10) >= 40)) {
ts->interrupt_mask.button = 0x10;
}
} else if(!strncmp(ts->fw_info.product_id, "TM2369", 6)) { //
ts->ic_panel_type = G_IC7020_G2_TPK;
TOUCH_INFO_MSG("IC is 7020, H pattern, panel is G2. TPK");
ts->interrupt_mask.button = 0x10;
} else if(!strncmp(ts->fw_info.product_id, "TM2372", 6)) { //
ts->ic_panel_type = GJ_IC7020_GFF_H_PTN;
TOUCH_INFO_MSG("IC is 7020, H pattern, panel is GFF.");
if((fw_info->ic_fw_version[0] == 'E') &&
((int)simple_strtol(&fw_info->ic_fw_version[1], NULL, 10) >= 2)) {
ts->interrupt_mask.button = 0x10;
}
} else if(!strncmp(ts->fw_info.product_id, "PLG124", 6)) { //
ts->ic_panel_type = GK_IC7020_G1F;
TOUCH_INFO_MSG("IC is 7020, H pattern, panel is G1F.");
ts->interrupt_mask.button = 0x10;
} else if(!strncmp(ts->fw_info.product_id, "PLG192", 6)) { //
ts->ic_panel_type = GK_IC7020_GFF_SUNTEL;
TOUCH_INFO_MSG("IC is 7020, H pattern, panel is GFF. SUNTEL");
ts->interrupt_mask.button = 0x10;
} else if(!strncmp(ts->fw_info.product_id, "PLG193", 6)) { //
ts->ic_panel_type = GK_IC7020_GFF_LGIT;
TOUCH_INFO_MSG("IC is 7020, H pattern, panel is GFF. LGIT");
ts->interrupt_mask.button = 0x10;
} else if(!strncmp(ts->fw_info.product_id, "PLG207", 6)) { //
ts->ic_panel_type = GK_IC7020_GFF_LGIT_HYBRID;
TOUCH_INFO_MSG("IC is 7020, H pattern, panel is GFF. LGIT");
ts->interrupt_mask.button = 0x10;
} else if(!strncmp(ts->fw_info.product_id, "PLG121", 6)) { //
ts->ic_panel_type = GV_IC7020_G2_H_PTN_LGIT;
TOUCH_INFO_MSG("IC is 7020, H pattern, panel is G2. LGIT");
ts->interrupt_mask.button = 0x10;
} else if(!strncmp(ts->fw_info.product_id, "PLG184", 6)) { //
ts->ic_panel_type = GV_IC7020_G2_H_PTN_TPK;
TOUCH_INFO_MSG("IC is 7020, H pattern, panel is G2. TPK");
ts->interrupt_mask.button = 0x10;
} else if(!strncmp(ts->fw_info.product_id, "S7020", 5)) { //
TOUCH_INFO_MSG("UNKNOWN PANEL, Product id is S7020.");
ts->interrupt_mask.button = 0x10;
} else {
TOUCH_INFO_MSG("UNKNOWN PANEL");
}
#endif
#if defined(ARRAYED_TOUCH_FW_BIN)
for (cnt = 0; cnt < sizeof(SynaFirmware)/sizeof(SynaFirmware[0]); cnt++) {
strncpy(ts->fw_info.fw_image_product_id, &SynaFirmware[cnt][16], 10);
if (!(strncmp(ts->fw_info.product_id , ts->fw_info.fw_image_product_id, 10)))
break;
}
strncpy(ts->fw_info.image_config_id, &SynaFirmware[cnt][0xb100],4);
ts->fw_info.fw_start = (unsigned char *)&SynaFirmware[cnt][0];
ts->fw_info.fw_size = sizeof(SynaFirmware[0]);
#else
#ifdef G_ONLY
switch(ts->ic_panel_type){
case G_IC7020_GFF:
case G_IC7020_G2:
case G_IC3203_G2:
case G_IC7020_G2_LGIT:
memcpy(&SynaFirmware[0], &SynaFirmware_TM2000[0], sizeof(SynaFirmware));
break;
#ifdef CONFIG_MACH_APQ8064_J1A
//
#else
case G_IC7020_G2_TPK:
memcpy(&SynaFirmware[0], &SynaFirmware_TM2369[0], sizeof(SynaFirmware));
break;
#endif
default:
TOUCH_ERR_MSG("UNKNOWN PANEL. SynaImage set error");
break;
}
#endif
#if defined(CONFIG_MACH_APQ8064_GK_KR) || defined(CONFIG_MACH_APQ8064_GKATT) || defined(CONFIG_MACH_APQ8064_GKGLOBAL)|| defined(CONFIG_MACH_MSM8974_G3_KDDI_EVB)
switch(ts->ic_panel_type){
case GK_IC7020_G1F:
memcpy(&SynaFirmware[0], &SynaFirmware_PLG124[0], sizeof(SynaFirmware));
break;
case GK_IC7020_GFF_SUNTEL:
TOUCH_INFO_MSG("GK_IC7020_GFF_SUNTEL");
memcpy(&SynaFirmware[0], &SynaFirmware_PLG192[0], sizeof(SynaFirmware));
break;
case GK_IC7020_GFF_LGIT:
memcpy(&SynaFirmware[0], &SynaFirmware_PLG193[0], sizeof(SynaFirmware));
break;
case GK_IC7020_GFF_LGIT_HYBRID:
memcpy(&SynaFirmware[0], &SynaFirmware_PLG207[0], sizeof(SynaFirmware));
break;
default:
TOUCH_ERR_MSG("UNKNOWN PANEL(GK). SynaImage set error");
break;
}
#elif defined(CONFIG_MACH_APQ8064_GVDCM)
switch(ts->ic_panel_type){
case GV_IC7020_G2_H_PTN_LGIT:
memcpy(&SynaFirmware[0], &SynaFirmware_PLG121[0], sizeof(SynaFirmware));
break;
case GV_IC7020_G2_H_PTN_TPK:
memcpy(&SynaFirmware[0], &SynaFirmware_PLG184[0], sizeof(SynaFirmware));
break;
default:
TOUCH_ERR_MSG("UNKNOWN PANEL(GV). SynaImage set error");
break;
}
#endif
strncpy(ts->fw_info.fw_image_product_id, &SynaFirmware[16], 10);
strncpy(ts->fw_info.image_config_id, &SynaFirmware[0xb100],4);
#ifdef CUST_G_TOUCH
strncpy(fw_info->syna_img_fw_version, &SynaFirmware[0xb100], 4);
strncpy(fw_info->syna_img_fw_product_id, &SynaFirmware[0x0040], 6);
strncpy(ts->fw_info.syna_img_product_id, &SynaFirmware[0x0040], 6);
strncpy(ts->fw_info.syna_img_fw_ver, &SynaFirmware[0xb100],4);
#endif
ts->fw_info.fw_start = (unsigned char *)&SynaFirmware[0];
ts->fw_info.fw_size = sizeof(SynaFirmware);
#endif
ts->fw_info.fw_image_rev = ts->fw_info.fw_start[31];
if (unlikely(touch_i2c_read(ts->client, FLASH_CONTROL_REG, sizeof(flash_control), &flash_control) < 0)) {
TOUCH_ERR_MSG("FLASH_CONTROL_REG read fail\n");
return -EIO;
}
if (unlikely(touch_i2c_read(ts->client, DEVICE_STATUS_REG, sizeof(device_status), &device_status) < 0)) {
TOUCH_ERR_MSG("DEVICE_STATUS_REG read fail\n");
return -EIO;
}
/* */
if(device_status & DEVICE_STATUS_FLASH_PROG
|| (device_status & DEVICE_CRC_ERROR_MASK) != 0
|| (flash_control & FLASH_STATUS_MASK) != 0) {
TOUCH_ERR_MSG("Firmware has a unknown-problem, so it needs firmware-upgrade.\n");
TOUCH_ERR_MSG("FLASH_CONTROL[%x] DEVICE_STATUS_REG[%x]\n", (u32)flash_control, (u32)device_status);
TOUCH_ERR_MSG("FW-upgrade Force Rework.\n");
/* */
ts->fw_info.fw_rev = 0;
snprintf(ts->fw_info.config_id, sizeof(ts->fw_info.config_id), "ERR");
#ifdef CUST_G_TOUCH
fw_info->fw_force_rework = true;
#endif
}
return 0;
}
int synaptics_ts_init(struct i2c_client* client, struct touch_fw_info* fw_info)
{
struct synaptics_ts_data* ts =
(struct synaptics_ts_data*)get_touch_handle(client);
u8 buf = 0;
if (touch_debug_mask & DEBUG_TRACE)
TOUCH_DEBUG_MSG("\n");
if (!ts->is_probed) {
if (unlikely(get_ic_info(ts, fw_info) < 0))
return -EIO;
}
if(ts->pdata->role->ghost_detection_enable) {
if(ts_charger_plug==0){
if (unlikely(touch_i2c_write_byte(client, DEVICE_CONTROL_REG,
DEVICE_CONTROL_NORMAL_OP | DEVICE_CONTROL_CONFIGURED) < 0)) {
TOUCH_ERR_MSG("DEVICE_CONTROL_REG write fail\n");
return -EIO;
}
} else if(ts_charger_plug==1){
if (unlikely(touch_i2c_write_byte(client, DEVICE_CONTROL_REG,
DEVICE_CONTROL_NORMAL_OP | DEVICE_CONTROL_CONFIGURED | DEVICE_CHARGER_CONNECTED) < 0)) {
TOUCH_ERR_MSG("DEVICE_CONTROL_REG write fail\n");
return -EIO;
}
#ifdef CUST_G_TOUCH_FREQ_HOPPING
if (unlikely(synaptics_ts_page_data_read(client, 0x01, 0x04, 1, &buf) < 0)) {
TOUCH_ERR_MSG("Current Hopping Index read fail\n");
return -EIO;
}
if(buf == 3) cur_hopping_idx = 3;
else cur_hopping_idx = 4;
TOUCH_INFO_MSG("cur_hopping_idx [ %s ] = %x\n", __func__, buf);
switch(ts_charger_type) {
case 0:
case 1:
if(cns_en && cur_hopping_idx != 4){
buf = 0x84;
synaptics_ts_page_data_write(client, 0x01, 0x04, 1, &buf);
cur_hopping_idx = 4;
TOUCH_INFO_MSG("cur_hopping_idx [ %s ] = %x\n", __func__, buf);
}
break;
default:
break;
}
#endif
}
if (unlikely(touch_i2c_read(client, DEVICE_CONTROL_REG, 1, &buf) < 0)) {
TOUCH_ERR_MSG("DEVICE_CONTROL_REG read fail\n");
return -EIO;
}
TOUCH_INFO_MSG("DEVICE CONTROL_REG = %x\n", buf);
} else {
if (unlikely(touch_i2c_write_byte(client, DEVICE_CONTROL_REG,
DEVICE_CONTROL_NORMAL_OP | DEVICE_CONTROL_CONFIGURED) < 0)) {
TOUCH_ERR_MSG("DEVICE_CONTROL_REG write fail\n");
return -EIO;
}
}
if (unlikely(touch_i2c_read(client, INTERRUPT_ENABLE_REG,
1, &buf) < 0)) {
TOUCH_ERR_MSG("INTERRUPT_ENABLE_REG read fail\n");
return -EIO;
}
if (unlikely(touch_i2c_write_byte(client, INTERRUPT_ENABLE_REG,
buf | ts->interrupt_mask.abs | ts->interrupt_mask.button) < 0)) {
TOUCH_ERR_MSG("INTERRUPT_ENABLE_REG write fail\n");
return -EIO;
}
if(ts->pdata->role->report_mode == CONTINUOUS_REPORT_MODE) {
#ifdef CUST_G_TOUCH
if (unlikely(touch_i2c_write_byte(client, TWO_D_REPORTING_MODE,
REPORT_BEYOND_CLIP | ABS_FILTER | REPORT_MODE_CONTINUOUS) < 0)) {
TOUCH_ERR_MSG("TWO_D_REPORTING_MODE write fail\n");
return -EIO;
}
#else
if (unlikely(touch_i2c_write_byte(client, TWO_D_REPORTING_MODE,
REPORT_MODE_CONTINUOUS) < 0)) {
TOUCH_ERR_MSG("TWO_D_REPORTING_MODE write fail\n");
return -EIO;
}
#endif
} else { /* */
#ifdef CUST_G_TOUCH
if (unlikely(touch_i2c_write_byte(client, TWO_D_REPORTING_MODE,
REPORT_BEYOND_CLIP | ABS_FILTER | REPORT_MODE_REDUCED) < 0)) {
TOUCH_ERR_MSG("TWO_D_REPORTING_MODE write fail\n");
return -EIO;
}
#else
if (unlikely(touch_i2c_write_byte(client, TWO_D_REPORTING_MODE,
REPORT_MODE_REDUCED) < 0)) {
TOUCH_ERR_MSG("TWO_D_REPORTING_MODE write fail\n");
return -EIO;
}
#endif
if (unlikely(touch_i2c_write_byte(client, DELTA_X_THRESH_REG,
ts->pdata->role->delta_pos_threshold) < 0)) {
TOUCH_ERR_MSG("DELTA_X_THRESH_REG write fail\n");
return -EIO;
}
if (unlikely(touch_i2c_write_byte(client, DELTA_Y_THRESH_REG,
ts->pdata->role->delta_pos_threshold) < 0)) {
TOUCH_ERR_MSG("DELTA_Y_THRESH_REG write fail\n");
return -EIO;
}
}
if (unlikely(touch_i2c_read(client, INTERRUPT_STATUS_REG, 1, &buf) < 0)) {
TOUCH_ERR_MSG("INTERRUPT_STATUS_REG read fail\n");
return -EIO; //
}
if (unlikely(touch_i2c_read(client, FINGER_STATE_REG, sizeof(ts->ts_data.finger.finger_status_reg),
ts->ts_data.finger.finger_status_reg) < 0)) {
TOUCH_ERR_MSG("FINGER_STATE_REG read fail\n");
return -EIO; //
}
ts->is_probed = 1;
return 0;
}
int synaptics_ts_power(struct i2c_client* client, int power_ctrl)
{
struct synaptics_ts_data* ts =
(struct synaptics_ts_data*)get_touch_handle(client);
if (touch_debug_mask & DEBUG_TRACE)
TOUCH_DEBUG_MSG("\n");
switch (power_ctrl) {
case POWER_OFF:
if (ts->pdata->pwr->use_regulator) {
regulator_disable(ts->regulator_vio);
regulator_disable(ts->regulator_vdd);
}
else
ts->pdata->pwr->power(client, 0);
break;
case POWER_ON:
if (ts->pdata->pwr->use_regulator) {
regulator_enable(ts->regulator_vdd);
regulator_enable(ts->regulator_vio);
}
else
ts->pdata->pwr->power(client, 1);
break;
case POWER_SLEEP:
if (unlikely(touch_i2c_write_byte(client, DEVICE_CONTROL_REG,
DEVICE_CONTROL_SLEEP | DEVICE_CONTROL_CONFIGURED) < 0)) {
TOUCH_ERR_MSG("DEVICE_CONTROL_REG write fail\n");
return -EIO;
}
break;
case POWER_WAKE:
if (unlikely(touch_i2c_write_byte(client, DEVICE_CONTROL_REG,
DEVICE_CONTROL_NORMAL_OP | DEVICE_CONTROL_CONFIGURED) < 0)) {
TOUCH_ERR_MSG("DEVICE_CONTROL_REG write fail\n");
return -EIO;
}
break;
default:
return -EIO;
break;
}
return 0;
}
int synaptics_ts_probe(struct lge_touch_data* lge_touch_ts)
{
struct synaptics_ts_data* ts;
int ret = 0;
struct i2c_client* client = lge_touch_ts->client;
if (touch_debug_mask & DEBUG_TRACE)
TOUCH_DEBUG_MSG("\n");
ts = kzalloc(sizeof(struct synaptics_ts_data), GFP_KERNEL);
if (!ts) {
TOUCH_ERR_MSG("Can not allocate memory\n");
ret = -ENOMEM;
goto err_alloc_data_failed;
}
set_touch_handle(client, ts);
ts->client = client;
ts->pdata = lge_touch_ts->pdata;
if (ts->pdata->pwr->use_regulator) {
ts->regulator_vdd = regulator_get_exclusive(NULL, ts->pdata->pwr->vdd);
if (IS_ERR(ts->regulator_vdd)) {
TOUCH_ERR_MSG("FAIL: regulator_get_vdd - %s\n", ts->pdata->pwr->vdd);
ret = -EPERM;
goto err_get_vdd_failed;
}
ts->regulator_vio = regulator_get_exclusive(NULL, ts->pdata->pwr->vio);
if (IS_ERR(ts->regulator_vio)) {
TOUCH_ERR_MSG("FAIL: regulator_get_vio - %s\n", ts->pdata->pwr->vio);
ret = -EPERM;
goto err_get_vio_failed;
}
if (ts->pdata->pwr->vdd_voltage > 0) {
ret = regulator_set_voltage(ts->regulator_vdd, ts->pdata->pwr->vdd_voltage, ts->pdata->pwr->vdd_voltage);
if (ret < 0)
TOUCH_ERR_MSG("FAIL: VDD voltage setting - (%duV)\n", ts->pdata->pwr->vdd_voltage);
}
if (ts->pdata->pwr->vio_voltage > 0) {
ret = regulator_set_voltage(ts->regulator_vio, ts->pdata->pwr->vio_voltage, ts->pdata->pwr->vio_voltage);
if (ret < 0)
TOUCH_ERR_MSG("FAIL: VIO voltage setting - (%duV)\n",ts->pdata->pwr->vio_voltage);
}
}
return ret;
err_get_vio_failed:
if (ts->pdata->pwr->use_regulator) {
regulator_put(ts->regulator_vdd);
}
err_get_vdd_failed:
err_alloc_data_failed:
kfree(ts);
return ret;
}
#ifdef CUST_G_TOUCH
int synaptics_ts_resolution(struct i2c_client* client) {
struct synaptics_ts_data* ts =
(struct synaptics_ts_data*)get_touch_handle(client);
u8 resolution[2] = {0};
if(ts->pdata->role->key_type == TOUCH_HARD_KEY) {
if (unlikely(touch_i2c_read(ts->client, SENSOR_MAX_X_POS, sizeof(resolution), resolution) < 0)) {
TOUCH_ERR_MSG("SENSOR_MAX_X read fail\n");
return -EIO; //
}
TOUCH_INFO_MSG("SENSOR_MAX_X=%d", (int)(resolution[1] << 8 | resolution[0]));
ts->pdata->caps->x_max = (int)(resolution[1] << 8 | resolution[0]);
if (unlikely(touch_i2c_read(ts->client, SENSOR_MAX_Y_POS, sizeof(resolution), resolution) < 0)) {
TOUCH_ERR_MSG("SENSOR_MAX_Y read fail\n");
return -EIO; //
}
TOUCH_INFO_MSG("SENSOR_MAX_Y=%d", (int)(resolution[1] << 8 | resolution[0]));
ts->pdata->caps->y_max = (int)(resolution[1] << 8 | resolution[0]);
}
return 0;
}
#endif
void synaptics_ts_remove(struct i2c_client* client)
{
struct synaptics_ts_data* ts =
(struct synaptics_ts_data*)get_touch_handle(client);
if (touch_debug_mask & DEBUG_TRACE)
TOUCH_DEBUG_MSG("\n");
if (ts->pdata->pwr->use_regulator) {
regulator_put(ts->regulator_vio);
regulator_put(ts->regulator_vdd);
}
kfree(ts);
}
int synaptics_ts_fw_upgrade(struct i2c_client* client, struct touch_fw_info* fw_info)
{
struct synaptics_ts_data* ts =
(struct synaptics_ts_data*)get_touch_handle(client);
int ret = 0;
ts->is_probed = 0;
ret = FirmwareUpgrade(ts, fw_info->fw_upgrade.fw_path);
/* */
if (ret >= 0)
get_ic_info(ts, fw_info);
return ret;
}
#ifdef CUST_G_TOUCH
int synaptics_ts_ic_ctrl(struct i2c_client *client, u8 code, u32 value)
#else
int synaptics_ts_ic_ctrl(struct i2c_client *client, u8 code, u16 value)
#endif
{
struct synaptics_ts_data* ts =
(struct synaptics_ts_data*)get_touch_handle(client);
u8 buf = 0;
switch (code)
{
case IC_CTRL_BASELINE:
switch (value)
{
case BASELINE_OPEN:
#ifdef CUST_G_TOUCH
break;
#endif
if (unlikely(synaptics_ts_page_data_write_byte(client, ANALOG_PAGE,
ANALOG_CONTROL_REG, FORCE_FAST_RELAXATION) < 0)) {
TOUCH_ERR_MSG("ANALOG_CONTROL_REG write fail\n");
return -EIO;
}
msleep(10);
if (unlikely(synaptics_ts_page_data_write_byte(client, ANALOG_PAGE,
ANALOG_COMMAND_REG, FORCE_UPDATE) < 0)) {
TOUCH_ERR_MSG("ANALOG_COMMAND_REG write fail\n");
return -EIO;
}
if (unlikely(touch_debug_mask & DEBUG_GHOST))
TOUCH_INFO_MSG("BASELINE_OPEN\n");
break;
case BASELINE_FIX:
#ifdef CUST_G_TOUCH
break;
#endif
if (unlikely(synaptics_ts_page_data_write_byte(client, ANALOG_PAGE,
ANALOG_CONTROL_REG, 0x00) < 0)) {
TOUCH_ERR_MSG("ANALOG_CONTROL_REG write fail\n");
return -EIO;
}
msleep(10);
if (unlikely(synaptics_ts_page_data_write_byte(client, ANALOG_PAGE,
ANALOG_COMMAND_REG, FORCE_UPDATE) < 0)) {
TOUCH_ERR_MSG("ANALOG_COMMAND_REG write fail\n");
return -EIO;
}
if (unlikely(touch_debug_mask & DEBUG_GHOST))
TOUCH_INFO_MSG("BASELINE_FIX\n");
break;
case BASELINE_REBASE:
/* */
if (likely(ts->finger_fc.dsc.id != 0)) {
if (unlikely(touch_i2c_write_byte(client, FINGER_COMMAND_REG, 0x1) < 0)) {
TOUCH_ERR_MSG("finger baseline reset command write fail\n");
return -EIO;
}
}
break;
default:
break;
}
break;
case IC_CTRL_READ:
#ifdef CUST_G_TOUCH
if (unlikely(touch_i2c_write_byte(client, PAGE_SELECT_REG, ((value & 0xFF00) >> 8)) < 0)) {
TOUCH_ERR_MSG("PAGE_SELECT_REG write fail\n");
return -EIO;
}
if (touch_i2c_read(client, (value & 0xFF), 1, &buf) < 0) {
TOUCH_ERR_MSG("IC register read fail\n");
return -EIO;
}
if (unlikely(touch_i2c_write_byte(client, PAGE_SELECT_REG, 0x00) < 0)) {
TOUCH_ERR_MSG("PAGE_SELECT_REG write fail\n");
return -EIO;
}
#else
if (touch_i2c_read(client, value, 1, &buf) < 0) {
TOUCH_ERR_MSG("IC register read fail\n");
return -EIO;
}
#endif
break;
case IC_CTRL_WRITE:
#ifdef CUST_G_TOUCH
if (unlikely(touch_i2c_write_byte(client, PAGE_SELECT_REG, ((value & 0xFF0000) >> 16)) < 0)) {
TOUCH_ERR_MSG("PAGE_SELECT_REG write fail\n");
return -EIO;
}
if (touch_i2c_write_byte(client, ((value & 0xFF00) >> 8), (value & 0xFF)) < 0) {
TOUCH_ERR_MSG("IC register write fail\n");
return -EIO;
}
if (unlikely(touch_i2c_write_byte(client, PAGE_SELECT_REG, 0x00) < 0)) {
TOUCH_ERR_MSG("PAGE_SELECT_REG write fail\n");
return -EIO;
}
#else
if (touch_i2c_write_byte(client, ((value & 0xFF00) >> 8), (value & 0xFF)) < 0) {
TOUCH_ERR_MSG("IC register write fail\n");
return -EIO;
}
#endif
break;
case IC_CTRL_RESET_CMD:
if (unlikely(touch_i2c_write_byte(client, DEVICE_COMMAND_REG, 0x1) < 0)) {
TOUCH_ERR_MSG("IC Reset command write fail\n");
return -EIO;
}
break;
case IC_CTRL_DOUBLE_TAP_WAKEUP_MODE: //
switch (value)
{
unsigned char *r_mem = NULL;
case 0: /* */
{
r_mem = kzalloc(sizeof(char) * (6), GFP_KERNEL);
if (touch_i2c_read(ts->client, REPORT_WAKEUP_GESTURE_ONLY_REG,(3), r_mem) < 0) {
TOUCH_ERR_MSG("%d bytes read fail!", (3));
} else {
if(*(r_mem+2) !=0x0) {
*(r_mem+2) = 0;
if(touch_i2c_write(ts->client, REPORT_WAKEUP_GESTURE_ONLY_REG,(3), r_mem) < 0)
TOUCH_ERR_MSG("REPORT_WAKEUP_GESTURE_ONLY_REG write fail");
}
}
if(touch_i2c_write_byte(ts->client, DOZE_INTERVAL_REG, 1) < 0) {
TOUCH_ERR_MSG("DOZE_INTERVAL_REG write fail");
if(r_mem != NULL) kfree(r_mem);
return 0;
}
if(touch_i2c_write_byte(ts->client, 0x10, 10) < 0) {
TOUCH_ERR_MSG("DOZE_WAKEUP_TRESHOLD_REG write fail");
if(r_mem != NULL) kfree(r_mem);
return 0;
}
if(r_mem != NULL) kfree(r_mem);
}
break;
case 1: /* */
{
r_mem = kzalloc(sizeof(char) * (9), GFP_KERNEL);
*(r_mem+0) = 0x1;
*(r_mem+1) = 0x14;
#if defined(CONFIG_LGE_Z_TOUCHSCREEN)
*(r_mem+2) = 0xa;
#else
*(r_mem+2) = 0x3;
#endif
*(r_mem+3) = 0x6;
*(r_mem+4) = 0x2;
*(r_mem+5) = 0x2;
#if defined(CONFIG_LGE_Z_TOUCHSCREEN)
if (get_touch_panel_info(ts) == TOUCH_PANEL_H_PATTERN) { /* */
if(touch_i2c_write(ts->client, WAKEUP_GESTURE_ENABEL_REG,(6), r_mem) < 0) {
TOUCH_ERR_MSG("WAKEUP_GESTURE_ENABEL_REG write fail");
if(r_mem != NULL) kfree(r_mem);
return -EIO;
}
} else { /* */
if(touch_i2c_write(ts->client, WAKEUP_GESTURE_ENABEL_REG,(1), r_mem) < 0) {
TOUCH_ERR_MSG("WAKEUP_GESTURE_ENABEL_REG write fail");
if(r_mem != NULL) kfree(r_mem);
return -EIO;
}
}
if (touch_i2c_read(ts->client, MINIMUM_PEAK_AMPLITUDE_REG,(3), r_mem) < 0) {
TOUCH_ERR_MSG("%d bytes read fail!", (3));
} else {
*(r_mem+2) = 0x28;
if(touch_i2c_write(ts->client, MINIMUM_PEAK_AMPLITUDE_REG,(3), r_mem) < 0) {
TOUCH_ERR_MSG("Peak_merge_threshold write fail");
if(r_mem != NULL) kfree(r_mem);
return 0;
}
}
#else
if(touch_i2c_write(ts->client, WAKEUP_GESTURE_ENABEL_REG,(6), r_mem) < 0) {
TOUCH_ERR_MSG("WAKEUP_GESTURE_ENABEL_REG write fail");
if(r_mem != NULL) kfree(r_mem);
return -EIO;
}
#endif
if(touch_i2c_write_byte(ts->client, DOZE_INTERVAL_REG, 5) < 0) {
TOUCH_ERR_MSG("DOZE_INTERVAL_REG write fail");
if(r_mem != NULL) kfree(r_mem);
return -EIO;
}
#if defined(CONFIG_LGE_Z_TOUCHSCREEN)
if(touch_i2c_write_byte(ts->client, 0x10, 20) < 0) {
TOUCH_ERR_MSG("DOZE_WAKEUP_TRESHOLD_REG write fail");
if(r_mem != NULL) kfree(r_mem);
return -EIO;
}
#else
if(touch_i2c_write_byte(ts->client, 0x10, 30) < 0) {
TOUCH_ERR_MSG("DOZE_WAKEUP_TRESHOLD_REG write fail");
if(r_mem != NULL) kfree(r_mem);
return -EIO;
}
#endif
if (touch_i2c_read(ts->client, REPORT_WAKEUP_GESTURE_ONLY_REG,(3), r_mem) < 0) {
TOUCH_ERR_MSG("%d bytes read fail!", (3));
} else {
*(r_mem+2) = 0x2;
if(touch_i2c_write(ts->client, REPORT_WAKEUP_GESTURE_ONLY_REG,(3), r_mem) < 0)
TOUCH_ERR_MSG("REPORT_WAKEUP_GESTURE_ONLY_REG write fail");
}
#if defined(CONFIG_LGE_Z_TOUCHSCREEN)
if (get_touch_panel_info(ts) == TOUCH_PANEL_H_PATTERN) { /* */
*(r_mem+0) = 0x4c;
*(r_mem+1) = 0x00;
*(r_mem+2) = 0x00;
*(r_mem+3) = 0x00;
*(r_mem+4) = 0x84;
*(r_mem+5) = 0x02;
*(r_mem+6) = 0x00;
*(r_mem+7) = 0x05;
*(r_mem+8) = 60;
} else { /* */
*(r_mem+0) = 0x82;
*(r_mem+1) = 0x0;
*(r_mem+2) = 0x0;
*(r_mem+3) = 0x0;
*(r_mem+4) = 0xB6;
*(r_mem+5) = 0x3;
*(r_mem+6) = 0x6c;
*(r_mem+7) = 0x7;
*(r_mem+8) = 60;
}
#else
*(r_mem+0) = 0x82;
*(r_mem+1) = 0x0;
*(r_mem+2) = 0x0;
*(r_mem+3) = 0x0;
*(r_mem+4) = 0xB6;
*(r_mem+5) = 0x3;
*(r_mem+6) = 0x80;
*(r_mem+7) = 0x7;
*(r_mem+8) = 60;
#endif
if(touch_i2c_write(ts->client, DOUBLE_TAP_AREA_REG,(9), r_mem) < 0)
TOUCH_ERR_MSG("DOUBLE_TAP_AREA_REG write fail");
if(r_mem != NULL) kfree(r_mem);
}
break;
}
break;
case IC_CTRL_REPORT_MODE:
switch (value)
{
case 0: //
#ifdef CUST_G_TOUCH
if (unlikely(touch_i2c_write_byte(client, TWO_D_REPORTING_MODE,
REPORT_BEYOND_CLIP | ABS_FILTER | REPORT_MODE_CONTINUOUS) < 0)) {
TOUCH_ERR_MSG("TWO_D_REPORTING_MODE write fail\n");
return -EIO;
}
#else
if (unlikely(touch_i2c_write_byte(client, TWO_D_REPORTING_MODE,
REPORT_MODE_CONTINUOUS) < 0)) {
TOUCH_ERR_MSG("TWO_D_REPORTING_MODE write fail\n");
return -EIO;
}
#endif
break;
case 1: //
#ifdef CUST_G_TOUCH
if (unlikely(touch_i2c_write_byte(client, TWO_D_REPORTING_MODE,
REPORT_BEYOND_CLIP | ABS_FILTER | REPORT_MODE_REDUCED) < 0)) {
TOUCH_ERR_MSG("TWO_D_REPORTING_MODE write fail\n");
return -EIO;
}
#else
if (unlikely(touch_i2c_write_byte(client, TWO_D_REPORTING_MODE,
REPORT_MODE_REDUCED) < 0)) {
TOUCH_ERR_MSG("TWO_D_REPORTING_MODE write fail\n");
return -EIO;
}
#endif
default:
break;
}
break;
default:
break;
}
return buf;
}
struct touch_device_driver synaptics_ts_driver = {
.probe = synaptics_ts_probe,
#ifdef CUST_G_TOUCH
.resolution = synaptics_ts_resolution,
#endif
.remove = synaptics_ts_remove,
.init = synaptics_ts_init,
.data = synaptics_ts_get_data,
.power = synaptics_ts_power,
.fw_upgrade = synaptics_ts_fw_upgrade,
.ic_ctrl = synaptics_ts_ic_ctrl,
};
static void async_touch_init(void *data, async_cookie_t cookie)
{
touch_driver_register(&synaptics_ts_driver);
return;
}
static int __devinit touch_init(void)
{
if (touch_debug_mask & DEBUG_TRACE)
TOUCH_DEBUG_MSG("\n");
async_schedule(async_touch_init, NULL);
return 0;
}
static void __exit touch_exit(void)
{
if (touch_debug_mask & DEBUG_TRACE)
TOUCH_DEBUG_MSG("\n");
touch_driver_unregister();
}
module_init(touch_init);
module_exit(touch_exit);
MODULE_AUTHOR("yehan.ahn@lge.com, hyesung.shin@lge.com");
MODULE_DESCRIPTION("LGE Touch Driver");
MODULE_LICENSE("GPL");
|
curbthepain/revkernel_us990
|
drivers/input/touchscreen/touch_synaptics_kddi_evb.c
|
C
|
gpl-2.0
| 48,729
|
/**
* @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
!(function(window, document){
'use strict';
/** Method to convert numbers to local symbols. */
Date.convertNumbers = function(str) {
var str = str.toString();
if (Object.prototype.toString.call(JoomlaCalLocale.localLangNumbers) === '[object Array]') {
for (var i = 0; i < JoomlaCalLocale.localLangNumbers.length; i++) {
str = str.replace(new RegExp(i, 'g'), JoomlaCalLocale.localLangNumbers[i]);
}
}
return str;
};
/** Translates to english numbers a string. */
Date.toEnglish = function(str) {
str = this.toString();
var nums = [0,1,2,3,4,5,6,7,8,9];
for (var i = 0; i < 10; i++) {
str = str.replace(new RegExp(nums[i], 'g'), i);
}
return str;
};
var JoomlaCalendar = function (element) {
// Initialize only if the element exists
if (!element) {
throw new Error("Calendar setup failed:\n No valid element found, Please check your code");
}
if (typeof Date.parseFieldDate !== 'function') {
throw new Error("Calendar setup failed:\n No valid date helper, Please check your code");
}
if (element._joomlaCalendar) {
throw new Error('JoomlaCalendar instance already exists for the element');
}
element._joomlaCalendar = this;
this.writable = true;
this.hidden = true;
this.params = {};
this.element = element;
this.inputField = element.getElementsByTagName('input')[0];
this.button = element.getElementsByTagName('button')[0];
if (!this.inputField) {
throw new Error("Calendar setup failed:\n No valid input found, Please check your code");
}
// Prepare the parameters
this.params = {
debug: false,
clicked: false,
element: {style: {display: "none"}},
writable: true
};
var self = this,
btn = this.button,
instanceParams = {
inputField : this.inputField,
dateType : JoomlaCalLocale.dateType ? JoomlaCalLocale.dateType : 'gregorian',
direction : (document.dir !== undefined) ? document.dir : document.getElementsByTagName("html")[0].getAttribute("dir"),
firstDayOfWeek : btn.getAttribute("data-firstday") ? parseInt(btn.getAttribute("data-firstday")) : 0,
dateFormat : "%Y-%m-%d %H:%M:%S",
weekend : JoomlaCalLocale.weekend ? JoomlaCalLocale.weekend : [0,6],
minYear : JoomlaCalLocale.minYear ? JoomlaCalLocale.minYear : 1900,
maxYear : JoomlaCalLocale.maxYear ? JoomlaCalLocale.maxYear : 2100,
minYearTmp : btn.getAttribute("data-min-year"),
maxYearTmp : btn.getAttribute("data-max-year"),
weekendTmp : btn.getAttribute("data-weekend"),
time24 : true,
showsOthers : (parseInt(btn.getAttribute("data-show-others")) === 1) ? true : false,
showsTime : true,
weekNumbers : (parseInt(btn.getAttribute("data-week-numbers")) === 1) ? true : false,
showsTodayBtn : true,
compressedHeader: (parseInt(btn.getAttribute("data-only-months-nav")) === 1) ? true : false,
};
// Keep B/C
if (btn.getAttribute("data-dayformat")) {
instanceParams.dateFormat = btn.getAttribute("data-dayformat") ? btn.getAttribute("data-dayformat") : "%Y-%m-%d %H:%M:%S";
}
if (btn.getAttribute("data-time-24")) {
instanceParams.time24 = parseInt(btn.getAttribute("data-time-24")) === 24 ? true : false;
}
if (btn.getAttribute("data-show-time")) {
instanceParams.showsTime = parseInt(btn.getAttribute("data-show-time")) === 1 ? true : false;
}
if (btn.getAttribute("data-today-btn")) {
instanceParams.showsTodayBtn = parseInt(btn.getAttribute("data-today-btn")) === 1 ? true : false;
}
// Merge the parameters
for (var param in instanceParams) {
this.params[param] = instanceParams[param];
}
// Evaluate the min year
if (isInt(self.params.minYearTmp)) {
self.params.minYear = getBoundary(parseInt(self.params.minYearTmp), self.params.dateType);
}
// Evaluate the max year
if (isInt(self.params.maxYearTmp)) {
self.params.maxYear = getBoundary(parseInt(self.params.maxYearTmp), self.params.dateType);
}
// Evaluate the weekend days
if (self.params.weekendTmp !== "undefined") {
self.params.weekend = self.params.weekendTmp.split(',').map(function(item) { return parseInt(item, 10); });
}
// Event handler need to define here, to be able access in current context
this._dayMouseDown = function(event) {
return self._handleDayMouseDown(event);
};
this._calKeyEvent = function(event) {
return self._handleCalKeyEvent(event);
};
this._documentClick = function(event) {
return self._handleDocumentClick(event);
};
// Set it up
this.checkInputs();
// For the fields with readonly tag calendar will not initiate fully
if (this.inputField.getAttribute('readonly')) {
return;
}
this._create();
this._bindEvents();
};
JoomlaCalendar.prototype.checkInputs = function () {
// Get the date from the input
var inputAltValueDate = Date.parseFieldDate(this.inputField.getAttribute('data-alt-value'), this.params.dateFormat, 'gregorian');
if (this.inputField.value !== '') {
this.date = inputAltValueDate;
this.inputField.value = inputAltValueDate.print(this.params.dateFormat, this.params.dateType, true);
} else {
this.date = new Date();
}
};
/** Removes the calendar object from the DOM tree and destroys it and then recreates it. */
JoomlaCalendar.prototype.recreate = function () {
var element = this.element, el = element.querySelector('.js-calendar');
if (el) {
element._joomlaCalendar = null;
el.parentNode.removeChild(el);
new JoomlaCalendar(element);
}
};
/** Time Control */
JoomlaCalendar.prototype.updateTime = function (hours, mins, secs) {
var self = this,
date = self.date;
var d = self.date.getLocalDate(self.params.dateType),
m = self.date.getLocalMonth(self.params.dateType),
y = self.date.getLocalFullYear(self.params.dateType),
ampm = this.inputField.parentNode.parentNode.querySelectorAll('.time-ampm')[0];
if (!self.params.time24) {
if (/pm/i.test(ampm.value) && hours < 12) {
hours = parseInt(hours) + 12;
} else if (/am/i.test(ampm.value) && hours === 12) {
hours = 0;
}
}
date.setHours(hours);
date.setMinutes(parseInt(mins, 10));
date.setSeconds(date.getSeconds());
date.setLocalFullYear(self.params.dateType, y);
date.setLocalMonth(self.params.dateType, m);
date.setLocalDate(self.params.dateType, d);
self.dateClicked = false;
this.callHandler();
};
/** Method to set the date to the given date object */
JoomlaCalendar.prototype.setDate = function (date) {
if (!date.equalsTo(this.date)) {
this.date = date;
this.processCalendar(this.params.firstDayOfWeek, date);
}
};
/** Method to set the current date by a number, step */
JoomlaCalendar.prototype.moveCursorBy = function (step) {
var date = new Date(this.date);
date.setDate(date.getDate() - step);
this.setDate(date);
};
/** Reset select element */
JoomlaCalendar.prototype.resetSelected = function (element) {
var options = element.options;
var i = options.length;
while (i--) {
var current = options[i];
if (current.selected) {
current.selected = false;
}
}
};
/** Method to set the value for the input field */
JoomlaCalendar.prototype.callHandler = function () {
/** Output the date **/
this.inputField.setAttribute('data-alt-value', this.date.print(this.params.dateFormat, 'gregorian', false));
if (this.inputField.getAttribute('data-alt-value') && this.inputField.getAttribute('data-alt-value') !== '0000-00-00 00:00:00') {
this.inputField.value = this.date.print(this.params.dateFormat, this.params.dateType, true);
if (this.params.dateType !== 'gregorian') {
this.inputField.setAttribute('data-local-value', this.date.print(this.params.dateFormat, this.params.dateType, true));
}
}
this.inputField.value = this.date.print(this.params.dateFormat, this.params.dateType, true);
if (typeof this.inputField.onchange == "function") {
this.inputField.onchange();
}
if (this.dateClicked && typeof this.params.onUpdate === "function") {
this.params.onUpdate(this);
}
if (this.dateClicked) {
this.close();
} else {
this.processCalendar();
}
};
/** Method to close/hide the calendar */
JoomlaCalendar.prototype.close = function () {
document.activeElement.blur();
this.hide();
};
/** Method to show the calendar. */
JoomlaCalendar.prototype.show = function () {
/** This is needed for IE8 */
if (navigator.appName.indexOf("Internet Explorer")!==-1) {
var badBrowser = (
navigator.appVersion.indexOf("MSIE 9")===-1 &&
navigator.appVersion.indexOf("MSIE 1")===-1
);
if (badBrowser) {
if (window.jQuery && jQuery().chosen) {
var selItems = this.element.getElementsByTagName('select');
for (var i = 0; i < selItems.length; i++) {
jQuery(selItems[i]).chosen('destroy');
}
}
}
}
this.checkInputs();
this.inputField.focus();
this.dropdownElement.style.display = "block";
this.hidden = false;
document.addEventListener("keydown", this._calKeyEvent, true);
document.addEventListener("keypress", this._calKeyEvent, true);
document.addEventListener("mousedown", this._documentClick, true);
/** Move the calendar to top position if it doesn't fit below. */
var containerTmp = this.element.querySelector('.js-calendar');
if ((window.innerHeight + window.scrollY) < containerTmp.getBoundingClientRect().bottom + 20) {
containerTmp.style.marginTop = - (containerTmp.getBoundingClientRect().height + this.inputField.getBoundingClientRect().height) + "px";
}
this.processCalendar();
};
/** Method to hide the calendar. */
JoomlaCalendar.prototype.hide = function () {
document.removeEventListener("keydown", this._calKeyEvent, true);
document.removeEventListener("keypress", this._calKeyEvent, true);
document.removeEventListener("mousedown", this._documentClick, true);
this.dropdownElement.style.display = "none";
this.hidden = true;
};
/** Method to catch clicks outside of the calendar (used as close call) */
JoomlaCalendar.prototype._handleDocumentClick = function (ev) {
var el = ev.target;
if (el !== null && !el.classList.contains('time')) {
for (; el !== null && el !== this.element; el = el.parentNode);
}
if (el === null) {
document.activeElement.blur();
this.hide();
return stopCalEvent(ev);
}
};
/** Method to handle mouse click events (menus, buttons) **/
JoomlaCalendar.prototype._handleDayMouseDown = function (ev) {
var self = this,
el = ev.currentTarget,
target = ev.target || ev.srcElement;
if (target && target.hasAttribute('data-action')) {
return;
}
if (el.nodeName !== 'TD') { // A bootstrap inner button was pressed?
var testel = el.getParent('TD');
if (testel.nodeName === 'TD') { // Yes so use that element's td
el = testel;
} else { // No - try to find the table this way
el = el.getParent('TD');
if (el.classList.contains('js-calendar')) {
el = el.getElementsByTagName('table')[0];
}
}
} else { // Check that doesn't have a button and is not a day td
if (!(target.classList.contains('js-btn')) && !el.classList.contains('day') && !el.classList.contains('title')) {
return;
}
}
if (!el || el.disabled) {
return false;
}
if (typeof el.navtype === "undefined" || el.navtype !== 300) {
if (el.navtype === 50) { el._current = el.innerHTML; }
if (target === el || target.parentNode === el) { self.cellClick(el, ev); }
var mon = null;
if (typeof el.month !== "undefined") {
mon = el;
}
if (typeof el.parentNode.month !== "undefined") {
mon = el.parentNode;
}
var date = null;
if (mon) {
date = new Date(self.date);
if (mon.month !== date.getLocalMonth(self.params.dateType)) {
date.setLocalMonth(self.params.dateType, mon.month);
self.setDate(date);
self.dateClicked = false;
this.callHandler();
}
} else {
var year = null;
if (typeof el.year !== "undefined") {
year = target;
}
if (typeof el.parentNode.year !== "undefined") {
year = target.parentNode;
}
if (year) {
date = new Date(self.date);
if (year.year !== date.getLocalFullYear(self.params.dateType)) {
date.setFullYear(self.params.dateType, year.year);
self.setDate(date);
self.dateClicked = false;
this.callHandler();
}
}
}
}
return stopCalEvent(ev);
};
/** Method to handle mouse click events (dates) **/
JoomlaCalendar.prototype.cellClick = function (el, ev) {
var self = this,
closing = false,
newdate = false,
date = null;
if (typeof el.navtype === "undefined") {
if (self.currentDateEl) {
el.classList.add("selected");
self.currentDateEl = el.caldate;
closing = (self.currentDateEl === el.caldate);
if (!closing) {
self.currentDateEl = el.caldate;
}
}
self.date.setLocalDateOnly('gregorian', el.caldate);
var other_month = !(self.dateClicked = !el.otherMonth);
if (self.currentDateEl) { newdate = !el.disabled; }
if (other_month) {
this.processCalendar();
}
} else {
date = new Date(self.date);
self.dateClicked = false;
var year = date.getOtherFullYear(self.params.dateType), mon = date.getLocalMonth(self.params.dateType);
switch (el.navtype) {
case 400:
break;
case -2: // Prev year
if (!self.params.compressedHeader) {
if (year > self.params.minYear) {
date.setOtherFullYear(self.params.dateType, year - 1);
}
}
break;
case -1: // Prev month
var day = date.getLocalDate(self.params.dateType);
if (mon > 0) {
var max = date.getLocalMonthDays(self.params.dateType, mon - 1);
if (day > max) {
date.setLocalDate(self.params.dateType, max);
}
date.setLocalMonth(self.params.dateType, mon - 1);
} else if (year-- > self.params.minYear) {
date.setOtherFullYear(self.params.dateType, year);
var max = date.getLocalMonthDays(self.params.dateType, 11);
if (day > max) {
date.setLocalDate(self.params.dateType, max);
}
date.setLocalMonth(self.params.dateType, 11);
}
break;
case 1: // Next month
var day = date.getLocalDate(self.params.dateType);
if (mon < 11) {
var max = date.getLocalMonthDays(self.params.dateType, mon + 1);
if (day > max) {
date.setLocalDate(self.params.dateType, max);
}
date.setLocalMonth(self.params.dateType, mon + 1);
} else if (year < self.params.maxYear) {
date.setOtherFullYear(self.params.dateType, year + 1);
var max = date.getLocalMonthDays(self.params.dateType, 0);
if (day > max) {
date.setLocalDate(self.params.dateType, max);
}
date.setLocalMonth(self.params.dateType, 0);
}
break;
case 2: // Next year
if (!self.params.compressedHeader)
if (year < self.params.maxYear) {
date.setOtherFullYear(self.params.dateType, year + 1);
}
break;
case 0: // Today
break;
}
if (!date.equalsTo(self.date)) {
this.setDate(date);
newdate = true;
} else if (el.navtype === 0) {
newdate = closing = true;
}
}
if (newdate) {
if (self.params.showsTime) {
this.dateClicked = false;
}
ev && this.callHandler();
}
el.classList.remove("hilite");
if (closing && !self.params.showsTime) {
self.dateClicked = false;
ev && this.close();
}
};
/** Method to handle keyboard click events **/
JoomlaCalendar.prototype._handleCalKeyEvent = function (ev) {
var self = this,
K = ev.keyCode;
// Get value from input
if (ev.target === this.inputField && (K === 13 || K === 9)) {
this.close();
}
if (self.params.direction === 'rtl') {
if (K === 37) {
K = 39;
} else if (K === 39) {
K = 37;
}
}
if (K === 32) { // KEY Shift + space (now)
if (ev.shiftKey) {
ev.preventDefault();
this.cellClick(self._nav_now, ev);
self.close();
}
}
if (K === 27) { // KEY esc (close);
this.close();
}
if (K === 38) { // KEY up (previous week)
this.moveCursorBy(7);
}
if (K === 40) { // KEY down (next week)
this.moveCursorBy( -7);
}
if (K === 37) { // KEY left (previous day)
this.moveCursorBy(1);
}
if (K === 39) { // KEY right (next day)
this.moveCursorBy( -1);
}
if (ev.target === this.inputField && !(K>48 || K<57 || K===186 || K===189 || K===190 || K===32)) {
return stopCalEvent(ev);
}
};
/** Method to create the html structure of the calendar */
JoomlaCalendar.prototype._create = function () {
var self = this,
parent = this.element,
table = createElement("table"),
div = createElement("div");
this.table = table;
table.className = 'table';
table.cellSpacing = 0;
table.cellPadding = 0;
table.style.marginBottom = 0;
this.dropdownElement = div;
parent.appendChild(div);
if (this.params.direction) {
div.style.direction = this.params.direction;
}
div.className = 'js-calendar';
div.style.position = "absolute";
div.style.boxShadow = "0px 0px 70px 0px rgba(0,0,0,0.67)";
div.style.minWidth = this.inputField.width;
div.style.padding = '0';
div.style.display = "none";
div.style.left = "auto";
div.style.top = "auto";
div.style.zIndex = 1060;
div.style.borderRadius = "20px";
this.wrapper = createElement('div');
this.wrapper.className = 'calendar-container';
div.appendChild(this.wrapper);
this.wrapper.appendChild(table);
var thead = createElement("thead", table);
thead.className = 'calendar-header';
var cell = null,
row = null,
cal = this,
hh = function (text, cs, navtype, node, styles, classes, dataAttr) {
node = node ? node : "td";
styles = styles ? styles : {};
cell = createElement(node, row);
if (cs) {
classes = classes ? 'class="' + classes + '"' : '';
cell.colSpan = cs;
}
for (var key in styles) {
cell.style[key] = styles[key];
}
for (var key in dataAttr) {
cell.setAttribute(key, dataAttr[key]);
}
if (navtype !== 0 && Math.abs(navtype) <= 2) {
cell.className += " nav";
}
if (cs) {
cell.addEventListener("mousedown", self._dayMouseDown, true);
}
cell.calendar = cal;
cell.navtype = navtype;
if (navtype !== 0 && Math.abs(navtype) <= 2) {
cell.innerHTML = "<a " + classes + " style='display:inline;padding:2px 6px;cursor:pointer;text-decoration:none;' unselectable='on'>" + text + "</a>";
} else {
cell.innerHTML = cs ? "<div unselectable='on'" + classes + ">" + text + "</div>" : text;
if (!cs && classes) {
cell.className = classes;
}
}
return cell;
};
if (this.params.compressedHeader === false) { // Head - year
row = createElement("tr", thead);
row.className = "calendar-head-row";
this._nav_py = hh("‹", 1, -2, '', {"text-align": "center", "font-size": "18px", "line-height": "18px"}, 'js-btn btn-prev-year'); // Previous year button
this.title = hh('<div style="text-align:center;font-size:18px"><span></span></div>', this.params.weekNumbers ? 6 : 5, 300);
this.title.className = "title";
this._nav_ny = hh(" ›", 1, 2, '', {"text-align": "center", "font-size": "18px", "line-height": "18px"}, 'js-btn btn-next-year'); // Next year button
}
row = createElement("tr", thead); // Head - month
row.className = "calendar-head-row";
this._nav_pm = hh("‹", 1, -1, '', {"text-align": "center", "font-size": "2em", "line-height": "1em"}, 'js-btn btn-prev-month'); // Previous month button
this._nav_month = hh('<div style="text-align:center;font-size:1.2em"><span></span></div>', this.params.weekNumbers ? 6 : 5, 888, 'td', {'textAlign': 'center'});
this._nav_month.className = "title";
this._nav_nm = hh(" ›", 1, 1, '', {"text-align": "center", "font-size": "2em", "line-height": "1em"}, 'js-btn btn-next-month'); // Next month button
row = createElement("tr", thead); // day names
row.className = self.params.weekNumbers ? "daynames wk" : "daynames";
if (this.params.weekNumbers) {
cell = createElement("td", row);
cell.className = "day-name wn";
cell.innerHTML = JoomlaCalLocale.wk;
}
for (var i = 7; i > 0; --i) {
cell = createElement("td", row);
if (!i) {
cell.calendar = self;
}
}
this.firstdayname = (this.params.weekNumbers) ? row.firstChild.nextSibling : row.firstChild;
var fdow = this.params.firstDayOfWeek,
cell = this.firstdayname,
weekend = JoomlaCalLocale.weekend;
for (var i = 0; i < 7; ++i) {
var realday = (i + fdow) % 7;
cell.classList.add("day-name");
this.params.weekNumbers ? cell.classList.add('day-name-week') : '';
if (i) {
cell.calendar = self;
cell.fdow = realday;
}
if (weekend.indexOf(weekend) !== -1) {
cell.classList.add("weekend");
}
cell.innerHTML = JoomlaCalLocale.shortDays[(i + fdow) % 7];
cell = cell.nextSibling;
}
var tbody = createElement("tbody", table);
this.tbody = tbody;
for (i = 6; i > 0; --i) {
row = createElement("tr", tbody);
if (this.params.weekNumbers) {
cell = createElement("td", row);
}
for (var j = 7; j > 0; --j) {
cell = createElement("td", row);
cell.calendar = this;
cell.addEventListener("mousedown", this._dayMouseDown, true);
}
}
if (this.params.showsTime) {
row = createElement("tr", tbody);
row.className = "time";
cell = createElement("td", row);
cell.className = "time time-title";
cell.colSpan = 1;
cell.style.verticalAlign = 'middle';
cell.innerHTML = " ";
var cell1 = createElement("td", row);
cell1.className = "time hours-select";
cell1.colSpan = 2;
var cell2 = createElement("td", row);
cell2.className = "time minutes-select";
cell2.colSpan = 2;
(function () {
function makeTimePart(className, selected, range_start, range_end, cellTml) {
var part = createElement("select", cellTml), num;
part.calendar = self;
part.className = className;
part.setAttribute('data-chosen', true); // avoid Chosen, hack
part.style.width = '100%';
part.navtype = 50;
part._range = [];
for (var i = range_start; i <= range_end; ++i) {
var txt, selAttr = '';
if (i === selected) {
selAttr = true;
}
if (i < 10 && range_end >= 10) {
num = '0' + i;
txt = Date.convertNumbers('0') + Date.convertNumbers(i);
} else {
num = '' + i;
txt = '' + Date.convertNumbers(i);
}
part.options.add(new Option(txt, num, selAttr, selAttr));
}
return part;
}
var hrs = self.date.getHours(),
mins = self.date.getMinutes(),
t12 = !self.params.time24,
pm = (self.date.getHours() > 12);
if (t12 && pm) {
hrs -= 12;
}
var H = makeTimePart("time time-hours", hrs, t12 ? 1 : 0, t12 ? 12 : 23, cell1),
M = makeTimePart("time time-minutes", mins, 0, 59, cell2),
AP = null;
cell = createElement("td", row);
cell.className = "time ampm-select";
cell.colSpan = self.params.weekNumbers ? 1 : 2;
if (t12) {
var selAttr = true,
altDate = Date.parseFieldDate(self.inputField.getAttribute('data-alt-value'), self.params.dateFormat, 'gregorian');
pm = (altDate.getHours() > 12);
var part = createElement("select", cell);
part.className = "time-ampm";
part.style.width = '100%';
part.options.add(new Option(JoomlaCalLocale.PM, "pm", pm ? selAttr : '', pm ? selAttr : ''));
part.options.add(new Option(JoomlaCalLocale.AM, "am", pm ? '' : selAttr, pm ? '' : selAttr));
AP = part;
// Event listener for the am/pm select
AP.addEventListener("change", function (event) {
self.updateTime(event.target.parentNode.parentNode.childNodes[1].childNodes[0].value,
event.target.parentNode.parentNode.childNodes[2].childNodes[0].value,
event.target.parentNode.parentNode.childNodes[3].childNodes[0].value);
}, false);
} else {
cell.innerHTML = " ";
cell.colSpan = self.params.weekNumbers ? 3 : 2;
}
H.addEventListener("change", function (event) {
self.updateTime(event.target.parentNode.parentNode.childNodes[1].childNodes[0].value,
event.target.parentNode.parentNode.childNodes[2].childNodes[0].value,
event.target.parentNode.parentNode.childNodes[3].childNodes[0].value);
}, false);
M.addEventListener("change", function (event) {
self.updateTime(event.target.parentNode.parentNode.childNodes[1].childNodes[0].value,
event.target.parentNode.parentNode.childNodes[2].childNodes[0].value,
event.target.parentNode.parentNode.childNodes[3].childNodes[0].value);
}, false);
})();
}
row = createElement("div", this.wrapper);
row.className = "buttons-wrapper btn-group";
this._nav_save = hh(JoomlaCalLocale.save, '', 100, 'button', '', 'js-btn btn btn-clear', {"data-action": "clear"});
if (!this.inputField.hasAttribute('required')) {
var savea = row.querySelector('[data-action="clear"]');
savea.addEventListener("click", function (e) {
e.preventDefault();
var days = self.table.querySelectorAll('td');
for (var i = 0; i < days.length; i++) {
if (days[i].classList.contains('selected')) {
days[i].classList.remove('selected');
break;
}
}
self.inputField.setAttribute('data-alt-value', "0000-00-00 00:00:00");
self.inputField.setAttribute('value', '');
self.inputField.value = '';
});
}
if (this.params.showsTodayBtn) {
this._nav_now = hh(JoomlaCalLocale.today, '', 0, 'button', '', 'js-btn btn btn-today', {"data-action": "today"});
var todaya = this.wrapper.querySelector('[data-action="today"]');
todaya.addEventListener('click', function (e) {
e.preventDefault();
self.date.setLocalDateOnly('gregorian', new Date()); // TODAY
self.dateClicked = true;
self.callHandler();
self.close();
});
}
this._nav_exit = hh(JoomlaCalLocale.exit, '', 999, 'button', '', 'js-btn btn btn-exit', {"data-action": "exit"});
var exita = this.wrapper.querySelector('[data-action="exit"]');
exita.addEventListener('click', function (e) {
e.preventDefault();
if (!self.dateClicked) {
if (self.inputField.value) {
if (self.params.dateType !== 'gregorian') {
self.inputField.setAttribute('data-local-value', self.inputField.value);
}
if (typeof self.dateClicked === 'undefined') {
// value needs to be validated
self.inputField.setAttribute('data-alt-value', Date.parseFieldDate(self.inputField.value, self.params.dateFormat, self.params.dateType)
.print(self.params.dateFormat, 'gregorian', false));
} else {
self.inputField.setAttribute('data-alt-value', self.date.print(self.params.dateFormat, 'gregorian', false));
}
} else {
self.inputField.setAttribute('data-alt-value', '0000-00-00 00:00:00');
}
self.date = Date.parseFieldDate(self.inputField.getAttribute('data-alt-value'), self.params.dateFormat, self.params.dateType);
}
self.close();
});
this.processCalendar();
};
/** Method to append numbers to the calendar table */
JoomlaCalendar.prototype.processCalendar = function () {
this.table.style.visibility = "hidden";
var firstDayOfWeek = this.params.firstDayOfWeek,
date = this.date,
today = new Date(),
TY = today.getLocalFullYear(this.params.dateType),
TM = today.getLocalMonth(this.params.dateType),
TD = today.getLocalDate(this.params.dateType),
year = date.getOtherFullYear(this.params.dateType),
hrs = date.getHours(),
mins = date.getMinutes(),
secs = date.getSeconds(),
t12 = !this.params.time24;
if (year < this.params.minYear) { // Check min,max year
year = this.params.minYear;
date.getOtherFullYear(this.params.dateType, year);
} else if (year > this.params.maxYear) {
year = this.params.maxYear;
date.getOtherFullYear(this.params.dateType, year);
}
this.params.firstDayOfWeek = firstDayOfWeek;
this.date = new Date(date);
var month = date.getLocalMonth(this.params.dateType);
var mday = date.getLocalDate(this.params.dateType);
// Compute the first day that would actually be displayed in the calendar, even if it's from the previous month.
date.setLocalDate(this.params.dateType, 1);
var day1 = (date.getLocalDay(this.params.dateType) - this.params.firstDayOfWeek) % 7;
if (day1 < 0) {
day1 += 7;
}
date.setLocalDate(this.params.dateType, - day1);
date.setLocalDate(this.params.dateType, date.getLocalDate(this.params.dateType) + 1);
var row = this.tbody.firstChild,
ar_days = this.ar_days = new Array(),
weekend = JoomlaCalLocale.weekend,
monthDays = parseInt(date.getLocalWeekDays(this.params.dateType));
/** Fill the table **/
for (var i = 0; i < monthDays; ++i, row = row.nextSibling) {
var cell = row.firstChild;
if (this.params.weekNumbers) {
cell.className = "day wn";
cell.innerHTML = date.getLocalWeekNumber(this.params.dateType); //date.convertNumbers();
cell = cell.nextSibling;
}
row.className = this.params.weekNumbers ? "daysrow wk" : "daysrow";
var hasdays = false, iday,
dpos = ar_days[i] = [],
totalDays = monthDays + 1;
for (var j = 0; j < totalDays; ++j, cell = cell.nextSibling, date.setLocalDate(this.params.dateType, iday + 1)) {
cell.className = "day";
cell.style['textAlign'] = 'center';
iday = date.getLocalDate(this.params.dateType);
var wday = date.getLocalDay(this.params.dateType);
cell.pos = i << 4 | j;
dpos[j] = cell;
var current_month = (date.getLocalMonth(this.params.dateType) === month);
if (!current_month) {
if (this.params.showsOthers) {
cell.className += " disabled othermonth ";
cell.otherMonth = true;
} else {
cell.className += " emptycell";
cell.innerHTML = " ";
cell.disabled = true;
continue;
}
} else {
cell.otherMonth = false;
hasdays = true;
cell.style.cursor = "pointer";
}
cell.disabled = false;
cell.innerHTML = this.params.debug ? iday : Date.convertNumbers(iday); // translated day number for each cell
if (!cell.disabled) {
cell.caldate = new Date(date);
if (current_month && iday === mday) {
cell.className += " selected";
this.currentDateEl = cell;
}
if (date.getLocalFullYear(this.params.dateType) === TY && date.getLocalMonth(this.params.dateType) === TM && iday === TD) {
cell.className += " today";
}
if (weekend.indexOf(wday) !== -1)
cell.className += " weekend";
}
}
if (!(hasdays || this.params.showsOthers)) {
row.style.display = 'none';
row.className = "emptyrow";
} else {
row.style.display = '';
}
}
/* Set the time */
if (this.params.showsTime) {
if (hrs > 12 && t12) {
hrs -= 12;
}
hrs = (hrs < 10) ? "0" + hrs : hrs;
mins = (mins < 10) ? "0" + mins : mins;
var hoursEl = this.table.querySelector('.time-hours'),
minsEl = this.table.querySelector('.time-minutes');
/* remove the selected class for the hours*/
this.resetSelected(hoursEl);
hoursEl.value = hrs;
/* remove the selected class for the minutes*/
this.resetSelected(minsEl);
minsEl.value = mins;
if (!this.params.time24)
{
var dateAlt = new Date(this.inputField.getAttribute('data-alt-value')),
ampmEl = this.table.querySelector('.time-ampm'),
hrsAlt = dateAlt.getHours();
if (hrsAlt > 12) {
/* remove the selected class for the am-pm*/
this.resetSelected(ampmEl);
ampmEl.value = 'pm';
}
}
}
if (!this.params.compressedHeader) {
this._nav_month.getElementsByTagName('span')[0].innerHTML = this.params.debug ? month + ' ' + JoomlaCalLocale.months[month] : JoomlaCalLocale.months[month];
this.title.getElementsByTagName('span')[0].innerHTML = this.params.debug ? year + ' ' + Date.convertNumbers(year.toString()) : Date.convertNumbers(year.toString());
} else {
var tmpYear = Date.convertNumbers(year.toString());
this._nav_month.getElementsByTagName('span')[0].innerHTML = !this.params.monthBefore ? JoomlaCalLocale.months[month] + ' - ' + tmpYear : tmpYear + ' - ' + JoomlaCalLocale.months[month] ;
}
this.table.style.visibility = "visible";
};
/** Method to listen for the click event on the input button. **/
JoomlaCalendar.prototype._bindEvents = function () {
var self = this;
this.inputField.addEventListener('blur', function(event) {
var calObj = JoomlaCalendar.getCalObject(this)._joomlaCalendar;
// If calendar is open we will handle the event elsewhere
if (calObj.dropdownElement.style.display === 'block') {
event.preventDefault();
return;
}
if (calObj) {
if (calObj.inputField.value) {
if (typeof calObj.params.dateClicked === 'undefined') {
calObj.inputField.setAttribute('data-local-value', calObj.inputField.value);
if (calObj.params.dateType !== 'gregorian') {
// We need to transform the date for the data-alt-value
var ndate, date = Date.parseFieldDate(calObj.inputField.value, calObj.params.dateFormat, calObj.params.dateType);
ndate = Date.localCalToGregorian(date.getFullYear(), date.getMonth(), date.getDate());
date.setFullYear(ndate[0]);
date.setMonth(ndate[1]);
date.setDate(ndate[2]);
calObj.inputField.setAttribute('data-alt-value', date.print(calObj.params.dateFormat, 'gregorian', false));
} else {
calObj.inputField.setAttribute('data-alt-value', Date.parseFieldDate(calObj.inputField.value, calObj.params.dateFormat, calObj.params.dateType)
.print(calObj.params.dateFormat, 'gregorian', false));
}
} else {
calObj.inputField.setAttribute('data-alt-value', calObj.date.print(calObj.params.dateFormat, 'gregorian', false));
}
} else {
calObj.inputField.setAttribute('data-alt-value', '0000-00-00 00:00:00');
}
calObj.date = Date.parseFieldDate(calObj.inputField.getAttribute('data-alt-value'), calObj.params.dateFormat, calObj.params.dateType);
}
self.close();
}, true);
this.button.addEventListener('click', function() {
self.show();
}, false);
};
/** Helpers **/
var stopCalEvent = function (ev) { ev || (ev = window.event); ev.preventDefault(); ev.stopPropagation(); return false; };
var createElement = function (type, parent) { var el = null; el = document.createElement(type); if (typeof parent !== "undefined") { parent.appendChild(el); } return el; };
var isInt = function (input) { return !isNaN(input) && (function(x) { return (x | 0) === x; })(parseFloat(input)) };
var getBoundary = function (input, type) { var date = new Date(); var y = date.getLocalFullYear(type); return y + input; };
/**
* IE8 polyfill for indexOf()
*/
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(elt) {
var len = this.length >>> 0,
from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0) {
from += len;
}
for (; from < len; from++) {
if (from in this && this[from] === elt) {
return from;
}
}
return -1;
};
}
/** Method to get the active calendar element through any descendant element. */
JoomlaCalendar.getCalObject = function(element) {
if (!element) {
return false;
}
while (element.parentNode) {
element = element.parentNode;
if (element.classList.contains('field-calendar')) {
return element;
}
}
return false;
};
/** Method to change input values with the data-alt-value values. **/
JoomlaCalendar.prototype.setAltValue = function() {
var input = this.inputField;
if (input.getAttribute('disabled')) return;
input.value = input.getAttribute('data-alt-value') ? input.getAttribute('data-alt-value') : '';
};
/** Method to change the inputs before submit. **/
JoomlaCalendar.onSubmit = function() {
Joomla = window.Joomla || {};
if (!Joomla.calendarProcessed) {
Joomla.calendarProcessed = true;
var elements = document.querySelectorAll(".field-calendar");
for (var i = 0; i < elements.length; i++) {
var element = elements[i],
instance = element._joomlaCalendar;
if (instance) {
instance.setAltValue();
}
}
}
};
/**
* Init the Calendars on the page
*
* @param {Node} element The element node
* @param {HTMLElement} container The field container (optional)
*/
JoomlaCalendar.init = function (element, container) {
// Fall back for translation strings
window.JoomlaCalLocale = window.JoomlaCalLocale ? JoomlaCalLocale : {};
JoomlaCalLocale.today = JoomlaCalLocale.today ? JoomlaCalLocale.today : 'today';
JoomlaCalLocale.weekend = JoomlaCalLocale.weekend ? JoomlaCalLocale.weekend : [0, 6];
JoomlaCalLocale.localLangNumbers = JoomlaCalLocale.localLangNumbers ? JoomlaCalLocale.localLangNumbers : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
JoomlaCalLocale.wk = JoomlaCalLocale.wk ? JoomlaCalLocale.wk : 'wk';
JoomlaCalLocale.AM = JoomlaCalLocale.AM ? JoomlaCalLocale.AM : 'AM';
JoomlaCalLocale.PM = JoomlaCalLocale.PM ? JoomlaCalLocale.PM : 'PM';
JoomlaCalLocale.am = JoomlaCalLocale.am ? JoomlaCalLocale.am : 'am';
JoomlaCalLocale.pm = JoomlaCalLocale.pm ? JoomlaCalLocale.pm : 'pm';
JoomlaCalLocale.dateType = JoomlaCalLocale.dateType ? JoomlaCalLocale.dateType : 'gregorian';
JoomlaCalLocale.time = JoomlaCalLocale.time ? JoomlaCalLocale.time : 'time';
JoomlaCalLocale.days = JoomlaCalLocale.days ? JoomlaCalLocale.days : '["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]';
JoomlaCalLocale.shortDays = JoomlaCalLocale.shortDays ? JoomlaCalLocale.shortDays : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
JoomlaCalLocale.months = JoomlaCalLocale.months ? JoomlaCalLocale.months : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
JoomlaCalLocale.shortMonths = JoomlaCalLocale.shortMonths ? JoomlaCalLocale.shortMonths : ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
JoomlaCalLocale.minYear = JoomlaCalLocale.minYear ? JoomlaCalLocale.minYear : 1900;
JoomlaCalLocale.maxYear = JoomlaCalLocale.maxYear ? JoomlaCalLocale.maxYear : 2100;
JoomlaCalLocale.exit = JoomlaCalLocale.exit ? JoomlaCalLocale.exit : 'Cancel';
JoomlaCalLocale.clear = JoomlaCalLocale.clear ? JoomlaCalLocale.clear : 'Clear';
var instance = element._joomlaCalendar;
if (!instance) {
new JoomlaCalendar(element);
} else {
instance.recreate();
}
if (element && element.getElementsByTagName('input')[0] && element.getElementsByTagName('input')[0].form && !element.getElementsByTagName('input')[0].disabled) {
element.getElementsByTagName('input')[0].form.addEventListener('submit', JoomlaCalendar.onSubmit);
}
};
window.JoomlaCalendar = JoomlaCalendar;
/** Instantiate all the calendar fields when the document is ready */
document.addEventListener("DOMContentLoaded", function() {
var elements, i;
elements = document.querySelectorAll(".field-calendar");
for (i = 0; i < elements.length; i++) {
JoomlaCalendar.init(elements[i]);
}
window.jQuery && jQuery(document).on("subform-row-add", function (event, row) {
elements = row.querySelectorAll(".field-calendar");
for (i = 0; i < elements.length; i++) {
JoomlaCalendar.init(elements[i]);
}
});
/** B/C related code
* @deprecated 4.0
*/
window.Calendar = {};
/** B/C related code
* @deprecated 4.0
*/
Calendar.setup = function(obj) {
if (obj.inputField && document.getElementById(obj.inputField)) {
var element = document.getElementById(obj.inputField),
cal = element.parentNode.querySelectorAll('button')[0];
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
switch (property) {
case 'ifFormat':
if (cal) cal.setAttribute('data-dayformat', obj.ifFormat);
break;
case 'firstDay':
if (cal) cal.setAttribute('data-firstday', parseInt(obj.firstDay));
break;
case 'weekNumbers':
if (cal) cal.setAttribute('data-week-numbers', (obj.weekNumbers === "true" || obj.weekNumbers === true) ? '1' : '0');
break;
case 'showOthers':
if (cal) cal.setAttribute('data-show-others', (obj.showOthers === "true" || obj.showOthers === true) ? '1' : '0');
break;
case 'showsTime':
if (cal) cal.setAttribute('data-show-time', (obj.showsTime === "true" || obj.showsTime === true) ? '1' : '0');
break;
case 'timeFormat':
if (cal) cal.setAttribute('data-time-24', parseInt(obj.timeFormat));
break;
case 'displayArea':
case 'inputField':
case 'button':
case 'eventName':
case 'daFormat':
case 'disableFunc':
case 'dateStatusFunc':
case 'dateTooltipFunc':
case 'dateText':
case 'align':
case 'range':
case 'flat':
case 'flatCallback':
case 'onSelect':
case 'onClose':
case 'onUpdate':
case 'date':
case 'electric':
case 'step':
case 'position':
case 'cache':
case 'multiple':
break;
}
}
}
JoomlaCalendar.init(element.parentNode.parentNode);
}
return null;
};
});
})(window, document);
|
haydenyoung/joomla-cms
|
media/system/js/fields/calendar.js
|
JavaScript
|
gpl-2.0
| 42,917
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- /home/espenr/tmp/qt-3.3.8-espenr-2499/qt-x11-free-3.3.8/src/tools/qdatetime.cpp:1239 -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>QTime Class</title>
<style type="text/css"><!--
fn { margin-left: 1cm; text-indent: -1cm; }
a:link { color: #004faf; text-decoration: none }
a:visited { color: #672967; text-decoration: none }
body { background: #ffffff; color: black; }
--></style>
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr bgcolor="#E5E5E5">
<td valign=center>
<a href="index.html">
<font color="#004faf">Home</font></a>
| <a href="classes.html">
<font color="#004faf">All Classes</font></a>
| <a href="mainclasses.html">
<font color="#004faf">Main Classes</font></a>
| <a href="annotated.html">
<font color="#004faf">Annotated</font></a>
| <a href="groups.html">
<font color="#004faf">Grouped Classes</font></a>
| <a href="functions.html">
<font color="#004faf">Functions</font></a>
</td>
<td align="right" valign="center"><img src="logo32.png" align="right" width="64" height="32" border="0"></td></tr></table><h1 align=center>QTime Class Reference</h1>
<p>The QTime class provides clock time functions.
<a href="#details">More...</a>
<p>All the functions in this class are <a href="threads.html#reentrant">reentrant</a> when Qt is built with thread support.</p>
<p><tt>#include <<a href="qdatetime-h.html">qdatetime.h</a>></tt>
<p><a href="qtime-members.html">List of all member functions.</a>
<h2>Public Members</h2>
<ul>
<li class=fn><a href="#QTime"><b>QTime</b></a> ()</li>
<li class=fn><a href="#QTime-2"><b>QTime</b></a> ( int h, int m, int s = 0, int ms = 0 )</li>
<li class=fn>bool <a href="#isNull"><b>isNull</b></a> () const</li>
<li class=fn>bool <a href="#isValid"><b>isValid</b></a> () const</li>
<li class=fn>int <a href="#hour"><b>hour</b></a> () const</li>
<li class=fn>int <a href="#minute"><b>minute</b></a> () const</li>
<li class=fn>int <a href="#second"><b>second</b></a> () const</li>
<li class=fn>int <a href="#msec"><b>msec</b></a> () const</li>
<li class=fn>QString <a href="#toString-2"><b>toString</b></a> ( Qt::DateFormat f = Qt::TextDate ) const</li>
<li class=fn>QString <a href="#toString"><b>toString</b></a> ( const QString & format ) const</li>
<li class=fn>bool <a href="#setHMS"><b>setHMS</b></a> ( int h, int m, int s, int ms = 0 )</li>
<li class=fn>QTime <a href="#addSecs"><b>addSecs</b></a> ( int nsecs ) const</li>
<li class=fn>int <a href="#secsTo"><b>secsTo</b></a> ( const QTime & t ) const</li>
<li class=fn>QTime <a href="#addMSecs"><b>addMSecs</b></a> ( int ms ) const</li>
<li class=fn>int <a href="#msecsTo"><b>msecsTo</b></a> ( const QTime & t ) const</li>
<li class=fn>bool <a href="#operator-eq-eq"><b>operator==</b></a> ( const QTime & t ) const</li>
<li class=fn>bool <a href="#operator!-eq"><b>operator!=</b></a> ( const QTime & t ) const</li>
<li class=fn>bool <a href="#operator-lt"><b>operator<</b></a> ( const QTime & t ) const</li>
<li class=fn>bool <a href="#operator-lt-eq"><b>operator<=</b></a> ( const QTime & t ) const</li>
<li class=fn>bool <a href="#operator-gt"><b>operator></b></a> ( const QTime & t ) const</li>
<li class=fn>bool <a href="#operator-gt-eq"><b>operator>=</b></a> ( const QTime & t ) const</li>
<li class=fn>void <a href="#start"><b>start</b></a> ()</li>
<li class=fn>int <a href="#restart"><b>restart</b></a> ()</li>
<li class=fn>int <a href="#elapsed"><b>elapsed</b></a> () const</li>
</ul>
<h2>Static Public Members</h2>
<ul>
<li class=fn>QTime <a href="#currentTime-2"><b>currentTime</b></a> ()</li>
<li class=fn>QTime <a href="#currentTime"><b>currentTime</b></a> ( Qt::TimeSpec ts )</li>
<li class=fn>QTime <a href="#fromString"><b>fromString</b></a> ( const QString & s, Qt::DateFormat f = Qt::TextDate )</li>
<li class=fn>bool <a href="#isValid-2"><b>isValid</b></a> ( int h, int m, int s, int ms = 0 )</li>
</ul>
<h2>Related Functions</h2>
<ul>
<li class=fn>QDataStream & <a href="#operator-lt-lt"><b>operator<<</b></a> ( QDataStream & s, const QTime & t )</li>
<li class=fn>QDataStream & <a href="#operator-gt-gt"><b>operator>></b></a> ( QDataStream & s, QTime & t )</li>
</ul>
<hr><a name="details"></a><h2>Detailed Description</h2>
<p> The QTime class provides clock time functions.
<p>
<p> A QTime object contains a clock time, i.e. the number of hours,
minutes, seconds, and milliseconds since midnight. It can read the
current time from the system clock and measure a span of elapsed
time. It provides functions for comparing times and for
manipulating a time by adding a number of (milli)seconds.
<p> QTime uses the 24-hour clock format; it has no concept of AM/PM.
It operates in local time; it knows nothing about time zones or
daylight savings time.
<p> A QTime object is typically created either by giving the number of
hours, minutes, seconds, and milliseconds explicitly, or by using
the static function <a href="#currentTime">currentTime</a>(), which creates a QTime object
that contains the system's clock time. Note that the accuracy
depends on the accuracy of the underlying operating system; not
all systems provide 1-millisecond accuracy.
<p> The <a href="#hour">hour</a>(), <a href="#minute">minute</a>(), <a href="#second">second</a>(), and <a href="#msec">msec</a>() functions provide
access to the number of hours, minutes, seconds, and milliseconds
of the time. The same information is provided in textual format by
the <a href="#toString">toString</a>() function.
<p> QTime provides a full set of operators to compare two QTime
objects. One time is considered smaller than another if it is
earlier than the other.
<p> The time a given number of seconds or milliseconds later than a
given time can be found using the <a href="#addSecs">addSecs</a>() or <a href="#addMSecs">addMSecs</a>()
functions. Correspondingly, the number of (milli)seconds between
two times can be found using the <a href="#secsTo">secsTo</a>() or <a href="#msecsTo">msecsTo</a>() functions.
<p> QTime can be used to measure a span of elapsed time using the
<a href="#start">start</a>(), <a href="#restart">restart</a>(), and <a href="#elapsed">elapsed</a>() functions.
<p> <p>See also <a href="qdate.html">QDate</a>, <a href="qdatetime.html">QDateTime</a>, and <a href="time.html">Time and Date</a>.
<hr><h2>Member Function Documentation</h2>
<h3 class=fn><a name="QTime"></a>QTime::QTime ()
</h3>
<p> Constructs the time 0 hours, minutes, seconds and milliseconds,
i.e. 00:00:00.000 (midnight). This is a valid time.
<p> <p>See also <a href="#isValid">isValid</a>().
<h3 class=fn><a name="QTime-2"></a>QTime::QTime ( int h, int m, int s = 0, int ms = 0 )
</h3>
Constructs a time with hour <em>h</em>, minute <em>m</em>, seconds <em>s</em> and
milliseconds <em>ms</em>.
<p> <em>h</em> must be in the range 0..23, <em>m</em> and <em>s</em> must be in the
range 0..59, and <em>ms</em> must be in the range 0..999.
<p> <p>See also <a href="#isValid">isValid</a>().
<h3 class=fn><a href="qtime.html">QTime</a> <a name="addMSecs"></a>QTime::addMSecs ( int ms ) const
</h3>
Returns a QTime object containing a time <em>ms</em> milliseconds later
than the time of this object (or earlier if <em>ms</em> is negative).
<p> Note that the time will wrap if it passes midnight. See <a href="#addSecs">addSecs</a>()
for an example.
<p> <p>See also <a href="#addSecs">addSecs</a>() and <a href="#msecsTo">msecsTo</a>().
<h3 class=fn><a href="qtime.html">QTime</a> <a name="addSecs"></a>QTime::addSecs ( int nsecs ) const
</h3>
Returns a QTime object containing a time <em>nsecs</em> seconds later
than the time of this object (or earlier if <em>nsecs</em> is negative).
<p> Note that the time will wrap if it passes midnight.
<p> Example:
<pre>
QTime n( 14, 0, 0 ); // n == 14:00:00
QTime t;
t = n.<a href="#addSecs">addSecs</a>( 70 ); // t == 14:01:10
t = n.<a href="#addSecs">addSecs</a>( -70 ); // t == 13:58:50
t = n.<a href="#addSecs">addSecs</a>( 10*60*60 + 5 ); // t == 00:00:05
t = n.<a href="#addSecs">addSecs</a>( -15*60*60 ); // t == 23:00:00
</pre>
<p> <p>See also <a href="#addMSecs">addMSecs</a>(), <a href="#secsTo">secsTo</a>(), and <a href="qdatetime.html#addSecs">QDateTime::addSecs</a>().
<h3 class=fn><a href="qtime.html">QTime</a> <a name="currentTime"></a>QTime::currentTime ( <a href="qt.html#TimeSpec-enum">Qt::TimeSpec</a> ts )<tt> [static]</tt>
</h3>
Returns the current time as reported by the system clock, for the
TimeSpec <em>ts</em>. The default TimeSpec is LocalTime.
<p> Note that the accuracy depends on the accuracy of the underlying
operating system; not all systems provide 1-millisecond accuracy.
<p> <p>See also <a href="qt.html#TimeSpec-enum">Qt::TimeSpec</a>.
<p>Examples: <a href="aclock-example.html#x1201">aclock/aclock.cpp</a>, <a href="dclock-example.html#x1104">dclock/dclock.cpp</a>, <a href="tutorial1-12.html#x2398">t12/cannon.cpp</a>, and <a href="tictac-example.html#x40">tictac/tictac.cpp</a>.
<h3 class=fn><a href="qtime.html">QTime</a> <a name="currentTime-2"></a>QTime::currentTime ()<tt> [static]</tt>
</h3>
This is an overloaded member function, provided for convenience. It behaves essentially like the above function.
<p> Returns the current time as reported by the system clock.
<p> Note that the accuracy depends on the accuracy of the underlying
operating system; not all systems provide 1-millisecond accuracy.
<h3 class=fn>int <a name="elapsed"></a>QTime::elapsed () const
</h3>
Returns the number of milliseconds that have elapsed since the
last time <a href="#start">start</a>() or <a href="#restart">restart</a>() was called.
<p> Note that the counter wraps to zero 24 hours after the last call
to start() or restart.
<p> Note that the accuracy depends on the accuracy of the underlying
operating system; not all systems provide 1-millisecond accuracy.
<p> <b>Warning:</b> If the system's clock setting has been changed since the
last time start() or restart() was called, the result is
undefined. This can happen when daylight savings time is turned on
or off.
<p> <p>See also <a href="#start">start</a>() and <a href="#restart">restart</a>().
<h3 class=fn><a href="qtime.html">QTime</a> <a name="fromString"></a>QTime::fromString ( const <a href="qstring.html">QString</a> & s, <a href="qt.html#DateFormat-enum">Qt::DateFormat</a> f = Qt::TextDate )<tt> [static]</tt>
</h3>
Returns the representation <em>s</em> as a QTime using the format <em>f</em>,
or an invalid time if this is not possible.
<p> <b>Warning:</b> Note that <a href="qt.html#DateFormat-enum">Qt::LocalDate</a> cannot be used here.
<h3 class=fn>int <a name="hour"></a>QTime::hour () const
</h3>
Returns the hour part (0..23) of the time.
<p>Examples: <a href="aclock-example.html#x1202">aclock/aclock.cpp</a> and <a href="tictac-example.html#x41">tictac/tictac.cpp</a>.
<h3 class=fn>bool <a name="isNull"></a>QTime::isNull () const
</h3>
<p> Returns TRUE if the time is equal to 00:00:00.000; otherwise
returns FALSE. A null time is valid.
<p> <p>See also <a href="#isValid">isValid</a>().
<h3 class=fn>bool <a name="isValid"></a>QTime::isValid () const
</h3>
Returns TRUE if the time is valid; otherwise returns FALSE. The
time 23:30:55.746 is valid, whereas 24:12:30 is invalid.
<p> <p>See also <a href="#isNull">isNull</a>().
<h3 class=fn>bool <a name="isValid-2"></a>QTime::isValid ( int h, int m, int s, int ms = 0 )<tt> [static]</tt>
</h3>
This is an overloaded member function, provided for convenience. It behaves essentially like the above function.
<p> Returns TRUE if the specified time is valid; otherwise returns
FALSE.
<p> The time is valid if <em>h</em> is in the range 0..23, <em>m</em> and <em>s</em> are
in the range 0..59, and <em>ms</em> is in the range 0..999.
<p> Example:
<pre>
QTime::<a href="#isValid">isValid</a>(21, 10, 30); // returns TRUE
QTime::<a href="#isValid">isValid</a>(22, 5, 62); // returns FALSE
</pre>
<h3 class=fn>int <a name="minute"></a>QTime::minute () const
</h3>
Returns the minute part (0..59) of the time.
<p>Examples: <a href="aclock-example.html#x1203">aclock/aclock.cpp</a> and <a href="tictac-example.html#x42">tictac/tictac.cpp</a>.
<h3 class=fn>int <a name="msec"></a>QTime::msec () const
</h3>
Returns the millisecond part (0..999) of the time.
<h3 class=fn>int <a name="msecsTo"></a>QTime::msecsTo ( const <a href="qtime.html">QTime</a> & t ) const
</h3>
Returns the number of milliseconds from this time to <em>t</em> (which
is negative if <em>t</em> is earlier than this time).
<p> Because QTime measures time within a day and there are 86400
seconds in a day, the result is always between -86400000 and
86400000 msec.
<p> <p>See also <a href="#secsTo">secsTo</a>().
<h3 class=fn>bool <a name="operator!-eq"></a>QTime::operator!= ( const <a href="qtime.html">QTime</a> & t ) const
</h3>
<p> Returns TRUE if this time is different from <em>t</em>; otherwise returns FALSE.
<h3 class=fn>bool <a name="operator-lt"></a>QTime::operator< ( const <a href="qtime.html">QTime</a> & t ) const
</h3>
<p> Returns TRUE if this time is earlier than <em>t</em>; otherwise returns FALSE.
<h3 class=fn>bool <a name="operator-lt-eq"></a>QTime::operator<= ( const <a href="qtime.html">QTime</a> & t ) const
</h3>
<p> Returns TRUE if this time is earlier than or equal to <em>t</em>;
otherwise returns FALSE.
<h3 class=fn>bool <a name="operator-eq-eq"></a>QTime::operator== ( const <a href="qtime.html">QTime</a> & t ) const
</h3>
<p> Returns TRUE if this time is equal to <em>t</em>; otherwise returns FALSE.
<h3 class=fn>bool <a name="operator-gt"></a>QTime::operator> ( const <a href="qtime.html">QTime</a> & t ) const
</h3>
<p> Returns TRUE if this time is later than <em>t</em>; otherwise returns FALSE.
<h3 class=fn>bool <a name="operator-gt-eq"></a>QTime::operator>= ( const <a href="qtime.html">QTime</a> & t ) const
</h3>
<p> Returns TRUE if this time is later than or equal to <em>t</em>;
otherwise returns FALSE.
<h3 class=fn>int <a name="restart"></a>QTime::restart ()
</h3>
Sets this time to the current time and returns the number of
milliseconds that have elapsed since the last time <a href="#start">start</a>() or
<a href="#restart">restart</a>() was called.
<p> This function is guaranteed to be atomic and is thus very handy
for repeated measurements. Call start() to start the first
measurement and then restart() for each later measurement.
<p> Note that the counter wraps to zero 24 hours after the last call
to start() or restart().
<p> <b>Warning:</b> If the system's clock setting has been changed since the
last time start() or restart() was called, the result is
undefined. This can happen when daylight savings time is turned on
or off.
<p> <p>See also <a href="#start">start</a>(), <a href="#elapsed">elapsed</a>(), and <a href="#currentTime">currentTime</a>().
<h3 class=fn>int <a name="second"></a>QTime::second () const
</h3>
Returns the second part (0..59) of the time.
<p>Example: <a href="tictac-example.html#x43">tictac/tictac.cpp</a>.
<h3 class=fn>int <a name="secsTo"></a>QTime::secsTo ( const <a href="qtime.html">QTime</a> & t ) const
</h3>
Returns the number of seconds from this time to <em>t</em> (which is
negative if <em>t</em> is earlier than this time).
<p> Because QTime measures time within a day and there are 86400
seconds in a day, the result is always between -86400 and 86400.
<p> <p>See also <a href="#addSecs">addSecs</a>() and <a href="qdatetime.html#secsTo">QDateTime::secsTo</a>().
<p>Example: <a href="tutorial1-12.html#x2399">t12/cannon.cpp</a>.
<h3 class=fn>bool <a name="setHMS"></a>QTime::setHMS ( int h, int m, int s, int ms = 0 )
</h3>
Sets the time to hour <em>h</em>, minute <em>m</em>, seconds <em>s</em> and
milliseconds <em>ms</em>.
<p> <em>h</em> must be in the range 0..23, <em>m</em> and <em>s</em> must be in the
range 0..59, and <em>ms</em> must be in the range 0..999. Returns TRUE
if the set time is valid; otherwise returns FALSE.
<p> <p>See also <a href="#isValid">isValid</a>().
<h3 class=fn>void <a name="start"></a>QTime::start ()
</h3>
Sets this time to the current time. This is practical for timing:
<p> <pre>
QTime t;
t.<a href="#start">start</a>();
some_lengthy_task();
<a href="qapplication.html#qDebug">qDebug</a>( "Time elapsed: %d ms", t.<a href="#elapsed">elapsed</a>() );
</pre>
<p> <p>See also <a href="#restart">restart</a>(), <a href="#elapsed">elapsed</a>(), and <a href="#currentTime">currentTime</a>().
<h3 class=fn><a href="qstring.html">QString</a> <a name="toString"></a>QTime::toString ( const <a href="qstring.html">QString</a> & format ) const
</h3>
Returns the time as a string. The <em>format</em> parameter determines
the format of the result string.
<p> These expressions may be used:
<p> <center><table cellpadding="4" cellspacing="2" border="0">
<tr bgcolor="#a2c511"> <th valign="top">Expression <th valign="top">Output
<tr bgcolor="#f0f0f0"> <td valign="top">h
<td valign="top">the hour without a leading zero (0..23 or 1..12 if AM/PM display)
<tr bgcolor="#d0d0d0"> <td valign="top">hh
<td valign="top">the hour with a leading zero (00..23 or 01..12 if AM/PM display)
<tr bgcolor="#f0f0f0"> <td valign="top">m <td valign="top">the minute without a leading zero (0..59)
<tr bgcolor="#d0d0d0"> <td valign="top">mm <td valign="top">the minute with a leading zero (00..59)
<tr bgcolor="#f0f0f0"> <td valign="top">s <td valign="top">the second whithout a leading zero (0..59)
<tr bgcolor="#d0d0d0"> <td valign="top">ss <td valign="top">the second whith a leading zero (00..59)
<tr bgcolor="#f0f0f0"> <td valign="top">z <td valign="top">the milliseconds without leading zeroes (0..999)
<tr bgcolor="#d0d0d0"> <td valign="top">zzz <td valign="top">the milliseconds with leading zeroes (000..999)
<tr bgcolor="#f0f0f0"> <td valign="top">AP
<td valign="top">use AM/PM display. <em>AP</em> will be replaced by either "AM" or "PM".
<tr bgcolor="#d0d0d0"> <td valign="top">ap
<td valign="top">use am/pm display. <em>ap</em> will be replaced by either "am" or "pm".
</table></center>
<p> All other input characters will be ignored.
<p> Example format strings (assuming that the QTime is 14:13:09.042)
<p> <center><table cellpadding="4" cellspacing="2" border="0">
<tr bgcolor="#a2c511"> <th valign="top">Format <th valign="top">Result
<tr bgcolor="#f0f0f0"> <td valign="top">hh:mm:ss.zzz <td valign="top" colspan="1" rowspan="1"> 14:13:09.042
<tr bgcolor="#d0d0d0"> <td valign="top">h:m:s ap <td valign="top" colspan="1" rowspan="1"> 2:13:9 pm
</table></center>
<p> If the time is an invalid time, then <a href="qstring.html#QString-null">QString::null</a> will be returned.
<p> <p>See also <a href="qdate.html#toString">QDate::toString</a>() and <a href="qdatetime.html#toString">QDateTime::toString</a>().
<h3 class=fn><a href="qstring.html">QString</a> <a name="toString-2"></a>QTime::toString ( <a href="qt.html#DateFormat-enum">Qt::DateFormat</a> f = Qt::TextDate ) const
</h3>
This is an overloaded member function, provided for convenience. It behaves essentially like the above function.
<p> Returns the time as a string. Milliseconds are not included. The
<em>f</em> parameter determines the format of the string.
<p> If <em>f</em> is <a href="qt.html#DateFormat-enum">Qt::TextDate</a>, the string format is HH:MM:SS; e.g. 1
second before midnight would be "23:59:59".
<p> If <em>f</em> is <a href="qt.html#DateFormat-enum">Qt::ISODate</a>, the string format corresponds to the
ISO 8601 extended specification for representations of dates,
which is also HH:MM:SS.
<p> If <em>f</em> is Qt::LocalDate, the string format depends on the locale
settings of the system.
<p> If the time is an invalid time, then <a href="qstring.html#QString-null">QString::null</a> will be returned.
<hr><h2>Related Functions</h2>
<h3 class=fn><a href="qdatastream.html">QDataStream</a> & <a name="operator-lt-lt"></a>operator<< ( <a href="qdatastream.html">QDataStream</a> & s, const <a href="qtime.html">QTime</a> & t )
</h3>
<p> Writes time <em>t</em> to the stream <em>s</em>.
<p> <p>See also <a href="datastreamformat.html">Format of the QDataStream operators</a>.
<h3 class=fn><a href="qdatastream.html">QDataStream</a> & <a name="operator-gt-gt"></a>operator>> ( <a href="qdatastream.html">QDataStream</a> & s, <a href="qtime.html">QTime</a> & t )
</h3>
<p> Reads a time from the stream <em>s</em> into <em>t</em>.
<p> <p>See also <a href="datastreamformat.html">Format of the QDataStream operators</a>.
<!-- eof -->
<hr><p>
This file is part of the <a href="index.html">Qt toolkit</a>.
Copyright © 1995-2007
<a href="http://www.trolltech.com/">Trolltech</a>. All Rights Reserved.<p><address><hr><div align=center>
<table width=100% cellspacing=0 border=0><tr>
<td>Copyright © 2007
<a href="troll.html">Trolltech</a><td align=center><a href="trademarks.html">Trademarks</a>
<td align=right><div align=right>Qt 3.3.8</div>
</table></div></address></body>
</html>
|
OS2World/LIB-QT3_Toolkit_Vbox
|
doc/html/qtime.html
|
HTML
|
gpl-2.0
| 21,834
|
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef AGS_METAENGINE_H
#define AGS_METAENGINE_H
#include "common/achievements.h"
#include "engines/advancedDetector.h"
class AGSMetaEngine : public AdvancedMetaEngine {
public:
const char *getName() const override;
Common::Error createInstance(OSystem *syst, Engine **engine, const ADGameDescription *desc) const override;
SaveStateList listSaves(const char *target) const override;
int getAutosaveSlot() const override {
return 0;
}
int getMaximumSaveSlot() const override {
return 998;
}
/**
* Return the name of the save file for the given slot and optional target,
* or a pattern for matching filenames against.
*
* @param saveGameIdx Index of the save, or kSavegameFilePattern
* for returning a filename pattern.
* @param target Game target. If omitted, then the engine ID is used.
*/
Common::String getSavegameFile(int saveGameIdx, const char *target = nullptr) const override;
GUI::OptionsContainerWidget *buildEngineOptionsWidgetDynamic(GUI::GuiObject *boss, const Common::String &name, const Common::String &target) const override;
/**
* Determine whether the engine supports the specified MetaEngine feature.
*
* Used by e.g. the launcher to determine whether to enable the Load button.
*/
bool hasFeature(MetaEngineFeature f) const override;
/**
* Return meta information from the specified save state.
*
* Depending on the MetaEngineFeatures set, this can include
* thumbnails, save date and time, play time.
*
* @param target Name of a config manager target.
* @param slot Slot number of the save state.
*/
SaveStateDescriptor querySaveMetaInfos(const char *target, int slot) const override;
/**
* Remove the specified save state.
*
* @param target Name of a config manager target.
* @param slot Slot number of the save state to be removed.
*/
void removeSaveState(const char *target, int slot) const override;
const Common::AchievementDescriptionList* getAchievementDescriptionList() const override;
};
#endif
|
vanfanel/scummvm
|
engines/ags/metaengine.h
|
C
|
gpl-2.0
| 2,992
|
/* Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/err.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/irqdomain.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_platform.h>
#include <linux/memory.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/krait-regulator.h>
#include <linux/msm_tsens.h>
#include <linux/msm_thermal.h>
#include <asm/mach/map.h>
#include <asm/hardware/gic.h>
#include <asm/mach/map.h>
#include <asm/mach/arch.h>
#include <mach/board.h>
#include <mach/gpiomux.h>
#include <mach/msm_iomap.h>
#ifdef CONFIG_ION_MSM
#include <mach/ion.h>
#endif
#include <mach/msm_memtypes.h>
#include <mach/msm_smd.h>
#include <mach/restart.h>
#include <mach/rpm-smd.h>
#include <mach/rpm-regulator-smd.h>
#include <mach/socinfo.h>
#include <mach/msm_smem.h>
#include "../board-dt.h"
#include "../clock.h"
#include "../devices.h"
#include "../spm.h"
#include "../pm.h"
#include "../modem_notifier.h"
#include "../platsmp.h"
#include <mach/board_lge.h>
#ifdef CONFIG_MACH_MSM8974_G2_VZW
#include <linux/platform_data/lge_android_usb.h>
#endif
static struct memtype_reserve msm8974_reserve_table[] __initdata = {
[MEMTYPE_SMI] = {
},
[MEMTYPE_EBI0] = {
.flags = MEMTYPE_FLAGS_1M_ALIGN,
},
[MEMTYPE_EBI1] = {
.flags = MEMTYPE_FLAGS_1M_ALIGN,
},
};
static int msm8974_paddr_to_memtype(phys_addr_t paddr)
{
return MEMTYPE_EBI1;
}
static struct reserve_info msm8974_reserve_info __initdata = {
.memtype_reserve_table = msm8974_reserve_table,
.paddr_to_memtype = msm8974_paddr_to_memtype,
};
void __init msm_8974_reserve(void)
{
reserve_info = &msm8974_reserve_info;
of_scan_flat_dt(dt_scan_for_memory_reserve, msm8974_reserve_table);
#ifdef CONFIG_MACH_LGE
of_scan_flat_dt(lge_init_dt_scan_chosen, NULL);
#endif
msm_reserve();
lge_reserve();
}
static void __init msm8974_early_memory(void)
{
reserve_info = &msm8974_reserve_info;
of_scan_flat_dt(dt_scan_for_memory_hole, msm8974_reserve_table);
}
#ifdef CONFIG_LGE_LCD_TUNING
static struct platform_device lcd_misc_device = {
.name = "lcd_misc_msm",
.id = 0,
};
void __init lge_add_lcd_misc_devices(void)
{
platform_device_register(&lcd_misc_device);
}
#endif
#ifdef CONFIG_MACH_MSM8974_G2_VZW
struct lge_android_usb_platform_data lge_android_usb_pdata = {
.vendor_id = 0x1004,
.factory_pid = 0x6000,
.iSerialNumber = 0,
.product_name = "LGE Android Phone",
.manufacturer_name = "LG Electronics Inc.",
.factory_composition = "acm,diag",
};
struct platform_device lge_android_usb_device = {
.name = "lge_android_usb",
.id = -1,
.dev = {
.platform_data = &lge_android_usb_pdata,
},
};
void __init lge_add_android_usb_devices(void)
{
platform_device_register(&lge_android_usb_device);
}
#endif /* CONFIG_MACH_MSM8974_G2_VZW */
/*
* Used to satisfy dependencies for devices that need to be
* run early or in a particular order. Most likely your device doesn't fall
* into this category, and thus the driver should not be added here. The
* EPROBE_DEFER can satisfy most dependency problems.
*/
/* */
#if defined(CONFIG_BCMDHD) || defined(CONFIG_BCMDHD_MODULE)
extern void init_bcm_wifi(void);
#endif
/* */
void __init msm8974_add_drivers(void)
{
msm_smem_init();
msm_init_modem_notifier_list();
msm_smd_init();
msm_rpm_driver_init();
msm_pm_sleep_status_init();
rpm_regulator_smd_driver_init();
msm_spm_device_init();
krait_power_init();
if (of_board_is_rumi())
msm_clock_init(&msm8974_rumi_clock_init_data);
else
msm_clock_init(&msm8974_clock_init_data);
tsens_tm_init_driver();
msm_thermal_device_init();
#ifdef CONFIG_LGE_LCD_TUNING
lge_add_lcd_misc_devices();
#endif
lge_add_persistent_device();
#ifdef CONFIG_LGE_QFPROM_INTERFACE
lge_add_qfprom_devices();
#endif
#ifdef CONFIG_LGE_ECO_MODE
lge_add_lge_kernel_devices();
#endif
#ifdef CONFIG_LGE_DIAG_ENABLE_SYSFS
lge_add_diag_devices();
#endif
#ifdef CONFIG_MACH_MSM8974_G2_VZW
lge_add_android_usb_devices();
#endif
/* */
#if defined(CONFIG_BCMDHD) || defined(CONFIG_BCMDHD_MODULE)
init_bcm_wifi();
#endif
/* */
}
static struct of_dev_auxdata msm_hsic_host_adata[] = {
OF_DEV_AUXDATA("qcom,hsic-host", 0xF9A00000, "msm_hsic_host", NULL),
{}
};
static struct of_dev_auxdata msm8974_auxdata_lookup[] __initdata = {
OF_DEV_AUXDATA("qcom,hsusb-otg", 0xF9A55000, \
"msm_otg", NULL),
OF_DEV_AUXDATA("qcom,ehci-host", 0xF9A55000, \
"msm_ehci_host", NULL),
OF_DEV_AUXDATA("qcom,dwc-usb3-msm", 0xF9200000, \
"msm_dwc3", NULL),
OF_DEV_AUXDATA("qcom,usb-bam-msm", 0xF9304000, \
"usb_bam", NULL),
OF_DEV_AUXDATA("qcom,spi-qup-v2", 0xF9924000, \
"spi_qsd.1", NULL),
OF_DEV_AUXDATA("qcom,msm-sdcc", 0xF9824000, \
"msm_sdcc.1", NULL),
OF_DEV_AUXDATA("qcom,msm-sdcc", 0xF98A4000, \
"msm_sdcc.2", NULL),
OF_DEV_AUXDATA("qcom,msm-sdcc", 0xF9864000, \
"msm_sdcc.3", NULL),
OF_DEV_AUXDATA("qcom,msm-sdcc", 0xF98E4000, \
"msm_sdcc.4", NULL),
OF_DEV_AUXDATA("qcom,sdhci-msm", 0xF9824900, \
"msm_sdcc.1", NULL),
OF_DEV_AUXDATA("qcom,sdhci-msm", 0xF98A4900, \
"msm_sdcc.2", NULL),
OF_DEV_AUXDATA("qcom,sdhci-msm", 0xF9864900, \
"msm_sdcc.3", NULL),
OF_DEV_AUXDATA("qcom,sdhci-msm", 0xF98E4900, \
"msm_sdcc.4", NULL),
OF_DEV_AUXDATA("qcom,msm-rng", 0xF9BFF000, \
"msm_rng", NULL),
OF_DEV_AUXDATA("qcom,qseecom", 0xFE806000, \
"qseecom", NULL),
OF_DEV_AUXDATA("qcom,mdss_mdp", 0xFD900000, "mdp.0", NULL),
OF_DEV_AUXDATA("qcom,msm-tsens", 0xFC4A8000, \
"msm-tsens", NULL),
OF_DEV_AUXDATA("qcom,qcedev", 0xFD440000, \
"qcedev.0", NULL),
OF_DEV_AUXDATA("qcom,qcrypto", 0xFD440000, \
"qcrypto.0", NULL),
OF_DEV_AUXDATA("qcom,hsic-host", 0xF9A00000, \
"msm_hsic_host", NULL),
OF_DEV_AUXDATA("qcom,hsic-smsc-hub", 0, "msm_smsc_hub",
msm_hsic_host_adata),
{}
};
static void __init msm8974_map_io(void)
{
msm_map_8974_io();
}
void __init msm8974_init(void)
{
struct of_dev_auxdata *adata = msm8974_auxdata_lookup;
if (socinfo_init() < 0)
pr_err("%s: socinfo_init() failed\n", __func__);
msm_8974_init_gpiomux();
regulator_has_full_constraints();
board_dt_populate(adata);
msm8974_add_drivers();
}
void __init msm8974_init_very_early(void)
{
msm8974_early_memory();
}
static const char *msm8974_dt_match[] __initconst = {
"qcom,msm8974",
"qcom,apq8074",
NULL
};
DT_MACHINE_START(MSM8974_DT, "Qualcomm MSM 8974 (Flattened Device Tree)")
.map_io = msm8974_map_io,
.init_irq = msm_dt_init_irq,
.init_machine = msm8974_init,
.handle_irq = gic_handle_irq,
.timer = &msm_dt_timer,
.dt_compat = msm8974_dt_match,
.reserve = msm_8974_reserve,
.init_very_early = msm8974_init_very_early,
.restart = msm_restart,
.smp = &msm8974_smp_ops,
MACHINE_END
|
lawnn/Dorimanx-LG-G2-D802-Kernel
|
arch/arm/mach-msm/lge/board-8974-g2-us.c
|
C
|
gpl-2.0
| 7,474
|
/*
* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
Name: Boss_Vazruden_the_Herald
%Complete: 90
Comment:
Category: Hellfire Citadel, Hellfire Ramparts
EndScriptData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "SpellInfo.h"
#include "hellfire_ramparts.h"
enum Says
{
SAY_INTRO = 0,
SAY_WIPE = 0,
SAY_AGGRO = 1,
SAY_KILL = 2,
SAY_DIE = 3,
EMOTE = 0
};
enum Spells
{
SPELL_FIREBALL = 34653,
SPELL_FIREBALL_H = 36920,
SPELL_CONE_OF_FIRE = 30926,
SPELL_CONE_OF_FIRE_H = 36921,
SPELL_SUMMON_LIQUID_FIRE = 23971,
SPELL_SUMMON_LIQUID_FIRE_H = 30928,
SPELL_BELLOWING_ROAR = 39427,
SPELL_REVENGE = 19130,
SPELL_REVENGE_H = 40392,
SPELL_KIDNEY_SHOT = 30621,
SPELL_FIRE_NOVA_VISUAL = 19823
};
const float VazrudenMiddle[3] = { -1406.5f, 1746.5f, 81.2f };
const float VazrudenRing[2][3] =
{
{ -1430.0f, 1705.0f, 112.0f },
{ -1377.0f, 1760.0f, 112.0f }
};
class boss_nazan : public CreatureScript
{
public:
boss_nazan() : CreatureScript("boss_nazan") { }
struct boss_nazanAI : public BossAI
{
boss_nazanAI(Creature* creature) : BossAI(creature, DATA_NAZAN)
{
VazrudenGUID = 0;
flight = true;
}
void Reset() override
{
Fireball_Timer = 4000;
Fly_Timer = 45000;
Turn_Timer = 0;
}
void EnterCombat(Unit* /*who*/) override { }
void IsSummonedBy(Unit* summoner) override
{
if (summoner->GetEntry() == NPC_VAZRUDEN_HERALD)
VazrudenGUID = summoner->GetGUID();
}
void JustSummoned(Creature* summoned) override
{
if (summoned && summoned->GetEntry() == NPC_LIQUID_FIRE)
{
summoned->SetLevel(me->getLevel());
summoned->setFaction(me->getFaction());
summoned->CastSpell(summoned, DUNGEON_MODE(SPELL_SUMMON_LIQUID_FIRE, SPELL_SUMMON_LIQUID_FIRE_H), true);
summoned->CastSpell(summoned, SPELL_FIRE_NOVA_VISUAL, true);
}
}
void SpellHitTarget(Unit* target, const SpellInfo* entry) override
{
if (target && entry->Id == uint32(SPELL_FIREBALL))
me->SummonCreature(NPC_LIQUID_FIRE, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation(), TEMPSUMMON_TIMED_DESPAWN, 30000);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
if (Fireball_Timer <= diff)
{
if (Unit* victim = SelectTarget(SELECT_TARGET_RANDOM, 0))
DoCast(victim, DUNGEON_MODE(SPELL_FIREBALL, SPELL_FIREBALL_H), true);
Fireball_Timer = urand(4000, 7000);
}
else
Fireball_Timer -= diff;
if (flight) // phase 1 - the flight
{
Creature* Vazruden = Unit::GetCreature(*me, VazrudenGUID);
if (Fly_Timer < diff || !(Vazruden && Vazruden->IsAlive() && Vazruden->HealthAbovePct(20)))
{
flight = false;
BellowingRoar_Timer = 6000;
ConeOfFire_Timer = 12000;
me->SetDisableGravity(false);
me->SetWalk(true);
me->GetMotionMaster()->Clear();
if (Unit* victim = SelectTarget(SELECT_TARGET_NEAREST, 0))
AttackStart(victim);
DoStartMovement(me->GetVictim());
Talk(EMOTE);
return;
}
else
Fly_Timer -= diff;
if (Turn_Timer <= diff)
{
uint32 waypoint = (Fly_Timer/10000)%2;
if (!me->IsWithinDist3d(VazrudenRing[waypoint][0], VazrudenRing[waypoint][1], VazrudenRing[waypoint][2], 5))
me->GetMotionMaster()->MovePoint(0, VazrudenRing[waypoint][0], VazrudenRing[waypoint][1], VazrudenRing[waypoint][2]);
Turn_Timer = 10000;
}
else
Turn_Timer -= diff;
}
else // phase 2 - land fight
{
if (ConeOfFire_Timer <= diff)
{
DoCast(me, DUNGEON_MODE(SPELL_CONE_OF_FIRE, SPELL_CONE_OF_FIRE_H));
ConeOfFire_Timer = 12000;
Fireball_Timer = 4000;
}
else
ConeOfFire_Timer -= diff;
if (IsHeroic())
{
if (BellowingRoar_Timer <= diff)
{
DoCast(me, SPELL_BELLOWING_ROAR);
BellowingRoar_Timer = 45000;
}
else
BellowingRoar_Timer -= diff;
}
DoMeleeAttackIfReady();
}
}
private:
uint32 Fireball_Timer;
uint32 ConeOfFire_Timer;
uint32 BellowingRoar_Timer;
uint32 Fly_Timer;
uint32 Turn_Timer;
bool flight;
uint64 VazrudenGUID;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new boss_nazanAI(creature);
}
};
class boss_vazruden : public CreatureScript
{
public:
boss_vazruden() : CreatureScript("boss_vazruden") { }
struct boss_vazrudenAI : public BossAI
{
boss_vazrudenAI(Creature* creature) : BossAI(creature, DATA_VAZRUDEN) { }
void Reset() override
{
Revenge_Timer = 4000;
UnsummonCheck = 2000;
WipeSaid = false;
_Reset();
}
void EnterCombat(Unit* /*who*/) override
{
Talk(SAY_AGGRO);
_EnterCombat();
}
void KilledUnit(Unit* who) override
{
if (who && who->GetEntry() != NPC_VAZRUDEN)
Talk(SAY_KILL);
}
void JustDied(Unit* killer) override
{
if (killer && killer != me)
Talk(SAY_DIE);
_JustDied();
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
{
if (UnsummonCheck < diff && me->IsAlive())
{
if (!WipeSaid)
{
Talk(SAY_WIPE);
WipeSaid = true;
}
me->DisappearAndDie();
}
else
UnsummonCheck -= diff;
return;
}
if (Revenge_Timer <= diff)
{
if (Unit* victim = me->GetVictim())
DoCast(victim, DUNGEON_MODE(SPELL_REVENGE, SPELL_REVENGE_H));
Revenge_Timer = 5000;
}
else
Revenge_Timer -= diff;
DoMeleeAttackIfReady();
}
private:
uint32 Revenge_Timer;
bool WipeSaid;
uint32 UnsummonCheck;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new boss_vazrudenAI(creature);
}
};
class boss_vazruden_the_herald : public CreatureScript
{
public:
boss_vazruden_the_herald() : CreatureScript("boss_vazruden_the_herald") { }
struct boss_vazruden_the_heraldAI : public ScriptedAI
{
boss_vazruden_the_heraldAI(Creature* creature) : ScriptedAI(creature)
{
summoned = false;
sentryDown = false;
lootSpawned = false;
NazanGUID = 0;
VazrudenGUID = 0;
}
void Reset() override
{
phase = 0;
waypoint = 0;
check = 0;
UnsummonAdds();
}
void UnsummonAdds()
{
if (summoned)
{
Creature* Nazan = Unit::GetCreature(*me, NazanGUID);
if (!Nazan)
Nazan = me->FindNearestCreature(NPC_NAZAN, 5000);
if (Nazan)
{
Nazan->DisappearAndDie();
NazanGUID = 0;
}
Creature* Vazruden = Unit::GetCreature(*me, VazrudenGUID);
if (!Vazruden)
Vazruden = me->FindNearestCreature(NPC_VAZRUDEN, 5000);
if (Vazruden)
{
Vazruden->DisappearAndDie();
VazrudenGUID = 0;
}
summoned = false;
me->ClearUnitState(UNIT_STATE_ROOT);
me->SetVisible(true);
}
}
void SummonAdds()
{
if (!summoned)
{
if (Creature* Vazruden = me->SummonCreature(NPC_VAZRUDEN, VazrudenMiddle[0], VazrudenMiddle[1], VazrudenMiddle[2], 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 6000000))
VazrudenGUID = Vazruden->GetGUID();
if (Creature* Nazan = me->SummonCreature(NPC_NAZAN, VazrudenMiddle[0], VazrudenMiddle[1], VazrudenMiddle[2], 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 6000000))
NazanGUID = Nazan->GetGUID();
summoned = true;
me->SetVisible(false);
me->AddUnitState(UNIT_STATE_ROOT);
}
}
void EnterCombat(Unit* /*who*/) override
{
if (phase == 0)
{
phase = 1;
check = 0;
Talk(SAY_INTRO);
}
}
void JustSummoned(Creature* summoned) override
{
if (!summoned)
return;
Unit* victim = me->GetVictim();
if (summoned->GetEntry() == NPC_NAZAN)
{
summoned->SetDisableGravity(true);
summoned->SetSpeed(MOVE_FLIGHT, 2.5f);
if (victim)
AttackStartNoMove(victim);
}
else
if (victim)
summoned->AI()->AttackStart(victim);
}
void SentryDownBy(Unit* killer)
{
if (sentryDown)
{
AttackStartNoMove(killer);
sentryDown = false;
}
else
sentryDown = true;
}
void UpdateAI(uint32 diff) override
{
switch (phase)
{
case 0: // circle around the platform
return;
break;
case 1: // go to the middle and begin the fight
if (check <= diff)
{
if (!me->IsWithinDist3d(VazrudenMiddle[0], VazrudenMiddle[1], VazrudenMiddle[2], 5))
{
me->GetMotionMaster()->Clear();
me->GetMotionMaster()->MovePoint(0, VazrudenMiddle[0], VazrudenMiddle[1], VazrudenMiddle[2]);
check = 1000;
}
else
{
SummonAdds();
phase = 2;
return;
}
}
else
check -= diff;
break;
default: // adds do the job now
if (check <= diff)
{
Creature* Nazan = Unit::GetCreature(*me, NazanGUID);
Creature* Vazruden = Unit::GetCreature(*me, VazrudenGUID);
if ((Nazan && Nazan->IsAlive()) || (Vazruden && Vazruden->IsAlive()))
{
if ((Nazan && Nazan->GetVictim()) || (Vazruden && Vazruden->GetVictim()))
return;
else
{
UnsummonAdds();
EnterEvadeMode();
return;
}
}
else if (!lootSpawned)
{
me->SummonGameObject(DUNGEON_MODE(GO_FEL_IRON_CHEST_NORMAL, GO_FEL_IRON_CHECT_HEROIC), VazrudenMiddle[0], VazrudenMiddle[1], VazrudenMiddle[2], 0, 0, 0, 0, 0, 0);
me->SetLootRecipient(NULL); // don't think this is necessary..
//me->Kill(me);
lootSpawned = true;
}
check = 2000;
}
else
check -= diff;
break;
}
}
private:
uint32 phase;
uint32 waypoint;
uint32 check;
bool sentryDown;
uint64 NazanGUID;
uint64 VazrudenGUID;
bool summoned;
bool lootSpawned;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new boss_vazruden_the_heraldAI(creature);
}
};
class npc_hellfire_sentry : public CreatureScript
{
public:
npc_hellfire_sentry() : CreatureScript("npc_hellfire_sentry") { }
struct npc_hellfire_sentryAI : public ScriptedAI
{
npc_hellfire_sentryAI(Creature* creature) : ScriptedAI(creature) { }
void Reset() override
{
KidneyShot_Timer = urand(3000, 7000);
}
void EnterCombat(Unit* /*who*/) override { }
void JustDied(Unit* killer) override
{
if (Creature* herald = me->FindNearestCreature(NPC_VAZRUDEN_HERALD, 150))
CAST_AI(boss_vazruden_the_herald::boss_vazruden_the_heraldAI, herald->AI())->SentryDownBy(killer);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
if (KidneyShot_Timer <= diff)
{
if (Unit* victim = me->GetVictim())
DoCast(victim, SPELL_KIDNEY_SHOT);
KidneyShot_Timer = 20000;
}
else
KidneyShot_Timer -= diff;
DoMeleeAttackIfReady();
}
private:
uint32 KidneyShot_Timer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_hellfire_sentryAI(creature);
}
};
void AddSC_boss_vazruden_the_herald()
{
new boss_vazruden_the_herald();
new boss_vazruden();
new boss_nazan();
new npc_hellfire_sentry();
}
|
aikon-com-cn/InfinityCore
|
src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_vazruden_the_herald.cpp
|
C++
|
gpl-2.0
| 17,183
|
<font face="Verdana, Arial" size=3 color="#0000cc">
<b>Request for pathological lab test</b></font>
<p>
<font size=2 face="verdana,arial" >
<?php
if(!$src){
?>
<a name="sday"><img <?php echo createComIcon('../','frage.gif','0') ?>> <font color="#990000"><b></a>
The patient's label is not attached. What should I do?</b></font>
<ul>
<b>Step 1: </b>Enter either a full information or a few letters from a patient's information, like for example first name, or family name,
or the encounter number.
<p>Example 1: enter "21000012" or "12".
<br>Example 2: enter "Guerero" or "gue".
<br>Example 3: enter "Alfredo" or "Alf".<p>
<b>Step 2: </b>Click the <img <?php echo createLDImgSrc('../','searchlamp.gif','0') ?>> button to start searching. <p>
<b>Step 3: </b> If the search finds a result, select the right person from the displayed list by clicking its
<img <?php echo createLDImgSrc('../','ok_small.gif','0') ?>> button.
</ul>
<?php
}else{
?>
<a name="stime"><img <?php echo createComIcon('../','frage.gif','0') ?>> <font color="#990000"><b></a>
What to fill in the request form?</b></font>
<ul>
<b>The compulsory fields to fill in or check are:</b>
<ul>
<li>Type of specimen
<li>Description of specimen text box
<li>Date of operation
<li>Doctor or surgeon responsible for the request
</ul>
</ul>
<a name="send"><img <?php echo createComIcon('../','frage.gif','0') ?>> <font color="#990000"><b></a>
How to send the test request?</b></font>
<ul>
<b>Step: </b>Click the <img <?php echo createLDImgSrc('../','abschic.gif','0') ?>> button.
</ul>
<?php
}
?>
|
timschofield/care2x
|
help/sr/help_sr_request_patho.php
|
PHP
|
gpl-2.0
| 1,586
|
/*
*
* This source code is part of
*
* G R O M A C S
*
* GROningen MAchine for Chemical Simulations
*
* VERSION 3.2.0
* Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
* Copyright (c) 1991-2000, University of Groningen, The Netherlands.
* Copyright (c) 2001-2004, The GROMACS development team,
* check out http://www.gromacs.org for more information.
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* If you want to redistribute modifications, please consider that
* scientific software is very special. Version control is crucial -
* bugs must be traceable. We will be happy to consider code for
* inclusion in the official distribution, but derived work must not
* be called official GROMACS. Details are found in the README & COPYING
* files - if they are missing, get the official version at www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the papers on the package - you can find them in the top README file.
*
* For more info, check our website at http://www.gromacs.org
*
* And Hey:
* Gromacs Runs On Most of All Computer Systems
*/
#ifndef _warninp_h
#define _warninp_h
#include "typedefs.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Abstract type for warning bookkeeping */
typedef struct warninp *warninp_t;
warninp_t
init_warning(gmx_bool bAllowWarnings,int maxwarning);
/* Initialize the warning data structure.
* If bAllowWarnings=FALSE, all warnings (calls to warning()) will be
* transformed into errors, calls to warning_note still produce notes.
* maxwarning determines the maximum number of warnings that are allowed
* for proceeding. When this number is exceeded check_warning_error
* and done_warning will generate a fatal error.
* bAllowWarnings=TRUE should only be used by programs that have
* a -maxwarn command line option.
*/
void
set_warning_line(warninp_t wi,const char *fn,int line);
/* Set filename and linenumber for the warning */
int
get_warning_line(warninp_t wi);
/* Get linenumber for the warning */
const char *
get_warning_file(warninp_t wi);
/* Get filename for the warning */
void
warning(warninp_t wi,const char *s);
/* Issue a warning, with the string s. If s == NULL, then warn_buf
* will be printed instead. The file and line set by set_warning_line
* are printed, nwarn_warn (local) is incremented.
* A fatal error will be generated after processing the input
* when nwarn_warn is larger than maxwarning passed to init_warning.
* So warning should only be called for issues that should be resolved,
* otherwise warning_note should be called.
*/
void
warning_note(warninp_t wi,const char *s);
/* Issue a note, with the string s. If s == NULL, then warn_buf
* will be printed instead. The file and line set by set_warning_line
* are printed, nwarn_note (local) is incremented.
* This is for issues which could be a problem for some systems,
* but 100% ok for other systems.
*/
void
warning_error(warninp_t wi,const char *s);
/* Issue an error, with the string s. If s == NULL, then warn_buf
* will be printed instead. The file and line set by set_warning_line
* are printed, nwarn_error (local) is incremented.
*/
void
check_warning_error(warninp_t wi,int f_errno,const char *file,int line);
/* When warning_error has been called at least once gmx_fatal is called,
* otherwise does nothing.
*/
void
done_warning(warninp_t wi,int f_errno,const char *file,int line);
/* Should be called when finished processing the input file.
* Prints the number of notes and warnings
* and generates a fatal error when errors were found or too many
* warnings were generatesd.
* Frees the data structure pointed to by wi.
*/
void
_too_few(warninp_t wi,const char *fn,int line);
#define too_few(wi) _too_few(wi,__FILE__,__LINE__)
/* Issue a warning stating 'Too few parameters' */
void
_incorrect_n_param(warninp_t wi,const char *fn,int line);
#define incorrect_n_param(wi) _incorrect_n_param(wi,__FILE__,__LINE__)
/* Issue a warning stating 'Incorrect number of parameters' */
#ifdef __cplusplus
}
#endif
#endif /* _warninp_h */
|
tectronics/force-distribution-analysis.gromacs-4-5-3
|
include/warninp.h
|
C
|
gpl-2.0
| 4,406
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.4.2_09) on Sun Sep 04 19:19:00 CDT 2005 -->
<TITLE>
com.anji.tournament (ANJI API)
</TITLE>
<META NAME="keywords" CONTENT="com.anji.tournament package">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="com.anji.tournament (ANJI API)";
}
</SCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<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=3 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="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </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>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../com/anji/run/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../com/anji/ttt/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.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>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<H2>
Package com.anji.tournament
</H2>
<code>com.anji.tournament</code> contains classes to handle tournaments and games.
<P>
<B>See:</B>
<BR>
<A HREF="#package_description"><B>Description</B></A>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
<B>Interface Summary</B></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/Game.html" title="interface in com.anji.tournament">Game</A></B></TD>
<TD>Game does not carry state of a specific contest between two players.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/IteratedPlayer.html" title="interface in com.anji.tournament">IteratedPlayer</A></B></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/Player.html" title="interface in com.anji.tournament">Player</A></B></TD>
<TD>Abstract player interface.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/PlayerTranscriber.html" title="interface in com.anji.tournament">PlayerTranscriber</A></B></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/Tournament.html" title="interface in com.anji.tournament">Tournament</A></B></TD>
<TD>Abstract class that manages a list of players, has them play each other in matches, and
returns the results.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
<B>Class Summary</B></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/Bracket.html" title="class in com.anji.tournament">Bracket</A></B></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/CompositeTournament.html" title="class in com.anji.tournament">CompositeTournament</A></B></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/DirectTournament.html" title="class in com.anji.tournament">DirectTournament</A></B></TD>
<TD>Each contestant plays 1 game against each opponent.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/DoubleEliminationTournament.html" title="class in com.anji.tournament">DoubleEliminationTournament</A></B></TD>
<TD>Standard double elimination tournament, except players are re-seeded after every round.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/GameConfiguration.html" title="class in com.anji.tournament">GameConfiguration</A></B></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/GameResults.html" title="class in com.anji.tournament">GameResults</A></B></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/IteratedGame.html" title="class in com.anji.tournament">IteratedGame</A></B></TD>
<TD>This is a game composed of iterating over a component game.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/KRandomOppsTournament.html" title="class in com.anji.tournament">KRandomOppsTournament</A></B></TD>
<TD>Each subject plays at least <i>k </i> games against a random set of opponents.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/PlayerResults.html" title="class in com.anji.tournament">PlayerResults</A></B></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/PlayerResultsScoreComparator.html" title="class in com.anji.tournament">PlayerResultsScoreComparator</A></B></TD>
<TD>Sorts <code>PlayerResult</code> objects in descending order of score.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/PlayerStats.html" title="class in com.anji.tournament">PlayerStats</A></B></TD>
<TD>Collates win-loss-tie results.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/ScoringWeights.html" title="class in com.anji.tournament">ScoringWeights</A></B></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/SimpleTournament.html" title="class in com.anji.tournament">SimpleTournament</A></B></TD>
<TD>Abstract class that manages a list of <code>Player</code> contestants, has them play each
other in matches, and packages the results.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/SingleEliminationTournament.html" title="class in com.anji.tournament">SingleEliminationTournament</A></B></TD>
<TD>Standard double elimination tournament, except players are re-seeded after every round.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/TournamentFitnessFunction.html" title="class in com.anji.tournament">TournamentFitnessFunction</A></B></TD>
<TD>Fitness function in which chromosomes are evaluated by their phenotypes playing a set of
matches.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../com/anji/tournament/TournamentPlayerResults.html" title="class in com.anji.tournament">TournamentPlayerResults</A></B></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="package_description"><!-- --></A><H2>
Package com.anji.tournament Description
</H2>
<P>
<code>com.anji.tournament</code> contains classes to handle tournaments and games.
A <code>Tournament</code> is a series of matches between a population of
<code>Player</code> objects, where the particular tournament logic determines who
plays whom, and how many times. A <code>Game</code> is an individual contest between
two players. <code>Game</code> and <code>IteratedGame</code> form a
<a href="http://www.javaworld.com/javaworld/jw-09-2002/jw-0913-designpatterns.html">composite</a>
design pattern. An <code>IteratedGame</code> might represent a match, or a series of
trials, or any hierarchy of contests and sub-contests.
<code>TournamentFitnessFunction</code> ties this all to the genetic algorithm
framework.
<P>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<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=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_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="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </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>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../com/anji/run/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../com/anji/ttt/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.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>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
|
RaeveSpam/ANJIProject
|
docs/javadoc/com/anji/tournament/package-summary.html
|
HTML
|
gpl-2.0
| 12,300
|
<?Php
/******************************************/
/* FECHA: 13/08/2007 */
/* AUTOR: ING. ZULHEYMAR RODRÍGUEZ */
/******************************************/
session_start();
require_once("sigesp_sfc_c_reportes.php");
$reporte = new sigesp_sfc_c_reportes('LETTER','portrait','REPORTE 1');
$io_pdf = new class_pdf('LETTER','portrait');
$io_pdf->selectFont('../../../shared/ezpdf/fonts/Helvetica.afm');
$io_pdf->set_margenes(10,10,10,10);
require_once("../../shared/class_folder/sigesp_include.php");
require_once("../../shared/class_folder/class_mensajes.php");
require_once("../../shared/class_folder/class_sql.php");
require_once("../../shared/class_folder/class_funciones.php");
require_once("../../shared/class_folder/class_datastore.php");
require_once("../../shared/class_folder/class_fecha.php");
$io_fecha=new class_fecha();
$io_datastore= new class_datastore();
$io_include=new sigesp_include();
$io_connect=$io_include->uf_conectar();
$io_msg=new class_mensajes();
$io_sql=new class_sql($io_connect);
$io_data=new class_datastore();
$io_funcion=new class_funciones();
$io_pdf = $reporte->get_pdf();
$io_pdf->numerar_paginas(6);
$reporte->add_titulo("center",10,11,"PEDIDO DE ARTICULOS");
$ls_sql=$_GET["sql"];
$ls_sql=str_replace("\\","",$ls_sql);
$ls_sql=str_replace("/","",$ls_sql);
$rs_datauni=$io_sql->select($ls_sql);
if($rs_datauni==false&&($io_sql->message!=""))
{
$io_msg->message("No hay registros");
}
else
{
$la_pedido=$io_sql->obtener_datos($rs_datauni);
}
$reporte->add_titulo("right",25,7,"No. ".$la_pedido["numpedido"][1]);
$ls_fecha="".substr($la_pedido["fecpedido"][1],8,2)."/".substr($la_pedido["fecpedido"][1],5,2)."/".substr($la_pedido["fecpedido"][1],0,4)."";
$reporte->add_titulo("right",28,7,"Fecha: ".$ls_fecha);
$reporte->add_titulo("left",34,7,"Agrotienda: ".$la_pedido["dentie"][1]);
$reporte->add_titulo("left",37,7,"Unidad Ejecutora: ".$la_pedido["coduniadm"][1]." ".$la_pedido["denuniadm"][1]);
$reporte->add_titulo("left",41,7,"Dirección: ".$la_pedido["dirtie"][1]);
$reporte->add_titulo("right",47,7,"Asesor: ".$la_pedido["nomusu"][1]);
$reporte->add_titulo("left",44,7,"Teléfonos: ".$la_pedido["teltie"][1]);
$reporte->add_titulo("left",47,7,"Rif: ".$la_pedido["riftie"][1]);
$li_cuotas=(count($la_pedido,COUNT_RECURSIVE)/count($la_pedido)) - 1;
$la_total=0;
$la_iva=0;
for($i=0;$i<$li_cuotas;$i++)
{
$la_datos[$i]["<b>Código</b>"]= $la_pedido["codart"][$i+1];
$la_datos[$i]["<b>Descripción</b>"]= $la_pedido["denart"][$i+1];
$la_datos[$i]["<b>Cantidad</b>"]= number_format($la_pedido["cantped"][$i+1],2, ',', '.');
}
$io_pdf->ezSetY(550);
$la_anchos_col = array(35,80,20,20,20);
$la_justificaciones = array('center','left','right','right','right');
$la_opciones = array( "color_fondo" => array(229,229,229),
"color_texto" => array(0,0,0),
"anchos_col" => $la_anchos_col,
"tamano_texto"=> 7,
"lineas"=>1,
"alineacion_col"=>$la_justificaciones,
"margen_horizontal"=>1);
$io_pdf->add_tabla(15,$la_datos,$la_opciones);
$reporte->add_titulo("left",215,6,"OBSERVACIÓN: ".$la_pedido["obspedido"][1]);
$io_pdf->ezStream();
?>
|
omerta/huayra
|
sfc/reportes/sigesp_sfc_rep_pedido.php
|
PHP
|
gpl-2.0
| 3,426
|
/*
* recordables_map.h
*
* This file is part of NEST.
*
* Copyright (C) 2004 The NEST Initiative
*
* NEST is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* NEST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with NEST. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef RECORDABLES_MAP_H
#define RECORDABLES_MAP_H
// C++ includes:
#include <cassert>
#include <map>
#include <string>
#include <utility>
// Includes from nestkernel:
#include "nest_types.h"
// Includes from sli:
#include "arraydatum.h"
#include "name.h"
namespace nest
{
/**
* Map names of recordables to data access functions.
*
* This map identifies the data access functions for recordable
* state variables in model neurons.
* Each neuron model shall have exactly one static instance
* of RecordablesMap.
*
* @note The map is initialized by the create() member function
* and not by the constructor because of the following
* conflict: The recordablesMap_ shall be a private static
* member of its host class, since the same map applies
* to all objects. Creation by a constructor leads to static
* initialization conflicts with the Name class. Thus,
* creation is deferred to the plain constructor of the host
* Node class, which is called only once to create the
* model prototype instance.
*
* @see multimeter, UniversalDataLogger
* @ingroup Devices
*/
template < typename HostNode >
class RecordablesMap : public std::map< Name, double ( HostNode::* )() const >
{
typedef std::map< Name, double ( HostNode::* )() const > Base_;
public:
virtual ~RecordablesMap()
{
}
//! Datatype for access functions
typedef double ( HostNode::*DataAccessFct )() const;
/**
* Create the map.
* This function must be specialized for each class owning a
* Recordables map and must fill the map. This should happen
* as part of the original constructor for the Node.
*/
void create();
/**
* Obtain SLI list of all recordables, for use by get_status().
* @todo This fct should return the recordables_ entry, but since
* filling recordables_ leads to seg fault on exit, we just
* build the list every time, even though that beats the
* goal of being more efficient ...
*/
ArrayDatum
get_list() const
{
ArrayDatum recordables;
for ( typename Base_::const_iterator it = this->begin(); it != this->end();
++it )
{
recordables.push_back( new LiteralDatum( it->first ) );
}
return recordables;
// the entire function should just be
// return recordables_;
}
private:
//! Insertion functions to be used in create(), adds entry to map and list
void
insert_( const Name& n, const DataAccessFct f )
{
Base_::insert( std::make_pair( n, f ) );
// Line below leads to seg-fault if nest is quit right after start,
// see comment on get_list()
// recordables_.push_back(LiteralDatum(n));
}
/**
* SLI list of names of recordables
* @todo Once the segfault-on-exit issue mentioned in the comment on
* get_list() is resolved, the next code line should be activated again.
*
*/
// ArrayDatum recordables_;
};
template < typename HostNode >
void
RecordablesMap< HostNode >::create()
{
assert( false );
}
//! Class that reads out state vector elements, used by UniversalDataLogger
template < typename HostNode >
class DataAccessFunctor
{
// Pointer instead of reference required to avoid problems with
// copying element in std::map when using libc++ under C++11.
HostNode* parent_;
size_t elem_;
public:
DataAccessFunctor( HostNode& n, size_t elem )
: parent_( &n )
, elem_( elem ){};
double operator()() const
{
return parent_->get_state_element( elem_ );
};
};
/**
* Map names of recordables to DataAccessFunctors.
*
* This map identifies the DataAccessFunctors for recordable state
* variables in multisynapse model neurons.
* As the number of synapse receptors can be modified at runtime,
* each neuron shall have its own instance of DynamicRecordablesMap.
* Furthermore, the neurons are able to insert and erase elements from
* the map at runtime.
*
* @see multimeter, UniversalDataLogger
* @ingroup Devices
*/
template < typename HostNode >
class DynamicRecordablesMap
: public std::map< Name, const DataAccessFunctor< HostNode > >
{
typedef std::map< Name, const DataAccessFunctor< HostNode > > Base_;
public:
virtual ~DynamicRecordablesMap()
{
}
//! Datatype for access callable
typedef DataAccessFunctor< HostNode > DataAccessFct;
/**
* Create the map.
* This function must be specialized for each class instance owning a
* Recordables map and must fill the map. This should happen
* as part of the original constructor for the Node.
*/
void create( HostNode& n );
/**
* Obtain SLI list of all recordables, for use by get_status().
* @todo This fct should return the recordables_ entry, but since
* filling recordables_ leads to seg fault on exit, we just
* build the list every time, even though that beats the
* goal of being more efficient ...
*/
ArrayDatum
get_list() const
{
ArrayDatum recordables;
for ( typename Base_::const_iterator it = this->begin(); it != this->end();
++it )
{
recordables.push_back( new LiteralDatum( it->first ) );
}
return recordables;
}
//! Insertion functions to be used in create(), adds entry to map and list
void
insert( const Name& n, const DataAccessFct& f )
{
Base_::insert( std::make_pair( n, f ) );
}
//! Erase functions to be used when setting state, removes entry from map and
//! list
void
erase( const Name& n )
{
// .toString() required as work-around for #339, remove when #348 is solved.
typename DynamicRecordablesMap< HostNode >::iterator it =
this->find( n.toString() );
// If the Name is not in the map, throw an error
if ( it == this->end() )
{
throw KeyError( n, "DynamicRecordablesMap", "erase" );
}
Base_::erase( it );
}
};
template < typename HostNode >
void
DynamicRecordablesMap< HostNode >::create( HostNode& n )
{
assert( false );
}
}
#endif
|
tobikausk/nest-simulator
|
nestkernel/recordables_map.h
|
C
|
gpl-2.0
| 6,717
|
// Avisynth C Interface Version 0.20
// Copyright 2003 Kevin Atkinson
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit
// http://www.gnu.org/copyleft/gpl.html .
//
// As a special exception, I give you permission to link to the
// Avisynth C interface with independent modules that communicate with
// the Avisynth C interface solely through the interfaces defined in
// avisynth_c.h, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting combined work
// under terms of your choice, provided that every copy of the
// combined work is accompanied by a complete copy of the source code
// of the Avisynth C interface and Avisynth itself (with the version
// used to produce the combined work), being distributed under the
// terms of the GNU General Public License plus this exception. An
// independent module is a module which is not derived from or based
// on Avisynth C Interface, such as 3rd-party filters, import and
// export plugins, or graphical user interfaces.
#ifndef AVS_CONFIG_H
#define AVS_CONFIG_H
// Undefine this to get cdecl calling convention
#define AVSC_USE_STDCALL 1
// NOTE TO PLUGIN AUTHORS:
// Because FRAME_ALIGN can be substantially higher than the alignment
// a plugin actually needs, plugins should not use FRAME_ALIGN to check for
// alignment. They should always request the exact alignment value they need.
// This is to make sure that plugins work over the widest range of AviSynth
// builds possible.
#define FRAME_ALIGN 64
#if defined(_M_AMD64) || defined(__x86_64)
# define X86_64
#elif defined(_M_IX86) || defined(__i386__)
# define X86_32
// VS2017 introduced _M_ARM64
#elif defined(_M_ARM64) || defined(__aarch64__)
# define ARM64
#elif defined(_M_ARM) || defined(__arm__)
# define ARM32
#else
# error Unsupported CPU architecture.
#endif
// VC++ LLVM-Clang-cl MinGW-Gnu
// MSVC x x
// MSVC_PURE x
// CLANG x
// GCC x
#if defined(__clang__)
// Check clang first. clang-cl also defines __MSC_VER
// We set MSVC because they are mostly compatible
# define CLANG
#if defined(_MSC_VER)
# define MSVC
# define AVS_FORCEINLINE __attribute__((always_inline))
#else
# define AVS_FORCEINLINE __attribute__((always_inline)) inline
#endif
#elif defined(_MSC_VER)
# define MSVC
# define MSVC_PURE
# define AVS_FORCEINLINE __forceinline
#elif defined(__GNUC__)
# define GCC
# define AVS_FORCEINLINE __attribute__((always_inline)) inline
#else
# error Unsupported compiler.
# define AVS_FORCEINLINE inline
# undef __forceinline
# define __forceinline inline
#endif
#if defined(_WIN32)
# define AVS_WINDOWS
#elif defined(__linux__)
# define AVS_LINUX
# define AVS_POSIX
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
# define AVS_BSD
# define AVS_POSIX
#elif defined(__APPLE__)
# define AVS_MACOS
# define AVS_POSIX
#else
# error Operating system unsupported.
#endif
// useful warnings disabler macros for supported compilers
#if defined(_MSC_VER)
#define DISABLE_WARNING_PUSH __pragma(warning( push ))
#define DISABLE_WARNING_POP __pragma(warning( pop ))
#define DISABLE_WARNING(warningNumber) __pragma(warning( disable : warningNumber ))
#define DISABLE_WARNING_UNREFERENCED_LOCAL_VARIABLE DISABLE_WARNING(4101)
#define DISABLE_WARNING_UNREFERENCED_FUNCTION DISABLE_WARNING(4505)
// other warnings you want to deactivate...
#elif defined(__GNUC__) || defined(__clang__)
#define DO_PRAGMA(X) _Pragma(#X)
#define DISABLE_WARNING_PUSH DO_PRAGMA(GCC diagnostic push)
#define DISABLE_WARNING_POP DO_PRAGMA(GCC diagnostic pop)
#define DISABLE_WARNING(warningName) DO_PRAGMA(GCC diagnostic ignored #warningName)
#define DISABLE_WARNING_UNREFERENCED_LOCAL_VARIABLE DISABLE_WARNING(-Wunused-variable)
#define DISABLE_WARNING_UNREFERENCED_FUNCTION DISABLE_WARNING(-Wunused-function)
// other warnings you want to deactivate...
#else
#define DISABLE_WARNING_PUSH
#define DISABLE_WARNING_POP
#define DISABLE_WARNING_UNREFERENCED_LOCAL_VARIABLE
#define DISABLE_WARNING_UNREFERENCED_FUNCTION
// other warnings you want to deactivate...
#endif
#if defined(AVS_POSIX)
#define NEW_AVSVALUE
#else
#define NEW_AVSVALUE
#endif
#if defined(AVS_WINDOWS)
// Windows XP does not have proper initialization for
// thread local variables.
// Use workaround instead __declspec(thread)
#define XP_TLS
#endif
#endif //AVS_CONFIG_H
|
Nevcairiel/LAVFilters
|
thirdparty/64/include/avisynth/avs/config.h
|
C
|
gpl-2.0
| 5,226
|
<?php
use SeleniumClient\By;
use SeleniumClient\SelectElement;
use SeleniumClient\WebDriver;
use SeleniumClient\WebDriverWait;
use SeleniumClient\DesiredCapabilities;
use SeleniumClient\WebElement;
/**
* @package Joomla.Test
* @subpackage Webdriver
*
* @copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
/**
* Home Page Class
*
* @package Joomla.Test
* @subpackage Webdriver
* @since 3.2
*/
class SiteContentCategoriesPage extends SitePage
{
/**
* XPath string used to uniquely identify this page
*
* @var string
* @since 3.2
*/
protected $waitForXpath = "//main[@id='content']/ul/li[7]/span[contains(text(),'Article Categories')]";
/**
* URL used to uniquely identify this page
*
* @var string
* @since 3.2
*/
protected $url = 'index.php/using-joomla/extensions/components/content-component/article-categories';
/**
* Function which returns Title array of Categories present on the Page
*
*
* @return Array of Category Titles Visible
*/
public function getCategoryTitles()
{
$arrayElement=$this->driver->findElements(By::xPath("//h3//a[contains(text(), '')]"));
$arrayTitles = array();
for($i=0;$i<count($arrayElement);$i++)
{
$arrayTitles[$i]=$arrayElement[$i]->getText();
}
return $arrayTitles;
}
}
|
yulchitaj/TEST1
|
tests/system/webdriver/Pages/SiteContent/SiteContentCategoriesPage.php
|
PHP
|
gpl-2.0
| 1,544
|
/*
* ReverbSC.cpp - A native reverb based on an algorithm by Sean Costello
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <math.h>
#include "ReverbSC.h"
#include "embed.h"
#include "plugin_export.h"
#define DB2LIN(X) pow(10, X / 20.0f);
extern "C"
{
Plugin::Descriptor PLUGIN_EXPORT reverbsc_plugin_descriptor =
{
STRINGIFY( PLUGIN_NAME ),
"ReverbSC",
QT_TRANSLATE_NOOP( "PluginBrowser", "Reverb algorithm by Sean Costello" ),
"Paul Batchelor",
0x0123,
Plugin::Effect,
new PluginPixmapLoader( "logo" ),
NULL,
NULL
} ;
}
ReverbSCEffect::ReverbSCEffect( Model* parent, const Descriptor::SubPluginFeatures::Key* key ) :
Effect( &reverbsc_plugin_descriptor, parent, key ),
m_reverbSCControls( this )
{
sp_create(&sp);
sp->sr = Engine::mixer()->processingSampleRate();
sp_revsc_create(&revsc);
sp_revsc_init(sp, revsc);
sp_dcblock_create(&dcblk[0]);
sp_dcblock_create(&dcblk[1]);
sp_dcblock_init(sp, dcblk[0], Engine::mixer()->currentQualitySettings().sampleRateMultiplier() );
sp_dcblock_init(sp, dcblk[1], Engine::mixer()->currentQualitySettings().sampleRateMultiplier() );
}
ReverbSCEffect::~ReverbSCEffect()
{
sp_revsc_destroy(&revsc);
sp_dcblock_destroy(&dcblk[0]);
sp_dcblock_destroy(&dcblk[1]);
sp_destroy(&sp);
}
bool ReverbSCEffect::processAudioBuffer( sampleFrame* buf, const fpp_t frames )
{
if( !isEnabled() || !isRunning () )
{
return( false );
}
double outSum = 0.0;
const float d = dryLevel();
const float w = wetLevel();
SPFLOAT tmpL, tmpR;
SPFLOAT dcblkL, dcblkR;
ValueBuffer * inGainBuf = m_reverbSCControls.m_inputGainModel.valueBuffer();
ValueBuffer * sizeBuf = m_reverbSCControls.m_sizeModel.valueBuffer();
ValueBuffer * colorBuf = m_reverbSCControls.m_colorModel.valueBuffer();
ValueBuffer * outGainBuf = m_reverbSCControls.m_outputGainModel.valueBuffer();
for( fpp_t f = 0; f < frames; ++f )
{
sample_t s[2] = { buf[f][0], buf[f][1] };
const SPFLOAT inGain = (SPFLOAT)DB2LIN((inGainBuf ?
inGainBuf->values()[f]
: m_reverbSCControls.m_inputGainModel.value()));
const SPFLOAT outGain = (SPFLOAT)DB2LIN((outGainBuf ?
outGainBuf->values()[f]
: m_reverbSCControls.m_outputGainModel.value()));
s[0] *= inGain;
s[1] *= inGain;
revsc->feedback = (SPFLOAT)(sizeBuf ?
sizeBuf->values()[f]
: m_reverbSCControls.m_sizeModel.value());
revsc->lpfreq = (SPFLOAT)(colorBuf ?
colorBuf->values()[f]
: m_reverbSCControls.m_colorModel.value());
sp_revsc_compute(sp, revsc, &s[0], &s[1], &tmpL, &tmpR);
sp_dcblock_compute(sp, dcblk[0], &tmpL, &dcblkL);
sp_dcblock_compute(sp, dcblk[1], &tmpR, &dcblkR);
buf[f][0] = d * buf[f][0] + w * dcblkL * outGain;
buf[f][1] = d * buf[f][1] + w * dcblkR * outGain;
outSum += buf[f][0]*buf[f][0] + buf[f][1]*buf[f][1];
}
checkGate( outSum / frames );
return isRunning();
}
void ReverbSCEffect::changeSampleRate()
{
// Change sr variable in Soundpipe. does not need to be destroyed
sp->sr = Engine::mixer()->processingSampleRate();
mutex.lock();
sp_revsc_destroy(&revsc);
sp_dcblock_destroy(&dcblk[0]);
sp_dcblock_destroy(&dcblk[1]);
sp_revsc_create(&revsc);
sp_revsc_init(sp, revsc);
sp_dcblock_create(&dcblk[0]);
sp_dcblock_create(&dcblk[1]);
sp_dcblock_init(sp, dcblk[0], Engine::mixer()->currentQualitySettings().sampleRateMultiplier() );
sp_dcblock_init(sp, dcblk[1], Engine::mixer()->currentQualitySettings().sampleRateMultiplier() );
mutex.unlock();
}
extern "C"
{
// necessary for getting instance out of shared lib
PLUGIN_EXPORT Plugin * lmms_plugin_main( Model* parent, void* data )
{
return new ReverbSCEffect(
parent,
static_cast<const Plugin::Descriptor::SubPluginFeatures::Key*>(data)
);
}
}
|
tresf/lmms
|
plugins/ReverbSC/ReverbSC.cpp
|
C++
|
gpl-2.0
| 4,455
|
package com.litesuits.common.assist;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import com.litesuits.android.log.Log;
import java.lang.reflect.Method;
/**
* assist us in sensing state of the networks.
*
* need <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
*
* 半夜了,研究了一下Android的Network方面,发现网上有些文章理解的是不对的。
* 以下方法是我研究得出的结论和方法,如有误也感谢指出。
*
* @author MaTianyu
* 2014-1-8上午 00:33:11
*/
public class Network {
private static final String TAG = Network.class.getSimpleName();
public enum NetType {
None(1),
Mobile(2),
Wifi(4),
Other(8);
NetType(int value) {
this.value = value;
}
public int value;
}
public enum NetWorkType {
UnKnown(-1),
Wifi(1),
Net2G(2),
Net3G(3),
Net4G(4);
NetWorkType(int value) {
this.value = value;
}
public int value;
}
//
//public enum NetSubType {
// None(1),
// Mobile(2),
// Wifi(4),
// Other(8);
//
// NetType(int value) {
// this.value = value;
// }
//
// public int value;
//}
/**
* 获取ConnectivityManager
*/
public static ConnectivityManager getConnectivityManager(Context context) {
return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
/**
* 获取ConnectivityManager
*/
public static TelephonyManager getTelephonyManager(Context context) {
return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
}
/**
* 判断网络连接是否有效(此时可传输数据)。
*
* @return boolean 不管wifi,还是mobile net,只有当前在连接状态(可有效传输数据)才返回true,反之false。
*/
public static boolean isConnected(Context context) {
NetworkInfo net = getConnectivityManager(context).getActiveNetworkInfo();
return net != null && net.isConnected();
}
/**
* 判断有无网络正在连接中(查找网络、校验、获取IP等)。
*
* @return boolean 不管wifi,还是mobile net,只有当前在连接状态(可有效传输数据)才返回true,反之false。
*/
public static boolean isConnectedOrConnecting(Context context) {
NetworkInfo[] nets = getConnectivityManager(context).getAllNetworkInfo();
if (nets != null) {
for (NetworkInfo net : nets) {
if (net.isConnectedOrConnecting()) { return true; }
}
}
return false;
}
public static NetType getConnectedType(Context context) {
NetworkInfo net = getConnectivityManager(context).getActiveNetworkInfo();
if (net != null) {
switch (net.getType()) {
case ConnectivityManager.TYPE_WIFI:
return NetType.Wifi;
case ConnectivityManager.TYPE_MOBILE:
return NetType.Mobile;
default:
return NetType.Other;
}
}
return NetType.None;
}
/**
* 是否存在有效的WIFI连接
*/
public static boolean isWifiConnected(Context context) {
NetworkInfo net = getConnectivityManager(context).getActiveNetworkInfo();
return net != null && net.getType() == ConnectivityManager.TYPE_WIFI && net.isConnected();
}
/**
* 是否存在有效的移动连接
*
* @return boolean
*/
public static boolean isMobileConnected(Context context) {
NetworkInfo net = getConnectivityManager(context).getActiveNetworkInfo();
return net != null && net.getType() == ConnectivityManager.TYPE_MOBILE && net.isConnected();
}
/**
* 检测网络是否为可用状态
*/
public static boolean isAvailable(Context context) {
return isWifiAvailable(context) || (isMobileAvailable(context) && isMobileEnabled(context));
}
/**
* 判断是否有可用状态的Wifi,以下情况返回false:
* 1. 设备wifi开关关掉;
* 2. 已经打开飞行模式;
* 3. 设备所在区域没有信号覆盖;
* 4. 设备在漫游区域,且关闭了网络漫游。
*
* @return boolean wifi为可用状态(不一定成功连接,即Connected)即返回ture
*/
public static boolean isWifiAvailable(Context context) {
NetworkInfo[] nets = getConnectivityManager(context).getAllNetworkInfo();
if (nets != null) {
for (NetworkInfo net : nets) {
if (net.getType() == ConnectivityManager.TYPE_WIFI) { return net.isAvailable(); }
}
}
return false;
}
/**
* 判断有无可用状态的移动网络,注意关掉设备移动网络直接不影响此函数。
* 也就是即使关掉移动网络,那么移动网络也可能是可用的(彩信等服务),即返回true。
* 以下情况它是不可用的,将返回false:
* 1. 设备打开飞行模式;
* 2. 设备所在区域没有信号覆盖;
* 3. 设备在漫游区域,且关闭了网络漫游。
*
* @return boolean
*/
public static boolean isMobileAvailable(Context context) {
NetworkInfo[] nets = getConnectivityManager(context).getAllNetworkInfo();
if (nets != null) {
for (NetworkInfo net : nets) {
if (net.getType() == ConnectivityManager.TYPE_MOBILE) { return net.isAvailable(); }
}
}
return false;
}
/**
* 设备是否打开移动网络开关
*
* @return boolean 打开移动网络返回true,反之false
*/
public static boolean isMobileEnabled(Context context) {
try {
Method getMobileDataEnabledMethod = ConnectivityManager.class.getDeclaredMethod("getMobileDataEnabled");
getMobileDataEnabledMethod.setAccessible(true);
return (Boolean) getMobileDataEnabledMethod.invoke(getConnectivityManager(context));
} catch (Exception e) {
e.printStackTrace();
}
// 反射失败,默认开启
return true;
}
/**
* 打印当前各种网络状态
*
* @return boolean
*/
public static boolean printNetworkInfo(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo in = connectivity.getActiveNetworkInfo();
Log.i(TAG, "-------------$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$-------------");
Log.i(TAG, "getActiveNetworkInfo: " + in);
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
// if (info[i].getType() == ConnectivityManager.TYPE_WIFI) {
Log.i(TAG, "NetworkInfo[" + i + "]isAvailable : " + info[i].isAvailable());
Log.i(TAG, "NetworkInfo[" + i + "]isConnected : " + info[i].isConnected());
Log.i(TAG, "NetworkInfo[" + i + "]isConnectedOrConnecting : " + info[i].isConnectedOrConnecting());
Log.i(TAG, "NetworkInfo[" + i + "]: " + info[i]);
// }
}
Log.i(TAG, "\n");
} else {
Log.i(TAG, "getAllNetworkInfo is null");
}
}
return false;
}
/**
* get connected network type by {@link ConnectivityManager}
*
* such as WIFI, MOBILE, ETHERNET, BLUETOOTH, etc.
*
* @return {@link ConnectivityManager#TYPE_WIFI}, {@link ConnectivityManager#TYPE_MOBILE},
* {@link ConnectivityManager#TYPE_ETHERNET}...
*/
public static int getConnectedTypeINT(Context context) {
NetworkInfo net = getConnectivityManager(context).getActiveNetworkInfo();
if (net != null) {
if (Log.isPrint) {
Log.i(TAG, "NetworkInfo: " + net.toString());
}
return net.getType();
}
return -1;
}
/**
* get network type by {@link TelephonyManager}
*
* such as 2G, 3G, 4G, etc.
*
* @return {@link TelephonyManager#NETWORK_TYPE_CDMA}, {@link TelephonyManager#NETWORK_TYPE_GPRS},
* {@link TelephonyManager#NETWORK_TYPE_LTE}...
*/
public static int getTelNetworkTypeINT(Context context) {
return getTelephonyManager(context).getNetworkType();
}
/**
* GPRS 2G(2.5) General Packet Radia Service 114kbps
* EDGE 2G(2.75G) Enhanced Data Rate for GSM Evolution 384kbps
* UMTS 3G WCDMA 联通3G Universal Mobile Telecommunication System 完整的3G移动通信技术标准
* CDMA 2G 电信 Code Division Multiple Access 码分多址
* EVDO_0 3G (EVDO 全程 CDMA2000 1xEV-DO) Evolution - Data Only (Data Optimized) 153.6kps - 2.4mbps 属于3G
* EVDO_A 3G 1.8mbps - 3.1mbps 属于3G过渡,3.5G
* 1xRTT 2G CDMA2000 1xRTT (RTT - 无线电传输技术) 144kbps 2G的过渡,
* HSDPA 3.5G 高速下行分组接入 3.5G WCDMA High Speed Downlink Packet Access 14.4mbps
* HSUPA 3.5G High Speed Uplink Packet Access 高速上行链路分组接入 1.4 - 5.8 mbps
* HSPA 3G (分HSDPA,HSUPA) High Speed Packet Access
* IDEN 2G Integrated Dispatch Enhanced Networks 集成数字增强型网络 (属于2G,来自维基百科)
* EVDO_B 3G EV-DO Rev.B 14.7Mbps 下行 3.5G
* LTE 4G Long Term Evolution FDD-LTE 和 TDD-LTE , 3G过渡,升级版 LTE Advanced 才是4G
* EHRPD 3G CDMA2000向LTE 4G的中间产物 Evolved High Rate Packet Data HRPD的升级
* HSPAP 3G HSPAP 比 HSDPA 快些
*
* @return {@link NetWorkType}
*/
public static NetWorkType getNetworkType(Context context) {
int type = getConnectedTypeINT(context);
switch (type) {
case ConnectivityManager.TYPE_WIFI:
return NetWorkType.Wifi;
case ConnectivityManager.TYPE_MOBILE:
case ConnectivityManager.TYPE_MOBILE_DUN:
case ConnectivityManager.TYPE_MOBILE_HIPRI:
case ConnectivityManager.TYPE_MOBILE_MMS:
case ConnectivityManager.TYPE_MOBILE_SUPL:
int teleType = getTelephonyManager(context).getNetworkType();
switch (teleType) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
return NetWorkType.Net2G;
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
return NetWorkType.Net3G;
case TelephonyManager.NETWORK_TYPE_LTE:
return NetWorkType.Net4G;
default:
return NetWorkType.UnKnown;
}
default:
return NetWorkType.UnKnown;
}
}
}
|
androidDaniel/treasure
|
common/src/main/java/com/litesuits/common/assist/Network.java
|
Java
|
gpl-2.0
| 12,019
|
/* SPDX-License-Identifier: LGPL-2.1+ */
#pragma once
#include <linux/fiemap.h>
#include "time-util.h"
typedef struct SleepConfig {
bool allow_suspend; /* AllowSuspend */
bool allow_hibernate; /* AllowHibernation */
bool allow_s2h; /* AllowSuspendThenHibernate */
bool allow_hybrid_sleep; /* AllowHybridSleep */
char **suspend_modes; /* SuspendMode */
char **suspend_states; /* SuspendState */
char **hibernate_modes; /* HibernateMode */
char **hibernate_states; /* HibernateState */
char **hybrid_modes; /* HybridSleepMode */
char **hybrid_states; /* HybridSleepState */
usec_t hibernate_delay_sec; /* HibernateDelaySec */
} SleepConfig;
void free_sleep_config(SleepConfig *sc);
DEFINE_TRIVIAL_CLEANUP_FUNC(SleepConfig*, free_sleep_config);
/* entry in /proc/swaps */
typedef struct SwapEntry {
char *device;
char *type;
uint64_t size;
uint64_t used;
int priority;
} SwapEntry;
SwapEntry* swap_entry_free(SwapEntry *se);
DEFINE_TRIVIAL_CLEANUP_FUNC(SwapEntry*, swap_entry_free);
/*
* represents values for /sys/power/resume & /sys/power/resume_offset
* and the matching /proc/swap entry.
*/
typedef struct HibernateLocation {
char *resume;
uint64_t resume_offset;
SwapEntry *swap;
} HibernateLocation;
HibernateLocation* hibernate_location_free(HibernateLocation *hl);
DEFINE_TRIVIAL_CLEANUP_FUNC(HibernateLocation*, hibernate_location_free);
int sleep_settings(const char *verb, const SleepConfig *sleep_config, bool *ret_allow, char ***ret_modes, char ***ret_states);
int read_fiemap(int fd, struct fiemap **ret);
int parse_sleep_config(SleepConfig **sleep_config);
int find_hibernate_location(HibernateLocation **ret_hibernate_location);
int can_sleep(const char *verb);
int can_sleep_disk(char **types);
int can_sleep_state(char **types);
|
heftig/systemd
|
src/shared/sleep-config.h
|
C
|
gpl-2.0
| 1,971
|
/* SportsPress */
.sp-align-left {
text-align: left;
}
.sp-align-right {
text-align: right;
}
.sp-align-center {
text-align: center;
}
/* Header */
.sp-header {
position: relative;
overflow: visible;
}
/* Templates */
.sp-template {
margin-bottom: 1.5em;
}
.sp-template-logo,
.sp-template-photo {
float: left;
margin-bottom: 2em;
margin-right: 2em;
max-width: 50%;
}
.sp-template-event-logos {
text-align: center;
}
.sp-template-details {
display: inline;
}
.sp-template-details dl {
overflow: hidden;
}
/* Data Tables */
.sp-scrollable-table-wrapper {
width: 100%;
overflow: hidden;
overflow-x: auto;
position: relative;
}
.sp-data-table {
width: 100%;
table-layout: auto;
border-spacing: 0;
}
.sp-paginated-table {
margin-bottom: 0;
}
.sp-data-table thead th {
white-space: nowrap;
}
.sp-data-table thead .sorting,
.sp-data-table thead .sorting_asc,
.sp-data-table thead .sorting_desc,
.sp-data-table thead .sorting_asc_disabled,
.sp-data-table thead .sorting_desc_disabled {
cursor: pointer;
}
.sp-data-table tbody a {
text-decoration: none;
}
.sp-data-table .sorting:after,
.sp-data-table .sorting_asc:after,
.sp-data-table .sorting_desc:after {
font-family: dashicons;
}
.sp-data-table .sorting:after {
content: "\f156";
color: transparent;
position: absolute;
}
.sp-data-table .sorting_asc:after {
content: "\f142";
position: absolute;
}
.sp-data-table .sorting_desc:after {
content: "\f140";
position: absolute;
}
.sp-data-table .data-number,
.sp-data-table .data-rank {
width: 1px;
}
/* Pagination */
.sp-table-wrapper .dataTables_paginate {
text-align: center;
}
.sp-table-wrapper .dataTables_paginate .paginate_button {
margin: 0.5em;
cursor: pointer;
display: inline-block;
}
.sp-table-wrapper .dataTables_paginate .previous {
float: left;
margin-left: 0;
}
.sp-table-wrapper .dataTables_paginate .next {
float: right;
margin-right: 0;
}
.sp-table-wrapper .dataTables_paginate .current {
opacity: 0.5;
color: inherit;
cursor: default;
}
.sp-table-wrapper .dataTables_paginate .disabled {
opacity: 0;
cursor: default;
}
/* Post Excerpt */
.sp-excerpt {
display: block;
margin-bottom: 1em;
}
/* League Table */
.sp-league-table td.has-logo {
line-height: 2em;
}
.sp-league-table .data-name .team-logo {
width: 2em;
height: 2em;
margin-right: 0.25em;
display: block;
float: left;
text-align: center;
}
.sp-league-table .data-name .team-logo img {
width: auto;
height: auto;
max-width: 2em;
max-height: 2em;
}
/* Player List */
.sp-player-list td {
line-height: 2em;
}
.sp-player-list .data-name .player-photo,
.sp-player-list .data-name .player-flag {
width: 2em;
height: 2em;
margin-right: 0.25em;
display: block;
float: left;
text-align: center;
}
.sp-player-list .data-name .player-photo img,
.sp-player-list .data-name .player-flag img {
width: auto;
height: auto;
max-width: 2em;
max-height: 2em;
}
/* Button */
.sp-button {
border: none;
cursor: pointer;
}
/* Event Logos */
.sp-event-logos a {
text-decoration: none;
}
.sp-event-logos img {
display: inline !important;
vertical-align: middle;
}
/* Events */
.sp-event-overview,
.sp-event-performance-tables {
overflow: hidden;
clear: both;
}
/* Event Logos */
.sp-event-logos .sp-team-logo {
white-space: nowrap;
display: block;
}
.sp-event-logos .sp-team-logo .sp-team-result {
display: block;
margin: 0 0 1em;
}
.sp-event-logos .sp-team-logo:last-child .sp-team-result {
margin-bottom: 0;
}
/* Event Venue */
.sp-event-venue thead th {
white-space: normal;
}
/* Event Performance */
.sp-event-performance .sub-in,
.sp-event-performance .sub-out {
cursor: default;
}
.sp-event-performance .sub-in:before,
.sp-event-performance .sub-out:before {
font-family: dashicons;
}
.sp-event-performance .sub-in:before {
content: "\f140";
}
.sp-event-performance .sub-out:before {
content: "\f142";
}
.sp-event-performance .sp-performance-icons {
width: 25%;
}
/* Event Performance (Icons) */
.sp-event-performance-teams .sp-template-event-performance-icons {
box-sizing: border-box;
width: 50%;
float: left;
padding-right: 10px;
}
.sp-event-performance-teams .sp-template-event-performance-icons:nth-child(2n) {
float: right;
padding-right: 0;
padding-left: 10px;
}
/* Event Calendar */
.sp-event-calendar {
border-spacing: 0;
}
.sp-event-calendar a {
text-decoration: none;
}
.sp-event-calendar tbody td, .sp-event-calendar thead th {
text-align: center;
}
.sp-event-calendar #next {
text-align: right;
}
.sp-event-calendar #prev {
text-align: left;
}
/* Event List */
.sp-event-list .data-date date,
.sp-event-list .data-time date {
display: none !important;
}
.sp-event-list .data-article {
white-space: nowrap;
}
.sp-event-list .data-article a .dashicons {
padding-right: 3px;
}
.sp-event-list .data-time,
.sp-event-list .data-results {
white-space: nowrap;
}
.sp-event-list .data-teams img,
.sp-event-list .data-home img,
.sp-event-list .data-away img {
display: inline-block;
vertical-align: middle;
}
/* Event Blocks */
.sp-event-blocks thead {
display: none;
}
.sp-event-blocks .sp-event-date,
.sp-event-blocks .sp-event-time,
.sp-event-blocks .sp-event-results,
.sp-event-blocks .sp-event-title {
text-align: center;
display: block;
margin: 10px 20%;
padding: 0 20px;
clear: none;
}
.sp-event-blocks .sp-event-league,
.sp-event-blocks .sp-event-season,
.sp-event-blocks .sp-event-venue {
text-align: center;
margin: 0 20%;
padding: 0 20px;
}
.sp-event-blocks .team-logo {
width: 20%;
height: auto;
margin: 10px;
max-width: 6em;
}
.sp-event-blocks .logo-odd {
float: left;
}
.sp-event-blocks .logo-even {
float: right;
}
.sp-event-blocks .team-logo img {
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
}
.widget .sp-event-blocks .sp-event-title {
margin: 10px;
padding: 0;
clear: both;
}
/* Countdowns */
.sp-template-countdown .event-name {
overflow: visible;
}
.sp-template-countdown .team-logo {
width: 20%;
height: auto;
max-width: 4em;
}
.sp-template-countdown .logo-odd {
float: left;
margin-right: 10px;
}
.sp-template-countdown .logo-even {
float: right;
margin-left: 10px;
}
.sp-template-countdown .team-logo img {
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
}
.sp-template-countdown .sp-countdown {
clear: both;
}
/* Google Maps */
.sp-google-map {
height: 320px;
}
.sp-google-map img {
max-width: none !important;
}
.sp-venue-map {
margin-bottom: 4em;
}
/* View All */
.sp-view-all-link {
display: block;
margin-top: 0.5em;
}
/* Alternate */
.sp-data-table tbody tr.odd {
background: rgba(0, 0, 0, 0.02);
}
/* Highlight & Heading */
.sp-highlight,
.sp-heading {
font-weight: bold;
}
/* Hidden Responsive Element */
.sp-desktop {
display: none;
}
/* Media Queries */
@media screen and (min-width: 801px) {
/* Widget Alignment */
.sp-widget-align-none {
clear: both;
}
.sp-widget-align-left {
width: 50%;
float: left;
clear: left;
padding-right: 10px;
box-sizing: border-box;
}
.sp-widget-align-right {
width: 50%;
float: right;
clear: right;
padding-left: 10px;
box-sizing: border-box;
}
/* Hidden Responsive Element */
.sp-desktop {
display: block;
}
.sp-mobile {
display: none;
}
}
@media screen and (min-width: 601px) {
.sp-event-logos .sp-team-logo {
display: inline-block;
}
.sp-event-logos-2 .sp-team-logo {
display: inline;
}
.sp-event-logos-2 .sp-team-logo .sp-team-result {
display: inline-block;
margin: 0 0.25em;
}
}
|
dwisuseno/duabola
|
wp-content/plugins/sportspress/assets/css/sportspress.css
|
CSS
|
gpl-2.0
| 7,477
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace SnWebApplication
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
|
tusmester/sn-projecttemplates-tmp
|
src/SnWebApplicationWithWorkspaces/SnWebApplication/App_Start/RouteConfig.cs
|
C#
|
gpl-2.0
| 586
|
/**
* @brief Clock Tick Device Driver
*
* This routine utilizes the Decrementer Register common to the PPC family.
*
* The tick frequency is directly programmed to the configured number of
* microseconds per tick.
*/
/*
* COPYRIGHT (c) 1989-2014.
* On-Line Applications Research Corporation (OAR).
*
* The license and distribution terms for this file may in
* the file LICENSE in this distribution or at
* http://www.rtems.org/license/LICENSE.
*
* Modified to support the MPC750.
* Modifications Copyright (c) 1999 Eric Valette valette@crf.canon.fr
*/
#include <rtems.h>
#include <rtems/libio.h>
#include <rtems/clockdrv.h>
#include <stdlib.h> /* for atexit() */
#include <assert.h>
#include <libcpu/c_clock.h>
#include <libcpu/cpuIdent.h>
#include <libcpu/spr.h>
#include <rtems/bspIo.h> /* for printk() */
#include <libcpu/powerpc-utility.h>
#include <bspopts.h> /* for CLOCK_DRIVER_USE_FAST_IDLE */
SPR_RW(BOOKE_TCR)
SPR_RW(BOOKE_TSR)
SPR_RW(BOOKE_DECAR)
extern int BSP_connect_clock_handler (void);
/*
* Clock ticks since initialization
*/
volatile uint32_t Clock_driver_ticks;
/*
* This is the value programmed into the count down timer.
*/
static uint32_t Clock_Decrementer_value;
/*
* This is the value by which elapsed count down timer ticks are multiplied to
* give an elapsed duration in nanoseconds, left-shifted by 32 bits
*/
static uint64_t Clock_Decrementer_reference;
void clockOff(void* unused)
{
rtems_interrupt_level l;
if ( ppc_cpu_is_bookE() ) {
rtems_interrupt_disable(l);
_write_BOOKE_TCR(_read_BOOKE_TCR() & ~BOOKE_TCR_DIE);
rtems_interrupt_enable(l);
} else {
/*
* Nothing to do as we cannot disable all interrupts and
* the decrementer interrupt enable is MSR_EE
*/
}
}
void clockOn(void* unused)
{
rtems_interrupt_level l;
PPC_Set_decrementer( Clock_Decrementer_value );
if ( ppc_cpu_is_bookE() ) {
_write_BOOKE_DECAR( Clock_Decrementer_value );
rtems_interrupt_disable(l);
/* clear pending/stale irq */
_write_BOOKE_TSR( BOOKE_TSR_DIS );
/* enable */
_write_BOOKE_TCR( _read_BOOKE_TCR() | BOOKE_TCR_DIE );
rtems_interrupt_enable(l);
}
}
static void clockHandler(void)
{
#if (CLOCK_DRIVER_USE_FAST_IDLE == 1)
do {
rtems_clock_tick();
} while (
_Thread_Heir == _Thread_Executing
&& _Thread_Executing->Start.entry_point
== (Thread_Entry) rtems_configuration_get_idle_task()
);
#else
rtems_clock_tick();
#endif
}
static void (*clock_handler)(void);
/*
* Clock_isr
*
* This is the clock tick interrupt handler.
*
* Input parameters:
* vector - vector number
*
* Output parameters: NONE
*
* Return values: NONE
*
*/
void clockIsr(void *unused)
{
int decr;
/*
* The driver has seen another tick.
*/
do {
register uint32_t flags;
rtems_interrupt_disable(flags);
__asm__ volatile (
"mfdec %0; add %0, %0, %1; mtdec %0"
: "=&r"(decr)
: "r"(Clock_Decrementer_value)
);
rtems_interrupt_enable(flags);
Clock_driver_ticks += 1;
/*
* Real Time Clock counter/timer is set to automatically reload.
*/
clock_handler();
} while ( decr < 0 );
}
/*
* Clock_isr_bookE
*
* This is the clock tick interrupt handler
* for bookE CPUs. For efficiency reasons we
* provide a separate handler rather than
* checking the CPU type each time.
*/
void clockIsrBookE(void *unused)
{
/* Note: TSR bit has already been cleared in the exception handler */
/*
* The driver has seen another tick.
*/
Clock_driver_ticks += 1;
/*
* Real Time Clock counter/timer is set to automatically reload.
*/
clock_handler();
}
int clockIsOn(void* unused)
{
uint32_t msr_value;
_CPU_MSR_GET( msr_value );
if ( ppc_cpu_is_bookE() && ! (_read_BOOKE_TCR() & BOOKE_TCR_DIE) )
msr_value = 0;
if (msr_value & MSR_EE) return 1;
return 0;
}
/*
* Clock_exit
*
* This routine allows the clock driver to exit by masking the interrupt and
* disabling the clock's counter.
*/
void Clock_exit( void )
{
(void) BSP_disconnect_clock_handler ();
}
static uint32_t Clock_driver_nanoseconds_since_last_tick(void)
{
uint32_t clicks, tmp;
PPC_Get_decrementer( clicks );
/*
* Multiply by 1000 here separately from below so we do not overflow
* and get a negative value.
*/
tmp = (Clock_Decrementer_value - clicks) * 1000;
tmp /= (BSP_bus_frequency/BSP_time_base_divisor);
return tmp * 1000;
}
static uint32_t Clock_driver_nanoseconds_since_last_tick_bookE(void)
{
uint32_t clicks;
uint64_t c;
PPC_Get_decrementer( clicks );
c = Clock_Decrementer_value - clicks;
/*
* Check whether a clock tick interrupt is pending and hence that the
* decrementer's wrapped. If it has, we'll compensate by returning a time one
* tick period longer.
*
* We have to check interrupt status after reading the decrementer. If we
* don't, we may miss an interrupt and read a wrapped decrementer value
* without compensating for it
*/
if ( _read_BOOKE_TSR() & BOOKE_TSR_DIS )
{
/*
* Re-read the decrementer: The tick interrupt may have been
* generated and the decrementer wrapped during the time since we
* last read it and the time we checked the interrupt status
*/
PPC_Get_decrementer( clicks );
c = (Clock_Decrementer_value - clicks) + Clock_Decrementer_value;
}
return (uint32_t)((c * Clock_Decrementer_reference) >> 32);
}
/*
* Clock_initialize
*
* This routine initializes the clock driver.
*/
rtems_device_driver Clock_initialize(
rtems_device_major_number major,
rtems_device_minor_number minor,
void *pargp
)
{
rtems_interrupt_level l,tcr;
Clock_Decrementer_value = (BSP_bus_frequency/BSP_time_base_divisor)*
rtems_configuration_get_milliseconds_per_tick();
Clock_Decrementer_reference = ((uint64_t)1000000U<<32)/
(BSP_bus_frequency/BSP_time_base_divisor);
/* set the decrementer now, prior to installing the handler
* so no interrupts will happen in a while.
*/
PPC_Set_decrementer( (unsigned)-1 );
/* On a bookE CPU the decrementer works differently. It doesn't
* count past zero but we can enable auto-reload :-)
*/
if ( ppc_cpu_is_bookE() ) {
rtems_interrupt_disable(l);
tcr = _read_BOOKE_TCR();
tcr |= BOOKE_TCR_ARE;
tcr &= ~BOOKE_TCR_DIE;
_write_BOOKE_TCR(tcr);
rtems_interrupt_enable(l);
/*
* Set the nanoseconds since last tick handler
*/
rtems_clock_set_nanoseconds_extension(
Clock_driver_nanoseconds_since_last_tick_bookE
);
}
else
{
/*
* Set the nanoseconds since last tick handler
*/
rtems_clock_set_nanoseconds_extension(
Clock_driver_nanoseconds_since_last_tick
);
}
/*
* If a decrementer exception was pending, it is cleared by
* executing the default (nop) handler at this point;
* The next exception will then be taken by our clock handler.
* Clock handler installation initializes the decrementer to
* the correct value.
*/
clock_handler = clockHandler;
if (!BSP_connect_clock_handler ()) {
printk("Unable to initialize system clock\n");
rtems_fatal_error_occurred(1);
}
return RTEMS_SUCCESSFUL;
} /* Clock_initialize */
|
ragunath3252/rtems
|
c/src/lib/libcpu/powerpc/mpc6xx/clock/c_clock.c
|
C
|
gpl-2.0
| 7,389
|
<?php
/**
* XOOPS Profile module
*
* You may not change or alter any portion of this comment or credits
* of supporting developers from this source code or any supporting source code
* which is considered copyrighted (c) material of the original comment or credit authors.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* @copyright (c) 2000-2016 XOOPS Project (www.xoops.org)
* @license GNU GPL (https://www.gnu.org/licenses/gpl-2.0.html/)
* @package Profile
* @since 2.5.0
* @author Mage, Mamba
**/
include_once dirname(dirname(dirname(__DIR__))) . '/include/cp_header.php';
include_once __DIR__ . '/admin_header.php';
xoops_cp_header();
$module_info = $module_handler->get($xoopsModule->getVar('mid'));
$aboutAdmin = new ModuleAdmin();
echo $aboutAdmin->addNavigation(basename(__FILE__));
echo $aboutAdmin->renderAbout('xoopsfoundation@gmail.com', false);
include_once __DIR__ . '/admin_footer.php';
|
mambax7/XoopsCore25
|
htdocs/modules/profile/admin/about.php
|
PHP
|
gpl-2.0
| 1,121
|
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Catalog\Test\Unit\Model\Layer\Filter\DataProvider;
use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper;
use PHPUnit_Framework_MockObject_MockObject as MockObject;
/**
* Test for \Magento\Catalog\Model\Layer\Filter\DataProvider\Category
*/
class CategoryTest extends \PHPUnit_Framework_TestCase
{
/** @var \Magento\Catalog\Model\Category|MockObject */
private $category;
/** @var \Magento\Store\Model\Store|MockObject */
private $store;
/** @var \Magento\Catalog\Model\Layer|MockObject */
private $layer;
/** @var \Magento\Catalog\Model\CategoryFactory|MockObject */
private $categoryFactory;
/** @var \Magento\Framework\Registry|MockObject */
private $coreRegistry;
/**
* @var \Magento\Catalog\Model\Layer\Filter\DataProvider\Category
*/
private $target;
/**
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
*/
protected function setUp()
{
/** @var \Magento\Framework\Registry $var */
$this->coreRegistry = $var = $this->getMockBuilder('\Magento\Framework\Registry')
->disableOriginalConstructor()
->setMethods(['register'])
->getMock();
$this->category = $this->getMockBuilder('Magento\Catalog\Model\Category')
->disableOriginalConstructor()
->setMethods(['getId', 'setStoreId', 'load', 'getPathIds'])
->getMock();
$this->categoryFactory = $this->getMockBuilder('Magento\Catalog\Model\CategoryFactory')
->disableOriginalConstructor()
->setMethods(['create'])
->getMock();
$this->categoryFactory->expects($this->any())
->method('create')
->will($this->returnValue($this->category));
$this->store = $this->getMockBuilder('\Magento\Store\Model\Store')
->disableOriginalConstructor()
->setMethods(['getId'])
->getMock();
$this->layer = $this->getMockBuilder('Magento\Catalog\Model\Layer')
->disableOriginalConstructor()
->setMethods(['getCurrentStore', 'getCurrentCategory'])
->getMock();
$this->layer->expects($this->any())
->method('getCurrentStore')
->will($this->returnValue($this->store));
$objectManagerHelper = new ObjectManagerHelper($this);
$this->target = $objectManagerHelper->getObject(
'Magento\Catalog\Model\Layer\Filter\DataProvider\Category',
[
'coreRegistry' => $this->coreRegistry,
'categoryFactory' => $this->categoryFactory,
'layer' => $this->layer,
]
);
}
public function testGetCategoryWithAppliedId()
{
$storeId = 1234;
$categoryId = 4321;
$this->store->expects($this->once())
->method('getId')
->will($this->returnValue($storeId));
$this->layer->expects($this->any())
->method('getCurrentCategory')
->will($this->returnValue($this->category));
$this->category->expects($this->once())
->method('setStoreId')
->with($this->equalTo($storeId))
->will($this->returnSelf());
$this->category->expects($this->once())
->method('load')
->with($this->equalTo($categoryId))
->will($this->returnSelf());
$this->category->expects($this->any())
->method('getId')
->will($this->returnValue($categoryId));
$this->category->expects($this->any())
->method('getPathIds')
->will($this->returnValue([20, 10]));
$this->coreRegistry->expects($this->once())
->method('register')
->with(
$this->equalTo('current_category_filter'),
$this->equalTo($this->category),
$this->equalTo(true)
)
->will($this->returnSelf());
$this->target->setCategoryId($categoryId);
$this->assertSame($this->category, $this->target->getCategory());
$this->assertSame(20, $this->target->getResetValue());
return $this->target;
}
}
|
FPLD/project0
|
vendor/magento/module-catalog/Test/Unit/Model/Layer/Filter/DataProvider/CategoryTest.php
|
PHP
|
gpl-2.0
| 4,337
|
<?php
/**
* @package AcyMailing for Joomla!
* @version 5.5.0
* @author acyba.com
* @copyright (C) 2009-2016 ACYBA S.A.R.L. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?><?php
jimport( 'joomla.html.parameter' );
class acymailingView extends JView{
}
class acymailingControllerCompat extends JController{
}
function acymailing_loadResultArray(&$db){
return $db->loadResultArray();
}
function acymailing_loadMootools($loadMootoolsMoreLib = false){
JHTML::_('behavior.mootools');
}
function acymailing_getColumns($table){
$db = JFactory::getDBO();
$allfields = $db->getTableFields($table);
return reset($allfields);
}
function acymailing_getEscaped($value, $extra = false) {
$db = JFactory::getDBO();
return $db->getEscaped($value, $extra);
}
function acymailing_getFormToken() {
return JUtility::getToken();
}
if(!class_exists('acyParameter')){
class acyParameter extends JParameter{}
}
|
adamopoulosg/zagori_site
|
administrator/components/com_acymailing/compat/compat1.php
|
PHP
|
gpl-2.0
| 998
|
////////////////////////////////////////////////////////////////////////////////////////
//
// Nestopia - NES/Famicom emulator written in C++
//
// Copyright (C) 2003-2008 Martin Freij
//
// This file is part of Nestopia.
//
// Nestopia is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// Nestopia is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Nestopia; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////////////////////////////
#include <new>
#include "language/resource.h"
#include "NstApplicationException.hpp"
#include "NstApplicationInstance.hpp"
#include "NstSystemKeyboard.hpp"
#include "NstDirectInput.hpp"
#include "NstIoScreen.hpp"
#include "NstIoLog.hpp"
#if NST_MSVC
#pragma comment(lib,"dinput8")
#pragma comment(lib,"dxguid")
#endif
namespace Nestopia
{
namespace DirectX
{
HeapString DirectInput::Keyboard::keyNames[MAX_KEYS];
struct DirectInput::Joystick::Lookup
{
uint (*code)(const void* const);
ushort offset;
ushort axis;
wcstring name;
};
const DirectInput::Joystick::Lookup DirectInput::Joystick::table[TABLE_KEYS] =
{
{ KeyPosDir, DIJOFS_Y, AXIS_Y, L"+y" },
{ KeyPosDir, DIJOFS_X, AXIS_X, L"+x" },
{ KeyNegDir, DIJOFS_Y, AXIS_Y, L"-y" },
{ KeyNegDir, DIJOFS_X, AXIS_X, L"-x" },
{ KeyPosDir, DIJOFS_Z, AXIS_Z, L"+z" },
{ KeyNegDir, DIJOFS_Z, AXIS_Z, L"-z" },
{ KeyPosDir, DIJOFS_RY, AXIS_RY, L"+ry" },
{ KeyPosDir, DIJOFS_RX, AXIS_RX, L"+rx" },
{ KeyPosDir, DIJOFS_RY, AXIS_RY, L"-ry" },
{ KeyNegDir, DIJOFS_RX, AXIS_RX, L"-rx" },
{ KeyPosDir, DIJOFS_RZ, AXIS_RZ, L"+rz" },
{ KeyNegDir, DIJOFS_RZ, AXIS_RZ, L"-rz" },
{ KeyNegDir, DIJOFS_SLIDER(0), AXIS_SLIDER_0, L"-s0" },
{ KeyPosDir, DIJOFS_SLIDER(0), AXIS_SLIDER_0, L"+s0" },
{ KeyNegDir, DIJOFS_SLIDER(1), AXIS_SLIDER_1, L"-s1" },
{ KeyPosDir, DIJOFS_SLIDER(1), AXIS_SLIDER_1, L"+s1" },
{ KeyPovUp, DIJOFS_POV(0), AXIS_POV_0, L"-p0y" },
{ KeyPovRight, DIJOFS_POV(0), AXIS_POV_0, L"+p0x" },
{ KeyPovDown, DIJOFS_POV(0), AXIS_POV_0, L"+p0y" },
{ KeyPovLeft, DIJOFS_POV(0), AXIS_POV_0, L"-p0x" },
{ KeyPovUp, DIJOFS_POV(1), AXIS_POV_1, L"-p1y" },
{ KeyPovRight, DIJOFS_POV(1), AXIS_POV_1, L"+p1x" },
{ KeyPovDown, DIJOFS_POV(1), AXIS_POV_1, L"+p1y" },
{ KeyPovLeft, DIJOFS_POV(1), AXIS_POV_1, L"-p1x" },
{ KeyPovUp, DIJOFS_POV(2), AXIS_POV_2, L"-p2y" },
{ KeyPovRight, DIJOFS_POV(2), AXIS_POV_2, L"+p2x" },
{ KeyPovDown, DIJOFS_POV(2), AXIS_POV_2, L"+p2y" },
{ KeyPovLeft, DIJOFS_POV(2), AXIS_POV_2, L"-p2x" },
{ KeyPovUp, DIJOFS_POV(3), AXIS_POV_3, L"-p3y" },
{ KeyPovRight, DIJOFS_POV(3), AXIS_POV_3, L"+p3x" },
{ KeyPovDown, DIJOFS_POV(3), AXIS_POV_3, L"+p3y" },
{ KeyPovLeft, DIJOFS_POV(3), AXIS_POV_3, L"-p3x" }
};
#ifdef NST_MSVC_OPTIMIZE
#pragma optimize("t", on)
#endif
inline void DirectInput::Joystick::Calibrator::Fix(DIJOYSTATE& state) const
{
state.lX -= lX;
state.lY -= lY;
state.lZ -= lZ;
state.lRx -= lRx;
state.lRy -= lRy;
state.lRz -= lRz;
}
NST_FORCE_INLINE void DirectInput::Keyboard::Poll()
{
if (enabled)
{
HRESULT hResult;
if (FAILED(hResult=com.Poll()) || FAILED(hResult=com.GetDeviceState( Buffer::SIZE, buffer )))
OnError( hResult );
}
}
NST_FORCE_INLINE void DirectInput::Joystick::Poll()
{
if (enabled)
{
HRESULT hResult;
if (SUCCEEDED(hResult=com.Poll()) && SUCCEEDED(hResult=com.GetDeviceState( sizeof(state), &state )))
calibrator.Fix( state );
else
OnError( hResult );
}
}
void DirectInput::Poll()
{
keyboard.Poll();
for (Joysticks::Iterator it(joysticks.Begin()), end(joysticks.End()); it != end; ++it)
it->Poll();
}
#ifdef NST_MSVC_OPTIMIZE
#pragma optimize("", on)
#endif
DirectInput::Base::Base(HWND const h)
: com(Create()), hWnd(h) {}
DirectInput::Base::~Base()
{
com.Release();
}
IDirectInput8& DirectInput::Base::Create()
{
Io::Log() << "DirectInput: initializing..\r\n";
IDirectInput8* com;
if (FAILED(::DirectInput8Create( ::GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, reinterpret_cast<void**>(&com), NULL )))
throw Application::Exception( IDS_ERR_FAILED, L"DirectInput8Create()" );
return *com;
}
DirectInput::DirectInput(HWND const hWnd)
: base(hWnd), keyboard(base)
{
if (SUCCEEDED(base.com.EnumDevices( DI8DEVCLASS_GAMECTRL, EnumJoysticks, this, DIEDFL_ATTACHEDONLY )))
Io::Log() << "DirectInput: found " << joysticks.Size() << " attached joystick(s)\r\n";
else
Io::Log() << "DirectInput: IDirectInput8::EnumDevices() failed! No joysticks can be used!\r\n";
}
DirectInput::~DirectInput()
{
for (uint i=joysticks.Size(); i; )
joysticks[--i].Joystick::~Joystick();
}
BOOL CALLBACK DirectInput::EnumJoysticks(LPCDIDEVICEINSTANCE const instance,LPVOID const context)
{
if (instance)
{
DirectInput& directInput = *static_cast<DirectInput*>(context);
if (directInput.joysticks.Size() == MAX_JOYSTICKS)
{
Io::Log() << "DirectInput: warning, device count limit reached, stopping enumeration..\r\n";
return DIENUM_STOP;
}
Io::Log() << "DirectInput: enumerating device - name: "
<< (*instance->tszProductName ? instance->tszProductName : L"unknown")
<< ", GUID: "
<< System::Guid( instance->guidInstance ).GetString()
<< "\r\n";
directInput.joysticks.Grow();
try
{
new (&directInput.joysticks.Back()) Joystick( directInput.base, *instance );
}
catch (Joystick::Exception)
{
directInput.joysticks.Shrink();
Io::Log() << "DirectInput: warning, bogus device, continuing enumeration..\r\n";
}
}
return DIENUM_CONTINUE;
}
void DirectInput::Acquire()
{
keyboard.Acquire();
for (Joysticks::Iterator it(joysticks.Begin()), end(joysticks.End()); it != end; ++it)
it->Acquire();
}
void DirectInput::Unacquire()
{
keyboard.Unacquire();
for (Joysticks::Iterator it(joysticks.Begin()), end(joysticks.End()); it != end; ++it)
it->Unacquire();
}
void DirectInput::Calibrate()
{
for (Joysticks::Iterator it(joysticks.Begin()), end(joysticks.End()); it != end; ++it)
it->Calibrate();
}
void DirectInput::BeginScanMode(HWND hWnd) const
{
keyboard.BeginScanMode( hWnd );
for (Joysticks::ConstIterator it(joysticks.Begin()), end(joysticks.End()); it != end; ++it)
it->BeginScanMode();
}
void DirectInput::EndScanMode() const
{
keyboard.EndScanMode();
for (Joysticks::ConstIterator it(joysticks.Begin()), end(joysticks.End()); it != end; ++it)
it->EndScanMode();
}
void DirectInput::Build(const Key* const keys,const uint count)
{
keyboard.Enable( false );
for (const Key *it=keys, *const end=keys+count; it != end; ++it)
{
if (keyboard.Assigned( *it ))
{
keyboard.Enable( true );
break;
}
}
for (Joysticks::Iterator it(joysticks.Begin()), end(joysticks.End()); it != end; ++it)
{
it->Enable( false );
for (const Key *jt=keys, *const jend=keys+count; jt != jend; ++jt)
{
if (it->Assigned( *jt ))
{
it->Enable( true );
break;
}
}
}
}
DirectInput::ScanResult DirectInput::ScanKey(Key& key,const ScanMode scanMode)
{
const ScanResult scan = (scanMode == SCAN_MODE_ALL ? keyboard.Scan( key ) : SCAN_NO_KEY);
if (scan != SCAN_GOOD_KEY)
{
if (scan == SCAN_NO_KEY)
{
for (Joysticks::Iterator it(joysticks.Begin()), end(joysticks.End()); it != end; ++it)
{
if (it->Scan( key ))
return SCAN_GOOD_KEY;
}
}
key.Unmap();
}
return scan;
}
bool DirectInput::MapKey(Key& key,wcstring const name,const System::Guid* const guids,const uint numGuids) const
{
key.Unmap();
if
(
name && *name &&
(name[0] != '.' || name[1] != '.' || name[2] != '.' || name[3] != '\0')
)
{
if
(
(name[0] == '(') &&
(name[1] == 'j' || name[1] == 'J') &&
(name[2] == 'o' || name[2] == 'O') &&
(name[3] == 'y' || name[3] == 'Y') &&
(name[4] == ' ') &&
(name[5] >= '0' && name[5] <= '9') &&
(
(name[6] == ')' && name[7] == ' ') ||
(name[6] >= '0' && name[6] <= '9' && name[7] == ')' && name[8] == ' ')
)
)
{
uint index = name[5] - '0';
if (name[6] != ')')
index = (index * 10) + (name[6] - '0');
if (index < NST_MIN(MAX_JOYSTICKS,numGuids))
{
const System::Guid& guid = guids[index];
for (Joysticks::ConstIterator it(joysticks.Begin()), end(joysticks.End()); it != end; ++it)
{
if (it->GetGuid() == guid)
return it->Map( key, name + (name[7] == ' ' ? 8 : 9) );
}
}
}
else
{
return keyboard.Map( key, name );
}
}
return false;
}
const HeapString DirectInput::GetKeyName(const Key& key) const
{
if (key.Assigned())
{
if (keyboard.Assigned( key ))
{
return keyboard.GetName( key );
}
else
{
for (uint i=0, n=joysticks.Size(); i < n; ++i)
{
if (joysticks[i].Assigned( key ))
return HeapString("(joy ") << i << ") " << joysticks[i].GetName( key );
}
HeapString name;
if (key.vKey & FCONTROL)
name << System::Keyboard::GetName( VK_CONTROL ) << '+';
if (key.vKey & FALT)
name << System::Keyboard::GetName( VK_MENU ) << '+';
if (key.vKey & FSHIFT)
name << System::Keyboard::GetName( VK_SHIFT ) << '+';
name << System::Keyboard::GetName( key.vKey >> 8 );
return name;
}
}
return L"...";
}
DirectInput::Device::Device(IDirectInputDevice8& c)
: com(c), enabled(false) {}
DirectInput::Device::~Device()
{
com.Unacquire();
com.Release();
}
void DirectInput::Device::Enable(bool enable)
{
enabled = enable;
}
bool DirectInput::Device::Acquire(void* const data,const uint size)
{
return enabled && SUCCEEDED(com.Acquire()) && SUCCEEDED(com.Poll()) && SUCCEEDED(com.GetDeviceState( size, data ));
}
void DirectInput::Device::Unacquire()
{
com.Unacquire();
}
DirectInput::Keyboard::Keyboard(Base& base)
: Device(Create(base.com)), hWnd(base.hWnd)
{
for (uint i=0; i < MAX_KEYS; ++i)
keyNames[i] << i;
com.EnumObjects( EnumObjects, NULL, DIDFT_BUTTON );
SetCooperativeLevel( base.hWnd, COOPERATIVE_FLAGS );
Clear();
}
IDirectInputDevice8& DirectInput::Keyboard::Create(IDirectInput8& base)
{
IDirectInputDevice8* com;
if (FAILED(base.CreateDevice( GUID_SysKeyboard, &com, NULL )))
throw Application::Exception( IDS_ERR_FAILED, L"IDirectInput8::CreateDevice()" );
if (FAILED(com->SetDataFormat( &c_dfDIKeyboard )))
{
com->Release();
throw Application::Exception( IDS_ERR_FAILED, L"IDirectInputDevice8::SetDataFormat()" );
}
return *com;
}
BOOL CALLBACK DirectInput::Keyboard::EnumObjects(LPCDIDEVICEOBJECTINSTANCE const obj,LPVOID)
{
NST_VERIFY( obj->dwOfs < MAX_KEYS && *obj->tszName );
if (obj->dwOfs < MAX_KEYS && *obj->tszName)
{
HeapString& string = keyNames[obj->dwOfs];
string = obj->tszName;
::CharUpperBuff( string.Ptr(), 1 );
if (string.Length() > 1)
::CharLowerBuff( string.Ptr() + 1, string.Length() - 1 );
}
return DIENUM_CONTINUE;
}
void DirectInput::Keyboard::SetCooperativeLevel(HWND const hWnd,const DWORD flags) const
{
if (FAILED(com.SetCooperativeLevel( hWnd, flags )))
throw Application::Exception( IDS_ERR_FAILED, L"IDirectInputDevice8::SetCooperativeLevel()" );
}
bool DirectInput::Keyboard::Map(Key& key,wcstring name) const
{
for (uint i=0; i < MAX_KEYS; ++i)
{
if (keyNames[i] == name)
return Map( key, i );
}
return false;
}
bool DirectInput::Keyboard::Map(Key& key,const uint code) const
{
if (code && code <= 0xFF && code != DIK_LWIN)
{
key.data = buffer + code;
key.code = KeyDown;
return true;
}
return false;
}
void DirectInput::Keyboard::BeginScanMode(HWND hWndScan) const
{
com.Unacquire();
SetCooperativeLevel( hWndScan, SCAN_COOPERATIVE_FLAGS );
com.Acquire();
}
void DirectInput::Keyboard::EndScanMode() const
{
com.Unacquire();
SetCooperativeLevel( hWnd, COOPERATIVE_FLAGS );
}
bool DirectInput::Keyboard::Scan(uchar (&data)[MAX_KEYS]) const
{
if (SUCCEEDED(com.Poll()) && SUCCEEDED(com.GetDeviceState( MAX_KEYS, data )))
return true;
std::memset( data, 0, MAX_KEYS );
return false;
}
DirectInput::ScanResult DirectInput::Keyboard::Scan(Key& key) const
{
uchar data[MAX_KEYS];
if (Scan( data ))
{
for (uint i=0; i < MAX_KEYS; ++i)
{
if (data[i] & 0x80U)
{
switch (i)
{
case DIK_CAPITAL:
case DIK_NUMLOCK:
case DIK_SCROLL:
case DIK_KANA:
case DIK_KANJI:
continue;
default:
return Map( key, i ) ? SCAN_GOOD_KEY : SCAN_INVALID_KEY;
}
}
}
}
return SCAN_NO_KEY;
}
void DirectInput::Keyboard::OnError(const HRESULT hResult)
{
NST_ASSERT( FAILED(hResult) );
switch (hResult)
{
case DIERR_INPUTLOST:
case DIERR_NOTACQUIRED:
if (::GetActiveWindow() == hWnd)
{
Acquire();
break;
}
default:
Clear();
break;
}
}
bool DirectInput::Keyboard::Assigned(const Key& key) const
{
return key.data >= buffer && key.data < (buffer + Buffer::SIZE);
}
wcstring DirectInput::Keyboard::GetName(const Key& key) const
{
NST_VERIFY( Assigned(key) );
return keyNames[key.data - buffer].Ptr();
}
void DirectInput::Keyboard::Clear()
{
std::memset( buffer, 0, Buffer::SIZE );
}
void DirectInput::Keyboard::Acquire()
{
if (!Device::Acquire( buffer, Buffer::SIZE ))
Clear();
}
void DirectInput::Keyboard::Unacquire()
{
Device::Unacquire();
Clear();
}
DirectInput::Joystick::Joystick(Base& base,const DIDEVICEINSTANCE& instance)
:
Device (Create(base,instance.guidInstance)),
caps (com,instance),
calibrated (false),
scanEnabled (true),
deadZone (UINT_MAX),
axes (DEFAULT_AXES)
{
SetAxisDeadZone( DEFAULT_DEADZONE );
if (SUCCEEDED(com.Acquire()))
{
if (SUCCEEDED(com.Poll()))
com.GetDeviceState( sizeof(state), &state );
com.Unacquire();
}
}
DirectInput::Joystick::Calibrator::Calibrator()
:
lX (0),
lY (0),
lZ (0),
lRx (0),
lRy (0),
lRz (0)
{}
DirectInput::Joystick::Caps::Context::Context(Caps& c,IDirectInputDevice8& d)
: caps(c), com(d), numButtons(0) {}
DirectInput::Joystick::Caps::Caps(IDirectInputDevice8& com,const DIDEVICEINSTANCE& instance)
: axes(0), guid(instance.guidInstance), name(*instance.tszProductName ? instance.tszProductName : L"unknown")
{
Context context( *this, com );
if (FAILED(com.EnumObjects( EnumObjectsProc, &context, DIDFT_ALL )) || !(context.numButtons|axes))
throw ERR_API;
}
IDirectInputDevice8& DirectInput::Joystick::Create(Base& base,const GUID& guid)
{
IDirectInputDevice8* com;
if (FAILED(base.com.CreateDevice( guid, &com, NULL )))
throw ERR_API;
if
(
FAILED(com->SetDataFormat( &c_dfDIJoystick )) ||
FAILED(com->SetCooperativeLevel( base.hWnd, DISCL_BACKGROUND|DISCL_NONEXCLUSIVE ))
)
{
com->Release();
throw ERR_API;
}
return *com;
}
BOOL CALLBACK DirectInput::Joystick::Caps::EnumObjectsProc(LPCDIDEVICEOBJECTINSTANCE const info,LPVOID const ref)
{
Context& context = *static_cast<Context*>(ref);
if (info->guidType == GUID_Button)
{
++context.numButtons;
}
else
{
uint flag;
if ( info->guidType == GUID_XAxis ) flag = AXIS_X;
else if ( info->guidType == GUID_YAxis ) flag = AXIS_Y;
else if ( info->guidType == GUID_ZAxis ) flag = AXIS_Z;
else if ( info->guidType == GUID_RxAxis ) flag = AXIS_RX;
else if ( info->guidType == GUID_RyAxis ) flag = AXIS_RY;
else if ( info->guidType == GUID_RzAxis ) flag = AXIS_RZ;
else if ( info->guidType == GUID_POV )
{
if (context.caps.axes & AXIS_POV_3)
{
return DIENUM_CONTINUE;
}
else if (context.caps.axes & AXIS_POV_2)
{
flag = AXIS_POV_3;
}
else if (context.caps.axes & AXIS_POV_1)
{
flag = AXIS_POV_2;
}
else if (context.caps.axes & AXIS_POV_0)
{
flag = AXIS_POV_1;
}
else
{
flag = AXIS_POV_0;
}
}
else if ( info->guidType == GUID_Slider )
{
if (context.caps.axes & AXIS_SLIDER_1)
{
return DIENUM_CONTINUE;
}
else if (context.caps.axes & AXIS_SLIDER_0)
{
flag = AXIS_SLIDER_1;
}
else
{
flag = AXIS_SLIDER_0;
}
}
else
{
return DIENUM_CONTINUE;
}
if (info->dwType & DIDFT_AXIS)
{
Object::Pod<DIPROPRANGE> diprg;
diprg.diph.dwSize = sizeof(diprg);
diprg.diph.dwHeaderSize = sizeof(diprg.diph);
diprg.diph.dwHow = DIPH_BYID;
diprg.diph.dwObj = info->dwType;
diprg.lMin = AXIS_MIN_RANGE;
diprg.lMax = AXIS_MAX_RANGE;
if (FAILED(context.com.SetProperty( DIPROP_RANGE, &diprg.diph )))
{
if (FAILED(context.com.GetProperty( DIPROP_RANGE, &diprg.diph )) || diprg.lMin >= 0 || diprg.lMax <= 0)
{
Io::Log() << "DirectInput: warning, SetProperty(DIPROP_RANGE) failed, skipping axis..\r\n";
return DIENUM_CONTINUE;
}
}
}
context.caps.axes |= flag;
}
return DIENUM_CONTINUE;
}
bool DirectInput::Joystick::SetAxisDeadZone(const uint value)
{
NST_ASSERT( value <= DEADZONE_MAX );
if (deadZone != value)
{
deadZone = value;
Object::Pod<DIPROPDWORD> diprd;
diprd.diph.dwSize = sizeof(diprd);
diprd.diph.dwHeaderSize = sizeof(diprd.diph);
diprd.diph.dwHow = DIPH_DEVICE;
diprd.dwData = value * 100;
com.SetProperty( DIPROP_DEADZONE, &diprd.diph );
return true;
}
return false;
}
void DirectInput::Joystick::Clear()
{
state.Clear();
state.rgdwPOV[3] = state.rgdwPOV[2] = state.rgdwPOV[1] = state.rgdwPOV[0] = DWORD(~0UL);
}
void DirectInput::Joystick::Acquire()
{
if (Device::Acquire( &state, sizeof(state) ))
{
if (!calibrated)
{
calibrated = true;
calibrator.Reset( state, false );
}
calibrator.Fix( state );
}
else
{
Clear();
}
}
void DirectInput::Joystick::Unacquire()
{
Device::Unacquire();
Clear();
}
inline void DirectInput::Joystick::Calibrator::Reset(DIJOYSTATE& state,bool full)
{
lX = full ? state.lX : 0;
lY = full ? state.lY : 0;
lZ = state.lZ;
lRx = state.lRx;
lRy = state.lRy;
lRz = state.lRz;
}
void DirectInput::Joystick::Calibrate()
{
if (SUCCEEDED(com.Acquire()))
{
Object::Pod<DIJOYSTATE> tmp;
if (SUCCEEDED(com.Poll()) && SUCCEEDED(com.GetDeviceState( sizeof(tmp), &tmp )))
{
calibrated = true;
calibrator.Reset( tmp, true );
}
com.Unacquire();
}
}
void DirectInput::Joystick::BeginScanMode() const
{
com.Acquire();
}
void DirectInput::Joystick::EndScanMode() const
{
com.Unacquire();
}
bool DirectInput::Joystick::Scan(Key& key)
{
DIJOYSTATE tmp;
if (scanEnabled && SUCCEEDED(com.Poll()) && SUCCEEDED(com.GetDeviceState( sizeof(tmp), &tmp )))
{
if (!calibrated)
{
calibrated = true;
calibrator.Reset( tmp, false );
}
calibrator.Fix( tmp );
for (uint i=0; i < Caps::NUM_BUTTONS; ++i)
{
if (tmp.rgbButtons[i] & 0x80U)
{
key.data = state.rgbButtons + i;
key.code = KeyDown;
return true;
}
}
for (uint i=0; i < TABLE_KEYS; ++i)
{
if (caps.axes & axes & table[i].axis)
{
key.data = reinterpret_cast<const BYTE*>(&tmp) + table[i].offset;
key.code = table[i].code;
if (key.GetState())
{
key.data = reinterpret_cast<const BYTE*>(&state) + table[i].offset;
return true;
}
}
}
}
return false;
}
bool DirectInput::Joystick::Map(Key& key,wcstring const name) const
{
if (*name)
{
if (name[0] >= '0' && name[0] <= '9')
{
uint index = name[0] - '0';
if (name[1] >= '0' && name[1] <= '9')
index = (index * 10) + (name[1] - '0');
if (index < Caps::NUM_BUTTONS)
{
key.data = state.rgbButtons + index;
key.code = KeyDown;
return true;
}
}
else
{
const GenericString axis( name );
for (uint i=TABLE_KEYS; i; )
{
if (caps.axes & table[--i].axis)
{
if (axis == table[i].name)
{
key.data = reinterpret_cast<const BYTE*>(&state) + table[i].offset;
key.code = table[i].code;
return true;
}
}
}
}
}
return false;
}
bool DirectInput::Joystick::Assigned(const Key& key) const
{
return
(
key.data >= reinterpret_cast<const BYTE*>(&state) &&
key.data < reinterpret_cast<const BYTE*>(&state) + sizeof(state)
);
}
wcstring DirectInput::Joystick::GetName(const Key& key) const
{
NST_VERIFY( Assigned(key) );
if (key.code == KeyDown)
{
static wchar_t button[] = L"xx";
const uint index = key.data - state.rgbButtons;
button[0] = index < 10 ? '0' + index : '0' + index / 10;
button[1] = index < 10 ? '\0' : '0' + index % 10;
return button;
}
for (const Lookup* it = table; ; ++it)
{
if (key.data == reinterpret_cast<const BYTE*>(&state) + it->offset && key.code == it->code)
return it->name;
}
}
void DirectInput::Joystick::OnError(const HRESULT hResult)
{
NST_ASSERT( FAILED(hResult) );
switch (hResult)
{
case DIERR_INPUTLOST:
case DIERR_NOTACQUIRED:
Acquire();
break;
case DIERR_UNPLUGGED:
Enable( false );
Io::Screen() << L"Error! Joystick unplugged!";
default:
Clear();
break;
}
}
#ifdef NST_MSVC_OPTIMIZE
#pragma optimize("t", on)
#endif
uint DirectInput::KeyDown(const void* const data)
{
return 0U - (*static_cast<const BYTE*>(data) >> 7);
}
uint DirectInput::KeyPosDir(const void* const data)
{
if (LONG_MIN >> (sizeof(long) * CHAR_BIT - 1) == ~0UL)
return (-*static_cast<const long*>(data) >> (sizeof(long) * CHAR_BIT - 1));
else
return (*static_cast<const long*>(data) > 0) ? ~0U : 0U;
}
uint DirectInput::KeyNegDir(const void* const data)
{
if (LONG_MIN >> (sizeof(long) * CHAR_BIT - 1) == ~0UL)
return (*static_cast<const long*>(data) >> (sizeof(long) * CHAR_BIT - 1));
else
return (*static_cast<const long*>(data) < 0) ? ~0U : 0U;
}
uint DirectInput::KeyPovUp(const void* const data)
{
const DWORD pov = *static_cast<const DWORD*>(data);
return
(
(pov & Joystick::POV_CENTER) != Joystick::POV_CENTER &&
(pov >= Joystick::POV_UPLEFT || pov <= Joystick::POV_UPRIGHT)
) ? ~0U : 0U;
}
uint DirectInput::KeyPovRight(const void* const data)
{
const DWORD pov = *static_cast<const DWORD*>(data);
return
(
(pov & Joystick::POV_CENTER) != Joystick::POV_CENTER &&
(pov >= Joystick::POV_UPRIGHT && pov <= Joystick::POV_DOWNRIGHT)
) ? ~0U : 0U;
}
uint DirectInput::KeyPovDown(const void* const data)
{
const DWORD pov = *static_cast<const DWORD*>(data);
return
(
(pov & Joystick::POV_CENTER) != Joystick::POV_CENTER &&
(pov >= Joystick::POV_DOWNRIGHT && pov <= Joystick::POV_DOWNLEFT)
) ? ~0U : 0U;
}
uint DirectInput::KeyPovLeft(const void* const data)
{
const DWORD pov = *static_cast<const DWORD*>(data);
return
(
(pov & Joystick::POV_CENTER) != Joystick::POV_CENTER &&
(pov >= Joystick::POV_DOWNLEFT && pov <= Joystick::POV_UPLEFT)
) ? ~0U : 0U;
}
uint DirectInput::KeyNone(const void* const)
{
return 0;
}
bool DirectInput::Key::GetToggle(bool& prev) const
{
if (GetState())
{
if (!prev)
{
prev = true;
return true;
}
}
else
{
prev = false;
}
return false;
}
#ifdef NST_MSVC_OPTIMIZE
#pragma optimize("", on)
#endif
bool DirectInput::Key::MapVirtualKey(const uint code,const uint vk1,const uint vk2,const uint vk3)
{
Unmap();
if (!code || code > 0xFF)
return false;
vKey = code << 8;
if (vk1 == VK_MENU || vk2 == VK_MENU || vk3 == VK_MENU)
vKey |= FALT;
if (vk1 == VK_SHIFT || vk2 == VK_SHIFT || vk3 == VK_SHIFT)
vKey |= FSHIFT;
if (vk1 == VK_CONTROL || vk2 == VK_CONTROL || vk3 == VK_CONTROL)
vKey |= FCONTROL;
// forbidden keys:
//
// ALT+F4
// ALT+F6
// ALT+TAB
// ALT+SPACE
// ALT+ESC
// CTRL+F4
// CTRL+ESC
// CTRL+ALT+DELETE
// LWIN
switch (code)
{
case VK_F4:
if (vKey & FCONTROL)
return false;
case VK_F6:
case VK_TAB:
case VK_SPACE:
if (vKey & FALT)
return false;
break;
case VK_ESCAPE:
if (vKey & (FCONTROL|FALT))
return false;
break;
case VK_DELETE:
if ((vKey & (FCONTROL|FALT)) == (FCONTROL|FALT))
return false;
break;
case VK_LWIN:
return false;
}
return true;
}
bool DirectInput::Key::MapVirtualKey(GenericString name)
{
Unmap();
if (name.Empty())
return false;
const GenericString vkNames[3] =
{
System::Keyboard::GetName( VK_CONTROL ),
System::Keyboard::GetName( VK_MENU ),
System::Keyboard::GetName( VK_SHIFT )
};
uint vk[3] = {0,0,0};
for (uint i=0; i < 3; ++i)
{
for (uint j=0; j < 3; ++j)
{
if (!vk[j] && name.Length() > vkNames[j].Length() && name(0,vkNames[j].Length()) == vkNames[j] && name[vkNames[j].Length()] == '+')
{
vk[j] = (j==0 ? VK_CONTROL : j==1 ? VK_MENU : VK_SHIFT);
name = name( vkNames[j].Length() + 1 );
break;
}
}
}
return MapVirtualKey( System::Keyboard::GetKey( name ), vk[0], vk[1], vk[2] );
}
bool DirectInput::Key::IsVirtualKey() const
{
return (code == KeyNone && data);
}
bool DirectInput::Key::GetVirtualKey(ACCEL& accel) const
{
if (code == KeyNone && data)
{
accel.fVirt = (vKey & 0xFF) | FVIRTKEY;
accel.key = vKey >> 8;
return true;
}
accel.fVirt = 0;
accel.key = 0;
return false;
}
}
}
|
JasonGoemaat/NestopiaDx9
|
source/win32/NstDirectInput.cpp
|
C++
|
gpl-2.0
| 27,427
|
<?php
/**
* @package Joomla.Administrator
* @subpackage Application
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access.
defined('_JEXEC') or die;
/*
* Joomla! system checks.
*/
@ini_set('magic_quotes_runtime', 0);
@ini_set('zend.ze1_compatibility_mode', '0');
/*
* Installation check, and check on removal of the install directory.
*/
if (!file_exists(JPATH_CONFIGURATION.'/configuration.php') || (filesize(JPATH_CONFIGURATION.'/configuration.php') < 10) || file_exists(JPATH_INSTALLATION.'/index.php')) {
header('Location: ../installation/index.php');
exit();
}
//
// Joomla system startup.
//
// System includes.
require_once JPATH_LIBRARIES.'/import.php';
// Force library to be in JError legacy mode
JError::$legacy = true;
JError::setErrorHandling(E_NOTICE, 'message');
JError::setErrorHandling(E_WARNING, 'message');
JError::setErrorHandling(E_ERROR, 'message', array('JError', 'customErrorPage'));
// Botstrap the CMS libraries.
require_once JPATH_LIBRARIES.'/cms.php';
// Pre-Load configuration.
ob_start();
require_once JPATH_CONFIGURATION.'/configuration.php';
ob_end_clean();
// System configuration.
$config = new JConfig();
// Set the error_reporting
switch ($config->error_reporting)
{
case 'default':
case '-1':
break;
case 'none':
case '0':
error_reporting(0);
break;
case 'simple':
error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('display_errors', 1);
break;
case 'maximum':
error_reporting(E_ALL);
ini_set('display_errors', 1);
break;
case 'development':
error_reporting(-1);
ini_set('display_errors', 1);
break;
default:
error_reporting($config->error_reporting);
ini_set('display_errors', 1);
break;
}
define('JDEBUG', $config->debug);
unset($config);
/*
* Joomla! framework loading.
*/
// System profiler.
if (JDEBUG) {
jimport('joomla.error.profiler');
$_PROFILER = JProfiler::getInstance('Application');
}
// Joomla! library imports.
jimport('joomla.application.menu');
jimport('joomla.environment.uri');
jimport('joomla.html.parameter');
jimport('joomla.utilities.utility');
jimport('joomla.event.dispatcher');
jimport('joomla.utilities.arrayhelper');
|
NavaINT1876/ccustoms
|
administrator/includes/framework.php
|
PHP
|
gpl-2.0
| 2,396
|
/*
* (C) Copyright 2012
* Emcraft Systems, <www.emcraft.com>
* Alexander Potashev <aspotashev@emcraft.com>
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#ifndef _MACH_KINETIS_IOMUX_H_
#define _MACH_KINETIS_IOMUX_H_
#include <linux/init.h>
/*
* Bits and bit groups inside the PCR registers (Pin Control Registers)
*/
/* Pin Mux Control (selects pin function) */
#define KINETIS_GPIO_CONFIG_MUX_BITS 8
/* Pull Enable (pull-down by default) */
#define KINETIS_GPIO_CONFIG_PE_BIT 1
#define KINETIS_GPIO_CONFIG_PE_MSK (1 << KINETIS_GPIO_CONFIG_PE_BIT)
/* Pull Select (0=pull-down, 1=pull-up) */
#define KINETIS_GPIO_CONFIG_PS_BIT 0
#define KINETIS_GPIO_CONFIG_PS_MSK (1 << KINETIS_GPIO_CONFIG_PS_BIT)
/* Drive Strength Enable (high drive strength) */
#define KINETIS_GPIO_CONFIG_DSE_MSK (1 << 6)
/* Interrupt */
#define KINETIS_GPIO_CONFIG_IRQC_MSK (0xf << 16)
#define KINETIS_GPIO_CONFIG_IRQC_LOW (0x8 << 16)
#define KINETIS_GPIO_CONFIG_IRQC_RISE (0x9 << 16)
#define KINETIS_GPIO_CONFIG_IRQC_FALL (0xa << 16)
#define KINETIS_GPIO_CONFIG_IRQC_EITHER (0xb << 16)
#define KINETIS_GPIO_CONFIG_IRQC_HIGH (0xc << 16)
/*
* These macros should be used to compute the value for the second argument of
* `kinetis_gpio_config()` (`regval`). This value will be copied into a PCR
* register.
*/
/* The simplest macro that only allow to configure the MUX bits */
#define KINETIS_GPIO_CONFIG_MUX(mux) \
(mux << KINETIS_GPIO_CONFIG_MUX_BITS)
/* Also enable the pull-down register */
#define KINETIS_GPIO_CONFIG_PULLDOWN(mux) \
(KINETIS_GPIO_CONFIG_MUX(mux) | KINETIS_GPIO_CONFIG_PE_MSK)
/* Also enable the pull-up register */
#define KINETIS_GPIO_CONFIG_PULLUP(mux) \
(KINETIS_GPIO_CONFIG_MUX(mux) | \
KINETIS_GPIO_CONFIG_PE_MSK | KINETIS_GPIO_CONFIG_PS_MSK)
/* Also enable high drive strength */
#define KINETIS_GPIO_CONFIG_DSE(mux) \
(KINETIS_GPIO_CONFIG_MUX(mux) | KINETIS_GPIO_CONFIG_DSE_MSK)
/*
* TBD: similar macros with more options
*/
/*
* Number of pins in all ports
*/
#define KINETIS_GPIO_PORT_PINS 32
/*
* Maximum possible number of GPIO ports (A..F on K70)
*/
#define KINETIS_GPIO_PORTS 6
/*
* PORTx register map
*/
struct kinetis_port_regs {
u32 pcr[32]; /* Pin Control Registers */
u32 gpclr; /* Global Pin Control Low Register */
u32 gpchr; /* Global Pin Control High Register */
u32 rsv0[6];
u32 isfr; /* Interrupt Status Flag Register */
u32 rsv1[7];
u32 dfer; /* Digital Filter Enable Register */
u32 dfcr; /* Digital Filter Clock Register */
u32 dfwr; /* Digital Filter Width Register */
};
/*
* PORTx registers base
*/
#define KINETIS_PORT_BASE(port) (KINETIS_AIPS0PERIPH_BASE + \
0x00049000 + (port) * 0x1000)
#define KINETIS_PORT(port) ((volatile struct kinetis_port_regs *) \
KINETIS_PORT_BASE(port))
/*
* GPIO ports
*/
#define KINETIS_GPIO_PORT_A 0
#define KINETIS_GPIO_PORT_B 1
#define KINETIS_GPIO_PORT_C 2
#define KINETIS_GPIO_PORT_D 3
#define KINETIS_GPIO_PORT_E 4
#define KINETIS_GPIO_PORT_F 5
/*
* GPIO descriptor
*/
struct kinetis_gpio_dsc {
unsigned int port; /* GPIO port */
unsigned int pin; /* GPIO pin */
};
struct kinetis_gpio_pin_config {
struct kinetis_gpio_dsc dsc;
u32 regval; /* Value for writing into the PCR register */
};
int kinetis_gpio_config(const struct kinetis_gpio_dsc *dsc, u32 regval);
int kinetis_gpio_config_mask(const struct kinetis_gpio_dsc *dsc, u32 mask);
int kinetis_gpio_config_unmask(const struct kinetis_gpio_dsc *dsc, u32 mask);
void __init kinetis_iomux_init(void);
#endif /* _MACH_KINETIS_IOMUX_H_ */
|
thanhnhiel/linux-emcraft
|
arch/arm/mach-kinetis/include/mach/iomux.h
|
C
|
gpl-2.0
| 4,271
|
/* Conversion from and to EBCDIC-ES-A.
Copyright (C) 1998 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <drepper@cygnus.com>, 1998.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <stdint.h>
/* Get the conversion table. */
#include <ebcdic-es-a.h>
#define CHARSET_NAME "EBCDIC-ES-A//"
#define HAS_HOLES 1 /* Not all 256 character are defined. */
#include <8bit-generic.c>
|
nslu2/glibc
|
iconvdata/ebcdic-es-a.c
|
C
|
gpl-2.0
| 1,157
|
/*
* Copyright (C) 2007-2015 Team Kodi
* http://kodi.tv
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Kodi; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#pragma once
#include "system.h"
#if defined(HAS_LIBAMCODEC)
#include "cores/VideoPlayer/VideoRenderers/BaseRenderer.h"
class CRendererAML : public CBaseRenderer
{
public:
CRendererAML();
virtual ~CRendererAML();
// Registration
static CBaseRenderer* Create(CVideoBuffer *buffer);
static bool Register();
virtual bool RenderCapture(CRenderCapture* capture) override;
virtual void AddVideoPicture(const VideoPicture &picture, int index, double currentClock) override;
virtual void ReleaseBuffer(int idx) override;
virtual bool Configure(const VideoPicture &picture, float fps, unsigned flags, unsigned int orientation) override;
virtual bool IsConfigured() override { return m_bConfigured; };
virtual bool ConfigChanged(const VideoPicture &picture) { return false; };
virtual CRenderInfo GetRenderInfo() override;
virtual void FlipPage(int source) override;
virtual void UnInit() override {};
virtual void Reset() override;
virtual void Update() override {};
virtual void RenderUpdate(bool clear, unsigned int flags = 0, unsigned int alpha = 255) override;
virtual bool SupportsMultiPassRendering()override { return false; };
// Player functions
virtual bool IsGuiLayer() override { return false; };
// Feature support
virtual bool Supports(ESCALINGMETHOD method) override { return false; };
virtual bool Supports(ERENDERFEATURE feature) override;
private:
int m_iRenderBuffer;
static const int m_numRenderBuffers = 4;
struct BUFFER
{
BUFFER() : videoBuffer(nullptr) {};
CVideoBuffer *videoBuffer;
int duration;
} m_buffers[m_numRenderBuffers];
int m_prevVPts;
bool m_bConfigured;
};
#endif
|
popcornmix/xbmc
|
xbmc/cores/VideoPlayer/VideoRenderers/HwDecRender/RendererAML.h
|
C
|
gpl-2.0
| 2,411
|
/***
This file is part of systemd.
Copyright 2013 Lennart Poettering
systemd is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
systemd is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <sys/epoll.h>
#include <sys/timerfd.h>
#include <sys/wait.h>
#include "sd-daemon.h"
#include "sd-event.h"
#include "sd-id128.h"
#include "alloc-util.h"
#include "fd-util.h"
#include "hashmap.h"
#include "list.h"
#include "macro.h"
#include "missing.h"
#include "prioq.h"
#include "process-util.h"
#include "set.h"
#include "signal-util.h"
#include "string-table.h"
#include "string-util.h"
#include "time-util.h"
#include "util.h"
#define DEFAULT_ACCURACY_USEC (250 * USEC_PER_MSEC)
typedef enum EventSourceType {
SOURCE_IO,
SOURCE_TIME_REALTIME,
SOURCE_TIME_BOOTTIME,
SOURCE_TIME_MONOTONIC,
SOURCE_TIME_REALTIME_ALARM,
SOURCE_TIME_BOOTTIME_ALARM,
SOURCE_SIGNAL,
SOURCE_CHILD,
SOURCE_DEFER,
SOURCE_POST,
SOURCE_EXIT,
SOURCE_WATCHDOG,
_SOURCE_EVENT_SOURCE_TYPE_MAX,
_SOURCE_EVENT_SOURCE_TYPE_INVALID = -1
} EventSourceType;
static const char* const event_source_type_table[_SOURCE_EVENT_SOURCE_TYPE_MAX] = {
[SOURCE_IO] = "io",
[SOURCE_TIME_REALTIME] = "realtime",
[SOURCE_TIME_BOOTTIME] = "bootime",
[SOURCE_TIME_MONOTONIC] = "monotonic",
[SOURCE_TIME_REALTIME_ALARM] = "realtime-alarm",
[SOURCE_TIME_BOOTTIME_ALARM] = "boottime-alarm",
[SOURCE_SIGNAL] = "signal",
[SOURCE_CHILD] = "child",
[SOURCE_DEFER] = "defer",
[SOURCE_POST] = "post",
[SOURCE_EXIT] = "exit",
[SOURCE_WATCHDOG] = "watchdog",
};
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(event_source_type, int);
/* All objects we use in epoll events start with this value, so that
* we know how to dispatch it */
typedef enum WakeupType {
WAKEUP_NONE,
WAKEUP_EVENT_SOURCE,
WAKEUP_CLOCK_DATA,
WAKEUP_SIGNAL_DATA,
_WAKEUP_TYPE_MAX,
_WAKEUP_TYPE_INVALID = -1,
} WakeupType;
#define EVENT_SOURCE_IS_TIME(t) IN_SET((t), SOURCE_TIME_REALTIME, SOURCE_TIME_BOOTTIME, SOURCE_TIME_MONOTONIC, SOURCE_TIME_REALTIME_ALARM, SOURCE_TIME_BOOTTIME_ALARM)
struct sd_event_source {
WakeupType wakeup;
unsigned n_ref;
sd_event *event;
void *userdata;
sd_event_handler_t prepare;
char *description;
EventSourceType type:5;
int enabled:3;
bool pending:1;
bool dispatching:1;
bool floating:1;
int64_t priority;
unsigned pending_index;
unsigned prepare_index;
unsigned pending_iteration;
unsigned prepare_iteration;
LIST_FIELDS(sd_event_source, sources);
union {
struct {
sd_event_io_handler_t callback;
int fd;
uint32_t events;
uint32_t revents;
bool registered:1;
} io;
struct {
sd_event_time_handler_t callback;
usec_t next, accuracy;
unsigned earliest_index;
unsigned latest_index;
} time;
struct {
sd_event_signal_handler_t callback;
struct signalfd_siginfo siginfo;
int sig;
} signal;
struct {
sd_event_child_handler_t callback;
siginfo_t siginfo;
pid_t pid;
int options;
} child;
struct {
sd_event_handler_t callback;
} defer;
struct {
sd_event_handler_t callback;
} post;
struct {
sd_event_handler_t callback;
unsigned prioq_index;
} exit;
};
};
struct clock_data {
WakeupType wakeup;
int fd;
/* For all clocks we maintain two priority queues each, one
* ordered for the earliest times the events may be
* dispatched, and one ordered by the latest times they must
* have been dispatched. The range between the top entries in
* the two prioqs is the time window we can freely schedule
* wakeups in */
Prioq *earliest;
Prioq *latest;
usec_t next;
bool needs_rearm:1;
};
struct signal_data {
WakeupType wakeup;
/* For each priority we maintain one signal fd, so that we
* only have to dequeue a single event per priority at a
* time. */
int fd;
int64_t priority;
sigset_t sigset;
sd_event_source *current;
};
struct sd_event {
unsigned n_ref;
int epoll_fd;
int watchdog_fd;
Prioq *pending;
Prioq *prepare;
/* timerfd_create() only supports these five clocks so far. We
* can add support for more clocks when the kernel learns to
* deal with them, too. */
struct clock_data realtime;
struct clock_data boottime;
struct clock_data monotonic;
struct clock_data realtime_alarm;
struct clock_data boottime_alarm;
usec_t perturb;
sd_event_source **signal_sources; /* indexed by signal number */
Hashmap *signal_data; /* indexed by priority */
Hashmap *child_sources;
unsigned n_enabled_child_sources;
Set *post_sources;
Prioq *exit;
pid_t original_pid;
unsigned iteration;
dual_timestamp timestamp;
usec_t timestamp_boottime;
int state;
bool exit_requested:1;
bool need_process_child:1;
bool watchdog:1;
bool profile_delays:1;
int exit_code;
pid_t tid;
sd_event **default_event_ptr;
usec_t watchdog_last, watchdog_period;
unsigned n_sources;
LIST_HEAD(sd_event_source, sources);
usec_t last_run, last_log;
unsigned delays[sizeof(usec_t) * 8];
};
static void source_disconnect(sd_event_source *s);
static int pending_prioq_compare(const void *a, const void *b) {
const sd_event_source *x = a, *y = b;
assert(x->pending);
assert(y->pending);
/* Enabled ones first */
if (x->enabled != SD_EVENT_OFF && y->enabled == SD_EVENT_OFF)
return -1;
if (x->enabled == SD_EVENT_OFF && y->enabled != SD_EVENT_OFF)
return 1;
/* Lower priority values first */
if (x->priority < y->priority)
return -1;
if (x->priority > y->priority)
return 1;
/* Older entries first */
if (x->pending_iteration < y->pending_iteration)
return -1;
if (x->pending_iteration > y->pending_iteration)
return 1;
return 0;
}
static int prepare_prioq_compare(const void *a, const void *b) {
const sd_event_source *x = a, *y = b;
assert(x->prepare);
assert(y->prepare);
/* Enabled ones first */
if (x->enabled != SD_EVENT_OFF && y->enabled == SD_EVENT_OFF)
return -1;
if (x->enabled == SD_EVENT_OFF && y->enabled != SD_EVENT_OFF)
return 1;
/* Move most recently prepared ones last, so that we can stop
* preparing as soon as we hit one that has already been
* prepared in the current iteration */
if (x->prepare_iteration < y->prepare_iteration)
return -1;
if (x->prepare_iteration > y->prepare_iteration)
return 1;
/* Lower priority values first */
if (x->priority < y->priority)
return -1;
if (x->priority > y->priority)
return 1;
return 0;
}
static int earliest_time_prioq_compare(const void *a, const void *b) {
const sd_event_source *x = a, *y = b;
assert(EVENT_SOURCE_IS_TIME(x->type));
assert(x->type == y->type);
/* Enabled ones first */
if (x->enabled != SD_EVENT_OFF && y->enabled == SD_EVENT_OFF)
return -1;
if (x->enabled == SD_EVENT_OFF && y->enabled != SD_EVENT_OFF)
return 1;
/* Move the pending ones to the end */
if (!x->pending && y->pending)
return -1;
if (x->pending && !y->pending)
return 1;
/* Order by time */
if (x->time.next < y->time.next)
return -1;
if (x->time.next > y->time.next)
return 1;
return 0;
}
static usec_t time_event_source_latest(const sd_event_source *s) {
return usec_add(s->time.next, s->time.accuracy);
}
static int latest_time_prioq_compare(const void *a, const void *b) {
const sd_event_source *x = a, *y = b;
assert(EVENT_SOURCE_IS_TIME(x->type));
assert(x->type == y->type);
/* Enabled ones first */
if (x->enabled != SD_EVENT_OFF && y->enabled == SD_EVENT_OFF)
return -1;
if (x->enabled == SD_EVENT_OFF && y->enabled != SD_EVENT_OFF)
return 1;
/* Move the pending ones to the end */
if (!x->pending && y->pending)
return -1;
if (x->pending && !y->pending)
return 1;
/* Order by time */
if (time_event_source_latest(x) < time_event_source_latest(y))
return -1;
if (time_event_source_latest(x) > time_event_source_latest(y))
return 1;
return 0;
}
static int exit_prioq_compare(const void *a, const void *b) {
const sd_event_source *x = a, *y = b;
assert(x->type == SOURCE_EXIT);
assert(y->type == SOURCE_EXIT);
/* Enabled ones first */
if (x->enabled != SD_EVENT_OFF && y->enabled == SD_EVENT_OFF)
return -1;
if (x->enabled == SD_EVENT_OFF && y->enabled != SD_EVENT_OFF)
return 1;
/* Lower priority values first */
if (x->priority < y->priority)
return -1;
if (x->priority > y->priority)
return 1;
return 0;
}
static void free_clock_data(struct clock_data *d) {
assert(d);
assert(d->wakeup == WAKEUP_CLOCK_DATA);
safe_close(d->fd);
prioq_free(d->earliest);
prioq_free(d->latest);
}
static void event_free(sd_event *e) {
sd_event_source *s;
assert(e);
while ((s = e->sources)) {
assert(s->floating);
source_disconnect(s);
sd_event_source_unref(s);
}
assert(e->n_sources == 0);
if (e->default_event_ptr)
*(e->default_event_ptr) = NULL;
safe_close(e->epoll_fd);
safe_close(e->watchdog_fd);
free_clock_data(&e->realtime);
free_clock_data(&e->boottime);
free_clock_data(&e->monotonic);
free_clock_data(&e->realtime_alarm);
free_clock_data(&e->boottime_alarm);
prioq_free(e->pending);
prioq_free(e->prepare);
prioq_free(e->exit);
free(e->signal_sources);
hashmap_free(e->signal_data);
hashmap_free(e->child_sources);
set_free(e->post_sources);
free(e);
}
_public_ int sd_event_new(sd_event** ret) {
sd_event *e;
int r;
assert_return(ret, -EINVAL);
e = new0(sd_event, 1);
if (!e)
return -ENOMEM;
e->n_ref = 1;
e->watchdog_fd = e->epoll_fd = e->realtime.fd = e->boottime.fd = e->monotonic.fd = e->realtime_alarm.fd = e->boottime_alarm.fd = -1;
e->realtime.next = e->boottime.next = e->monotonic.next = e->realtime_alarm.next = e->boottime_alarm.next = USEC_INFINITY;
e->realtime.wakeup = e->boottime.wakeup = e->monotonic.wakeup = e->realtime_alarm.wakeup = e->boottime_alarm.wakeup = WAKEUP_CLOCK_DATA;
e->original_pid = getpid();
e->perturb = USEC_INFINITY;
r = prioq_ensure_allocated(&e->pending, pending_prioq_compare);
if (r < 0)
goto fail;
e->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
if (e->epoll_fd < 0) {
r = -errno;
goto fail;
}
if (secure_getenv("SD_EVENT_PROFILE_DELAYS")) {
log_debug("Event loop profiling enabled. Logarithmic histogram of event loop iterations in the range 2^0 ... 2^63 us will be logged every 5s.");
e->profile_delays = true;
}
*ret = e;
return 0;
fail:
event_free(e);
return r;
}
_public_ sd_event* sd_event_ref(sd_event *e) {
if (!e)
return NULL;
assert(e->n_ref >= 1);
e->n_ref++;
return e;
}
_public_ sd_event* sd_event_unref(sd_event *e) {
if (!e)
return NULL;
assert(e->n_ref >= 1);
e->n_ref--;
if (e->n_ref <= 0)
event_free(e);
return NULL;
}
static bool event_pid_changed(sd_event *e) {
assert(e);
/* We don't support people creating an event loop and keeping
* it around over a fork(). Let's complain. */
return e->original_pid != getpid();
}
static void source_io_unregister(sd_event_source *s) {
int r;
assert(s);
assert(s->type == SOURCE_IO);
if (event_pid_changed(s->event))
return;
if (!s->io.registered)
return;
r = epoll_ctl(s->event->epoll_fd, EPOLL_CTL_DEL, s->io.fd, NULL);
if (r < 0)
log_debug_errno(errno, "Failed to remove source %s (type %s) from epoll: %m",
strna(s->description), event_source_type_to_string(s->type));
s->io.registered = false;
}
static int source_io_register(
sd_event_source *s,
int enabled,
uint32_t events) {
struct epoll_event ev = {};
int r;
assert(s);
assert(s->type == SOURCE_IO);
assert(enabled != SD_EVENT_OFF);
ev.events = events;
ev.data.ptr = s;
if (enabled == SD_EVENT_ONESHOT)
ev.events |= EPOLLONESHOT;
if (s->io.registered)
r = epoll_ctl(s->event->epoll_fd, EPOLL_CTL_MOD, s->io.fd, &ev);
else
r = epoll_ctl(s->event->epoll_fd, EPOLL_CTL_ADD, s->io.fd, &ev);
if (r < 0)
return -errno;
s->io.registered = true;
return 0;
}
static clockid_t event_source_type_to_clock(EventSourceType t) {
switch (t) {
case SOURCE_TIME_REALTIME:
return CLOCK_REALTIME;
case SOURCE_TIME_BOOTTIME:
return CLOCK_BOOTTIME;
case SOURCE_TIME_MONOTONIC:
return CLOCK_MONOTONIC;
case SOURCE_TIME_REALTIME_ALARM:
return CLOCK_REALTIME_ALARM;
case SOURCE_TIME_BOOTTIME_ALARM:
return CLOCK_BOOTTIME_ALARM;
default:
return (clockid_t) -1;
}
}
static EventSourceType clock_to_event_source_type(clockid_t clock) {
switch (clock) {
case CLOCK_REALTIME:
return SOURCE_TIME_REALTIME;
case CLOCK_BOOTTIME:
return SOURCE_TIME_BOOTTIME;
case CLOCK_MONOTONIC:
return SOURCE_TIME_MONOTONIC;
case CLOCK_REALTIME_ALARM:
return SOURCE_TIME_REALTIME_ALARM;
case CLOCK_BOOTTIME_ALARM:
return SOURCE_TIME_BOOTTIME_ALARM;
default:
return _SOURCE_EVENT_SOURCE_TYPE_INVALID;
}
}
static struct clock_data* event_get_clock_data(sd_event *e, EventSourceType t) {
assert(e);
switch (t) {
case SOURCE_TIME_REALTIME:
return &e->realtime;
case SOURCE_TIME_BOOTTIME:
return &e->boottime;
case SOURCE_TIME_MONOTONIC:
return &e->monotonic;
case SOURCE_TIME_REALTIME_ALARM:
return &e->realtime_alarm;
case SOURCE_TIME_BOOTTIME_ALARM:
return &e->boottime_alarm;
default:
return NULL;
}
}
static int event_make_signal_data(
sd_event *e,
int sig,
struct signal_data **ret) {
struct epoll_event ev = {};
struct signal_data *d;
bool added = false;
sigset_t ss_copy;
int64_t priority;
int r;
assert(e);
if (event_pid_changed(e))
return -ECHILD;
if (e->signal_sources && e->signal_sources[sig])
priority = e->signal_sources[sig]->priority;
else
priority = 0;
d = hashmap_get(e->signal_data, &priority);
if (d) {
if (sigismember(&d->sigset, sig) > 0) {
if (ret)
*ret = d;
return 0;
}
} else {
r = hashmap_ensure_allocated(&e->signal_data, &uint64_hash_ops);
if (r < 0)
return r;
d = new0(struct signal_data, 1);
if (!d)
return -ENOMEM;
d->wakeup = WAKEUP_SIGNAL_DATA;
d->fd = -1;
d->priority = priority;
r = hashmap_put(e->signal_data, &d->priority, d);
if (r < 0) {
free(d);
return r;
}
added = true;
}
ss_copy = d->sigset;
assert_se(sigaddset(&ss_copy, sig) >= 0);
r = signalfd(d->fd, &ss_copy, SFD_NONBLOCK|SFD_CLOEXEC);
if (r < 0) {
r = -errno;
goto fail;
}
d->sigset = ss_copy;
if (d->fd >= 0) {
if (ret)
*ret = d;
return 0;
}
d->fd = r;
ev.events = EPOLLIN;
ev.data.ptr = d;
r = epoll_ctl(e->epoll_fd, EPOLL_CTL_ADD, d->fd, &ev);
if (r < 0) {
r = -errno;
goto fail;
}
if (ret)
*ret = d;
return 0;
fail:
if (added) {
d->fd = safe_close(d->fd);
hashmap_remove(e->signal_data, &d->priority);
free(d);
}
return r;
}
static void event_unmask_signal_data(sd_event *e, struct signal_data *d, int sig) {
assert(e);
assert(d);
/* Turns off the specified signal in the signal data
* object. If the signal mask of the object becomes empty that
* way removes it. */
if (sigismember(&d->sigset, sig) == 0)
return;
assert_se(sigdelset(&d->sigset, sig) >= 0);
if (sigisemptyset(&d->sigset)) {
/* If all the mask is all-zero we can get rid of the structure */
hashmap_remove(e->signal_data, &d->priority);
assert(!d->current);
safe_close(d->fd);
free(d);
return;
}
assert(d->fd >= 0);
if (signalfd(d->fd, &d->sigset, SFD_NONBLOCK|SFD_CLOEXEC) < 0)
log_debug_errno(errno, "Failed to unset signal bit, ignoring: %m");
}
static void event_gc_signal_data(sd_event *e, const int64_t *priority, int sig) {
struct signal_data *d;
static const int64_t zero_priority = 0;
assert(e);
/* Rechecks if the specified signal is still something we are
* interested in. If not, we'll unmask it, and possibly drop
* the signalfd for it. */
if (sig == SIGCHLD &&
e->n_enabled_child_sources > 0)
return;
if (e->signal_sources &&
e->signal_sources[sig] &&
e->signal_sources[sig]->enabled != SD_EVENT_OFF)
return;
/*
* The specified signal might be enabled in three different queues:
*
* 1) the one that belongs to the priority passed (if it is non-NULL)
* 2) the one that belongs to the priority of the event source of the signal (if there is one)
* 3) the 0 priority (to cover the SIGCHLD case)
*
* Hence, let's remove it from all three here.
*/
if (priority) {
d = hashmap_get(e->signal_data, priority);
if (d)
event_unmask_signal_data(e, d, sig);
}
if (e->signal_sources && e->signal_sources[sig]) {
d = hashmap_get(e->signal_data, &e->signal_sources[sig]->priority);
if (d)
event_unmask_signal_data(e, d, sig);
}
d = hashmap_get(e->signal_data, &zero_priority);
if (d)
event_unmask_signal_data(e, d, sig);
}
static void source_disconnect(sd_event_source *s) {
sd_event *event;
assert(s);
if (!s->event)
return;
assert(s->event->n_sources > 0);
switch (s->type) {
case SOURCE_IO:
if (s->io.fd >= 0)
source_io_unregister(s);
break;
case SOURCE_TIME_REALTIME:
case SOURCE_TIME_BOOTTIME:
case SOURCE_TIME_MONOTONIC:
case SOURCE_TIME_REALTIME_ALARM:
case SOURCE_TIME_BOOTTIME_ALARM: {
struct clock_data *d;
d = event_get_clock_data(s->event, s->type);
assert(d);
prioq_remove(d->earliest, s, &s->time.earliest_index);
prioq_remove(d->latest, s, &s->time.latest_index);
d->needs_rearm = true;
break;
}
case SOURCE_SIGNAL:
if (s->signal.sig > 0) {
if (s->event->signal_sources)
s->event->signal_sources[s->signal.sig] = NULL;
event_gc_signal_data(s->event, &s->priority, s->signal.sig);
}
break;
case SOURCE_CHILD:
if (s->child.pid > 0) {
if (s->enabled != SD_EVENT_OFF) {
assert(s->event->n_enabled_child_sources > 0);
s->event->n_enabled_child_sources--;
}
(void) hashmap_remove(s->event->child_sources, PID_TO_PTR(s->child.pid));
event_gc_signal_data(s->event, &s->priority, SIGCHLD);
}
break;
case SOURCE_DEFER:
/* nothing */
break;
case SOURCE_POST:
set_remove(s->event->post_sources, s);
break;
case SOURCE_EXIT:
prioq_remove(s->event->exit, s, &s->exit.prioq_index);
break;
default:
assert_not_reached("Wut? I shouldn't exist.");
}
if (s->pending)
prioq_remove(s->event->pending, s, &s->pending_index);
if (s->prepare)
prioq_remove(s->event->prepare, s, &s->prepare_index);
event = s->event;
s->type = _SOURCE_EVENT_SOURCE_TYPE_INVALID;
s->event = NULL;
LIST_REMOVE(sources, event->sources, s);
event->n_sources--;
if (!s->floating)
sd_event_unref(event);
}
static void source_free(sd_event_source *s) {
assert(s);
source_disconnect(s);
free(s->description);
free(s);
}
static int source_set_pending(sd_event_source *s, bool b) {
int r;
assert(s);
assert(s->type != SOURCE_EXIT);
if (s->pending == b)
return 0;
s->pending = b;
if (b) {
s->pending_iteration = s->event->iteration;
r = prioq_put(s->event->pending, s, &s->pending_index);
if (r < 0) {
s->pending = false;
return r;
}
} else
assert_se(prioq_remove(s->event->pending, s, &s->pending_index));
if (EVENT_SOURCE_IS_TIME(s->type)) {
struct clock_data *d;
d = event_get_clock_data(s->event, s->type);
assert(d);
prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
prioq_reshuffle(d->latest, s, &s->time.latest_index);
d->needs_rearm = true;
}
if (s->type == SOURCE_SIGNAL && !b) {
struct signal_data *d;
d = hashmap_get(s->event->signal_data, &s->priority);
if (d && d->current == s)
d->current = NULL;
}
return 0;
}
static sd_event_source *source_new(sd_event *e, bool floating, EventSourceType type) {
sd_event_source *s;
assert(e);
s = new0(sd_event_source, 1);
if (!s)
return NULL;
s->n_ref = 1;
s->event = e;
s->floating = floating;
s->type = type;
s->pending_index = s->prepare_index = PRIOQ_IDX_NULL;
if (!floating)
sd_event_ref(e);
LIST_PREPEND(sources, e->sources, s);
e->n_sources++;
return s;
}
_public_ int sd_event_add_io(
sd_event *e,
sd_event_source **ret,
int fd,
uint32_t events,
sd_event_io_handler_t callback,
void *userdata) {
sd_event_source *s;
int r;
assert_return(e, -EINVAL);
assert_return(fd >= 0, -EBADF);
assert_return(!(events & ~(EPOLLIN|EPOLLOUT|EPOLLRDHUP|EPOLLPRI|EPOLLERR|EPOLLHUP|EPOLLET)), -EINVAL);
assert_return(callback, -EINVAL);
assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
assert_return(!event_pid_changed(e), -ECHILD);
s = source_new(e, !ret, SOURCE_IO);
if (!s)
return -ENOMEM;
s->wakeup = WAKEUP_EVENT_SOURCE;
s->io.fd = fd;
s->io.events = events;
s->io.callback = callback;
s->userdata = userdata;
s->enabled = SD_EVENT_ON;
r = source_io_register(s, s->enabled, events);
if (r < 0) {
source_free(s);
return r;
}
if (ret)
*ret = s;
return 0;
}
static void initialize_perturb(sd_event *e) {
sd_id128_t bootid = {};
/* When we sleep for longer, we try to realign the wakeup to
the same time wihtin each minute/second/250ms, so that
events all across the system can be coalesced into a single
CPU wakeup. However, let's take some system-specific
randomness for this value, so that in a network of systems
with synced clocks timer events are distributed a
bit. Here, we calculate a perturbation usec offset from the
boot ID. */
if (_likely_(e->perturb != USEC_INFINITY))
return;
if (sd_id128_get_boot(&bootid) >= 0)
e->perturb = (bootid.qwords[0] ^ bootid.qwords[1]) % USEC_PER_MINUTE;
}
static int event_setup_timer_fd(
sd_event *e,
struct clock_data *d,
clockid_t clock) {
struct epoll_event ev = {};
int r, fd;
assert(e);
assert(d);
if (_likely_(d->fd >= 0))
return 0;
fd = timerfd_create(clock, TFD_NONBLOCK|TFD_CLOEXEC);
if (fd < 0)
return -errno;
ev.events = EPOLLIN;
ev.data.ptr = d;
r = epoll_ctl(e->epoll_fd, EPOLL_CTL_ADD, fd, &ev);
if (r < 0) {
safe_close(fd);
return -errno;
}
d->fd = fd;
return 0;
}
static int time_exit_callback(sd_event_source *s, uint64_t usec, void *userdata) {
assert(s);
return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
}
_public_ int sd_event_add_time(
sd_event *e,
sd_event_source **ret,
clockid_t clock,
uint64_t usec,
uint64_t accuracy,
sd_event_time_handler_t callback,
void *userdata) {
EventSourceType type;
sd_event_source *s;
struct clock_data *d;
int r;
assert_return(e, -EINVAL);
assert_return(accuracy != (uint64_t) -1, -EINVAL);
assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
assert_return(!event_pid_changed(e), -ECHILD);
if (IN_SET(clock, CLOCK_BOOTTIME, CLOCK_BOOTTIME_ALARM) &&
!clock_boottime_supported())
return -EOPNOTSUPP;
if (!callback)
callback = time_exit_callback;
type = clock_to_event_source_type(clock);
assert_return(type >= 0, -EOPNOTSUPP);
d = event_get_clock_data(e, type);
assert(d);
r = prioq_ensure_allocated(&d->earliest, earliest_time_prioq_compare);
if (r < 0)
return r;
r = prioq_ensure_allocated(&d->latest, latest_time_prioq_compare);
if (r < 0)
return r;
if (d->fd < 0) {
r = event_setup_timer_fd(e, d, clock);
if (r < 0)
return r;
}
s = source_new(e, !ret, type);
if (!s)
return -ENOMEM;
s->time.next = usec;
s->time.accuracy = accuracy == 0 ? DEFAULT_ACCURACY_USEC : accuracy;
s->time.callback = callback;
s->time.earliest_index = s->time.latest_index = PRIOQ_IDX_NULL;
s->userdata = userdata;
s->enabled = SD_EVENT_ONESHOT;
d->needs_rearm = true;
r = prioq_put(d->earliest, s, &s->time.earliest_index);
if (r < 0)
goto fail;
r = prioq_put(d->latest, s, &s->time.latest_index);
if (r < 0)
goto fail;
if (ret)
*ret = s;
return 0;
fail:
source_free(s);
return r;
}
static int signal_exit_callback(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
assert(s);
return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
}
_public_ int sd_event_add_signal(
sd_event *e,
sd_event_source **ret,
int sig,
sd_event_signal_handler_t callback,
void *userdata) {
sd_event_source *s;
struct signal_data *d;
sigset_t ss;
int r;
assert_return(e, -EINVAL);
assert_return(SIGNAL_VALID(sig), -EINVAL);
assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
assert_return(!event_pid_changed(e), -ECHILD);
if (!callback)
callback = signal_exit_callback;
r = pthread_sigmask(SIG_SETMASK, NULL, &ss);
if (r != 0)
return -r;
if (!sigismember(&ss, sig))
return -EBUSY;
if (!e->signal_sources) {
e->signal_sources = new0(sd_event_source*, _NSIG);
if (!e->signal_sources)
return -ENOMEM;
} else if (e->signal_sources[sig])
return -EBUSY;
s = source_new(e, !ret, SOURCE_SIGNAL);
if (!s)
return -ENOMEM;
s->signal.sig = sig;
s->signal.callback = callback;
s->userdata = userdata;
s->enabled = SD_EVENT_ON;
e->signal_sources[sig] = s;
r = event_make_signal_data(e, sig, &d);
if (r < 0) {
source_free(s);
return r;
}
/* Use the signal name as description for the event source by default */
(void) sd_event_source_set_description(s, signal_to_string(sig));
if (ret)
*ret = s;
return 0;
}
_public_ int sd_event_add_child(
sd_event *e,
sd_event_source **ret,
pid_t pid,
int options,
sd_event_child_handler_t callback,
void *userdata) {
sd_event_source *s;
int r;
assert_return(e, -EINVAL);
assert_return(pid > 1, -EINVAL);
assert_return(!(options & ~(WEXITED|WSTOPPED|WCONTINUED)), -EINVAL);
assert_return(options != 0, -EINVAL);
assert_return(callback, -EINVAL);
assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
assert_return(!event_pid_changed(e), -ECHILD);
r = hashmap_ensure_allocated(&e->child_sources, NULL);
if (r < 0)
return r;
if (hashmap_contains(e->child_sources, PID_TO_PTR(pid)))
return -EBUSY;
s = source_new(e, !ret, SOURCE_CHILD);
if (!s)
return -ENOMEM;
s->child.pid = pid;
s->child.options = options;
s->child.callback = callback;
s->userdata = userdata;
s->enabled = SD_EVENT_ONESHOT;
r = hashmap_put(e->child_sources, PID_TO_PTR(pid), s);
if (r < 0) {
source_free(s);
return r;
}
e->n_enabled_child_sources++;
r = event_make_signal_data(e, SIGCHLD, NULL);
if (r < 0) {
e->n_enabled_child_sources--;
source_free(s);
return r;
}
e->need_process_child = true;
if (ret)
*ret = s;
return 0;
}
_public_ int sd_event_add_defer(
sd_event *e,
sd_event_source **ret,
sd_event_handler_t callback,
void *userdata) {
sd_event_source *s;
int r;
assert_return(e, -EINVAL);
assert_return(callback, -EINVAL);
assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
assert_return(!event_pid_changed(e), -ECHILD);
s = source_new(e, !ret, SOURCE_DEFER);
if (!s)
return -ENOMEM;
s->defer.callback = callback;
s->userdata = userdata;
s->enabled = SD_EVENT_ONESHOT;
r = source_set_pending(s, true);
if (r < 0) {
source_free(s);
return r;
}
if (ret)
*ret = s;
return 0;
}
_public_ int sd_event_add_post(
sd_event *e,
sd_event_source **ret,
sd_event_handler_t callback,
void *userdata) {
sd_event_source *s;
int r;
assert_return(e, -EINVAL);
assert_return(callback, -EINVAL);
assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
assert_return(!event_pid_changed(e), -ECHILD);
r = set_ensure_allocated(&e->post_sources, NULL);
if (r < 0)
return r;
s = source_new(e, !ret, SOURCE_POST);
if (!s)
return -ENOMEM;
s->post.callback = callback;
s->userdata = userdata;
s->enabled = SD_EVENT_ON;
r = set_put(e->post_sources, s);
if (r < 0) {
source_free(s);
return r;
}
if (ret)
*ret = s;
return 0;
}
_public_ int sd_event_add_exit(
sd_event *e,
sd_event_source **ret,
sd_event_handler_t callback,
void *userdata) {
sd_event_source *s;
int r;
assert_return(e, -EINVAL);
assert_return(callback, -EINVAL);
assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
assert_return(!event_pid_changed(e), -ECHILD);
r = prioq_ensure_allocated(&e->exit, exit_prioq_compare);
if (r < 0)
return r;
s = source_new(e, !ret, SOURCE_EXIT);
if (!s)
return -ENOMEM;
s->exit.callback = callback;
s->userdata = userdata;
s->exit.prioq_index = PRIOQ_IDX_NULL;
s->enabled = SD_EVENT_ONESHOT;
r = prioq_put(s->event->exit, s, &s->exit.prioq_index);
if (r < 0) {
source_free(s);
return r;
}
if (ret)
*ret = s;
return 0;
}
_public_ sd_event_source* sd_event_source_ref(sd_event_source *s) {
if (!s)
return NULL;
assert(s->n_ref >= 1);
s->n_ref++;
return s;
}
_public_ sd_event_source* sd_event_source_unref(sd_event_source *s) {
if (!s)
return NULL;
assert(s->n_ref >= 1);
s->n_ref--;
if (s->n_ref <= 0) {
/* Here's a special hack: when we are called from a
* dispatch handler we won't free the event source
* immediately, but we will detach the fd from the
* epoll. This way it is safe for the caller to unref
* the event source and immediately close the fd, but
* we still retain a valid event source object after
* the callback. */
if (s->dispatching) {
if (s->type == SOURCE_IO)
source_io_unregister(s);
source_disconnect(s);
} else
source_free(s);
}
return NULL;
}
_public_ int sd_event_source_set_description(sd_event_source *s, const char *description) {
assert_return(s, -EINVAL);
assert_return(!event_pid_changed(s->event), -ECHILD);
return free_and_strdup(&s->description, description);
}
_public_ int sd_event_source_get_description(sd_event_source *s, const char **description) {
assert_return(s, -EINVAL);
assert_return(description, -EINVAL);
assert_return(s->description, -ENXIO);
assert_return(!event_pid_changed(s->event), -ECHILD);
*description = s->description;
return 0;
}
_public_ sd_event *sd_event_source_get_event(sd_event_source *s) {
assert_return(s, NULL);
return s->event;
}
_public_ int sd_event_source_get_pending(sd_event_source *s) {
assert_return(s, -EINVAL);
assert_return(s->type != SOURCE_EXIT, -EDOM);
assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
assert_return(!event_pid_changed(s->event), -ECHILD);
return s->pending;
}
_public_ int sd_event_source_get_io_fd(sd_event_source *s) {
assert_return(s, -EINVAL);
assert_return(s->type == SOURCE_IO, -EDOM);
assert_return(!event_pid_changed(s->event), -ECHILD);
return s->io.fd;
}
_public_ int sd_event_source_set_io_fd(sd_event_source *s, int fd) {
int r;
assert_return(s, -EINVAL);
assert_return(fd >= 0, -EBADF);
assert_return(s->type == SOURCE_IO, -EDOM);
assert_return(!event_pid_changed(s->event), -ECHILD);
if (s->io.fd == fd)
return 0;
if (s->enabled == SD_EVENT_OFF) {
s->io.fd = fd;
s->io.registered = false;
} else {
int saved_fd;
saved_fd = s->io.fd;
assert(s->io.registered);
s->io.fd = fd;
s->io.registered = false;
r = source_io_register(s, s->enabled, s->io.events);
if (r < 0) {
s->io.fd = saved_fd;
s->io.registered = true;
return r;
}
epoll_ctl(s->event->epoll_fd, EPOLL_CTL_DEL, saved_fd, NULL);
}
return 0;
}
_public_ int sd_event_source_get_io_events(sd_event_source *s, uint32_t* events) {
assert_return(s, -EINVAL);
assert_return(events, -EINVAL);
assert_return(s->type == SOURCE_IO, -EDOM);
assert_return(!event_pid_changed(s->event), -ECHILD);
*events = s->io.events;
return 0;
}
_public_ int sd_event_source_set_io_events(sd_event_source *s, uint32_t events) {
int r;
assert_return(s, -EINVAL);
assert_return(s->type == SOURCE_IO, -EDOM);
assert_return(!(events & ~(EPOLLIN|EPOLLOUT|EPOLLRDHUP|EPOLLPRI|EPOLLERR|EPOLLHUP|EPOLLET)), -EINVAL);
assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
assert_return(!event_pid_changed(s->event), -ECHILD);
/* edge-triggered updates are never skipped, so we can reset edges */
if (s->io.events == events && !(events & EPOLLET))
return 0;
if (s->enabled != SD_EVENT_OFF) {
r = source_io_register(s, s->enabled, events);
if (r < 0)
return r;
}
s->io.events = events;
source_set_pending(s, false);
return 0;
}
_public_ int sd_event_source_get_io_revents(sd_event_source *s, uint32_t* revents) {
assert_return(s, -EINVAL);
assert_return(revents, -EINVAL);
assert_return(s->type == SOURCE_IO, -EDOM);
assert_return(s->pending, -ENODATA);
assert_return(!event_pid_changed(s->event), -ECHILD);
*revents = s->io.revents;
return 0;
}
_public_ int sd_event_source_get_signal(sd_event_source *s) {
assert_return(s, -EINVAL);
assert_return(s->type == SOURCE_SIGNAL, -EDOM);
assert_return(!event_pid_changed(s->event), -ECHILD);
return s->signal.sig;
}
_public_ int sd_event_source_get_priority(sd_event_source *s, int64_t *priority) {
assert_return(s, -EINVAL);
assert_return(!event_pid_changed(s->event), -ECHILD);
return s->priority;
}
_public_ int sd_event_source_set_priority(sd_event_source *s, int64_t priority) {
int r;
assert_return(s, -EINVAL);
assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
assert_return(!event_pid_changed(s->event), -ECHILD);
if (s->priority == priority)
return 0;
if (s->type == SOURCE_SIGNAL && s->enabled != SD_EVENT_OFF) {
struct signal_data *old, *d;
/* Move us from the signalfd belonging to the old
* priority to the signalfd of the new priority */
assert_se(old = hashmap_get(s->event->signal_data, &s->priority));
s->priority = priority;
r = event_make_signal_data(s->event, s->signal.sig, &d);
if (r < 0) {
s->priority = old->priority;
return r;
}
event_unmask_signal_data(s->event, old, s->signal.sig);
} else
s->priority = priority;
if (s->pending)
prioq_reshuffle(s->event->pending, s, &s->pending_index);
if (s->prepare)
prioq_reshuffle(s->event->prepare, s, &s->prepare_index);
if (s->type == SOURCE_EXIT)
prioq_reshuffle(s->event->exit, s, &s->exit.prioq_index);
return 0;
}
_public_ int sd_event_source_get_enabled(sd_event_source *s, int *m) {
assert_return(s, -EINVAL);
assert_return(m, -EINVAL);
assert_return(!event_pid_changed(s->event), -ECHILD);
*m = s->enabled;
return 0;
}
_public_ int sd_event_source_set_enabled(sd_event_source *s, int m) {
int r;
assert_return(s, -EINVAL);
assert_return(m == SD_EVENT_OFF || m == SD_EVENT_ON || m == SD_EVENT_ONESHOT, -EINVAL);
assert_return(!event_pid_changed(s->event), -ECHILD);
/* If we are dead anyway, we are fine with turning off
* sources, but everything else needs to fail. */
if (s->event->state == SD_EVENT_FINISHED)
return m == SD_EVENT_OFF ? 0 : -ESTALE;
if (s->enabled == m)
return 0;
if (m == SD_EVENT_OFF) {
switch (s->type) {
case SOURCE_IO:
source_io_unregister(s);
s->enabled = m;
break;
case SOURCE_TIME_REALTIME:
case SOURCE_TIME_BOOTTIME:
case SOURCE_TIME_MONOTONIC:
case SOURCE_TIME_REALTIME_ALARM:
case SOURCE_TIME_BOOTTIME_ALARM: {
struct clock_data *d;
s->enabled = m;
d = event_get_clock_data(s->event, s->type);
assert(d);
prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
prioq_reshuffle(d->latest, s, &s->time.latest_index);
d->needs_rearm = true;
break;
}
case SOURCE_SIGNAL:
s->enabled = m;
event_gc_signal_data(s->event, &s->priority, s->signal.sig);
break;
case SOURCE_CHILD:
s->enabled = m;
assert(s->event->n_enabled_child_sources > 0);
s->event->n_enabled_child_sources--;
event_gc_signal_data(s->event, &s->priority, SIGCHLD);
break;
case SOURCE_EXIT:
s->enabled = m;
prioq_reshuffle(s->event->exit, s, &s->exit.prioq_index);
break;
case SOURCE_DEFER:
case SOURCE_POST:
s->enabled = m;
break;
default:
assert_not_reached("Wut? I shouldn't exist.");
}
} else {
switch (s->type) {
case SOURCE_IO:
r = source_io_register(s, m, s->io.events);
if (r < 0)
return r;
s->enabled = m;
break;
case SOURCE_TIME_REALTIME:
case SOURCE_TIME_BOOTTIME:
case SOURCE_TIME_MONOTONIC:
case SOURCE_TIME_REALTIME_ALARM:
case SOURCE_TIME_BOOTTIME_ALARM: {
struct clock_data *d;
s->enabled = m;
d = event_get_clock_data(s->event, s->type);
assert(d);
prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
prioq_reshuffle(d->latest, s, &s->time.latest_index);
d->needs_rearm = true;
break;
}
case SOURCE_SIGNAL:
s->enabled = m;
r = event_make_signal_data(s->event, s->signal.sig, NULL);
if (r < 0) {
s->enabled = SD_EVENT_OFF;
event_gc_signal_data(s->event, &s->priority, s->signal.sig);
return r;
}
break;
case SOURCE_CHILD:
if (s->enabled == SD_EVENT_OFF)
s->event->n_enabled_child_sources++;
s->enabled = m;
r = event_make_signal_data(s->event, SIGCHLD, NULL);
if (r < 0) {
s->enabled = SD_EVENT_OFF;
s->event->n_enabled_child_sources--;
event_gc_signal_data(s->event, &s->priority, SIGCHLD);
return r;
}
break;
case SOURCE_EXIT:
s->enabled = m;
prioq_reshuffle(s->event->exit, s, &s->exit.prioq_index);
break;
case SOURCE_DEFER:
case SOURCE_POST:
s->enabled = m;
break;
default:
assert_not_reached("Wut? I shouldn't exist.");
}
}
if (s->pending)
prioq_reshuffle(s->event->pending, s, &s->pending_index);
if (s->prepare)
prioq_reshuffle(s->event->prepare, s, &s->prepare_index);
return 0;
}
_public_ int sd_event_source_get_time(sd_event_source *s, uint64_t *usec) {
assert_return(s, -EINVAL);
assert_return(usec, -EINVAL);
assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
assert_return(!event_pid_changed(s->event), -ECHILD);
*usec = s->time.next;
return 0;
}
_public_ int sd_event_source_set_time(sd_event_source *s, uint64_t usec) {
struct clock_data *d;
assert_return(s, -EINVAL);
assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
assert_return(!event_pid_changed(s->event), -ECHILD);
s->time.next = usec;
source_set_pending(s, false);
d = event_get_clock_data(s->event, s->type);
assert(d);
prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
prioq_reshuffle(d->latest, s, &s->time.latest_index);
d->needs_rearm = true;
return 0;
}
_public_ int sd_event_source_get_time_accuracy(sd_event_source *s, uint64_t *usec) {
assert_return(s, -EINVAL);
assert_return(usec, -EINVAL);
assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
assert_return(!event_pid_changed(s->event), -ECHILD);
*usec = s->time.accuracy;
return 0;
}
_public_ int sd_event_source_set_time_accuracy(sd_event_source *s, uint64_t usec) {
struct clock_data *d;
assert_return(s, -EINVAL);
assert_return(usec != (uint64_t) -1, -EINVAL);
assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
assert_return(!event_pid_changed(s->event), -ECHILD);
if (usec == 0)
usec = DEFAULT_ACCURACY_USEC;
s->time.accuracy = usec;
source_set_pending(s, false);
d = event_get_clock_data(s->event, s->type);
assert(d);
prioq_reshuffle(d->latest, s, &s->time.latest_index);
d->needs_rearm = true;
return 0;
}
_public_ int sd_event_source_get_time_clock(sd_event_source *s, clockid_t *clock) {
assert_return(s, -EINVAL);
assert_return(clock, -EINVAL);
assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
assert_return(!event_pid_changed(s->event), -ECHILD);
*clock = event_source_type_to_clock(s->type);
return 0;
}
_public_ int sd_event_source_get_child_pid(sd_event_source *s, pid_t *pid) {
assert_return(s, -EINVAL);
assert_return(pid, -EINVAL);
assert_return(s->type == SOURCE_CHILD, -EDOM);
assert_return(!event_pid_changed(s->event), -ECHILD);
*pid = s->child.pid;
return 0;
}
_public_ int sd_event_source_set_prepare(sd_event_source *s, sd_event_handler_t callback) {
int r;
assert_return(s, -EINVAL);
assert_return(s->type != SOURCE_EXIT, -EDOM);
assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
assert_return(!event_pid_changed(s->event), -ECHILD);
if (s->prepare == callback)
return 0;
if (callback && s->prepare) {
s->prepare = callback;
return 0;
}
r = prioq_ensure_allocated(&s->event->prepare, prepare_prioq_compare);
if (r < 0)
return r;
s->prepare = callback;
if (callback) {
r = prioq_put(s->event->prepare, s, &s->prepare_index);
if (r < 0)
return r;
} else
prioq_remove(s->event->prepare, s, &s->prepare_index);
return 0;
}
_public_ void* sd_event_source_get_userdata(sd_event_source *s) {
assert_return(s, NULL);
return s->userdata;
}
_public_ void *sd_event_source_set_userdata(sd_event_source *s, void *userdata) {
void *ret;
assert_return(s, NULL);
ret = s->userdata;
s->userdata = userdata;
return ret;
}
static usec_t sleep_between(sd_event *e, usec_t a, usec_t b) {
usec_t c;
assert(e);
assert(a <= b);
if (a <= 0)
return 0;
if (a >= USEC_INFINITY)
return USEC_INFINITY;
if (b <= a + 1)
return a;
initialize_perturb(e);
/*
Find a good time to wake up again between times a and b. We
have two goals here:
a) We want to wake up as seldom as possible, hence prefer
later times over earlier times.
b) But if we have to wake up, then let's make sure to
dispatch as much as possible on the entire system.
We implement this by waking up everywhere at the same time
within any given minute if we can, synchronised via the
perturbation value determined from the boot ID. If we can't,
then we try to find the same spot in every 10s, then 1s and
then 250ms step. Otherwise, we pick the last possible time
to wake up.
*/
c = (b / USEC_PER_MINUTE) * USEC_PER_MINUTE + e->perturb;
if (c >= b) {
if (_unlikely_(c < USEC_PER_MINUTE))
return b;
c -= USEC_PER_MINUTE;
}
if (c >= a)
return c;
c = (b / (USEC_PER_SEC*10)) * (USEC_PER_SEC*10) + (e->perturb % (USEC_PER_SEC*10));
if (c >= b) {
if (_unlikely_(c < USEC_PER_SEC*10))
return b;
c -= USEC_PER_SEC*10;
}
if (c >= a)
return c;
c = (b / USEC_PER_SEC) * USEC_PER_SEC + (e->perturb % USEC_PER_SEC);
if (c >= b) {
if (_unlikely_(c < USEC_PER_SEC))
return b;
c -= USEC_PER_SEC;
}
if (c >= a)
return c;
c = (b / (USEC_PER_MSEC*250)) * (USEC_PER_MSEC*250) + (e->perturb % (USEC_PER_MSEC*250));
if (c >= b) {
if (_unlikely_(c < USEC_PER_MSEC*250))
return b;
c -= USEC_PER_MSEC*250;
}
if (c >= a)
return c;
return b;
}
static int event_arm_timer(
sd_event *e,
struct clock_data *d) {
struct itimerspec its = {};
sd_event_source *a, *b;
usec_t t;
int r;
assert(e);
assert(d);
if (!d->needs_rearm)
return 0;
else
d->needs_rearm = false;
a = prioq_peek(d->earliest);
if (!a || a->enabled == SD_EVENT_OFF || a->time.next == USEC_INFINITY) {
if (d->fd < 0)
return 0;
if (d->next == USEC_INFINITY)
return 0;
/* disarm */
r = timerfd_settime(d->fd, TFD_TIMER_ABSTIME, &its, NULL);
if (r < 0)
return r;
d->next = USEC_INFINITY;
return 0;
}
b = prioq_peek(d->latest);
assert_se(b && b->enabled != SD_EVENT_OFF);
t = sleep_between(e, a->time.next, time_event_source_latest(b));
if (d->next == t)
return 0;
assert_se(d->fd >= 0);
if (t == 0) {
/* We don' want to disarm here, just mean some time looooong ago. */
its.it_value.tv_sec = 0;
its.it_value.tv_nsec = 1;
} else
timespec_store(&its.it_value, t);
r = timerfd_settime(d->fd, TFD_TIMER_ABSTIME, &its, NULL);
if (r < 0)
return -errno;
d->next = t;
return 0;
}
static int process_io(sd_event *e, sd_event_source *s, uint32_t revents) {
assert(e);
assert(s);
assert(s->type == SOURCE_IO);
/* If the event source was already pending, we just OR in the
* new revents, otherwise we reset the value. The ORing is
* necessary to handle EPOLLONESHOT events properly where
* readability might happen independently of writability, and
* we need to keep track of both */
if (s->pending)
s->io.revents |= revents;
else
s->io.revents = revents;
return source_set_pending(s, true);
}
static int flush_timer(sd_event *e, int fd, uint32_t events, usec_t *next) {
uint64_t x;
ssize_t ss;
assert(e);
assert(fd >= 0);
assert_return(events == EPOLLIN, -EIO);
ss = read(fd, &x, sizeof(x));
if (ss < 0) {
if (errno == EAGAIN || errno == EINTR)
return 0;
return -errno;
}
if (_unlikely_(ss != sizeof(x)))
return -EIO;
if (next)
*next = USEC_INFINITY;
return 0;
}
static int process_timer(
sd_event *e,
usec_t n,
struct clock_data *d) {
sd_event_source *s;
int r;
assert(e);
assert(d);
for (;;) {
s = prioq_peek(d->earliest);
if (!s ||
s->time.next > n ||
s->enabled == SD_EVENT_OFF ||
s->pending)
break;
r = source_set_pending(s, true);
if (r < 0)
return r;
prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
prioq_reshuffle(d->latest, s, &s->time.latest_index);
d->needs_rearm = true;
}
return 0;
}
static int process_child(sd_event *e) {
sd_event_source *s;
Iterator i;
int r;
assert(e);
e->need_process_child = false;
/*
So, this is ugly. We iteratively invoke waitid() with P_PID
+ WNOHANG for each PID we wait for, instead of using
P_ALL. This is because we only want to get child
information of very specific child processes, and not all
of them. We might not have processed the SIGCHLD even of a
previous invocation and we don't want to maintain a
unbounded *per-child* event queue, hence we really don't
want anything flushed out of the kernel's queue that we
don't care about. Since this is O(n) this means that if you
have a lot of processes you probably want to handle SIGCHLD
yourself.
We do not reap the children here (by using WNOWAIT), this
is only done after the event source is dispatched so that
the callback still sees the process as a zombie.
*/
HASHMAP_FOREACH(s, e->child_sources, i) {
assert(s->type == SOURCE_CHILD);
if (s->pending)
continue;
if (s->enabled == SD_EVENT_OFF)
continue;
zero(s->child.siginfo);
r = waitid(P_PID, s->child.pid, &s->child.siginfo,
WNOHANG | (s->child.options & WEXITED ? WNOWAIT : 0) | s->child.options);
if (r < 0)
return -errno;
if (s->child.siginfo.si_pid != 0) {
bool zombie =
s->child.siginfo.si_code == CLD_EXITED ||
s->child.siginfo.si_code == CLD_KILLED ||
s->child.siginfo.si_code == CLD_DUMPED;
if (!zombie && (s->child.options & WEXITED)) {
/* If the child isn't dead then let's
* immediately remove the state change
* from the queue, since there's no
* benefit in leaving it queued */
assert(s->child.options & (WSTOPPED|WCONTINUED));
waitid(P_PID, s->child.pid, &s->child.siginfo, WNOHANG|(s->child.options & (WSTOPPED|WCONTINUED)));
}
r = source_set_pending(s, true);
if (r < 0)
return r;
}
}
return 0;
}
static int process_signal(sd_event *e, struct signal_data *d, uint32_t events) {
bool read_one = false;
int r;
assert(e);
assert_return(events == EPOLLIN, -EIO);
/* If there's a signal queued on this priority and SIGCHLD is
on this priority too, then make sure to recheck the
children we watch. This is because we only ever dequeue
the first signal per priority, and if we dequeue one, and
SIGCHLD might be enqueued later we wouldn't know, but we
might have higher priority children we care about hence we
need to check that explicitly. */
if (sigismember(&d->sigset, SIGCHLD))
e->need_process_child = true;
/* If there's already an event source pending for this
* priority we don't read another */
if (d->current)
return 0;
for (;;) {
struct signalfd_siginfo si;
ssize_t n;
sd_event_source *s = NULL;
n = read(d->fd, &si, sizeof(si));
if (n < 0) {
if (errno == EAGAIN || errno == EINTR)
return read_one;
return -errno;
}
if (_unlikely_(n != sizeof(si)))
return -EIO;
assert(SIGNAL_VALID(si.ssi_signo));
read_one = true;
if (e->signal_sources)
s = e->signal_sources[si.ssi_signo];
if (!s)
continue;
if (s->pending)
continue;
s->signal.siginfo = si;
d->current = s;
r = source_set_pending(s, true);
if (r < 0)
return r;
return 1;
}
}
static int source_dispatch(sd_event_source *s) {
int r = 0;
assert(s);
assert(s->pending || s->type == SOURCE_EXIT);
if (s->type != SOURCE_DEFER && s->type != SOURCE_EXIT) {
r = source_set_pending(s, false);
if (r < 0)
return r;
}
if (s->type != SOURCE_POST) {
sd_event_source *z;
Iterator i;
/* If we execute a non-post source, let's mark all
* post sources as pending */
SET_FOREACH(z, s->event->post_sources, i) {
if (z->enabled == SD_EVENT_OFF)
continue;
r = source_set_pending(z, true);
if (r < 0)
return r;
}
}
if (s->enabled == SD_EVENT_ONESHOT) {
r = sd_event_source_set_enabled(s, SD_EVENT_OFF);
if (r < 0)
return r;
}
s->dispatching = true;
switch (s->type) {
case SOURCE_IO:
r = s->io.callback(s, s->io.fd, s->io.revents, s->userdata);
break;
case SOURCE_TIME_REALTIME:
case SOURCE_TIME_BOOTTIME:
case SOURCE_TIME_MONOTONIC:
case SOURCE_TIME_REALTIME_ALARM:
case SOURCE_TIME_BOOTTIME_ALARM:
r = s->time.callback(s, s->time.next, s->userdata);
break;
case SOURCE_SIGNAL:
r = s->signal.callback(s, &s->signal.siginfo, s->userdata);
break;
case SOURCE_CHILD: {
bool zombie;
zombie = s->child.siginfo.si_code == CLD_EXITED ||
s->child.siginfo.si_code == CLD_KILLED ||
s->child.siginfo.si_code == CLD_DUMPED;
r = s->child.callback(s, &s->child.siginfo, s->userdata);
/* Now, reap the PID for good. */
if (zombie)
waitid(P_PID, s->child.pid, &s->child.siginfo, WNOHANG|WEXITED);
break;
}
case SOURCE_DEFER:
r = s->defer.callback(s, s->userdata);
break;
case SOURCE_POST:
r = s->post.callback(s, s->userdata);
break;
case SOURCE_EXIT:
r = s->exit.callback(s, s->userdata);
break;
case SOURCE_WATCHDOG:
case _SOURCE_EVENT_SOURCE_TYPE_MAX:
case _SOURCE_EVENT_SOURCE_TYPE_INVALID:
assert_not_reached("Wut? I shouldn't exist.");
}
s->dispatching = false;
if (r < 0)
log_debug_errno(r, "Event source %s (type %s) returned error, disabling: %m",
strna(s->description), event_source_type_to_string(s->type));
if (s->n_ref == 0)
source_free(s);
else if (r < 0)
sd_event_source_set_enabled(s, SD_EVENT_OFF);
return 1;
}
static int event_prepare(sd_event *e) {
int r;
assert(e);
for (;;) {
sd_event_source *s;
s = prioq_peek(e->prepare);
if (!s || s->prepare_iteration == e->iteration || s->enabled == SD_EVENT_OFF)
break;
s->prepare_iteration = e->iteration;
r = prioq_reshuffle(e->prepare, s, &s->prepare_index);
if (r < 0)
return r;
assert(s->prepare);
s->dispatching = true;
r = s->prepare(s, s->userdata);
s->dispatching = false;
if (r < 0)
log_debug_errno(r, "Prepare callback of event source %s (type %s) returned error, disabling: %m",
strna(s->description), event_source_type_to_string(s->type));
if (s->n_ref == 0)
source_free(s);
else if (r < 0)
sd_event_source_set_enabled(s, SD_EVENT_OFF);
}
return 0;
}
static int dispatch_exit(sd_event *e) {
sd_event_source *p;
int r;
assert(e);
p = prioq_peek(e->exit);
if (!p || p->enabled == SD_EVENT_OFF) {
e->state = SD_EVENT_FINISHED;
return 0;
}
sd_event_ref(e);
e->iteration++;
e->state = SD_EVENT_EXITING;
r = source_dispatch(p);
e->state = SD_EVENT_INITIAL;
sd_event_unref(e);
return r;
}
static sd_event_source* event_next_pending(sd_event *e) {
sd_event_source *p;
assert(e);
p = prioq_peek(e->pending);
if (!p)
return NULL;
if (p->enabled == SD_EVENT_OFF)
return NULL;
return p;
}
static int arm_watchdog(sd_event *e) {
struct itimerspec its = {};
usec_t t;
int r;
assert(e);
assert(e->watchdog_fd >= 0);
t = sleep_between(e,
e->watchdog_last + (e->watchdog_period / 2),
e->watchdog_last + (e->watchdog_period * 3 / 4));
timespec_store(&its.it_value, t);
/* Make sure we never set the watchdog to 0, which tells the
* kernel to disable it. */
if (its.it_value.tv_sec == 0 && its.it_value.tv_nsec == 0)
its.it_value.tv_nsec = 1;
r = timerfd_settime(e->watchdog_fd, TFD_TIMER_ABSTIME, &its, NULL);
if (r < 0)
return -errno;
return 0;
}
static int process_watchdog(sd_event *e) {
assert(e);
if (!e->watchdog)
return 0;
/* Don't notify watchdog too often */
if (e->watchdog_last + e->watchdog_period / 4 > e->timestamp.monotonic)
return 0;
sd_notify(false, "WATCHDOG=1");
e->watchdog_last = e->timestamp.monotonic;
return arm_watchdog(e);
}
_public_ int sd_event_prepare(sd_event *e) {
int r;
assert_return(e, -EINVAL);
assert_return(!event_pid_changed(e), -ECHILD);
assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
assert_return(e->state == SD_EVENT_INITIAL, -EBUSY);
if (e->exit_requested)
goto pending;
e->iteration++;
e->state = SD_EVENT_PREPARING;
r = event_prepare(e);
e->state = SD_EVENT_INITIAL;
if (r < 0)
return r;
r = event_arm_timer(e, &e->realtime);
if (r < 0)
return r;
r = event_arm_timer(e, &e->boottime);
if (r < 0)
return r;
r = event_arm_timer(e, &e->monotonic);
if (r < 0)
return r;
r = event_arm_timer(e, &e->realtime_alarm);
if (r < 0)
return r;
r = event_arm_timer(e, &e->boottime_alarm);
if (r < 0)
return r;
if (event_next_pending(e) || e->need_process_child)
goto pending;
e->state = SD_EVENT_ARMED;
return 0;
pending:
e->state = SD_EVENT_ARMED;
r = sd_event_wait(e, 0);
if (r == 0)
e->state = SD_EVENT_ARMED;
return r;
}
_public_ int sd_event_wait(sd_event *e, uint64_t timeout) {
struct epoll_event *ev_queue;
unsigned ev_queue_max;
int r, m, i;
assert_return(e, -EINVAL);
assert_return(!event_pid_changed(e), -ECHILD);
assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
assert_return(e->state == SD_EVENT_ARMED, -EBUSY);
if (e->exit_requested) {
e->state = SD_EVENT_PENDING;
return 1;
}
ev_queue_max = MAX(e->n_sources, 1u);
ev_queue = newa(struct epoll_event, ev_queue_max);
m = epoll_wait(e->epoll_fd, ev_queue, ev_queue_max,
timeout == (uint64_t) -1 ? -1 : (int) ((timeout + USEC_PER_MSEC - 1) / USEC_PER_MSEC));
if (m < 0) {
if (errno == EINTR) {
e->state = SD_EVENT_PENDING;
return 1;
}
r = -errno;
goto finish;
}
dual_timestamp_get(&e->timestamp);
if (clock_boottime_supported())
e->timestamp_boottime = now(CLOCK_BOOTTIME);
for (i = 0; i < m; i++) {
if (ev_queue[i].data.ptr == INT_TO_PTR(SOURCE_WATCHDOG))
r = flush_timer(e, e->watchdog_fd, ev_queue[i].events, NULL);
else {
WakeupType *t = ev_queue[i].data.ptr;
switch (*t) {
case WAKEUP_EVENT_SOURCE:
r = process_io(e, ev_queue[i].data.ptr, ev_queue[i].events);
break;
case WAKEUP_CLOCK_DATA: {
struct clock_data *d = ev_queue[i].data.ptr;
r = flush_timer(e, d->fd, ev_queue[i].events, &d->next);
break;
}
case WAKEUP_SIGNAL_DATA:
r = process_signal(e, ev_queue[i].data.ptr, ev_queue[i].events);
break;
default:
assert_not_reached("Invalid wake-up pointer");
}
}
if (r < 0)
goto finish;
}
r = process_watchdog(e);
if (r < 0)
goto finish;
r = process_timer(e, e->timestamp.realtime, &e->realtime);
if (r < 0)
goto finish;
r = process_timer(e, e->timestamp_boottime, &e->boottime);
if (r < 0)
goto finish;
r = process_timer(e, e->timestamp.monotonic, &e->monotonic);
if (r < 0)
goto finish;
r = process_timer(e, e->timestamp.realtime, &e->realtime_alarm);
if (r < 0)
goto finish;
r = process_timer(e, e->timestamp_boottime, &e->boottime_alarm);
if (r < 0)
goto finish;
if (e->need_process_child) {
r = process_child(e);
if (r < 0)
goto finish;
}
if (event_next_pending(e)) {
e->state = SD_EVENT_PENDING;
return 1;
}
r = 0;
finish:
e->state = SD_EVENT_INITIAL;
return r;
}
_public_ int sd_event_dispatch(sd_event *e) {
sd_event_source *p;
int r;
assert_return(e, -EINVAL);
assert_return(!event_pid_changed(e), -ECHILD);
assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
assert_return(e->state == SD_EVENT_PENDING, -EBUSY);
if (e->exit_requested)
return dispatch_exit(e);
p = event_next_pending(e);
if (p) {
sd_event_ref(e);
e->state = SD_EVENT_RUNNING;
r = source_dispatch(p);
e->state = SD_EVENT_INITIAL;
sd_event_unref(e);
return r;
}
e->state = SD_EVENT_INITIAL;
return 1;
}
static void event_log_delays(sd_event *e) {
char b[ELEMENTSOF(e->delays) * DECIMAL_STR_MAX(unsigned) + 1];
unsigned i;
int o;
for (i = o = 0; i < ELEMENTSOF(e->delays); i++) {
o += snprintf(&b[o], sizeof(b) - o, "%u ", e->delays[i]);
e->delays[i] = 0;
}
log_debug("Event loop iterations: %.*s", o, b);
}
_public_ int sd_event_run(sd_event *e, uint64_t timeout) {
int r;
assert_return(e, -EINVAL);
assert_return(!event_pid_changed(e), -ECHILD);
assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
assert_return(e->state == SD_EVENT_INITIAL, -EBUSY);
if (e->profile_delays && e->last_run) {
usec_t this_run;
unsigned l;
this_run = now(CLOCK_MONOTONIC);
l = u64log2(this_run - e->last_run);
assert(l < sizeof(e->delays));
e->delays[l]++;
if (this_run - e->last_log >= 5*USEC_PER_SEC) {
event_log_delays(e);
e->last_log = this_run;
}
}
r = sd_event_prepare(e);
if (r == 0)
/* There was nothing? Then wait... */
r = sd_event_wait(e, timeout);
if (e->profile_delays)
e->last_run = now(CLOCK_MONOTONIC);
if (r > 0) {
/* There's something now, then let's dispatch it */
r = sd_event_dispatch(e);
if (r < 0)
return r;
return 1;
}
return r;
}
_public_ int sd_event_loop(sd_event *e) {
int r;
assert_return(e, -EINVAL);
assert_return(!event_pid_changed(e), -ECHILD);
assert_return(e->state == SD_EVENT_INITIAL, -EBUSY);
sd_event_ref(e);
while (e->state != SD_EVENT_FINISHED) {
r = sd_event_run(e, (uint64_t) -1);
if (r < 0)
goto finish;
}
r = e->exit_code;
finish:
sd_event_unref(e);
return r;
}
_public_ int sd_event_get_fd(sd_event *e) {
assert_return(e, -EINVAL);
assert_return(!event_pid_changed(e), -ECHILD);
return e->epoll_fd;
}
_public_ int sd_event_get_state(sd_event *e) {
assert_return(e, -EINVAL);
assert_return(!event_pid_changed(e), -ECHILD);
return e->state;
}
_public_ int sd_event_get_exit_code(sd_event *e, int *code) {
assert_return(e, -EINVAL);
assert_return(code, -EINVAL);
assert_return(!event_pid_changed(e), -ECHILD);
if (!e->exit_requested)
return -ENODATA;
*code = e->exit_code;
return 0;
}
_public_ int sd_event_exit(sd_event *e, int code) {
assert_return(e, -EINVAL);
assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
assert_return(!event_pid_changed(e), -ECHILD);
e->exit_requested = true;
e->exit_code = code;
return 0;
}
_public_ int sd_event_now(sd_event *e, clockid_t clock, uint64_t *usec) {
assert_return(e, -EINVAL);
assert_return(usec, -EINVAL);
assert_return(!event_pid_changed(e), -ECHILD);
assert_return(IN_SET(clock,
CLOCK_REALTIME,
CLOCK_REALTIME_ALARM,
CLOCK_MONOTONIC,
CLOCK_BOOTTIME,
CLOCK_BOOTTIME_ALARM), -EOPNOTSUPP);
if (IN_SET(clock, CLOCK_BOOTTIME, CLOCK_BOOTTIME_ALARM) && !clock_boottime_supported())
return -EOPNOTSUPP;
if (!dual_timestamp_is_set(&e->timestamp)) {
/* Implicitly fall back to now() if we never ran
* before and thus have no cached time. */
*usec = now(clock);
return 1;
}
switch (clock) {
case CLOCK_REALTIME:
case CLOCK_REALTIME_ALARM:
*usec = e->timestamp.realtime;
break;
case CLOCK_MONOTONIC:
*usec = e->timestamp.monotonic;
break;
case CLOCK_BOOTTIME:
case CLOCK_BOOTTIME_ALARM:
*usec = e->timestamp_boottime;
break;
default:
assert_not_reached("Unknown clock?");
}
return 0;
}
_public_ int sd_event_default(sd_event **ret) {
static thread_local sd_event *default_event = NULL;
sd_event *e = NULL;
int r;
if (!ret)
return !!default_event;
if (default_event) {
*ret = sd_event_ref(default_event);
return 0;
}
r = sd_event_new(&e);
if (r < 0)
return r;
e->default_event_ptr = &default_event;
e->tid = gettid();
default_event = e;
*ret = e;
return 1;
}
_public_ int sd_event_get_tid(sd_event *e, pid_t *tid) {
assert_return(e, -EINVAL);
assert_return(tid, -EINVAL);
assert_return(!event_pid_changed(e), -ECHILD);
if (e->tid != 0) {
*tid = e->tid;
return 0;
}
return -ENXIO;
}
_public_ int sd_event_set_watchdog(sd_event *e, int b) {
int r;
assert_return(e, -EINVAL);
assert_return(!event_pid_changed(e), -ECHILD);
if (e->watchdog == !!b)
return e->watchdog;
if (b) {
struct epoll_event ev = {};
r = sd_watchdog_enabled(false, &e->watchdog_period);
if (r <= 0)
return r;
/* Issue first ping immediately */
sd_notify(false, "WATCHDOG=1");
e->watchdog_last = now(CLOCK_MONOTONIC);
e->watchdog_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC);
if (e->watchdog_fd < 0)
return -errno;
r = arm_watchdog(e);
if (r < 0)
goto fail;
ev.events = EPOLLIN;
ev.data.ptr = INT_TO_PTR(SOURCE_WATCHDOG);
r = epoll_ctl(e->epoll_fd, EPOLL_CTL_ADD, e->watchdog_fd, &ev);
if (r < 0) {
r = -errno;
goto fail;
}
} else {
if (e->watchdog_fd >= 0) {
epoll_ctl(e->epoll_fd, EPOLL_CTL_DEL, e->watchdog_fd, NULL);
e->watchdog_fd = safe_close(e->watchdog_fd);
}
}
e->watchdog = !!b;
return e->watchdog;
fail:
e->watchdog_fd = safe_close(e->watchdog_fd);
return r;
}
_public_ int sd_event_get_watchdog(sd_event *e) {
assert_return(e, -EINVAL);
assert_return(!event_pid_changed(e), -ECHILD);
return e->watchdog;
}
|
thom311/systemd
|
src/libsystemd/sd-event/sd-event.c
|
C
|
gpl-2.0
| 82,466
|
/* GStreamer
* Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
* 2000 Wim Taymans <wtay@chello.be>
* 2003 Benjamin Otte <in7y118@public.uni-hamburg.de>
*
* gstelementfactory.c: GstElementFactory object, support routines
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/**
* SECTION:gstelementfactory
* @short_description: Create GstElements from a factory
* @see_also: #GstElement, #GstPlugin, #GstPluginFeature, #GstPadTemplate.
*
* #GstElementFactory is used to create instances of elements. A
* GstElementfactory can be added to a #GstPlugin as it is also a
* #GstPluginFeature.
*
* Use the gst_element_factory_find() and gst_element_factory_create()
* functions to create element instances or use gst_element_factory_make() as a
* convenient shortcut.
*
* The following code example shows you how to create a GstFileSrc element.
*
* <example>
* <title>Using an element factory</title>
* <programlisting language="c">
* #include <gst/gst.h>
*
* GstElement *src;
* GstElementFactory *srcfactory;
*
* gst_init (&argc, &argv);
*
* srcfactory = gst_element_factory_find ("filesrc");
* g_return_if_fail (srcfactory != NULL);
* src = gst_element_factory_create (srcfactory, "src");
* g_return_if_fail (src != NULL);
* ...
* </programlisting>
* </example>
*
* Last reviewed on 2005-11-23 (0.9.5)
*/
#include "gst_private.h"
#include "gstelement.h"
#include "gstelementdetails.h"
#include "gstinfo.h"
#include "gsturi.h"
#include "gstregistry.h"
#include "gst.h"
#include "glib-compat-private.h"
GST_DEBUG_CATEGORY_STATIC (element_factory_debug);
#define GST_CAT_DEFAULT element_factory_debug
static void gst_element_factory_finalize (GObject * object);
static void gst_element_factory_cleanup (GstElementFactory * factory);
/* static guint gst_element_factory_signals[LAST_SIGNAL] = { 0 }; */
/* this is defined in gstelement.c */
extern GQuark _gst_elementclass_factory;
#define _do_init \
{ \
GST_DEBUG_CATEGORY_INIT (element_factory_debug, "GST_ELEMENT_FACTORY", \
GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, \
"element factories keep information about installed elements"); \
}
G_DEFINE_TYPE_WITH_CODE (GstElementFactory, gst_element_factory,
GST_TYPE_PLUGIN_FEATURE, _do_init);
static void
gst_element_factory_class_init (GstElementFactoryClass * klass)
{
GObjectClass *gobject_class = (GObjectClass *) klass;
gobject_class->finalize = gst_element_factory_finalize;
}
static void
gst_element_factory_init (GstElementFactory * factory)
{
factory->staticpadtemplates = NULL;
factory->numpadtemplates = 0;
factory->uri_type = GST_URI_UNKNOWN;
factory->uri_protocols = NULL;
factory->interfaces = NULL;
}
static void
gst_element_factory_finalize (GObject * object)
{
GstElementFactory *factory = GST_ELEMENT_FACTORY (object);
gst_element_factory_cleanup (factory);
G_OBJECT_CLASS (gst_element_factory_parent_class)->finalize (object);
}
/**
* gst_element_factory_find:
* @name: name of factory to find
*
* Search for an element factory of the given name. Refs the returned
* element factory; caller is responsible for unreffing.
*
* Returns: (transfer full): #GstElementFactory if found, NULL otherwise
*/
GstElementFactory *
gst_element_factory_find (const gchar * name)
{
GstPluginFeature *feature;
g_return_val_if_fail (name != NULL, NULL);
feature = gst_registry_find_feature (gst_registry_get_default (), name,
GST_TYPE_ELEMENT_FACTORY);
if (feature)
return GST_ELEMENT_FACTORY (feature);
/* this isn't an error, for instance when you query if an element factory is
* present */
GST_LOG ("no such element factory \"%s\"", name);
return NULL;
}
static void
gst_element_factory_cleanup (GstElementFactory * factory)
{
GList *item;
__gst_element_details_clear (&factory->details);
if (factory->meta_data) {
gst_structure_free ((GstStructure *) factory->meta_data);
factory->meta_data = NULL;
}
if (factory->type) {
factory->type = G_TYPE_INVALID;
}
for (item = factory->staticpadtemplates; item; item = item->next) {
GstStaticPadTemplate *templ = item->data;
GstCaps *caps = (GstCaps *) & (templ->static_caps);
/* FIXME: this is not threadsafe */
if (caps->refcount == 1) {
GstStructure *structure;
guint i;
for (i = 0; i < caps->structs->len; i++) {
structure = (GstStructure *) gst_caps_get_structure (caps, i);
gst_structure_set_parent_refcount (structure, NULL);
gst_structure_free (structure);
}
g_ptr_array_free (caps->structs, TRUE);
caps->refcount = 0;
}
g_slice_free (GstStaticPadTemplate, templ);
}
g_list_free (factory->staticpadtemplates);
factory->staticpadtemplates = NULL;
factory->numpadtemplates = 0;
factory->uri_type = GST_URI_UNKNOWN;
if (factory->uri_protocols) {
g_strfreev (factory->uri_protocols);
factory->uri_protocols = NULL;
}
g_list_free (factory->interfaces);
factory->interfaces = NULL;
}
/**
* gst_element_register:
* @plugin: (allow-none): #GstPlugin to register the element with, or NULL for
* a static element (note that passing NULL only works in GStreamer 0.10.13
* and later)
* @name: name of elements of this type
* @rank: rank of element (higher rank means more importance when autoplugging)
* @type: GType of element to register
*
* Create a new elementfactory capable of instantiating objects of the
* @type and add the factory to @plugin.
*
* Returns: TRUE, if the registering succeeded, FALSE on error
*/
gboolean
gst_element_register (GstPlugin * plugin, const gchar * name, guint rank,
GType type)
{
GstPluginFeature *existing_feature;
GstRegistry *registry;
GstElementFactory *factory;
GType *interfaces;
guint n_interfaces, i;
GstElementClass *klass;
GList *item;
g_return_val_if_fail (name != NULL, FALSE);
g_return_val_if_fail (g_type_is_a (type, GST_TYPE_ELEMENT), FALSE);
registry = gst_registry_get_default ();
/* check if feature already exists, if it exists there is no need to update it
* when the registry is getting updated, outdated plugins and all their
* features are removed and readded.
*/
existing_feature = gst_registry_lookup_feature (registry, name);
if (existing_feature) {
GST_DEBUG_OBJECT (registry, "update existing feature %p (%s)",
existing_feature, name);
factory = GST_ELEMENT_FACTORY_CAST (existing_feature);
factory->type = type;
existing_feature->loaded = TRUE;
g_type_set_qdata (type, _gst_elementclass_factory, factory);
gst_object_unref (existing_feature);
return TRUE;
}
factory =
GST_ELEMENT_FACTORY_CAST (g_object_newv (GST_TYPE_ELEMENT_FACTORY, 0,
NULL));
gst_plugin_feature_set_name (GST_PLUGIN_FEATURE_CAST (factory), name);
GST_LOG_OBJECT (factory, "Created new elementfactory for type %s",
g_type_name (type));
/* provide info needed during class structure setup */
g_type_set_qdata (type, _gst_elementclass_factory, factory);
klass = GST_ELEMENT_CLASS (g_type_class_ref (type));
if ((klass->details.longname == NULL) ||
(klass->details.klass == NULL) || (klass->details.author == NULL))
goto detailserror;
factory->type = type;
__gst_element_details_copy (&factory->details, &klass->details);
if (klass->meta_data) {
factory->meta_data = gst_structure_copy ((GstStructure *) klass->meta_data);
} else {
factory->meta_data = NULL;
}
for (item = klass->padtemplates; item; item = item->next) {
GstPadTemplate *templ = item->data;
GstStaticPadTemplate *newt;
gchar *caps_string = gst_caps_to_string (templ->caps);
newt = g_slice_new (GstStaticPadTemplate);
newt->name_template = g_intern_string (templ->name_template);
newt->direction = templ->direction;
newt->presence = templ->presence;
newt->static_caps.caps.refcount = 0;
newt->static_caps.string = g_intern_string (caps_string);
factory->staticpadtemplates =
g_list_append (factory->staticpadtemplates, newt);
g_free (caps_string);
}
factory->numpadtemplates = klass->numpadtemplates;
/* special stuff for URI handling */
if (g_type_is_a (type, GST_TYPE_URI_HANDLER)) {
GstURIHandlerInterface *iface = (GstURIHandlerInterface *)
g_type_interface_peek (klass, GST_TYPE_URI_HANDLER);
if (!iface || (!iface->get_type && !iface->get_type_full) ||
(!iface->get_protocols && !iface->get_protocols_full))
goto urierror;
if (iface->get_type)
factory->uri_type = iface->get_type ();
else if (iface->get_type_full)
factory->uri_type = iface->get_type_full (factory->type);
if (!GST_URI_TYPE_IS_VALID (factory->uri_type))
goto urierror;
if (iface->get_protocols)
factory->uri_protocols = g_strdupv (iface->get_protocols ());
else if (iface->get_protocols_full)
factory->uri_protocols = iface->get_protocols_full (factory->type);
if (!factory->uri_protocols)
goto urierror;
}
interfaces = g_type_interfaces (type, &n_interfaces);
for (i = 0; i < n_interfaces; i++) {
__gst_element_factory_add_interface (factory, g_type_name (interfaces[i]));
}
g_free (interfaces);
if (plugin && plugin->desc.name) {
GST_PLUGIN_FEATURE_CAST (factory)->plugin_name = plugin->desc.name;
GST_PLUGIN_FEATURE_CAST (factory)->plugin = plugin;
g_object_add_weak_pointer ((GObject *) plugin,
(gpointer *) & GST_PLUGIN_FEATURE_CAST (factory)->plugin);
} else {
GST_PLUGIN_FEATURE_CAST (factory)->plugin_name = "NULL";
GST_PLUGIN_FEATURE_CAST (factory)->plugin = NULL;
}
gst_plugin_feature_set_rank (GST_PLUGIN_FEATURE_CAST (factory), rank);
GST_PLUGIN_FEATURE_CAST (factory)->loaded = TRUE;
gst_registry_add_feature (registry, GST_PLUGIN_FEATURE_CAST (factory));
return TRUE;
/* ERRORS */
urierror:
{
GST_WARNING_OBJECT (factory, "error with uri handler!");
gst_element_factory_cleanup (factory);
return FALSE;
}
detailserror:
{
GST_WARNING_OBJECT (factory,
"The GstElementDetails don't seem to have been set properly");
gst_element_factory_cleanup (factory);
return FALSE;
}
}
/**
* gst_element_factory_create:
* @factory: factory to instantiate
* @name: (allow-none): name of new element, or NULL to automatically create
* a unique name
*
* Create a new element of the type defined by the given elementfactory.
* It will be given the name supplied, since all elements require a name as
* their first argument.
*
* Returns: (transfer full): new #GstElement or NULL if the element couldn't
* be created
*/
GstElement *
gst_element_factory_create (GstElementFactory * factory, const gchar * name)
{
GstElement *element;
GstElementClass *oclass;
GstElementFactory *newfactory;
g_return_val_if_fail (factory != NULL, NULL);
newfactory =
GST_ELEMENT_FACTORY (gst_plugin_feature_load (GST_PLUGIN_FEATURE
(factory)));
if (newfactory == NULL)
goto load_failed;
factory = newfactory;
if (name)
GST_INFO ("creating element \"%s\" named \"%s\"",
GST_PLUGIN_FEATURE_NAME (factory), GST_STR_NULL (name));
else
GST_INFO ("creating element \"%s\"", GST_PLUGIN_FEATURE_NAME (factory));
if (factory->type == 0)
goto no_type;
/* create an instance of the element, cast so we don't assert on NULL
* also set name as early as we can
*/
if (name)
element =
GST_ELEMENT_CAST (g_object_new (factory->type, "name", name, NULL));
else
element = GST_ELEMENT_CAST (g_object_newv (factory->type, 0, NULL));
if (G_UNLIKELY (element == NULL))
goto no_element;
/* fill in the pointer to the factory in the element class. The
* class will not be unreffed currently.
* Be thread safe as there might be 2 threads creating the first instance of
* an element at the same moment
*/
oclass = GST_ELEMENT_GET_CLASS (element);
if (!G_ATOMIC_POINTER_COMPARE_AND_EXCHANGE (&oclass->elementfactory, NULL,
factory))
gst_object_unref (factory);
GST_DEBUG ("created element \"%s\"", GST_PLUGIN_FEATURE_NAME (factory));
return element;
/* ERRORS */
load_failed:
{
GST_WARNING_OBJECT (factory,
"loading plugin containing feature %s returned NULL!", name);
return NULL;
}
no_type:
{
GST_WARNING_OBJECT (factory, "factory has no type");
gst_object_unref (factory);
return NULL;
}
no_element:
{
GST_WARNING_OBJECT (factory, "could not create element");
gst_object_unref (factory);
return NULL;
}
}
/**
* gst_element_factory_make:
* @factoryname: a named factory to instantiate
* @name: (allow-none): name of new element, or NULL to automatically create
* a unique name
*
* Create a new element of the type defined by the given element factory.
* If name is NULL, then the element will receive a guaranteed unique name,
* consisting of the element factory name and a number.
* If name is given, it will be given the name supplied.
*
* Returns: (transfer full): new #GstElement or NULL if unable to create element
*/
GstElement *
gst_element_factory_make (const gchar * factoryname, const gchar * name)
{
GstElementFactory *factory;
GstElement *element;
g_return_val_if_fail (factoryname != NULL, NULL);
g_return_val_if_fail (gst_is_initialized (), NULL);
GST_LOG ("gstelementfactory: make \"%s\" \"%s\"",
factoryname, GST_STR_NULL (name));
factory = gst_element_factory_find (factoryname);
if (factory == NULL)
goto no_factory;
GST_LOG_OBJECT (factory, "found factory %p", factory);
element = gst_element_factory_create (factory, name);
if (element == NULL)
goto create_failed;
gst_object_unref (factory);
return element;
/* ERRORS */
no_factory:
{
GST_INFO ("no such element factory \"%s\"!", factoryname);
return NULL;
}
create_failed:
{
GST_INFO_OBJECT (factory, "couldn't create instance!");
gst_object_unref (factory);
return NULL;
}
}
void
__gst_element_factory_add_static_pad_template (GstElementFactory * factory,
GstStaticPadTemplate * templ)
{
g_return_if_fail (factory != NULL);
g_return_if_fail (templ != NULL);
factory->staticpadtemplates =
g_list_append (factory->staticpadtemplates, templ);
factory->numpadtemplates++;
}
/**
* gst_element_factory_get_element_type:
* @factory: factory to get managed #GType from
*
* Get the #GType for elements managed by this factory. The type can
* only be retrieved if the element factory is loaded, which can be
* assured with gst_plugin_feature_load().
*
* Returns: the #GType for elements managed by this factory or 0 if
* the factory is not loaded.
*/
GType
gst_element_factory_get_element_type (GstElementFactory * factory)
{
g_return_val_if_fail (GST_IS_ELEMENT_FACTORY (factory), 0);
return factory->type;
}
/**
* gst_element_factory_get_longname:
* @factory: a #GstElementFactory
*
* Gets the longname for this factory
*
* Returns: the longname
*/
const gchar *
gst_element_factory_get_longname (GstElementFactory * factory)
{
g_return_val_if_fail (GST_IS_ELEMENT_FACTORY (factory), NULL);
return factory->details.longname;
}
/**
* gst_element_factory_get_klass:
* @factory: a #GstElementFactory
*
* Gets the class for this factory.
*
* Returns: the class
*/
const gchar *
gst_element_factory_get_klass (GstElementFactory * factory)
{
g_return_val_if_fail (GST_IS_ELEMENT_FACTORY (factory), NULL);
return factory->details.klass;
}
/**
* gst_element_factory_get_description:
* @factory: a #GstElementFactory
*
* Gets the description for this factory.
*
* Returns: the description
*/
const gchar *
gst_element_factory_get_description (GstElementFactory * factory)
{
g_return_val_if_fail (GST_IS_ELEMENT_FACTORY (factory), NULL);
return factory->details.description;
}
/**
* gst_element_factory_get_author:
* @factory: a #GstElementFactory
*
* Gets the author for this factory.
*
* Returns: the author
*/
const gchar *
gst_element_factory_get_author (GstElementFactory * factory)
{
g_return_val_if_fail (GST_IS_ELEMENT_FACTORY (factory), NULL);
return factory->details.author;
}
static const gchar *
gst_element_factory_get_meta_data (GstElementFactory * factory,
const gchar * key)
{
if (!factory->meta_data)
return NULL;
/* FIXME: do we want to support other types? */
return gst_structure_get_string ((GstStructure *) factory->meta_data, key);
}
/**
* gst_element_factory_get_documentation_uri:
* @factory: a #GstElementFactory
*
* Gets documentation uri for this factory if set.
*
* Since: 0.10.31
*
* Returns: the documentation uri
*/
const gchar *
gst_element_factory_get_documentation_uri (GstElementFactory * factory)
{
g_return_val_if_fail (GST_IS_ELEMENT_FACTORY (factory), NULL);
return gst_element_factory_get_meta_data (factory, "doc-uri");
}
/**
* gst_element_factory_get_icon_name:
* @factory: a #GstElementFactory
*
* Gets icon name for this factory if set.
*
* Since: 0.10.31
*
* Returns: the icon name
*/
const gchar *
gst_element_factory_get_icon_name (GstElementFactory * factory)
{
g_return_val_if_fail (GST_IS_ELEMENT_FACTORY (factory), NULL);
return gst_element_factory_get_meta_data (factory, "icon-name");
}
/**
* gst_element_factory_get_num_pad_templates:
* @factory: a #GstElementFactory
*
* Gets the number of pad_templates in this factory.
*
* Returns: the number of pad_templates
*/
guint
gst_element_factory_get_num_pad_templates (GstElementFactory * factory)
{
g_return_val_if_fail (GST_IS_ELEMENT_FACTORY (factory), 0);
return factory->numpadtemplates;
}
/**
* __gst_element_factory_add_interface:
* @elementfactory: The elementfactory to add the interface to
* @interfacename: Name of the interface
*
* Adds the given interfacename to the list of implemented interfaces of the
* element.
*/
void
__gst_element_factory_add_interface (GstElementFactory * elementfactory,
const gchar * interfacename)
{
g_return_if_fail (GST_IS_ELEMENT_FACTORY (elementfactory));
g_return_if_fail (interfacename != NULL);
g_return_if_fail (interfacename[0] != '\0'); /* no empty string */
elementfactory->interfaces =
g_list_prepend (elementfactory->interfaces,
(gpointer) g_intern_string (interfacename));
}
/**
* gst_element_factory_get_static_pad_templates:
* @factory: a #GstElementFactory
*
* Gets the #GList of #GstStaticPadTemplate for this factory.
*
* Returns: (transfer none) (element-type Gst.StaticPadTemplate): the
* static pad templates
*/
const GList *
gst_element_factory_get_static_pad_templates (GstElementFactory * factory)
{
g_return_val_if_fail (GST_IS_ELEMENT_FACTORY (factory), NULL);
return factory->staticpadtemplates;
}
/**
* gst_element_factory_get_uri_type:
* @factory: a #GstElementFactory
*
* Gets the type of URIs the element supports or #GST_URI_UNKNOWN if none.
*
* Returns: type of URIs this element supports
*/
gint
gst_element_factory_get_uri_type (GstElementFactory * factory)
{
g_return_val_if_fail (GST_IS_ELEMENT_FACTORY (factory), GST_URI_UNKNOWN);
return factory->uri_type;
}
/**
* gst_element_factory_get_uri_protocols:
* @factory: a #GstElementFactory
*
* Gets a NULL-terminated array of protocols this element supports or NULL if
* no protocols are supported. You may not change the contents of the returned
* array, as it is still owned by the element factory. Use g_strdupv() to
* make a copy of the protocol string array if you need to.
*
* Returns: (transfer none) (array zero-terminated=1): the supported protocols
* or NULL
*/
gchar **
gst_element_factory_get_uri_protocols (GstElementFactory * factory)
{
g_return_val_if_fail (GST_IS_ELEMENT_FACTORY (factory), NULL);
return factory->uri_protocols;
}
/**
* gst_element_factory_has_interface:
* @factory: a #GstElementFactory
* @interfacename: an interface name
*
* Check if @factory implements the interface with name @interfacename.
*
* Returns: #TRUE when @factory implement the interface.
*
* Since: 0.10.14
*/
gboolean
gst_element_factory_has_interface (GstElementFactory * factory,
const gchar * interfacename)
{
GList *walk;
g_return_val_if_fail (GST_IS_ELEMENT_FACTORY (factory), FALSE);
for (walk = factory->interfaces; walk; walk = g_list_next (walk)) {
gchar *iname = (gchar *) walk->data;
if (!strcmp (iname, interfacename))
return TRUE;
}
return FALSE;
}
typedef struct
{
GstElementFactoryListType type;
GstRank minrank;
} FilterData;
/**
* gst_element_factory_list_is_type:
* @factory: a #GstElementFactory
* @type: a #GstElementFactoryListType
*
* Check if @factory is of the given types.
*
* Returns: %TRUE if @factory is of @type.
*
* Since: 0.10.31
*/
gboolean
gst_element_factory_list_is_type (GstElementFactory * factory,
GstElementFactoryListType type)
{
gboolean res = FALSE;
const gchar *klass;
klass = gst_element_factory_get_klass (factory);
/* Filter by element type first, as soon as it matches
* one type, we skip all other tests */
if (!res && (type & GST_ELEMENT_FACTORY_TYPE_SINK))
res = (strstr (klass, "Sink") != NULL);
if (!res && (type & GST_ELEMENT_FACTORY_TYPE_SRC))
res = (strstr (klass, "Source") != NULL);
if (!res && (type & GST_ELEMENT_FACTORY_TYPE_DECODER))
res = (strstr (klass, "Decoder") != NULL);
if (!res && (type & GST_ELEMENT_FACTORY_TYPE_ENCODER))
res = (strstr (klass, "Encoder") != NULL);
if (!res && (type & GST_ELEMENT_FACTORY_TYPE_MUXER))
res = (strstr (klass, "Muxer") != NULL);
if (!res && (type & GST_ELEMENT_FACTORY_TYPE_DEMUXER))
res = (strstr (klass, "Demux") != NULL);
/* FIXME : We're actually parsing two Classes here... */
if (!res && (type & GST_ELEMENT_FACTORY_TYPE_PARSER))
res = ((strstr (klass, "Parser") != NULL)
&& (strstr (klass, "Codec") != NULL));
if (!res && (type & GST_ELEMENT_FACTORY_TYPE_DEPAYLOADER))
res = (strstr (klass, "Depayloader") != NULL);
if (!res && (type & GST_ELEMENT_FACTORY_TYPE_PAYLOADER))
res = (strstr (klass, "Payloader") != NULL);
if (!res && (type & GST_ELEMENT_FACTORY_TYPE_FORMATTER))
res = (strstr (klass, "Formatter") != NULL);
/* Filter by media type now, we only test if it
* matched any of the types above. */
if (res
&& (type & (GST_ELEMENT_FACTORY_TYPE_MEDIA_AUDIO |
GST_ELEMENT_FACTORY_TYPE_MEDIA_VIDEO |
GST_ELEMENT_FACTORY_TYPE_MEDIA_IMAGE)))
res = ((type & GST_ELEMENT_FACTORY_TYPE_MEDIA_AUDIO)
&& (strstr (klass, "Audio") != NULL))
|| ((type & GST_ELEMENT_FACTORY_TYPE_MEDIA_VIDEO)
&& (strstr (klass, "Video") != NULL))
|| ((type & GST_ELEMENT_FACTORY_TYPE_MEDIA_IMAGE)
&& (strstr (klass, "Image") != NULL));
return res;
}
static gboolean
element_filter (GstPluginFeature * feature, FilterData * data)
{
gboolean res;
/* we only care about element factories */
if (G_UNLIKELY (!GST_IS_ELEMENT_FACTORY (feature)))
return FALSE;
res = (gst_plugin_feature_get_rank (feature) >= data->minrank) &&
gst_element_factory_list_is_type (GST_ELEMENT_FACTORY_CAST (feature),
data->type);
return res;
}
/**
* gst_element_factory_list_get_elements:
* @type: a #GstElementFactoryListType
* @minrank: Minimum rank
*
* Get a list of factories that match the given @type. Only elements
* with a rank greater or equal to @minrank will be returned.
* The list of factories is returned by decreasing rank.
*
* Returns: (transfer full) (element-type Gst.ElementFactory): a #GList of
* #GstElementFactory elements. Use gst_plugin_feature_list_free() after
* usage.
*
* Since: 0.10.31
*/
GList *
gst_element_factory_list_get_elements (GstElementFactoryListType type,
GstRank minrank)
{
GList *result;
FilterData data;
/* prepare type */
data.type = type;
data.minrank = minrank;
/* get the feature list using the filter */
result = gst_default_registry_feature_filter ((GstPluginFeatureFilter)
element_filter, FALSE, &data);
/* sort on rank and name */
result = g_list_sort (result, gst_plugin_feature_rank_compare_func);
return result;
}
/**
* gst_element_factory_list_filter:
* @list: (transfer none) (element-type Gst.ElementFactory): a #GList of
* #GstElementFactory to filter
* @caps: a #GstCaps
* @direction: a #GstPadDirection to filter on
* @subsetonly: whether to filter on caps subsets or not.
*
* Filter out all the elementfactories in @list that can handle @caps in
* the given direction.
*
* If @subsetonly is %TRUE, then only the elements whose pads templates
* are a complete superset of @caps will be returned. Else any element
* whose pad templates caps can intersect with @caps will be returned.
*
* Returns: (transfer full) (element-type Gst.ElementFactory): a #GList of
* #GstElementFactory elements that match the given requisits.
* Use #gst_plugin_feature_list_free after usage.
*
* Since: 0.10.31
*/
GList *
gst_element_factory_list_filter (GList * list,
const GstCaps * caps, GstPadDirection direction, gboolean subsetonly)
{
GQueue results = G_QUEUE_INIT;
GST_DEBUG ("finding factories");
/* loop over all the factories */
for (; list; list = list->next) {
GstElementFactory *factory;
const GList *templates;
GList *walk;
factory = (GstElementFactory *) list->data;
GST_DEBUG ("Trying %s",
gst_plugin_feature_get_name ((GstPluginFeature *) factory));
/* get the templates from the element factory */
templates = gst_element_factory_get_static_pad_templates (factory);
for (walk = (GList *) templates; walk; walk = g_list_next (walk)) {
GstStaticPadTemplate *templ = walk->data;
/* we only care about the sink templates */
if (templ->direction == direction) {
GstCaps *tmpl_caps;
/* try to intersect the caps with the caps of the template */
tmpl_caps = gst_static_caps_get (&templ->static_caps);
/* FIXME, intersect is not the right method, we ideally want to check
* for a subset here */
/* check if the intersection is empty */
if ((subsetonly && gst_caps_is_subset (caps, tmpl_caps)) ||
(!subsetonly && gst_caps_can_intersect (caps, tmpl_caps))) {
/* non empty intersection, we can use this element */
g_queue_push_tail (&results, gst_object_ref (factory));
gst_caps_unref (tmpl_caps);
break;
}
gst_caps_unref (tmpl_caps);
}
}
}
return results.head;
}
|
atmark-techno/atmark-dist
|
user/gstreamer/gstreamer0.10/gstreamer0.10-0.10.36/gst/gstelementfactory.c
|
C
|
gpl-2.0
| 27,413
|
/* Implementation of gamma function according to ISO C.
Copyright (C) 1997-2015 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <math.h>
#include <math_private.h>
#include <float.h>
/* Coefficients B_2k / 2k(2k-1) of x^-(2k-1) inside exp in Stirling's
approximation to gamma function. */
static const double gamma_coeff[] =
{
0x1.5555555555555p-4,
-0xb.60b60b60b60b8p-12,
0x3.4034034034034p-12,
-0x2.7027027027028p-12,
0x3.72a3c5631fe46p-12,
-0x7.daac36664f1f4p-12,
};
#define NCOEFF (sizeof (gamma_coeff) / sizeof (gamma_coeff[0]))
/* Return gamma (X), for positive X less than 184, in the form R *
2^(*EXP2_ADJ), where R is the return value and *EXP2_ADJ is set to
avoid overflow or underflow in intermediate calculations. */
static double
gamma_positive (double x, int *exp2_adj)
{
int local_signgam;
if (x < 0.5)
{
*exp2_adj = 0;
return __ieee754_exp (__ieee754_lgamma_r (x + 1, &local_signgam)) / x;
}
else if (x <= 1.5)
{
*exp2_adj = 0;
return __ieee754_exp (__ieee754_lgamma_r (x, &local_signgam));
}
else if (x < 6.5)
{
/* Adjust into the range for using exp (lgamma). */
*exp2_adj = 0;
double n = __ceil (x - 1.5);
double x_adj = x - n;
double eps;
double prod = __gamma_product (x_adj, 0, n, &eps);
return (__ieee754_exp (__ieee754_lgamma_r (x_adj, &local_signgam))
* prod * (1.0 + eps));
}
else
{
double eps = 0;
double x_eps = 0;
double x_adj = x;
double prod = 1;
if (x < 12.0)
{
/* Adjust into the range for applying Stirling's
approximation. */
double n = __ceil (12.0 - x);
x_adj = math_narrow_eval (x + n);
x_eps = (x - (x_adj - n));
prod = __gamma_product (x_adj - n, x_eps, n, &eps);
}
/* The result is now gamma (X_ADJ + X_EPS) / (PROD * (1 + EPS)).
Compute gamma (X_ADJ + X_EPS) using Stirling's approximation,
starting by computing pow (X_ADJ, X_ADJ) with a power of 2
factored out. */
double exp_adj = -eps;
double x_adj_int = __round (x_adj);
double x_adj_frac = x_adj - x_adj_int;
int x_adj_log2;
double x_adj_mant = __frexp (x_adj, &x_adj_log2);
if (x_adj_mant < M_SQRT1_2)
{
x_adj_log2--;
x_adj_mant *= 2.0;
}
*exp2_adj = x_adj_log2 * (int) x_adj_int;
double ret = (__ieee754_pow (x_adj_mant, x_adj)
* __ieee754_exp2 (x_adj_log2 * x_adj_frac)
* __ieee754_exp (-x_adj)
* __ieee754_sqrt (2 * M_PI / x_adj)
/ prod);
exp_adj += x_eps * __ieee754_log (x_adj);
double bsum = gamma_coeff[NCOEFF - 1];
double x_adj2 = x_adj * x_adj;
for (size_t i = 1; i <= NCOEFF - 1; i++)
bsum = bsum / x_adj2 + gamma_coeff[NCOEFF - 1 - i];
exp_adj += bsum / x_adj;
return ret + ret * __expm1 (exp_adj);
}
}
double
__ieee754_gamma_r (double x, int *signgamp)
{
int32_t hx;
u_int32_t lx;
double ret;
EXTRACT_WORDS (hx, lx, x);
if (__glibc_unlikely (((hx & 0x7fffffff) | lx) == 0))
{
/* Return value for x == 0 is Inf with divide by zero exception. */
*signgamp = 0;
return 1.0 / x;
}
if (__builtin_expect (hx < 0, 0)
&& (u_int32_t) hx < 0xfff00000 && __rint (x) == x)
{
/* Return value for integer x < 0 is NaN with invalid exception. */
*signgamp = 0;
return (x - x) / (x - x);
}
if (__glibc_unlikely ((unsigned int) hx == 0xfff00000 && lx == 0))
{
/* x == -Inf. According to ISO this is NaN. */
*signgamp = 0;
return x - x;
}
if (__glibc_unlikely ((hx & 0x7ff00000) == 0x7ff00000))
{
/* Positive infinity (return positive infinity) or NaN (return
NaN). */
*signgamp = 0;
return x + x;
}
if (x >= 172.0)
{
/* Overflow. */
*signgamp = 0;
ret = math_narrow_eval (DBL_MAX * DBL_MAX);
return ret;
}
else
{
SET_RESTORE_ROUND (FE_TONEAREST);
if (x > 0.0)
{
*signgamp = 0;
int exp2_adj;
double tret = gamma_positive (x, &exp2_adj);
ret = __scalbn (tret, exp2_adj);
}
else if (x >= -DBL_EPSILON / 4.0)
{
*signgamp = 0;
ret = 1.0 / x;
}
else
{
double tx = __trunc (x);
*signgamp = (tx == 2.0 * __trunc (tx / 2.0)) ? -1 : 1;
if (x <= -184.0)
/* Underflow. */
ret = DBL_MIN * DBL_MIN;
else
{
double frac = tx - x;
if (frac > 0.5)
frac = 1.0 - frac;
double sinpix = (frac <= 0.25
? __sin (M_PI * frac)
: __cos (M_PI * (0.5 - frac)));
int exp2_adj;
double tret = M_PI / (-x * sinpix
* gamma_positive (-x, &exp2_adj));
ret = __scalbn (tret, -exp2_adj);
math_check_force_underflow_nonneg (ret);
}
}
ret = math_narrow_eval (ret);
}
if (isinf (ret) && x != 0)
{
if (*signgamp < 0)
{
ret = math_narrow_eval (-__copysign (DBL_MAX, ret) * DBL_MAX);
ret = -ret;
}
else
ret = math_narrow_eval (__copysign (DBL_MAX, ret) * DBL_MAX);
return ret;
}
else if (ret == 0)
{
if (*signgamp < 0)
{
ret = math_narrow_eval (-__copysign (DBL_MIN, ret) * DBL_MIN);
ret = -ret;
}
else
ret = math_narrow_eval (__copysign (DBL_MIN, ret) * DBL_MIN);
return ret;
}
else
return ret;
}
strong_alias (__ieee754_gamma_r, __gamma_r_finite)
|
gbenson/glibc
|
sysdeps/ieee754/dbl-64/e_gamma_r.c
|
C
|
gpl-2.0
| 6,157
|
/* Formatted output to strings.
Copyright (C) 1999, 2002, 2006-2007 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
#include <config.h>
/* Specification. */
#ifdef IN_LIBASPRINTF
# include "vasprintf.h"
#else
# include <stdio.h>
#endif
#include <stdarg.h>
int
asprintf (char **resultp, const char *format, ...)
{
va_list args;
int result;
va_start (args, format);
result = vasprintf (resultp, format, args);
va_end (args);
return result;
}
|
scs/uclinux
|
lib/libgsasl/libgsasl-1.0/gl/asprintf.c
|
C
|
gpl-2.0
| 1,171
|
<?php
// $Id: edit_users.js.php 2519 2012-10-22 16:53:57Z cimorrison $
require "../defaultincludes.inc";
header("Content-type: application/x-javascript");
expires_header(0); // Cannot cache file because it depends on $HTTP_REFERER
if ($use_strict)
{
echo "'use strict';\n";
}
// =================================================================================
// Extend the init() function
?>
var oldInitEditUsers = init;
init = function(args) {
oldInitEditUsers.apply(this, [args]);
<?php // Turn the list of users into a dataTable ?>
var tableOptions = {};
<?php
// Use an Ajax source if we can - gives much better performance for large tables
if (function_exists('json_encode'))
{
if (strpos($HTTP_REFERER, '?') !== FALSE)
{
list( ,$query_string) = explode('?', $HTTP_REFERER, 2);
}
$ajax_url = "edit_users.php?" . (empty($query_string) ? '' : "$query_string&") . "ajax=1";
?>
tableOptions.sAjaxSource = "<?php echo $ajax_url ?>";
<?php
}
// Get the sTypes and feed those into dataTables
?>
tableOptions.aoColumnDefs = getSTypes($('#users_table'));
var usersTable = makeDataTable('#users_table',
tableOptions,
{sWidth: "relative", iWidth: 33});
};
|
csusm-library/mrbs
|
web/js/edit_users.js.php
|
PHP
|
gpl-2.0
| 1,292
|
/* packet-lte-rrc-template.h
* Copyright 2009, Anders Broman <anders.broman@ericsson.com>
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald@wireshark.org>
* Copyright 1998 Gerald Combs
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef PACKET_LTE_RRC_H
#define PACKET_LTE_RRC_H
extern value_string_ext lte_rrc_messageIdentifier_vals_ext;
#include "packet-lte-rrc-exp.h"
#endif /* PACKET_LTE_RRC_H */
|
zzqcn/wireshark
|
epan/dissectors/asn1/lte-rrc/packet-lte-rrc-template.h
|
C
|
gpl-2.0
| 436
|
<?php
$lan = array(
'You do not have access to this page' => 'Non hai accesso a questa pagina',
'Select Message to view' => 'Seleziona un messaggio da visualizzare',
'Available Messages' => 'Messaggi disponibili',
'views' => 'visualizzazioni',
'rate' => 'percentuale',
'View Details for a Message' => 'Visualizzaziona dettagli per un messaggio',
'Subject' => 'Oggetto',
'Entered' => 'Inserito',
'Message Open Statistics' => 'Statistiche aperte del messaggio',
'Listing user %d to %d' => 'Elenca utenti da %d a %d',
'Entries' => 'Voci',
'firstview' => 'prima visualizzazione',
'lastview' => 'ultima visualizzazione',
'views' => 'visualizzazioni',
'responsetime' => 'tempo di risposta',
'sec' => 'sec',
# for 2.10.2
'there are currently no messages to view' => 'Al momento non ci sono messaggi da visualizzare',
);
?>
|
Ramir1/phplist
|
public_html/lists/admin/lan/it/mviews.php
|
PHP
|
gpl-2.0
| 853
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.