code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/*******************************************************************************
* Copyright (c) 2004, 2008 Actuate Corporation.
* 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
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.engine.data.dte;
import java.io.IOException;
import org.eclipse.birt.core.archive.IDocArchiveReader;
import org.eclipse.birt.report.engine.api.InstanceID;
public class DocumentDataSource
{
IDocArchiveReader dataSource;
InstanceID iid;
String bookmark;
public DocumentDataSource( IDocArchiveReader dataSource )
{
this( dataSource, null, null );
}
public DocumentDataSource( IDocArchiveReader dataSource, String bookmark, InstanceID iid )
{
this.dataSource = dataSource;
this.bookmark = bookmark;
if ( iid != null )
{
this.iid = iid;
}
}
public boolean isReportletDocument()
{
return bookmark!=null && iid!=null;
}
public void open( ) throws IOException
{
dataSource.open( );
}
public void close( ) throws IOException
{
dataSource.close( );
}
public IDocArchiveReader getDataSource( )
{
return dataSource;
}
public InstanceID getInstanceID( )
{
return iid;
}
public long getElementID( )
{
if ( iid != null )
{
return iid.getComponentID( );
}
return -1;
}
public String getBookmark( )
{
return bookmark;
}
}
|
sguan-actuate/birt
|
engine/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/data/dte/DocumentDataSource.java
|
Java
|
epl-1.0
| 1,658 |
/**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.fmiweather;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import java.math.BigDecimal;
import java.nio.file.Path;
import java.util.Optional;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openhab.binding.fmiweather.internal.client.Data;
import org.openhab.binding.fmiweather.internal.client.FMIResponse;
import org.openhab.binding.fmiweather.internal.client.Location;
/**
* Test cases for Client.parseMultiPointCoverageXml with a xml response having multiple places, parameters
* and timestamps
*
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
public class FMIResponseParsingMultiplePlacesTest extends AbstractFMIResponseParsingTest {
private Path observationsMultiplePlaces = getTestResource("observations_multiple_places.xml");
private Path forecastsMultiplePlaces = getTestResource("forecast_multiple_places.xml");
@NonNullByDefault({})
private FMIResponse observationsMultiplePlacesResponse;
@NonNullByDefault({})
private FMIResponse observationsMultiplePlacesNaNResponse;
@NonNullByDefault({})
private FMIResponse forecastsMultiplePlacesResponse;
// observation station points (observations_multiple_places.xml) have fmisid as their id
private Location emasalo = new Location("Porvoo Emäsalo", "101023", new BigDecimal("60.20382"),
new BigDecimal("25.62546"));
private Location kilpilahti = new Location("Porvoo Kilpilahti satama", "100683", new BigDecimal("60.30373"),
new BigDecimal("25.54916"));
private Location harabacka = new Location("Porvoo Harabacka", "101028", new BigDecimal("60.39172"),
new BigDecimal("25.60730"));
// forecast points (forecast_multiple_places.xml) have latitude,longitude as their id
private Location maarianhamina = new Location("Mariehamn", "60.09726,19.93481", new BigDecimal("60.09726"),
new BigDecimal("19.93481"));
private Location pointWithNoName = new Location("19.9,61.0973", "61.09726,19.90000", new BigDecimal("61.09726"),
new BigDecimal("19.90000"));
@BeforeEach
public void setUp() {
try {
observationsMultiplePlacesResponse = parseMultiPointCoverageXml(
readTestResourceUtf8(observationsMultiplePlaces));
observationsMultiplePlacesNaNResponse = parseMultiPointCoverageXml(
readTestResourceUtf8(observationsMultiplePlaces).replace("276.0", "NaN"));
forecastsMultiplePlacesResponse = parseMultiPointCoverageXml(readTestResourceUtf8(forecastsMultiplePlaces));
} catch (Throwable e) {
throw new RuntimeException("Test data malformed", e);
}
}
@SuppressWarnings("unchecked")
@Test
public void testLocationsMultiplePlacesObservations() {
// locations
assertThat(observationsMultiplePlacesResponse.getLocations().size(), is(3));
assertThat(observationsMultiplePlacesResponse.getLocations(),
hasItems(deeplyEqualTo(emasalo), deeplyEqualTo(kilpilahti), deeplyEqualTo(harabacka)));
}
@SuppressWarnings("unchecked")
@Test
public void testLocationsMultiplePlacesForecasts() {
// locations
assertThat(forecastsMultiplePlacesResponse.getLocations().size(), is(2));
assertThat(forecastsMultiplePlacesResponse.getLocations(),
hasItems(deeplyEqualTo(maarianhamina), deeplyEqualTo(pointWithNoName)));
}
@Test
public void testParametersMultipleObservations() {
for (Location location : new Location[] { emasalo, kilpilahti, harabacka }) {
Optional<Set<String>> parametersOptional = observationsMultiplePlacesResponse.getParameters(location);
Set<String> parameters = parametersOptional.get();
assertThat(parameters.size(), is(6));
assertThat(parameters, hasItems("wd_10min", "wg_10min", "rh", "p_sea", "ws_10min", "t2m"));
}
}
@Test
public void testParametersMultipleForecasts() {
for (Location location : new Location[] { maarianhamina, pointWithNoName }) {
Optional<Set<String>> parametersOptional = forecastsMultiplePlacesResponse.getParameters(location);
Set<String> parameters = parametersOptional.get();
assertThat(parameters.size(), is(2));
assertThat(parameters, hasItems("Temperature", "Humidity"));
}
}
@Test
public void testParseObservationsMultipleData() {
Data wd_10min = observationsMultiplePlacesResponse.getData(emasalo, "wd_10min").get();
assertThat(wd_10min, is(deeplyEqualTo(1552215600L, 60, "312.0", "286.0", "295.0", "282.0", "271.0", "262.0",
"243.0", "252.0", "262.0", "276.0")));
Data rh = observationsMultiplePlacesResponse.getData(kilpilahti, "rh").get();
assertThat(rh, is(deeplyEqualTo(1552215600L, 60, "73.0", "65.0", "60.0", "59.0", "57.0", "64.0", "66.0", "65.0",
"71.0", "77.0")));
}
@Test
public void testParseForecastsMultipleData() {
Data temperature = forecastsMultiplePlacesResponse.getData(maarianhamina, "Temperature").get();
assertThat(temperature, is(deeplyEqualTo(1553688000, 360, "3.84", "2.62", "2.26", "1.22", "5.47", "5.52",
"5.42", "4.78", "8.34", "7.15", null, null, null, null)));
Data temperature2 = forecastsMultiplePlacesResponse.getData(pointWithNoName, "Temperature").get();
assertThat(temperature2, is(deeplyEqualTo(1553688000, 360, "1.54", "2.91", "2.41", "2.36", "4.22", "5.28",
"4.58", "4.0", "4.79", "5.4", null, null, null, null)));
Data humidity = forecastsMultiplePlacesResponse.getData(maarianhamina, "Humidity").get();
assertThat(humidity, is(deeplyEqualTo(1553688000, 360, "66.57", "87.38", "85.77", "96.3", "75.74", "81.7",
"86.78", "87.96", "70.86", "76.35", null, null, null, null)));
Data humidity2 = forecastsMultiplePlacesResponse.getData(pointWithNoName, "Humidity").get();
assertThat(humidity2, is(deeplyEqualTo(1553688000, 360, "90.18", "86.22", "89.18", "89.43", "77.26", "78.55",
"83.36", "85.83", "80.82", "76.92", null, null, null, null)));
}
@Test
public void testParseObservations1NaN() {
// last value is null, due to NaN measurement value
Data wd_10min = observationsMultiplePlacesNaNResponse.getData(emasalo, "wd_10min").get();
assertThat(wd_10min, is(deeplyEqualTo(1552215600L, 60, "312.0", "286.0", "295.0", "282.0", "271.0", "262.0",
"243.0", "252.0", "262.0", null)));
}
}
|
openhab/openhab2
|
bundles/org.openhab.binding.fmiweather/src/test/java/org/openhab/binding/fmiweather/FMIResponseParsingMultiplePlacesTest.java
|
Java
|
epl-1.0
| 7,182 |
package org.eclipse.birt.report.tests.engine.api;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.content.ICellContent;
import org.eclipse.birt.report.engine.content.IColumn;
import org.eclipse.birt.report.engine.content.impl.ReportContent;
import org.eclipse.birt.report.tests.engine.BaseEmitter;
public class ICellContentTest extends BaseEmitter
{
private ICellContent cell = null;
private String reportName = "ICellContentTest.rptdesign";
private static int count = 0;
protected String getReportName( )
{
return reportName;
}
protected void setUp( ) throws Exception
{
super.setUp( );
removeResource( );
copyResource_INPUT( reportName, reportName );
cell = new ReportContent( ).createCellContent( );
}
public void tearDown( )
{
removeResource( );
}
/**
* Test set/getColSpan() method
*/
public void testColSpan( )
{
cell.setColSpan( 3 );
assertEquals( 3, cell.getColSpan( ) );
}
/**
* Test set/getRowSpan() method
*/
public void testRowSpan( )
{
cell.setRowSpan( 3 );
assertEquals( 3, cell.getRowSpan( ) );
}
/**
* Test set/getColumn() method
*/
public void testColumn( )
{
cell.setColumn( 5 );
assertEquals( 5, cell.getColumn( ) );
}
/**
* Test set/getDisplayGroupIcon() method
*/
public void testDisplayGroupIcon( )
{
cell.setDisplayGroupIcon( true );
assertTrue( cell.getDisplayGroupIcon( ) );
cell.setDisplayGroupIcon( false );
assertFalse( cell.getDisplayGroupIcon( ) );
}
public void testICellContentFromReport( ) throws EngineException
{
runandrender_emitter( EMITTER_HTML, false );
}
public void endCell( ICellContent cell )
{
if ( count == 0 )
{
assertEquals( 2, cell.getColSpan( ) );
assertEquals( 2, cell.getRowSpan( ) );
assertEquals( 0, cell.getRow( ) );
assertEquals( 0, cell.getColumn( ) );
IColumn column = cell.getColumnInstance( );
assertEquals( 5, column.getInstanceID( ).getComponentID( ) );
}
if ( count == 1 )
{
assertEquals( 1, cell.getColSpan( ) );
assertEquals( 1, cell.getRowSpan( ) );
assertEquals( 2, cell.getColumn( ) );
}
if ( count == 2 )
{
assertEquals( 1, cell.getColSpan( ) );
assertEquals( 1, cell.getRowSpan( ) );
assertEquals( 1, cell.getRow( ) );
}
count++;
}
}
|
sguan-actuate/birt
|
testsuites/org.eclipse.birt.report.tests.engine/src/org/eclipse/birt/report/tests/engine/api/ICellContentTest.java
|
Java
|
epl-1.0
| 2,307 |
/*******************************************************************************
* Copyright (c) 2011, 2020 Eurotech and/or its affiliates and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Eurotech
*******************************************************************************/
package org.eclipse.kura.core.deployment.util;
public class FileUtilities {
public static String getFileName(String dpName, String dpVersion, String extension) {
String packageFilename = new StringBuilder().append(dpName).append("-").append(dpVersion).append(extension)
.toString();
return packageFilename;
}
}
|
ctron/kura
|
kura/org.eclipse.kura.core.deployment/src/main/java/org/eclipse/kura/core/deployment/util/FileUtilities.java
|
Java
|
epl-1.0
| 848 |
###########################################################
#
# Copyright (c) 2005-2008, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permission.
#
#
#
__all__ = ['TacticNodeUtil']
import xmlrpclib, os, shutil
from node_data import NodeData
# importing 8.5 maya module
try:
import maya
except:
print("WARNING: module MayaApplication requires 'maya' module")
class TacticNodeUtil(object):
'''This class encapsulates functionality needed interact with information
to communicate with any application.'''
def __init__(self):
import maya.standalone
maya.standalone.initialize( name='python' )
import maya.cmds, maya.mel
from tactic_client_lib.application.maya import Maya
self.app = Maya()
def is_tactic_node(self, node_name):
'''Determines whether a particular node is a tactic node'''
pass
def get_all_tactic_nodes(self):
'''Gets all of the Tactic nodes in the session
@return
a list of all tactic node names
'''
tactic_nodes = []
nodes = self.app.get_nodes_by_name("tactic_*")
# go through each node an make sure that the attribute
# exists
for node in nodes:
if self.is_tactic_node(node):
tactic_nodes.append(node)
return tactic_nodes
def is_tactic_node(self, node_name):
'''determines whether the given node is a tactic node
'''
attribute = "tacticNodeData"
exists = self.mel("attributeExists %s %s" % (attribute, node_name))
if not exists:
return False
else:
return True
#
# action functions
#
def create_default_node(self, node_name, search_key=None, context=None):
'''Creates a default template structure when loading a context
that has no snapshots associated with it
@params
node_name: the name of the node to be created
search_key: a search_key representing the sobject that this node belongs
to
@return
the name of the tactic node created
'''
# create the node
type = "transform"
node_name = self.app.add_node(node_name, type)
# create the tactic node
tactic_type = "transform"
tactic_node_name = "tactic_%s" % node_name
tactic_node_name = self.app.add_node(tactic_node_name, tactic_type)
# add the tacticNodeData attribute and record the search type
node_data = NodeData(tactic_node_name)
if search_key:
node_data.set_attr("ref", "search_key", search_key)
if context:
node_data.set_attr("ref", "context", context)
node_data.commit()
# attache the tactic node to the node
self.mel("parent %s %s" % (tactic_node_name, node_name) )
return tactic_node_name
def add_snapshot_to_node(self, tactic_node_name, snapshot):
snapshot_code = snapshot.get('code')
search_type = snapshot.get('search_type')
search_id = snapshot.get('search_id')
context = snapshot.get('context')
version = snapshot.get('version')
revision = snapshot.get('revision')
node_data = NodeData(tactic_node_name)
node_data.set_attr("ref", "snapshot_code", snapshot_code)
node_data.set_attr("ref", "search_type", search_type)
node_data.set_attr("ref", "search_id", search_id)
node_data.set_attr("ref", "context", context)
node_data.set_attr("ref", "version", version)
node_data.set_attr("ref", "revision", revision)
node_data.commit()
def get_search_key(self, tactic_node_name):
'''gets the snapshot data on a particular tactic node
<node>
<ref context='model' version='3' search_type='prod/asset?project=bar' search_id='4'/>
</node>
'''
node_data = NodeData(tactic_node_name)
search_type = node_data.get_attr("ref", "search_key")
return search_type
def get_context(self, tactic_node_name):
'''gets the snapshot data on a particular tactic node
<node>
<ref context='model' version='3' search_type='prod/asset?project=bar' search_id='4'/>
</node>
'''
node_data = NodeData(tactic_node_name)
search_type = node_data.get_attr("ref", "context")
return search_type
def mel(self, cmd, verbose=None):
'''Excecute a mel command (TEMPORARY - use maya specific)'''
return maya.mel.eval(cmd)
class SnapshotXml(object):
'''Series of utilities to parse the snapshot xml'''
def __init__(self, snapshot_xml):
self.snapshot_xml = snapshot_xml
|
listyque/TACTIC-Handler
|
thlib/side/client/tactic_client_lib/application/common/tactic_node_util.py
|
Python
|
epl-1.0
| 4,995 |
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* 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
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.model.parser;
import org.eclipse.birt.report.model.core.DesignElement;
import org.eclipse.birt.report.model.metadata.PropertyDefn;
import org.eclipse.birt.report.model.metadata.StructureDefn;
import org.eclipse.birt.report.model.util.AbstractParseState;
import org.xml.sax.SAXException;
/**
* Parses the simple structure list, each of which has only one member. So it
* also can be considered as String List.
*/
public class SimpleStructureListState extends CompatibleListPropertyState
{
protected String memberName = null;
SimpleStructureListState( ModuleParserHandler theHandler,
DesignElement element )
{
super( theHandler, element );
}
/**
* Sets the member name which is the unique member in structure.
*
* @param memberName
* the member name to set
*/
public void setMemberName( String memberName )
{
this.memberName = memberName;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.util.AbstractParseState#startElement(java.lang.String)
*/
public AbstractParseState startElement( String tagName )
{
// The unique member name should be specified.
assert memberName != null;
int tagValue = tagName.toLowerCase( ).hashCode( );
if ( ParserSchemaConstants.PROPERTY_TAG == tagValue )
{
AbstractPropertyState state = new SimpleStructureState( handler,
element, propDefn );
return state;
}
return super.startElement( tagName );
}
class SimpleStructureState extends StructureState
{
SimpleStructureState( ModuleParserHandler theHandler,
DesignElement element, PropertyDefn propDefn )
{
super( theHandler, element, propDefn );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.util.AbstractParseState#end()
*/
public void end( ) throws SAXException
{
struct = createStructure( (StructureDefn) propDefn.getStructDefn( ) );
assert struct != null;
String value = text.toString( );
setMember( struct, propDefn.getName( ), memberName, value );
super.end( );
}
}
}
|
sguan-actuate/birt
|
model/org.eclipse.birt.report.model/src/org/eclipse/birt/report/model/parser/SimpleStructureListState.java
|
Java
|
epl-1.0
| 2,584 |
package org.jnect.demo.incquery.esper.events;
/**
* Type of the processed event.
*
* @author idavid
*/
public enum PatternMatchEventType {
NEW, LOST;
}
|
imbur/EMF-IncQuery-Examples
|
bodymodel/org.jnect.demo.incquery/src/org/jnect/demo/incquery/esper/events/PatternMatchEventType.java
|
Java
|
epl-1.0
| 167 |
/**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.groheondus.internal.discovery;
import static org.openhab.binding.groheondus.internal.GroheOndusBindingConstants.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.grohe.ondus.api.OndusService;
import org.grohe.ondus.api.model.BaseAppliance;
import org.openhab.binding.groheondus.internal.handler.GroheOndusAccountHandler;
import org.openhab.core.config.discovery.AbstractDiscoveryService;
import org.openhab.core.config.discovery.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.ThingUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Florian Schmidt - Initial contribution
*/
@NonNullByDefault
public class GroheOndusDiscoveryService extends AbstractDiscoveryService {
private static final String PROPERTY_APPLIANCE_ID = "applianceId";
private static final String PROPERTY_ROOM_ID = "roomId";
private static final String PROPERTY_LOCATION_ID = "locationId";
private final Logger logger = LoggerFactory.getLogger(GroheOndusDiscoveryService.class);
private final GroheOndusAccountHandler bridgeHandler;
public GroheOndusDiscoveryService(GroheOndusAccountHandler bridgeHandler) {
super(Collections
.unmodifiableSet(Stream.of(THING_TYPE_SENSE, THING_TYPE_SENSEGUARD).collect(Collectors.toSet())), 30);
logger.debug("initialize discovery service");
this.bridgeHandler = bridgeHandler;
this.activate(null);
}
@Override
protected void startScan() {
OndusService service;
try {
service = bridgeHandler.getService();
} catch (IllegalStateException e) {
logger.debug("No instance of OndusService given.", e);
return;
}
List<BaseAppliance> discoveredAppliances = new ArrayList<>();
try {
discoveredAppliances = service.appliances();
} catch (IOException e) {
logger.debug("Could not discover appliances.", e);
return;
}
discoveredAppliances.forEach(appliance -> {
ThingUID bridgeUID = bridgeHandler.getThing().getUID();
ThingUID thingUID = null;
switch (appliance.getType()) {
case org.grohe.ondus.api.model.guard.Appliance.TYPE:
thingUID = new ThingUID(THING_TYPE_SENSEGUARD, bridgeUID, appliance.getApplianceId());
break;
case org.grohe.ondus.api.model.sense.Appliance.TYPE:
thingUID = new ThingUID(THING_TYPE_SENSE, bridgeUID, appliance.getApplianceId());
break;
default:
return;
}
Map<String, Object> properties = new HashMap<>();
properties.put(PROPERTY_LOCATION_ID, appliance.getRoom().getLocation().getId());
properties.put(PROPERTY_ROOM_ID, appliance.getRoom().getId());
properties.put(PROPERTY_APPLIANCE_ID, appliance.getApplianceId());
DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withProperties(properties)
.withBridge(bridgeUID).withLabel(appliance.getName())
.withRepresentationProperty(PROPERTY_APPLIANCE_ID).build();
thingDiscovered(discoveryResult);
});
}
}
|
openhab/openhab2
|
bundles/org.openhab.binding.groheondus/src/main/java/org/openhab/binding/groheondus/internal/discovery/GroheOndusDiscoveryService.java
|
Java
|
epl-1.0
| 3,994 |
/*
* Copyright (c) 2014 Cisco Systems, Inc. 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.opendaylight.controller.sal.dom.broker.osgi;
import org.opendaylight.controller.sal.core.api.notify.NotificationListener;
import org.opendaylight.controller.sal.core.api.notify.NotificationPublishService;
import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.CompositeNode;
import org.osgi.framework.ServiceReference;
public class NotificationPublishServiceProxy extends AbstractBrokerServiceProxy<NotificationPublishService> implements NotificationPublishService {
public NotificationPublishServiceProxy(ServiceReference<NotificationPublishService> ref,
NotificationPublishService delegate) {
super(ref, delegate);
}
@Override
public Registration<NotificationListener> addNotificationListener(QName notification, NotificationListener listener) {
return addRegistration(getDelegate().addNotificationListener(notification, listener));
}
@Override
public void publish(CompositeNode notification) {
getDelegate().publish(notification);
}
}
|
yuyf10/opendaylight-controller
|
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/NotificationPublishServiceProxy.java
|
Java
|
epl-1.0
| 1,435 |
/*
// This software is subject to the terms of the Eclipse Public License v1.0
// Agreement, available at the following URL:
// http://www.eclipse.org/legal/epl-v10.html.
// You must accept the terms of that agreement to use this software.
//
// Copyright (C) 2006-2011 Pentaho
// All Rights Reserved.
*/
package mondrian.util;
import java.util.*;
/**
* Iterable list which filters undesirable elements.
* To be used instead of removing elements from an iterable list.
*
* @author Luis F. Canals
* @since december, 2007
*/
public class FilteredIterableList<T> extends AbstractSequentialList<T> {
private List<T> plainList;
private int size;
private boolean isEmpty;
private int lastIndex = 0;
private int lastGetIndex = -1;
private T lastGet = null;
private ListIterator<T> lastListIterator;
private final List<? extends T> internal;
private final Filter<T> filter;
private final Map<Integer, T> cached;
public FilteredIterableList(
final List<? extends T> list,
final Filter filter)
{
super();
this.plainList = null;
this.filter = filter;
this.internal = list;
this.isEmpty = ! this.listIterator(0).hasNext();
this.size = -1;
this.cached = new CacheMap<Integer, T>(4);
}
public T get(final int index) {
if (this.plainList != null) {
return this.plainList.get(index);
}
final T t = cached.get(index);
if (t != null) {
return cached.get(index);
} else {
if (index != this.lastGetIndex || index < 0) {
this.lastGet = super.get(index);
if (this.lastGet == null) {
throw new IndexOutOfBoundsException();
}
this.lastGetIndex = index;
}
cached.put(index, this.lastGet);
return this.lastGet;
}
}
public ListIterator<T> listIterator(final int index) {
if (this.plainList == null) {
if (index == this.lastIndex + 1 && this.lastListIterator != null) {
if (this.lastListIterator.hasNext()) {
this.lastIndex = index;
return this.lastListIterator;
} else {
throw new IndexOutOfBoundsException();
}
} else {
final Iterator<? extends T> it = internal.iterator();
T nextTmp = null;
while (it.hasNext()) {
final T n = it.next();
if (filter.accept(n)) {
nextTmp = n;
break;
}
}
final T first = nextTmp;
this.lastListIterator = new ListIterator<T>() {
private int idx = 0;
private T nxt = first;
private void postNext() {
while (it.hasNext()) {
final T n = it.next();
if (filter.accept(n)) {
nxt = n;
return;
}
}
nxt = null;
}
public boolean hasNext() {
return nxt != null;
}
public T next() {
idx++;
final T n = nxt;
cached.put(idx - 1, n);
postNext();
return n;
}
public int nextIndex() {
return idx;
}
public void add(final T t) {
throw new UnsupportedOperationException();
}
public void set(final T t) {
throw new UnsupportedOperationException();
}
public boolean hasPrevious() {
throw new UnsupportedOperationException();
}
public T previous() {
throw new UnsupportedOperationException();
}
public int previousIndex() {
throw new UnsupportedOperationException();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
this.lastIndex = 0;
}
for (int i = this.lastIndex; i < index; i++) {
if (!this.lastListIterator.hasNext()) {
throw new IndexOutOfBoundsException();
}
this.lastListIterator.next();
}
this.lastIndex = index;
return this.lastListIterator;
} else {
return plainList.listIterator(index);
}
}
public boolean isEmpty() {
return this.plainList != null ? this.plainList.isEmpty() : this.isEmpty;
}
public int size() {
if (this.size == -1) {
int s = this.lastIndex;
try {
final ListIterator<T> it = this.listIterator(this.lastIndex);
while (it.hasNext()) {
s++;
it.next();
}
} catch (IndexOutOfBoundsException ioobe) {
// Subyacent list is no more present...
}
this.size = s;
}
this.lastListIterator = null;
return this.size;
}
public Object[] toArray() {
ensurePlainList();
return this.plainList.toArray();
}
@Override
public <T> T[] toArray(T[] contents) {
ensurePlainList();
return this.plainList.toArray(contents);
}
private void ensurePlainList() {
if (this.plainList == null) {
final List<T> tmpPlainList = new ArrayList<T>();
for (final Iterator<T> it = this.listIterator(0); it.hasNext();) {
tmpPlainList.add(it.next());
}
this.plainList = tmpPlainList;
}
}
public int hashCode() {
return this.filter.hashCode();
}
/*
public List<T> subList(final int start, final int end) {
return new AbstractList<T>() {
public T get(final int index) {
return FilteredIterableList.this.get(index-start);
}
public int size() {
return FilteredIterableList.this.size() - start;
}
};
}
*/
//
// Inner classes ---------------------------------
//
/**
* Filter to determine which elements should be shown.
*/
public static interface Filter<T> {
public boolean accept(final T element);
}
}
// End FilteredIterableList.java
|
rfellows/mondrian
|
src/main/mondrian/util/FilteredIterableList.java
|
Java
|
epl-1.0
| 7,017 |
/*
* Copyright 2013 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.addon.javaee.ejb.ui;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import org.jboss.forge.addon.javaee.ejb.EJBOperations;
import org.jboss.forge.addon.javaee.ui.AbstractJavaEECommand;
import org.jboss.forge.addon.parser.java.facets.JavaSourceFacet;
import org.jboss.forge.addon.parser.java.resources.JavaResource;
import org.jboss.forge.addon.parser.java.resources.JavaResourceVisitor;
import org.jboss.forge.addon.projects.Project;
import org.jboss.forge.addon.resource.FileResource;
import org.jboss.forge.addon.resource.visit.VisitContext;
import org.jboss.forge.addon.ui.context.UIBuilder;
import org.jboss.forge.addon.ui.context.UIContext;
import org.jboss.forge.addon.ui.context.UIExecutionContext;
import org.jboss.forge.addon.ui.context.UISelection;
import org.jboss.forge.addon.ui.context.UIValidationContext;
import org.jboss.forge.addon.ui.hints.InputType;
import org.jboss.forge.addon.ui.input.UISelectOne;
import org.jboss.forge.addon.ui.metadata.WithAttributes;
import org.jboss.forge.addon.ui.result.Result;
import org.jboss.forge.addon.ui.result.Results;
import org.jboss.forge.addon.ui.util.Categories;
import org.jboss.forge.addon.ui.util.Metadata;
import org.jboss.forge.roaster.model.JavaType;
import org.jboss.forge.roaster.model.source.AnnotationSource;
import org.jboss.forge.roaster.model.source.JavaClassSource;
public class EJBSetClassTransactionAttributeCommand extends AbstractJavaEECommand
{
@Inject
@WithAttributes(label = "Target EJB", description = "The EJB on which the transaction type will be set", required = true, type = InputType.DROPDOWN)
private UISelectOne<JavaResource> targetEjb;
@Inject
@WithAttributes(label = "Transaction Type", description = "The type of the transaction", required = true)
private UISelectOne<TransactionAttributeType> type;
@Inject
private EJBOperations ejbOperations;
@Override
public Metadata getMetadata(UIContext context)
{
return Metadata.from(super.getMetadata(context), getClass()).name("EJB: Set Class Transaction Attribute")
.description("Set the transaction type of a given EJB")
.category(Categories.create(super.getMetadata(context).getCategory().getName(), "EJB"));
}
@Override
public void initializeUI(UIBuilder builder) throws Exception
{
setupEntities(builder.getUIContext());
builder.add(targetEjb).add(type);
}
private void setupEntities(UIContext context)
{
UISelection<FileResource<?>> selection = context.getInitialSelection();
Project project = getSelectedProject(context);
final List<JavaResource> entities = new ArrayList<>();
if (project != null)
{
project.getFacet(JavaSourceFacet.class).visitJavaSources(new JavaResourceVisitor()
{
@Override
public void visit(VisitContext context, JavaResource resource)
{
try
{
JavaType<?> javaType = resource.getJavaType();
if (ejbOperations.isEJB(javaType))
{
entities.add(resource);
}
}
catch (FileNotFoundException e)
{
// ignore
}
}
});
}
targetEjb.setValueChoices(entities);
int idx = -1;
if (!selection.isEmpty())
{
idx = entities.indexOf(selection.get());
}
if (idx == -1)
{
idx = entities.size() - 1;
}
if (idx != -1)
{
targetEjb.setDefaultValue(entities.get(idx));
}
}
@Override
public Result execute(UIExecutionContext context) throws Exception
{
JavaResource resource = targetEjb.getValue();
AnnotationSource<JavaClassSource> annotation;
JavaClassSource ejb = resource.getJavaType();
if (ejb.hasAnnotation(TransactionAttribute.class))
{
annotation = ejb.getAnnotation(TransactionAttribute.class);
}
else
{
annotation = ejb.addAnnotation(TransactionAttribute.class);
}
annotation.setEnumValue(type.getValue());
resource.setContents(ejb);
return Results.success("Transaction attribute set to [" + type.getValue() + "]");
}
@Override
public void validate(UIValidationContext validator)
{
super.validate(validator);
try
{
targetEjb.getValue().getJavaType();
}
catch (FileNotFoundException | NullPointerException e)
{
validator.addValidationError(targetEjb, "Type [" + targetEjb.getValue() + "] could not be found");
}
}
@Override
protected boolean isProjectRequired()
{
return true;
}
}
|
agoncal/core
|
javaee/impl/src/main/java/org/jboss/forge/addon/javaee/ejb/ui/EJBSetClassTransactionAttributeCommand.java
|
Java
|
epl-1.0
| 5,098 |
/*
* Copyright (c) 2016 Rogue Wave Software, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Rogue Wave Software, Inc. - initial API and implementation
*/
package org.eclipse.che.plugin.zdb.server.connection;
/**
* Abstract Zend debug message (common for client and engine messages).
*
* @author Bartlomiej Laczkowski
*/
public abstract class AbstractDbgMessage implements IDbgMessage {
@Override
public String getTransferEncoding() {
return ENCODING;
}
@Override
public void setTransferEncoding(String encoding) {
// TODO - support user preferred encoding
}
@Override
public String toString() {
return new StringBuilder(this.getClass().getSimpleName())
.append(" [ID=")
.append(getType())
.append(']')
.toString();
}
}
|
akervern/che
|
plugins/plugin-zend-debugger/che-plugin-zend-debugger-server/src/main/java/org/eclipse/che/plugin/zdb/server/connection/AbstractDbgMessage.java
|
Java
|
epl-1.0
| 996 |
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* 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
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.model.library;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.report.model.api.DesignFileException;
import org.eclipse.birt.report.model.api.EmbeddedImageHandle;
import org.eclipse.birt.report.model.api.GridHandle;
import org.eclipse.birt.report.model.api.ImageHandle;
import org.eclipse.birt.report.model.api.LibraryHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.command.LibraryException;
import org.eclipse.birt.report.model.api.elements.structures.EmbeddedImage;
import org.eclipse.birt.report.model.core.Module;
import org.eclipse.birt.report.model.core.ReferencableStructure;
import org.eclipse.birt.report.model.elements.ReportDesign;
import org.eclipse.birt.report.model.elements.interfaces.IImageItemModel;
import org.eclipse.birt.report.model.metadata.StructRefValue;
import org.eclipse.birt.report.model.util.BaseTestCase;
/**
* Tests the usage of structures in libraries.
*/
public class LibraryStructureTest extends BaseTestCase
{
/**
* Tests the usage of "libReference" in design file.
*
* @throws Exception
*/
public void testLibReference( ) throws Exception
{
openDesign( "LibraryStructureTest.xml" ); //$NON-NLS-1$
assertNotNull( designHandle );
// get the design embedded image
List images = designHandle.getListProperty( ReportDesign.IMAGES_PROP );
assertEquals( 2, images.size( ) );
EmbeddedImage image = designHandle.findImage( "design image2" ); //$NON-NLS-1$
assertNotNull( image );
StructRefValue libReference = (StructRefValue) image.getProperty(
design, ReferencableStructure.LIB_REFERENCE_MEMBER );
assertNotNull( libReference );
assertTrue( libReference.isResolved( ) );
// look up the library embedded image, and check the reference
LibraryHandle includeLib = designHandle.getLibrary( "Lib1" ); //$NON-NLS-1$
assertNotNull( includeLib );
EmbeddedImage includeImage = includeLib.findImage( "image3" ); //$NON-NLS-1$
assertNotNull( includeImage );
assertEquals( includeImage, libReference.getTargetStructure( ) );
// check the data and type of the design image -- equal those of the
// library image
assertNull( image.getLocalProperty( design, EmbeddedImage.DATA_MEMBER ) );
assertTrue( image.getProperty( design, EmbeddedImage.DATA_MEMBER ) == includeImage
.getProperty( includeLib.getModule( ),
EmbeddedImage.DATA_MEMBER ) );
assertTrue( Arrays.equals( image.getData( design ), includeImage
.getData( includeLib.getModule( ) ) ) );
save( );
// check the "imageName" of the image items in design
ImageHandle imageHandle = (ImageHandle) designHandle
.findElement( "Image1" ); //$NON-NLS-1$
assertNotNull( imageHandle );
assertEquals(
"design image1", imageHandle.getEmbeddedImage( ).getQualifiedName( ) ); //$NON-NLS-1$
imageHandle = (ImageHandle) designHandle.findElement( "Image2" ); //$NON-NLS-1$
assertNotNull( imageHandle );
assertEquals(
"design image2", imageHandle.getEmbeddedImage( ).getQualifiedName( ) ); //$NON-NLS-1$
}
/**
* Tests the resolve and unresolve of the structures.
*
* @throws Exception
*/
public void testResolveForStructure( ) throws Exception
{
openDesign( "LibraryStructureTest_1.xml" ); //$NON-NLS-1$
assertNotNull( designHandle );
// test the unresolve status of some embedded image and image item
EmbeddedImage image = designHandle.findImage( "design image4" ); //$NON-NLS-1$
assertNotNull( image );
StructRefValue libReference = (StructRefValue) image.getProperty(
design, ReferencableStructure.LIB_REFERENCE_MEMBER );
assertNotNull( libReference );
assertFalse( libReference.isResolved( ) );
assertEquals( "Lib2.image3", libReference.getQualifiedReference( ) ); //$NON-NLS-1$
ImageHandle imageHandle = (ImageHandle) designHandle
.findElement( "Image2" ); //$NON-NLS-1$
assertNotNull( imageHandle );
StructRefValue imageName = (StructRefValue) imageHandle.getElement( )
.getProperty( design, ImageHandle.IMAGE_NAME_PROP );
assertNotNull( imageName );
assertFalse( imageName.isResolved( ) );
assertEquals( "Lib2.image3", imageName.getName( ) ); //$NON-NLS-1$
assertNull( imageHandle.getEmbeddedImage( ) );
// add the library_2 to the design
designHandle.includeLibrary( "Library_2.xml", "Lib2" ); //$NON-NLS-1$//$NON-NLS-2$
LibraryHandle includeLib = designHandle.getLibrary( "Lib2" ); //$NON-NLS-1$
assertNotNull( includeLib );
assertEquals( 2, designHandle.getLibraries( ).size( ) );
// check the unresolved embedded image and image item again
libReference = (StructRefValue) image.getProperty( design,
ReferencableStructure.LIB_REFERENCE_MEMBER );
assertNotNull( libReference );
assertTrue( libReference.isResolved( ) );
assertEquals( "Lib2.image3", libReference.getQualifiedReference( ) ); //$NON-NLS-1$
imageHandle = (ImageHandle) designHandle.findElement( "Image2" ); //$NON-NLS-1$
assertNotNull( imageHandle );
imageName = (StructRefValue) imageHandle.getElement( ).getProperty(
design, ImageHandle.IMAGE_NAME_PROP );
assertNotNull( imageName );
assertTrue( imageName.isResolved( ) );
assertEquals( "Lib2.image3", imageName.getQualifiedReference( ) ); //$NON-NLS-1$
assertEquals( "image3", imageName.getName( ) ); //$NON-NLS-1$
assertEquals( "Lib2", imageName.getLibraryNamespace( ) ); //$NON-NLS-1$
assertNotNull( imageHandle.getEmbeddedImage( ) );
// drop the library and check the embedded image and image item again
designHandle.dropLibrary( includeLib );
libReference = (StructRefValue) image.getProperty( design,
ReferencableStructure.LIB_REFERENCE_MEMBER );
assertNotNull( libReference );
assertFalse( libReference.isResolved( ) );
assertEquals( "Lib2.image3", libReference.getQualifiedReference( ) ); //$NON-NLS-1$
imageHandle = (ImageHandle) designHandle.findElement( "Image2" ); //$NON-NLS-1$
assertNotNull( imageHandle );
imageName = (StructRefValue) imageHandle.getElement( ).getProperty(
design, ImageHandle.IMAGE_NAME_PROP );
assertNotNull( imageName );
assertFalse( imageName.isResolved( ) );
assertEquals( "Lib2.image3", imageName.getName( ) ); //$NON-NLS-1$
assertNull( imageHandle.getEmbeddedImage( ) );
// after undo, it is resolved again.
designHandle.getCommandStack( ).undo( );
imageName = (StructRefValue) imageHandle.getElement( ).getProperty(
design, ImageHandle.IMAGE_NAME_PROP );
assertNotNull( imageName );
assertTrue( imageName.isResolved( ) );
assertEquals( "Lib2.image3", imageName.getQualifiedReference( ) ); //$NON-NLS-1$
assertEquals( "image3", imageName.getName( ) ); //$NON-NLS-1$
assertEquals( "Lib2", imageName.getLibraryNamespace( ) ); //$NON-NLS-1$
}
/**
* Tests the visibility of the library structures.
*
* @throws Exception
*/
public void testVisibilityForStructure( ) throws Exception
{
openDesign( "LibraryStructureTest_2.xml" ); //$NON-NLS-1$
assertNotNull( designHandle );
LibraryHandle visibleLib = designHandle.getLibrary( "CompositeLib" ); //$NON-NLS-1$
assertNotNull( visibleLib );
EmbeddedImage image = designHandle.findImage( "design image3" ); //$NON-NLS-1$
assertNotNull( image );
StructRefValue libReference = (StructRefValue) image.getProperty(
design, ReferencableStructure.LIB_REFERENCE_MEMBER );
assertNotNull( libReference );
assertTrue( libReference.isResolved( ) );
assertEquals( "Lib1.image3", libReference.getQualifiedReference( ) ); //$NON-NLS-1$
LibraryHandle invisibleLib = visibleLib.getLibrary( "Lib1" ); //$NON-NLS-1$
assertNotNull( invisibleLib );
EmbeddedImage invisibleImage = invisibleLib.findImage( "image3" ); //$NON-NLS-1$
assertNotNull( invisibleImage );
}
/**
* Tests the getEmbeddedImage() in ImageHandle when extending or virtual
* extending.
*
* @throws Exception
*/
public void testEmbeddedImageInImageItem( ) throws Exception
{
openDesign( "LibraryStructureTest_3.xml" ); //$NON-NLS-1$
assertNotNull( designHandle );
libraryHandle = designHandle.getLibrary( "Lib1" ); //$NON-NLS-1$
assertNotNull( libraryHandle );
PropertyHandle images = libraryHandle
.getPropertyHandle( Module.IMAGES_PROP );
ImageHandle imageHandle = (ImageHandle) designHandle
.findElement( "image" ); //$NON-NLS-1$
assertNotNull( imageHandle );
assertEquals( "Lib1.image1", imageHandle.getImageName( ) ); //$NON-NLS-1$
assertEquals( "Lib1.image1", imageHandle //$NON-NLS-1$
.getProperty( IImageItemModel.IMAGE_NAME_PROP ) );
assertEquals( images.getAt( 0 ).getStructure( ), imageHandle
.getEmbeddedImage( ).getStructure( ) );
GridHandle gridHandle = (GridHandle) designHandle.findElement( "grid" ); //$NON-NLS-1$
assertNotNull( gridHandle );
imageHandle = (ImageHandle) gridHandle.getCell( 1, 1 ).getContent( )
.get( 0 );
assertNotNull( imageHandle );
assertEquals( images.getAt( 1 ).getStructure( ), imageHandle
.getEmbeddedImage( ).getStructure( ) );
assertEquals( "Lib1.image2", imageHandle.getImageName( ) ); //$NON-NLS-1$
assertEquals( "Lib1.image2", imageHandle //$NON-NLS-1$
.getProperty( IImageItemModel.IMAGE_NAME_PROP ) );
}
/**
* Test cases for Embedded images.
*
* @throws Exception
*/
public void testMultiExtendedElements( ) throws Exception
{
openDesign( "LibraryStructureTest_4.xml" ); //$NON-NLS-1$
ImageHandle imageHandle = (ImageHandle) designHandle
.findElement( "image1" ); //$NON-NLS-1$
assertEquals( "Lib1.image1", imageHandle.getImageName( ) ); //$NON-NLS-1$
assertEquals( "Lib1.image1", imageHandle //$NON-NLS-1$
.getProperty( IImageItemModel.IMAGE_NAME_PROP ) );
GridHandle gridHandle = (GridHandle) designHandle.findElement( "grid1" ); //$NON-NLS-1$
assertNotNull( gridHandle );
imageHandle = (ImageHandle) gridHandle.getCell( 1, 1 ).getContent( )
.get( 0 );
assertEquals( "Lib1.image2", imageHandle //$NON-NLS-1$
.getProperty( IImageItemModel.IMAGE_NAME_PROP ) );
assertEquals( "Lib1.image2", imageHandle.getImageName( ) ); //$NON-NLS-1$
EmbeddedImage emImage = designHandle.findImage( "Lib1.image1" ); //$NON-NLS-1$
assertNotNull( emImage );
emImage = designHandle.findImage( "Lib1.image2" ); //$NON-NLS-1$
assertNotNull( emImage );
}
/**
* Tests the library include library.
*/
public void testLibraryIncludeLibrary( )
{
try
{
openLibrary( "LibraryIncludingTwoLibraries.xml" ); //$NON-NLS-1$
}
catch ( DesignFileException e )
{
fail( );
}
assertNotNull( libraryHandle );
}
/**
* To create an embedded image from an existed embeded image.
*
* <ul>
* <li>1. create an embedded image. but the target module does not include
* the library.
* <li>2. create an embedded image. the target module includes the library.
* <li>3. if the base embedded image is on the design tree, the create
* image is null.
* </ul>
*
* @throws Exception
*/
public void testCreateImageFrom( ) throws Exception
{
openLibrary( "Library_1.xml" ); //$NON-NLS-1$
Iterator iter1 = libraryHandle.imagesIterator( );
EmbeddedImageHandle baseImage = (EmbeddedImageHandle) iter1.next( );
openDesign( "DesignWithoutLibrary.xml" ); //$NON-NLS-1$
// design not includes the library.
try
{
StructureFactory.newEmbeddedImageFrom( baseImage, "image1", //$NON-NLS-1$
designHandle );
fail( );
}
catch ( SemanticException e )
{
assertEquals( LibraryException.DESIGN_EXCEPTION_LIBRARY_NOT_FOUND,
e.getErrorCode( ) );
}
designHandle.includeLibrary( "Library_1.xml", "Lib1" ); //$NON-NLS-1$ //$NON-NLS-2$
EmbeddedImage newImage = StructureFactory.newEmbeddedImageFrom(
baseImage, "image1", designHandle ); //$NON-NLS-1$
assertEquals( "image1", newImage.getName( ) ); //$NON-NLS-1$
assertNotNull( newImage.getData( design ) );
assertNull( newImage.getLocalProperty( design,
EmbeddedImage.DATA_MEMBER ) );
StructRefValue refValue = (StructRefValue) newImage.getLocalProperty(
design, EmbeddedImage.LIB_REFERENCE_MEMBER );
assertNotNull( refValue );
assertEquals( "Lib1.image1", refValue.getQualifiedReference( ) ); //$NON-NLS-1$
designHandle.addImage( newImage );
// if the module of the base image is report design, do nothing.
iter1 = designHandle.imagesIterator( );
baseImage = (EmbeddedImageHandle) iter1.next( );
assertNull( StructureFactory.newEmbeddedImageFrom( baseImage, "image3", //$NON-NLS-1$
designHandle ) );
save( );
assertTrue( compareFile( "LibraryStructure_golden.xml" ) ); //$NON-NLS-1$
}
}
|
sguan-actuate/birt
|
model/org.eclipse.birt.report.model.tests/test/org/eclipse/birt/report/model/library/LibraryStructureTest.java
|
Java
|
epl-1.0
| 13,259 |
/*
* Copyright (c) 2012-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.plugin.pullrequest.client.vcs;
import com.google.gwt.user.client.rpc.AsyncCallback;
import java.util.List;
import javax.validation.constraints.NotNull;
import org.eclipse.che.api.core.model.workspace.config.ProjectConfig;
import org.eclipse.che.api.git.shared.Branch;
import org.eclipse.che.api.git.shared.PushResponse;
import org.eclipse.che.api.git.shared.Remote;
import org.eclipse.che.api.promises.client.Promise;
/** Service for VCS operations. */
public interface VcsService {
/**
* Add a remote to the project VCS metadata.
*
* @param project the project descriptor.
* @param remote the remote name.
* @param remoteUrl the remote URL.
* @param callback callback when the operation is done.
*/
void addRemote(
@NotNull ProjectConfig project,
@NotNull String remote,
@NotNull String remoteUrl,
@NotNull AsyncCallback<Void> callback);
/**
* Checkout a branch of the given project.
*
* @param project the project descriptor.
* @param branchName the name of the branch to checkout.
* @param createNew create a new branch if {@code true}.
* @param callback callback when the operation is done.
*/
void checkoutBranch(
@NotNull ProjectConfig project,
@NotNull String branchName,
boolean createNew,
@NotNull AsyncCallback<String> callback);
/**
* Commits the current changes of the given project.
*
* @param project the project descriptor.
* @param includeUntracked {@code true} to include untracked files, {@code false} otherwise.
* @param commitMessage the commit message.
* @param callback callback when the operation is done.
*/
void commit(
@NotNull ProjectConfig project,
boolean includeUntracked,
@NotNull String commitMessage,
@NotNull AsyncCallback<Void> callback);
/**
* Removes a remote to the project VCS metadata.
*
* @param project the project descriptor.
* @param remote the remote name.
* @param callback callback when the operation is done.
*/
void deleteRemote(
@NotNull ProjectConfig project,
@NotNull String remote,
@NotNull AsyncCallback<Void> callback);
/**
* Returns the name of the current branch for the given {@code project}.
*
* @param project the project.
* @return the promise that resolves branch name or rejects with an error
*/
Promise<String> getBranchName(ProjectConfig project);
/**
* Returns if the given project has uncommitted changes.
*
* @param project the project descriptor.
* @param callback what to do if the project has uncommitted changes.
*/
void hasUncommittedChanges(
@NotNull ProjectConfig project, @NotNull AsyncCallback<Boolean> callback);
/**
* Returns if a local branch with the given name exists in the given project.
*
* @param project the project descriptor.
* @param branchName the branch name.
* @param callback callback called when operation is done.
*/
void isLocalBranchWithName(
@NotNull ProjectConfig project,
@NotNull String branchName,
@NotNull AsyncCallback<Boolean> callback);
/**
* List the local branches.
*
* @param project the project descriptor.
* @param callback what to do with the branches list.
*/
void listLocalBranches(
@NotNull ProjectConfig project, @NotNull AsyncCallback<List<Branch>> callback);
/**
* Returns the list of the remotes for given {@code project}.
*
* @param project the project
* @return the promise which resolves {@literal List<Remote>} or rejects with an error
*/
Promise<List<Remote>> listRemotes(ProjectConfig project);
/**
* Push a local branch to remote.
*
* @param project the project descriptor.
* @param remote the remote name
* @param localBranchName the local branch name
*/
Promise<PushResponse> pushBranch(ProjectConfig project, String remote, String localBranchName);
}
|
akervern/che
|
plugins/plugin-pullrequest-parent/che-plugin-pullrequest-ide/src/main/java/org/eclipse/che/plugin/pullrequest/client/vcs/VcsService.java
|
Java
|
epl-1.0
| 4,296 |
/**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.mihome.internal.handler;
import static org.openhab.binding.mihome.internal.XiaomiGatewayBindingConstants.*;
import org.openhab.binding.mihome.internal.ChannelMapper;
import org.openhab.core.thing.Thing;
import com.google.gson.JsonObject;
/**
* Handles the Xiaomi aqara smart switch with two buttons
*
* @author Dieter Schmidt - Initial contribution
*/
public class XiaomiAqaraSensorSwitch2Handler extends XiaomiSensorBaseHandler {
private static final String CHANNEL_0 = "channel_0";
private static final String CHANNEL_1 = "channel_1";
private static final String DUAL_CHANNEL = "dual_channel";
public XiaomiAqaraSensorSwitch2Handler(Thing thing) {
super(thing);
}
@Override
protected void parseReport(JsonObject data) {
if (data.has(CHANNEL_0)) {
triggerChannel(CHANNEL_SWITCH_CH0,
ChannelMapper.getChannelEvent(data.get(CHANNEL_0).getAsString().toUpperCase()));
}
if (data.has(CHANNEL_1)) {
triggerChannel(CHANNEL_SWITCH_CH1,
ChannelMapper.getChannelEvent(data.get(CHANNEL_1).getAsString().toUpperCase()));
}
if (data.has(DUAL_CHANNEL)) {
triggerChannel(CHANNEL_SWITCH_DUAL_CH,
ChannelMapper.getChannelEvent(data.get(DUAL_CHANNEL).getAsString().toUpperCase()));
}
}
}
|
openhab/openhab2
|
bundles/org.openhab.binding.mihome/src/main/java/org/openhab/binding/mihome/internal/handler/XiaomiAqaraSensorSwitch2Handler.java
|
Java
|
epl-1.0
| 1,775 |
class VideoAttachment < ActiveRecord::Base
#belongs_to :attachable
attr_accessible :description,:file
belongs_to :attachable,polymorphic: true
has_many :comments, as: :commentable, dependent: :destroy
mount_uploader :file, VideoUploader
has_many :video_and_interests
has_many :interest,:through => :video_and_interests
has_reputation :votes,source: :user,aggregated_by: :sum
end
|
valekar/exbeeme2-
|
app/models/video_attachment.rb
|
Ruby
|
epl-1.0
| 405 |
/*******************************************************************************
* Copyright (c) 2012, 2014 UT-Battelle, LLC.
* 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
*
* Contributors:
* Initial API and implementation and/or initial documentation - Jay Jay Billings,
* Jordan H. Deyton, Dasha Gorin, Alexander J. McCaskey, Taylor Patterson,
* Claire Saunders, Matthew Wang, Anna Wojtowicz
*******************************************************************************/
package org.eclipse.ice.viz.service.geometry.widgets;
import java.net.URL;
import org.eclipse.ice.viz.service.datastructures.VizObject.VizObject;
import org.eclipse.ice.viz.service.geometry.shapes.AbstractShape;
import org.eclipse.ice.viz.service.geometry.shapes.ComplexShape;
import org.eclipse.ice.viz.service.geometry.shapes.Geometry;
import org.eclipse.ice.viz.service.geometry.shapes.IShape;
import org.eclipse.ice.viz.service.geometry.shapes.OperatorType;
import org.eclipse.ice.viz.service.geometry.shapes.Transformation;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.ui.internal.util.BundleUtility;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
/**
* <p>
* Opens a dialog box to replicate the selected shape
* </p>
* <p>
* This action should be enabled only when exactly one shape is selected.
* </p>
*
* @author Andrew P. Belt
*/
public class ActionReplicateShape extends Action {
/**
* <p>
* The current ShapeTreeView
* </p>
*
*/
private ShapeTreeView view;
/**
* The image descriptor associated with the duplicate action's icon
*/
private ImageDescriptor imageDescriptor;
/**
* <p>
* Initializes the instance with the current ShapeTreeView
* </p>
*
* @param view
* <p>
* The current ShapeTreeView
* </p>
*/
public ActionReplicateShape(ShapeTreeView view) {
this.view = view;
this.setText("Replicate Shape");
// Load replicate.gif icon from the bundle's icons/ directory
Bundle bundle = FrameworkUtil.getBundle(getClass());
URL imagePath = BundleUtility.find(bundle, "icons/replicate.gif");
imageDescriptor = ImageDescriptor.createFromURL(imagePath);
}
@Override
public ImageDescriptor getImageDescriptor() {
return imageDescriptor;
}
/**
* <p>
* Opens the replicate dialog box and clones the selected shape to the
* properties
* </p>
*
*/
@Override
public void run() {
Geometry geometry = (Geometry) view.treeViewer
.getInput();
// Check that only one shape is selected
ITreeSelection selection = (ITreeSelection) view.treeViewer
.getSelection();
TreePath[] paths = selection.getPaths();
if (paths.length != 1) {
return;
}
// Get the selected shape from the selection
Object selectedObject = paths[0].getLastSegment();
if (!(selectedObject instanceof IShape)) {
return;
}
IShape selectedShape = (IShape) selectedObject;
// Create a transformation, initialized from the selected shape's
// transformation
Transformation accumulatedTransformation = (Transformation) selectedShape
.getTransformation().clone();
// Open the dialog
ReplicateDialog replicateDialog = new ReplicateDialog(view.getSite()
.getShell());
if (replicateDialog.open() != IDialogConstants.OK_ID) {
return;
}
// Get the dialog parameters
int quantity = replicateDialog.getQuantity();
double[] shift = replicateDialog.getShift();
// Ignore the request if the desired quantity is 1
if (quantity == 1) {
return;
}
// Get the parent of the shape
// If the selected shape is a direct child of a GeometryComponent,
// its parent shape is null.
ComplexShape parentShape = (ComplexShape) selectedShape.getParent();
// Remove the selected shape from its original parent
synchronized (geometry) {
if (parentShape != null) {
parentShape.removeShape(selectedShape);
} else {
geometry.removeShape(selectedShape);
}
}
// Create a new parent union shape
ComplexShape replicateUnion = new ComplexShape(OperatorType.Union);
replicateUnion.setName("Replication");
replicateUnion.setId(((VizObject) selectedShape).getId());
for (int i = 1; i <= quantity; i++) {
// Clone the selected shape and remove its "selected" property
IShape clonedShape = (IShape) ((AbstractShape) selectedShape)
.clone();
clonedShape.removeProperty("selected");
((VizObject) clonedShape).setId(i);
// Add the translation
clonedShape
.setTransformation((Transformation) accumulatedTransformation
.clone());
// Add it to the replicated union
replicateUnion.addShape(clonedShape);
// Shift the transform for the next shape
accumulatedTransformation.translate(shift);
}
// Refresh the TreeViewer
if (parentShape != null) {
// The parent is an IShape
synchronized (geometry) {
parentShape.addShape(replicateUnion);
}
view.treeViewer.refresh(parentShape);
} else {
// The parent is the root GeometryComponent
synchronized (geometry) {
geometry.addShape(replicateUnion);
}
view.treeViewer.refresh();
}
view.treeViewer.expandToLevel(parentShape, 1);
}
}
|
nickstanish/ice
|
org.eclipse.ice.viz.service.geometry/src/org/eclipse/ice/viz/service/geometry/widgets/ActionReplicateShape.java
|
Java
|
epl-1.0
| 5,579 |
#!/bin/sh
# keep_text_section_prefix.sh -- test
# Copyright (C) 2018-2020 Free Software Foundation, Inc.
# Written by Sriraman Tallam <[email protected]>.
# This file is part of gold.
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
# MA 02110-1301, USA.
# The goal of this program is to verify if .text sections are separated
# according to their prefix. .text.hot, .text.unlikely, .text.startup and
# .text.exit must be separated in the final binary.
set -e
check()
{
awk "
BEGIN { saw1 = 0; saw2 = 0; err = 0; }
/.*$2\$/ { saw1 = 1; }
/.*$3\$/ {
saw2 = 1;
if (!saw1)
{
printf \"layout of $2 and $3 is not right\\n\";
err = 1;
exit 1;
}
}
END {
if (!saw1 && !err)
{
printf \"did not see $2\\n\";
exit 1;
}
if (!saw2 && !err)
{
printf \"did not see $3\\n\";
exit 1;
}
}" $1
}
check_str()
{
if ! grep -q "$2" "$1"
then
echo "Did not find expected output in $1:"
echo " $2"
echo ""
echo "Actual output below:"
cat "$1"
exit 1
fi
}
check_str keep_text_section_prefix_readelf.stdout ".text.hot .text .text.startup .text.exit .text.unlikely"
check keep_text_section_prefix_nm.stdout "hot_foo" "regular_foo"
check keep_text_section_prefix_nm.stdout "regular_foo" "startup_foo"
check keep_text_section_prefix_nm.stdout "startup_foo" "exit_foo"
check keep_text_section_prefix_nm.stdout "exit_foo" "unlikely_foo"
|
mattstock/binutils-bexkat1
|
gold/testsuite/keep_text_section_prefix.sh
|
Shell
|
gpl-2.0
| 2,052 |
<?php
/**
* Template Name: Full Width
*
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package Jobify
* @since Jobify 1.5
*/
get_header(); ?>
<?php while ( have_posts() ) : the_post(); ?>
<header class="page-header">
<h1 class="page-title"><?php the_title(); ?></h1>
</header>
<div id="primary" class="content-area">
<div id="content" class="site-content full" role="main">
<?php get_template_part( 'content', 'page' ); ?>
<?php comments_template(); ?>
</div><!-- #content -->
<?php do_action( 'jobify_loop_after' ); ?>
</div><!-- #primary -->
<?php endwhile; ?>
<?php get_footer(); ?>
|
INFT2100ITWorks/ITWorks
|
wp-content/themes/jobify/page-templates/full-width.php
|
PHP
|
gpl-2.0
| 637 |
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
$lang['footer.footer']='Copyright © 2003 - 2012. ASTPP - Open Source VOIP Billing Solution. All Rights Reserved.';
?>
|
bmurkoff/ASTPP
|
web_interface/astpp/application/modules/accounts/language/arabic/footer_lang.php
|
PHP
|
gpl-2.0
| 196 |
/*
Theme Name: WP Knowledge Base
Theme URI: http://ipanelthemes.com/kb/wp-knowledge-base-theme/
Author: swashata
Author URI: http://www.swashata.com/
Description: A responsive bootstrap based theme for maintaining multi product knowledge base on your WordPress site. Easily create knowledge bases with just posts and categories. You can also have images, support forum links and/or icons assigned to knowledge bases. The theme also has a comprehensive documentation which can be found at the ThemeURI ( http://ipanelthemes.com/kb/wp-knowledge-base-theme/ ). Requires atleast WordPress 3.5 due to jQuery dependency of bootstrap 3.0. Support for bbPress is added officially to version 1.6.0.
Version: 1.6.0
License: GNU General Public License
License URI: license.txt
Text Domain: ipt_kb
Domain Path: /languages/
Tags: gray, light, white, two-columns, right-sidebar, flexible-width, custom-header, custom-menu, featured-images, threaded-comments, translation-ready
WP Knowledge Base WordPress theme, Copyright (C) 2013 iPanelThemes.com
WP Knowledge Base WordPress theme is licensed under the GPL.
This theme, like WordPress, is licensed under the GPL.
Use it to make something cool, have fun, and share what you've learned with others.
===Bundled Resources===
Bootstrap - http://getbootstrap.com/
License: Distributed under the terms of the Apache 2.0 license.
Copyright: Twitter, http://twitter.com
Icomoon Icon Packs - http://icomoon.io/#icons
License: Distributed under the terms of the GPL
Copyright: IcoMoon, http://icomoon.io/
Sticky-Kit - http://leafo.net/sticky-kit/
License: Distributed under the terms of the WTFPL
Copyright: Leaf Corcoran, http://leafo.net
wp-bootstrap-navwalker - https://github.com/twittem/wp-bootstrap-navwalker
License: Distributed under the terms of the GPL-2.0+
Copyright: Edward McIntyre - @twittem
Google Fonts (Roboto and Oswald) - http://www.google.com/fonts/
License: Roboto font and Oswald font are distributed under the terms of the Apache License, version 2.0 and SIL Open Font License, 1.1 respectively
Copyright: Google Fonts, http://www.google.com/fonts/attribution
WP Knowledge Base is based on Underscores http://underscores.me/, (C) 2012-2013 Automattic, Inc.
Resetting and rebuilding styles have been helped along thanks to the fine work of
Eric Meyer http://meyerweb.com/eric/tools/css/reset/index.html
along with Nicolas Gallagher and Jonathan Neal http://necolas.github.com/normalize.css/
and Blueprint http://www.blueprintcss.org/
*/
/* =Reset
-------------------------------------------------------------- */
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
border: 0;
font-family: inherit;
font-size: 100%;
font-style: inherit;
font-weight: inherit;
margin: 0;
outline: 0;
padding: 0;
vertical-align: baseline;
}
html {
font-size: 62.5%; /* Corrects text resizing oddly in IE6/7 when body font-size is set using em units http://clagnut.com/blog/348/#c790 */
overflow-y: scroll; /* Keeps page centred in all browsers regardless of content height */
-webkit-text-size-adjust: 100%; /* Prevents iOS text size adjust after orientation change, without disabling user zoom */
-ms-text-size-adjust: 100%; /* www.456bereastreet.com/archive/201012/controlling_text_size_in_safari_for_ios_without_disabling_user_zoom/ */
}
body {
background: #fff;
}
article,
aside,
details,
figcaption,
figure,
footer,
header,
main,
nav,
section {
display: block;
}
ol, ul {
list-style: none;
}
table { /* tables still need 'cellspacing="0"' in the markup */
border-collapse: separate;
border-spacing: 0;
}
caption, th, td {
font-weight: normal;
text-align: left;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: "";
}
blockquote, q {
quotes: "" "";
}
a:focus {
outline: thin dotted;
}
a:hover,
a:active { /* Improves readability when focused and also mouse hovered in all browsers people.opera.com/patrickl/experiments/keyboard/test */
outline: 0;
}
a img {
border: 0;
}
/* =Global
----------------------------------------------- */
body {
word-wrap: break-word;
}
body,
input,
select,
textarea {
color: #404040;
font-family: sans-serif;
font-size: 16px;
font-size: 1.6rem;
line-height: 1.5;
}
/* Headings */
h1, h2, h3, h4, h5, h6 {
clear: both;
}
hr {
background-color: #ccc;
border: 0;
height: 1px;
margin-bottom: 1.5em;
}
/* Text elements */
p {
margin-bottom: 1.5em;
}
ul, ol {
margin: 0 0 1.5em 3em;
}
ul {
list-style: disc;
}
ol {
list-style: decimal;
}
li > ul,
li > ol {
margin-bottom: 0;
margin-left: 1.5em;
}
dt {
font-weight: bold;
}
dd {
margin: 0 1.5em 1.5em;
}
b, strong {
font-weight: bold;
}
dfn, cite, em, i {
font-style: italic;
}
blockquote {
margin: 0 1.5em;
}
address {
margin: 0 0 1.5em;
}
pre {
background: #eee;
font-family: "Courier 10 Pitch", Courier, monospace;
font-size: 15px;
font-size: 1.5rem;
line-height: 1.6;
margin-bottom: 1.6em;
max-width: 100%;
overflow: auto;
padding: 1.6em;
}
code, kbd, tt, var {
font: 15px Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace;
}
abbr, acronym {
border-bottom: 1px dotted #666;
cursor: help;
}
mark, ins {
background: #fff9c0;
text-decoration: none;
}
sup,
sub {
font-size: 75%;
height: 0;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
bottom: 1ex;
}
sub {
top: .5ex;
}
small {
font-size: 75%;
}
big {
font-size: 125%;
}
figure {
margin: 0;
}
table {
margin: 0 0 1.5em;
width: 100%;
}
th {
font-weight: bold;
}
img {
height: auto; /* Make sure images are scaled correctly. */
max-width: 100%; /* Adhere to container width. */
}
button,
input,
select,
textarea {
font-size: 100%; /* Corrects font size not being inherited in all browsers */
margin: 0; /* Addresses margins set differently in IE6/7, F3/4, S5, Chrome */
vertical-align: baseline; /* Improves appearance and consistency in all browsers */
*vertical-align: middle; /* Improves appearance and consistency in all browsers */
}
button,
input {
line-height: normal; /* Addresses FF3/4 setting line-height using !important in the UA stylesheet */
}
button,
input {
line-height: normal; /* Addresses FF3/4 setting line-height using !important in the UA stylesheet */
}
.entry-content input[type="reset"],
.entry-content input[type="submit"] {
border: 1px solid #ccc;
border-color: #ccc #ccc #bbb #ccc;
border-radius: 3px;
background: #e6e6e6;
color: rgba(0, 0, 0, .8);
cursor: pointer; /* Improves usability and consistency of cursor style between image-type 'input' and others */
-webkit-appearance: button; /* Corrects inability to style clickable 'input' types in iOS */
font-size: 12px;
font-size: 1.2rem;
line-height: 1;
padding: .6em 1em .4em;
}
input[type="reset"]:hover,
input[type="submit"]:hover {
border-color: #ccc #bbb #aaa #bbb;
}
.entry-content input[type="reset"]:focus,
.entry-content input[type="submit"]:focus,
.entry-content input[type="reset"]:active,
.entry-content input[type="submit"]:active {
border-color: #aaa #bbb #bbb #bbb;
}
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box; /* Addresses box sizing set to content-box in IE8/9 */
padding: 0; /* Addresses excess padding in IE8/9 */
}
input[type="search"] {
-webkit-appearance: textfield; /* Addresses appearance set to searchfield in S5, Chrome */
-webkit-box-sizing: content-box; /* Addresses box sizing set to border-box in S5, Chrome (include -moz to future-proof) */
-moz-box-sizing: content-box;
box-sizing: content-box;
}
input[type="search"]::-webkit-search-decoration { /* Corrects inner padding displayed oddly in S5, Chrome on OSX */
-webkit-appearance: none;
}
button::-moz-focus-inner,
input::-moz-focus-inner { /* Corrects inner padding and border displayed oddly in FF3/4 www.sitepen.com/blog/2008/05/14/the-devils-in-the-details-fixing-dojos-toolbar-buttons/ */
border: 0;
padding: 0;
}
input[type="text"],
input[type="email"],
input[type="url"],
input[type="password"],
input[type="search"],
textarea {
color: #666;
border: 1px solid #ccc;
border-radius: 3px;
}
input[type="text"]:focus,
input[type="email"]:focus,
input[type="url"]:focus,
input[type="password"]:focus,
input[type="search"]:focus,
textarea:focus {
color: #111;
}
input[type="text"],
input[type="email"],
input[type="url"],
input[type="password"],
input[type="search"] {
padding: 3px;
}
input.form-control {
padding: 6px 12px;
}
textarea {
overflow: auto; /* Removes default vertical scrollbar in IE6/7/8/9 */
padding-left: 3px;
vertical-align: top; /* Improves readability and alignment in all browsers */
width: 98%;
}
/* Alignment */
.alignleft {
display: inline;
float: left;
margin-right: 1.5em;
}
.alignright {
display: inline;
float: right;
margin-left: 1.5em;
}
.aligncenter {
clear: both;
display: block;
margin: 0 auto;
}
/* Text meant only for screen readers */
.screen-reader-text {
clip: rect(1px, 1px, 1px, 1px);
position: absolute !important;
}
.screen-reader-text:hover,
.screen-reader-text:active,
.screen-reader-text:focus {
background-color: #f1f1f1;
border-radius: 3px;
box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.6);
clip: auto !important;
color: #21759b;
display: block;
font-size: 14px;
font-weight: bold;
height: auto;
left: 5px;
line-height: normal;
padding: 15px 23px 14px;
text-decoration: none;
top: 5px;
width: auto;
z-index: 100000; /* Above WP toolbar */
}
/* Clearing */
.clear:before,
.clear:after,
.entry-content:before,
.entry-content:after,
.comment-content:before,
.comment-content:after,
.site-header:before,
.site-header:after,
.site-content:before,
.site-content:after,
.site-footer:before,
.site-footer:after {
content: '';
display: table;
}
.clear:after,
.entry-content:after,
.comment-content:after,
.site-header:after,
.site-content:after,
.site-footer:after {
clear: both;
}
/* =Header
----------------------------------------------- */
.site-title {
font-size: 18px;
margin: 15px 0 0;
clear: none;
}
.site-title a {
color: #777;
}
/* =Menu
----------------------------------------------- */
.main-navigation {
font-size: 1.5rem;
}
.main-navigation .glyphicon {
font-size: 16px;
margin-right: 5px;
}
.main-navigation .main-navigation-search-form {
width: 250px;
}
/* =Content
----------------------------------------------- */
.sticky {
}
.hentry {
margin: 0 0 1.5em;
}
.byline,
.updated {
display: none;
}
.single .byline,
.group-blog .byline {
display: inline;
}
.page-content,
.entry-content,
.entry-summary {
margin: 1.5em 0 0;
}
.page-links {
clear: both;
margin: 0 0 1.5em;
}
/* =Media
----------------------------------------------- */
a img {
opacity: 1;
-webkit-transition: opacity 400ms;
-moz-transition: opacity 400ms;
-ms-transition: opacity 400ms;
-o-transition: opacity 400ms;
transition: opacity 400ms;
}
a:hover img {
opacity: 0.7;
}
.entry-content img {
-webkit-box-shadow: 0 0 4px #eee;
-moz-box-shadow: 0 0 4px #eee;
box-shadow: 0 0 4px #eee;
border-radius: 4px;
border: 1px solid #ddd;
}
img[class*="wp-image-"] {
border-radius: 4px;
}
.page-content img.wp-smiley,
.entry-content img.wp-smiley,
.comment-content img.wp-smiley {
border: none;
margin-bottom: 0;
margin-top: 0;
padding: 0;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
}
.wp-caption {
border: 1px solid #ddd;
margin-bottom: 1.5em;
max-width: 100%;
border-radius: 4px;
padding: 4px;
line-height: 1;
-webkit-box-shadow: 0 0 4px #eee;
-moz-box-shadow: 0 0 4px #eee;
box-shadow: 0 0 4px #eee;
}
.wp-caption img[class*="wp-image-"] {
display: block;
margin: 0 auto;
max-width: 100%;
border-radius: 4px;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
border: none;
}
.wp-caption-text {
text-align: center;
font-size: 12px;
}
.wp-caption .wp-caption-text {
margin: 0.8075em 0;
}
.site-main .gallery {
margin-bottom: 1.5em;
}
.gallery-caption {
}
.site-main .gallery a img {
border: 1px solid #ddd !important;
height: auto;
max-width: 90%;
-webkit-box-shadow: 0 0 4px #eee;
-moz-box-shadow: 0 0 4px #eee;
box-shadow: 0 0 4px #eee;
}
.site-main .gallery dd {
margin: 0.8075em 0 0;
}
.site-main .gallery-columns-4 .gallery-item {
}
.site-main .gallery-columns-4 .gallery-item img {
}
/* Make sure embeds and iframes fit their containers */
embed,
iframe,
object {
max-width: 100%;
}
/* =Navigation
----------------------------------------------- */
.site-main [class*="navigation"] {
margin: 0 0 1.5em;
overflow: hidden;
}
[class*="navigation"] .nav-previous {
float: left;
width: 50%;
}
[class*="navigation"] .nav-next {
float: right;
text-align: right;
width: 50%;
}
.pagination-p {
float: left;
margin: 20px 10px 20px 0;
line-height: 32px;
}
/* =Author Metabox
----------------------------------------------- */
.author-meta .author-avatar {
margin-right: 20px;
}
.author-meta .author-avatar img {
border-radius: 100%;
}
.author-meta .author-meta-buttons {
margin-left: 20px;
}
.author-meta h4.author-meta-title {
clear: none;
margin-top: 0;
}
/* =Comments
----------------------------------------------- */
body .comment-form-comment.form-group {
margin-right: 0;
margin-left: 0;
}
body .col-sm-7 .comment-form-comment.form-group {
margin-right: -15px;
margin-left: -15px;
}
@media screen and (min-width: 768px) {
body .col-sm-7 .comment-form-comment.form-group {
margin-left: 0;
}
}
.col-sm-7 #comment {
height: 132px;
}
.comment-content a {
word-wrap: break-word;
}
.bypostauthor {
}
body .comment-reply-title {
clear: none;
}
.comment-list,
.comment-list ol,
.comment-list li {
list-style: none;
margin: 0 0 10px 0;
padding: 0;
}
@media screen and (min-width: 768px) {
.comment-list ol {
margin-left: 50px;
}
}
.comment-metadata,
.comment-awaiting-moderation {
line-height: 32px;
margin: 0;
}
/* =Widgets
----------------------------------------------- */
.widget {
margin: 0 0 1.5em;
}
/* Make sure select elements fit in widgets */
.widget select {
max-width: 100%;
}
/* Search widget */
.widget_search .search-submit {
display: none;
}
/* Widget iframe */
.widget iframe {
width: 100% !important;
height: auto;
overflow: hidden;
}
/* Affix Widget */
.ipt_kb_affix .list-group .list-group-item > .glyphicon {
font-size: 15px;
}
.ipt_kb_affix .list-group .list-group-item > i[class*="ipt-icon"] {
font-size: 16px;
}
.ipt_kb_affix .list-group-item.active-cat {
background-color: #f1f1f1;
}
.ipt_kb_affix .ipt-kb-toc {
font-size: 12px;
}
.ipt-kb-toc h4 {
clear: none;
}
.ipt_kb_affix .ipt-kb-toc h5 {
margin: 0;
}
#ipt-kb-toc-scrollspy {
margin-bottom: 10px;
}
#ipt-kb-toc-scrollspy ul {
margin: 0;
padding: 0;
list-style: none;
}
#ipt-kb-toc-scrollspy ul li {
line-height: 12px;
margin: 0;
padding: 0;
}
#ipt-kb-toc-scrollspy ul li.active {
font-weight: bold;
}
#ipt-kb-toc-scrollspy ul li a {
font-size: 12px;
padding: 7px 10px;
}
#ipt-kb-toc-scrollspy ul li.active a {
background-color: #f1f1f1;
}
#ipt-kb-affix-active-post .list-group-item {
padding: 5px 15px;
font-size: 12px;
border-radius: 0;
}
#ipt-kb-affix-active-post .list-group-item:first-child {
margin-top: -1px;
}
#ipt-kb-affix-active-post .list-group-item:last-child {
margin-bottom: -1px;
}
.ipt-kb-toc .accordion-toggle i.glyphicon {
font-size: 16px;
margin-left: 4px;
}
/* Social Widget */
.ipt-kb-social-widget .widget-title span {
color: #2A6496;
}
.ipt-kb-social-widget .ipt-kb-social-ul {
list-style-type: none;
margin: 0;
padding: 0;
text-align: center;
}
.ipt-kb-social-widget .ipt-kb-social-ul li {
display: inline-block;
width: 56px;
height: 56px;
margin: 0 2px;
}
.ipt-kb-social-widget .ipt-kb-social-ul li a {
text-align: center;
line-height: 56px;
height: 56px;
width: 56px;
display: block;
border-radius: 100%;
background-color: #f1f1f1;
border: 1px solid #ddd;
color: #ddd;
text-decoration: none;
-webkit-transition: all 400ms;
-moz-transition: all 400ms;
-ms-transition: all 400ms;
-o-transition: all 400ms;
transition: all 400ms;
}
.ipt-kb-social-widget .ipt-kb-social-ul li a i {
font-size: 32px;
line-height: 50px;
}
.ipt-kb-social-widget .ipt-kb-social-ul li a:hover {
color: #fff;
text-shadow: 0 0 2px #888;
}
.ipt-kb-social-widget .ipt-kb-social-ul li.facebook a:hover {
background-color: #3B5998;
border-color: #3B5998;
}
.ipt-kb-social-widget .ipt-kb-social-ul li.twitter a:hover {
background-color: #00A0D1;
border-color: #00A0D1;
}
.ipt-kb-social-widget .ipt-kb-social-ul li.gplus a:hover {
background-color: #C63D2D;
border-color: #C63D2D;
}
.ipt-kb-social-widget .ipt-kb-social-ul li.youtube a:hover {
background-color: #C4302B;
border-color: #C4302B;
}
.ipt-kb-social-widget .ipt-kb-social-ul li.vimeo a:hover {
background-color: #44BBFF;
border-color: #44BBFF;
}
.ipt-kb-social-widget .ipt-kb-social-ul li.pinterest a:hover {
background-color: #910101;
border-color: #910101;
}
.ipt-kb-social-widget .ipt-kb-social-ul li.envato a:hover {
background-color: #82B540;
border-color: #82B540;
}
/* =Footer
---------------------------------------------- */
#colophon {
padding: 10px 0 30px;
font-size: 1em;
min-height: 120px;
padding-bottom: 50px;
position: relative;
background-color: #eee;
}
#colophon .site-info {
text-align: center;
font-size: 12px;
bottom: 0;
position: absolute;
width: 100%;
}
/* =Knowledgebase Homepage
----------------------------------------------- */
#main .knowledgebase-title {
font-size: 17px;
margin-top: 10px;
}
#main .kb-home-cat-row .glyphicon,
#main .kb-cat-parent-row .glyphicon {
font-size: 16px;
}
#main .kb-home-cat-row .pagination .glyphicon,
#main .kb-cat-parent-row .pagination .glyphicon {
font-size: inherit;
}
#main .kb-home-cat-row [class*="glyphicon-"],
#main .kb-cat-parent-row [class*="glyphicon-"] {
font-size: 15px;
}
#main .entry-content h1 .glyphicon,
#main .entry-content h2 .glyphicon,
#main .entry-content h3 .glyphicon,
#main .entry-content h4 .glyphicon,
#main .entry-content h5 .glyphicon,
#main .entry-content h6 .glyphicon {
font-size: inherit;
margin-right: 5px;
}
.kb-post-list .badge {
margin-top: 3px;
}
.kb-post-list h3 {
clear: none;
margin: 0;
line-height: 24px;
font-size: 14px;
font-family: 'Roboto', sans-serif;
}
/* =Knowledgebase Parent Category
----------------------------------------------- */
#main .kb-parent-category-header {
margin-bottom: 20px;
}
#main .kb-parent-category-header .kb-pcat-icon {
margin-top: 0;
}
#main .kb-subcat .knowledgebase-title {
font-size: 17px;
margin-top: 0;
}
#main .kb-subcat-icon {
padding: 0;
}
#main .kb-subcat-icon .thumbnail {
height: 128px;
line-height: 128px;
}
#main .kb-subcat-icon .thumbnail .glyphicon {
font-size: 64px;
line-height: 111px;
}
#main .kb-subcat-icon .thumbnail i[class*="ipt-icon"] {
line-height: 105px;
}
#main .kb-scat-title {
margin-top: 0;
}
/* =Thumbnails
----------------------------------------------- */
#main .kb-thumb-small {
margin-right: 5px;
}
#main .kb-thumb-medium {
margin-right: 10px;
}
#main .kb-thumb-large {
margin-bottom: 10px;
}
/* =Breadcrumb
----------------------------------------------- */
#breadcrumbs {
margin-left: 0;
}
/* =Archive Page
----------------------------------------------- */
#main .page-header,
#main .page-title {
margin-top: 0;
}
#main footer.entry-meta {
margin-top: 10px;
}
#main footer.entry-meta .meta-data {
line-height: 32px;
}
/* =Singular Page
----------------------------------------------- */
#main .entry-title {
margin-top: 0;
}
/* =Bootstrap Helper
----------------------------------------------- */
.ipt-kb-popover-target {
display: none;
}
body .popover {
max-width: 680px;
}
body .hidden-xs .ipt_kb_like_article {
text-align: left;
}
body .ipt_kb_like_article_info {
line-height: 32px;
}
body .well p {
margin: 5px 0;
}
body .entry-content ul.nav-tabs,
body .entry-content ul.list-group {
margin-left: 0;
margin-top: 10px;
margin-bottom: 0;
}
body .entry-content ul.list-group {
margin-bottom: 10px;
}
body .tab-content {
margin: 0 0 20px 0;
padding: 10px;
border: 1px solid #ddd;
border-top: medium none;
border-radius: 0 4px 4px 4px;
}
body .popover-title button.pull-right {
font-size: 12px;
margin: -2px 0 0 10px;
}
body .label {
font-weight: normal;
}
body a .label {
text-decoration: none;
}
#secondary .list-group,
#secondary .nav {
margin: 0;
}
input[type="text"],
input[type="password"],
select,
textarea {
display: block;
width: 100%;
color: #555555;
vertical-align: middle;
background-color: #ffffff;
border: 1px solid #cccccc;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-webkit-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}
select {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
textarea {
height: auto;
}
input[type="text"]:focus,
input[type="password"]:focus,
select:focus,
textarea:focus {
border-color: #66afe9;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
}
input[type="text"][disabled],
input[type="text"][readonly],
fieldset[disabled] .form-control,
select[disabled],
textarea:disabled {
cursor: not-allowed;
background-color: #eeeeee;
}
button,
input[type="submit"] {
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 14px;
font-weight: normal;
line-height: 1.428571429;
text-align: center;
vertical-align: middle;
cursor: pointer;
border: 1px solid transparent;
border-radius: 4px;
white-space: nowrap;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
}
button:focus,
input[type="submit"]:focus {
outline: thin dotted #333;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
button:hover,
button:focus,
input[type="submit"]:hover,
input[type="submit"]:focus {
color: #333333;
text-decoration: none;
}
button:active,
button.active,
input[type="submit"]:active {
outline: 0;
background-image: none;
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
}
button.disabled,
button[disabled],
fieldset[disabled] .btn {
cursor: not-allowed;
pointer-events: none;
opacity: 0.65;
filter: alpha(opacity=65);
-webkit-box-shadow: none;
box-shadow: none;
}
button,
input[type="submit"] {
color: #333333;
background-color: #ffffff;
border-color: #cccccc;
}
button:hover,
button:focus,
button:active,
button.active,
input[type="submit"]:hover,
input[type="submit"]:focus {
color: #333333;
background-color: #ebebeb;
border-color: #adadad;
}
button:active,
button.active,
input[type="submit"]:active {
background-image: none;
}
button.disabled,
button[disabled],
button.disabled:hover,
button[disabled]:hover,
button.disabled:focus,
button[disabled]:focus,
button.disabled:active,
button[disabled]:active,
button.disabled.active,
button[disabled].active {
background-color: #ffffff;
border-color: #cccccc;
}
.list-group-item.active {
color: #fff;
}
/* =Post Content Styles
----------------------------------------------- */
body table {
border-collapse: collapse;
border: 1px solid #ddd;
}
body table tr,
body table td,
body table th {
border: 1px solid #ddd;
}
body table td,
body table th {
padding: 10px;
}
body table thead,
body table tfoot,
body table th {
background: #f6f6f6;
}
body blockquote,
body blockquote p,
.hentry blockquote,
.hentry blockquote p {
font-size: 14px;
}
body code {
white-space: normal;
}
/* =Syntax Highlighter Compatibility
------------------------------------------------- */
.syntaxhighlighter .container:before,
.syntaxhighlighter .container:after {
display: none;
}
.syntaxhighlighter *,
.syntaxhighlighter *:after,
.syntaxhighlighter *:before {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
.syntaxhighlighter code {
white-space: nowrap;
}
body .syntaxhighlighter table,
body .syntaxhighlighter table tbody,
body .syntaxhighlighter table tr,
body .syntaxhighlighter table td,
body .syntaxhighlighter table code,
body .syntaxhighlighter table div {
font-size: 12px !important;
}
/* =Captcha Plugin Compatibility
------------------------------------------------- */
/* Captcha Plugin */
.cptch_block {
overflow: hidden;
margin: 0 -15px 10px;
font-family: monospace;
text-align: left;
}
.cptch_block br,
.cptch_block + br {
display: none;
}
.cptch_block label {
float: left;
width: 33.333333%;
padding: 0 15px;
margin-right: 15px;
margin-top: 2px;
font-family: 'Roboto', 'Arial', sans-serif;
}
#commentform .cptch_block label {
width: 41.6667%;
}
.cptch_block #cptch_input {
width: 60px !important;
height: 34px !important;
line-height: 1.428571429 !important;
font-size: 14px !important;
padding: 6px 12px !important;
}
#secondary .widget .cptch_block label {
width: auto;
line-height: 2;
}
@media only screen and (max-width: 768px) {
.cptch_block {
margin: 0 0 10px;
}
.cptch_block label,
#secondary .widget .cptch_block label,
#commentform .cptch_block label {
width: 100%;
margin: 0 0 10px 0;
padding-left: 0;
}
}
/* =Wee little wpstats icon
------------------------------------------------- */
#wpstats {
display: block;
margin: 0 auto 10px;
}
|
joenefloresca/kbase
|
wp-content/themes/wp-knowledge-base/style.css
|
CSS
|
gpl-2.0
| 25,659 |
<?php
/**
* @package Joomla.Site
* @subpackage mod_custom
* @copyright Copyright (C) 2005 - 2012 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;
if ($params->def('prepare_content', 1))
{
JPluginHelper::importPlugin('content');
$module->content = JHtml::_('content.prepare', $module->content, '', 'mod_custom.content');
}
$moduleclass_sfx = htmlspecialchars($params->get('moduleclass_sfx'));
require JModuleHelper::getLayoutPath('mod_custom', $params->get('layout', 'default'));
|
tohakotliarenko/personality
|
modules/mod_custom/mod_custom.php
|
PHP
|
gpl-2.0
| 633 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* 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 [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Adminhtml
* @copyright Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Adminhtml Grid Renderer
*
* @category Mage
* @package Mage_Adminhtml
* @author Magento Core Team <[email protected]>
*/
class Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Longtext
extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
/**
* Render contents as a long text
*
* Text will be truncated as specified in string_limit, truncate or 250 by default
* Also it can be html-escaped and nl2br()
*
* @param Varien_Object $row
* @return string
*/
public function render(Varien_Object $row)
{
$truncateLength = 250;
// stringLength() is for legacy purposes
if ($this->getColumn()->getStringLimit()) {
$truncateLength = $this->getColumn()->getStringLimit();
}
if ($this->getColumn()->getTruncate()) {
$truncateLength = $this->getColumn()->getTruncate();
}
$text = Mage::helper('core/string')->truncate(parent::_getValue($row), $truncateLength);
if ($this->getColumn()->getEscape()) {
$text = $this->escapeHtml($text);
}
if ($this->getColumn()->getNl2br()) {
$text = nl2br($text);
}
return $text;
}
}
|
miguelangelramirez/magento.dev
|
app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Longtext.php
|
PHP
|
gpl-2.0
| 2,212 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="ThemeBucket">
<link rel="shortcut icon" href="images/favicon.png">
<title>Calendar</title>
<!--Core CSS -->
<link href="bs3/css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-reset.css" rel="stylesheet">
<link href="font-awesome/css/font-awesome.css" rel="stylesheet" />
<!--calendar css-->
<link href="js/fullcalendar/bootstrap-fullcalendar.css" rel="stylesheet" />
<!-- Custom styles for this template -->
<link href="css/style.css" rel="stylesheet">
<link href="css/style-responsive.css" rel="stylesheet" />
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]>
<script src="js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body>
<section id="container" >
<!--header start-->
<header class="header fixed-top clearfix">
<!--logo start-->
<div class="brand">
<a href="index.html" class="logo">
<img src="images/logo.png" alt="">
</a>
<div class="sidebar-toggle-box">
<div class="fa fa-bars"></div>
</div>
</div>
<!--logo end-->
<div class="nav notify-row" id="top_menu">
<!-- notification start -->
<ul class="nav top-menu">
<!-- settings start -->
<li class="dropdown">
<a data-toggle="dropdown" class="dropdown-toggle" href="#">
<i class="fa fa-tasks"></i>
<span class="badge bg-success">8</span>
</a>
<ul class="dropdown-menu extended tasks-bar">
<li>
<p class="">You have 8 pending tasks</p>
</li>
<li>
<a href="#">
<div class="task-info clearfix">
<div class="desc pull-left">
<h5>Target Sell</h5>
<p>25% , Deadline 12 June’13</p>
</div>
<span class="notification-pie-chart pull-right" data-percent="45">
<span class="percent"></span>
</span>
</div>
</a>
</li>
<li>
<a href="#">
<div class="task-info clearfix">
<div class="desc pull-left">
<h5>Product Delivery</h5>
<p>45% , Deadline 12 June’13</p>
</div>
<span class="notification-pie-chart pull-right" data-percent="78">
<span class="percent"></span>
</span>
</div>
</a>
</li>
<li>
<a href="#">
<div class="task-info clearfix">
<div class="desc pull-left">
<h5>Payment collection</h5>
<p>87% , Deadline 12 June’13</p>
</div>
<span class="notification-pie-chart pull-right" data-percent="60">
<span class="percent"></span>
</span>
</div>
</a>
</li>
<li>
<a href="#">
<div class="task-info clearfix">
<div class="desc pull-left">
<h5>Target Sell</h5>
<p>33% , Deadline 12 June’13</p>
</div>
<span class="notification-pie-chart pull-right" data-percent="90">
<span class="percent"></span>
</span>
</div>
</a>
</li>
<li class="external">
<a href="#">See All Tasks</a>
</li>
</ul>
</li>
<!-- settings end -->
<!-- inbox dropdown start-->
<li id="header_inbox_bar" class="dropdown">
<a data-toggle="dropdown" class="dropdown-toggle" href="#">
<i class="fa fa-envelope-o"></i>
<span class="badge bg-important">4</span>
</a>
<ul class="dropdown-menu extended inbox">
<li>
<p class="red">You have 4 Mails</p>
</li>
<li>
<a href="#">
<span class="photo"><img alt="avatar" src="images/avatar-mini.jpg"></span>
<span class="subject">
<span class="from">Jonathan Smith</span>
<span class="time">Just now</span>
</span>
<span class="message">
Hello, this is an example msg.
</span>
</a>
</li>
<li>
<a href="#">
<span class="photo"><img alt="avatar" src="images/avatar-mini-2.jpg"></span>
<span class="subject">
<span class="from">Jane Doe</span>
<span class="time">2 min ago</span>
</span>
<span class="message">
Nice admin template
</span>
</a>
</li>
<li>
<a href="#">
<span class="photo"><img alt="avatar" src="images/avatar-mini-3.jpg"></span>
<span class="subject">
<span class="from">Tasi sam</span>
<span class="time">2 days ago</span>
</span>
<span class="message">
This is an example msg.
</span>
</a>
</li>
<li>
<a href="#">
<span class="photo"><img alt="avatar" src="images/avatar-mini.jpg"></span>
<span class="subject">
<span class="from">Mr. Perfect</span>
<span class="time">2 hour ago</span>
</span>
<span class="message">
Hi there, its a test
</span>
</a>
</li>
<li>
<a href="#">See all messages</a>
</li>
</ul>
</li>
<!-- inbox dropdown end -->
<!-- notification dropdown start-->
<li id="header_notification_bar" class="dropdown">
<a data-toggle="dropdown" class="dropdown-toggle" href="#">
<i class="fa fa-bell-o"></i>
<span class="badge bg-warning">3</span>
</a>
<ul class="dropdown-menu extended notification">
<li>
<p>Notifications</p>
</li>
<li>
<div class="alert alert-info clearfix">
<span class="alert-icon"><i class="fa fa-bolt"></i></span>
<div class="noti-info">
<a href="#"> Server #1 overloaded.</a>
</div>
</div>
</li>
<li>
<div class="alert alert-danger clearfix">
<span class="alert-icon"><i class="fa fa-bolt"></i></span>
<div class="noti-info">
<a href="#"> Server #2 overloaded.</a>
</div>
</div>
</li>
<li>
<div class="alert alert-success clearfix">
<span class="alert-icon"><i class="fa fa-bolt"></i></span>
<div class="noti-info">
<a href="#"> Server #3 overloaded.</a>
</div>
</div>
</li>
</ul>
</li>
<!-- notification dropdown end -->
</ul>
<!-- notification end -->
</div>
<div class="top-nav clearfix">
<!--search & user info start-->
<ul class="nav pull-right top-menu">
<li>
<input type="text" class="form-control search" placeholder=" Search">
</li>
<!-- user login dropdown start-->
<li class="dropdown">
<a data-toggle="dropdown" class="dropdown-toggle" href="#">
<img alt="" src="images/avatar1_small.jpg">
<span class="username">John Doe</span>
<b class="caret"></b>
</a>
<ul class="dropdown-menu extended logout">
<li><a href="#"><i class=" fa fa-suitcase"></i>Profile</a></li>
<li><a href="#"><i class="fa fa-cog"></i> Settings</a></li>
<li><a href="login.html"><i class="fa fa-key"></i> Log Out</a></li>
</ul>
</li>
<!-- user login dropdown end -->
<li>
<div class="toggle-right-box">
<div class="fa fa-bars"></div>
</div>
</li>
</ul>
<!--search & user info end-->
</div>
</header>
<!--header end-->
<aside>
<div id="sidebar" class="nav-collapse">
<!-- sidebar menu start--> <div class="leftside-navigation">
<ul class="sidebar-menu" id="nav-accordion">
<li>
<a href="index.html">
<i class="fa fa-dashboard"></i>
<span>Dashboard</span>
</a>
</li>
<li class="sub-menu">
<a href="javascript:;">
<i class="fa fa-laptop"></i>
<span>Layouts</span>
</a>
<ul class="sub">
<li><a href="boxed_page.html">Boxed Page</a></li>
<li><a href="horizontal_menu.html">Horizontal Menu</a></li>
<li><a href="language_switch.html">Language Switch Bar</a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;" class="active">
<i class="fa fa-book"></i>
<span>UI Elements</span>
</a>
<ul class="sub">
<li><a href="general.html">General</a></li>
<li><a href="buttons.html">Buttons</a></li>
<li><a href="typography.html">Typography</a></li>
<li><a href="widget.html">Widget</a></li>
<li><a href="slider.html">Slider</a></li>
<li><a href="tree_view.html">Tree View</a></li>
<li><a href="nestable.html">Nestable</a></li>
<li><a href="grids.html">Grids</a></li>
<li class="active"><a href="calendar.html">Calender</a></li>
<li><a href="draggable_portlet.html">Draggable Portlet</a></li>
</ul>
</li>
<li>
<a href="fontawesome.html">
<i class="fa fa-bullhorn"></i>
<span>Fontawesome </span>
</a>
</li>
<li class="sub-menu">
<a href="javascript:;">
<i class="fa fa-th"></i>
<span>Data Tables</span>
</a>
<ul class="sub">
<li><a href="basic_table.html">Basic Table</a></li>
<li><a href="responsive_table.html">Responsive Table</a></li>
<li><a href="dynamic_table.html">Dynamic Table</a></li>
<li><a href="editable_table.html">Editable Table</a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;">
<i class="fa fa-tasks"></i>
<span>Form Components</span>
</a>
<ul class="sub">
<li><a href="form_component.html">Form Elements</a></li>
<li><a href="advanced_form.html">Advanced Components</a></li>
<li><a href="form_wizard.html">Form Wizard</a></li>
<li><a href="form_validation.html">Form Validation</a></li>
<li><a href="file_upload.html">Muliple File Upload</a></li>
<li><a href="dropzone.html">Dropzone</a></li>
<li><a href="inline_editor.html">Inline Editor</a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;">
<i class="fa fa-envelope"></i>
<span>Mail </span>
</a>
<ul class="sub">
<li><a href="mail.html">Inbox</a></li>
<li><a href="mail_compose.html">Compose Mail</a></li>
<li><a href="mail_view.html">View Mail</a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;">
<i class=" fa fa-bar-chart-o"></i>
<span>Charts</span>
</a>
<ul class="sub">
<li><a href="morris.html">Morris</a></li>
<li><a href="chartjs.html">Chartjs</a></li>
<li><a href="flot_chart.html">Flot Charts</a></li>
<li><a href="c3_chart.html">C3 Chart</a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;">
<i class=" fa fa-bar-chart-o"></i>
<span>Maps</span>
</a>
<ul class="sub">
<li><a href="google_map.html">Google Map</a></li>
<li><a href="vector_map.html">Vector Map</a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;">
<i class="fa fa-glass"></i>
<span>Extra</span>
</a>
<ul class="sub">
<li><a href="blank.html">Blank Page</a></li>
<li><a href="lock_screen.html">Lock Screen</a></li>
<li><a href="profile.html">Profile</a></li>
<li><a href="invoice.html">Invoice</a></li>
<li><a href="pricing_table.html">Pricing Table</a></li>
<li><a href="timeline.html">Timeline</a></li>
<li><a href="gallery.html">Media Gallery</a></li><li><a href="404.html">404 Error</a></li>
<li><a href="500.html">500 Error</a></li>
<li><a href="registration.html">Registration</a></li>
</ul>
</li>
<li>
<a href="login.html">
<i class="fa fa-user"></i>
<span>Login Page</span>
</a>
</li>
</ul></div>
<!-- sidebar menu end-->
</div>
</aside>
<!--sidebar end-->
<!--main content start-->
<section id="main-content">
<section class="wrapper">
<!-- page start-->
<section class="panel">
<header class="panel-heading">
Draggable Calendar
<span class="tools pull-right">
<a href="javascript:;" class="fa fa-chevron-down"></a>
<a href="javascript:;" class="fa fa-cog"></a>
<a href="javascript:;" class="fa fa-times"></a>
</span>
</header>
<div class="panel-body">
<!-- page start-->
<div class="row">
<aside class="col-lg-9">
<div id="calendar" class="has-toolbar"></div>
</aside>
<aside class="col-lg-3">
<h4 class="drg-event-title"> Draggable Events</h4>
<div id='external-events'>
<div class='external-event label label-primary'>My Event 1</div>
<div class='external-event label label-success'>My Event 2</div>
<div class='external-event label label-info'>My Event 3</div>
<div class='external-event label label-inverse'>My Event 4</div>
<div class='external-event label label-warning'>My Event 5</div>
<div class='external-event label label-danger'>My Event 6</div>
<div class='external-event label label-default'>My Event 7</div>
<div class='external-event label label-primary'>My Event 8</div>
<div class='external-event label label-info'>My Event 9</div>
<div class='external-event label label-success'>My Event 10</div>
<p class="border-top drp-rmv">
<input type='checkbox' id='drop-remove' />
remove after drop
</p>
</div>
</aside>
</div>
<!-- page end-->
</div>
</section>
<!-- page end-->
</section>
</section>
<!--main content end-->
<!--right sidebar start-->
<div class="right-sidebar">
<div class="search-row">
<input type="text" placeholder="Search" class="form-control">
</div>
<div class="right-stat-bar">
<ul class="right-side-accordion">
<li class="widget-collapsible">
<a href="#" class="head widget-head red-bg active clearfix">
<span class="pull-left">work progress (5)</span>
<span class="pull-right widget-collapse"><i class="ico-minus"></i></span>
</a>
<ul class="widget-container">
<li>
<div class="prog-row side-mini-stat clearfix">
<div class="side-graph-info">
<h4>Target sell</h4>
<p>
25%, Deadline 12 june 13
</p>
</div>
<div class="side-mini-graph">
<div class="target-sell">
</div>
</div>
</div>
<div class="prog-row side-mini-stat">
<div class="side-graph-info">
<h4>product delivery</h4>
<p>
55%, Deadline 12 june 13
</p>
</div>
<div class="side-mini-graph">
<div class="p-delivery">
<div class="sparkline" data-type="bar" data-resize="true" data-height="30" data-width="90%" data-bar-color="#39b7ab" data-bar-width="5" data-data="[200,135,667,333,526,996,564,123,890,564,455]">
</div>
</div>
</div>
</div>
<div class="prog-row side-mini-stat">
<div class="side-graph-info payment-info">
<h4>payment collection</h4>
<p>
25%, Deadline 12 june 13
</p>
</div>
<div class="side-mini-graph">
<div class="p-collection">
<span class="pc-epie-chart" data-percent="45">
<span class="percent"></span>
</span>
</div>
</div>
</div>
<div class="prog-row side-mini-stat">
<div class="side-graph-info">
<h4>delivery pending</h4>
<p>
44%, Deadline 12 june 13
</p>
</div>
<div class="side-mini-graph">
<div class="d-pending">
</div>
</div>
</div>
<div class="prog-row side-mini-stat">
<div class="col-md-12">
<h4>total progress</h4>
<p>
50%, Deadline 12 june 13
</p>
<div class="progress progress-xs mtop10">
<div style="width: 50%" aria-valuemax="100" aria-valuemin="0" aria-valuenow="20" role="progressbar" class="progress-bar progress-bar-info">
<span class="sr-only">50% Complete</span>
</div>
</div>
</div>
</div>
</li>
</ul>
</li>
<li class="widget-collapsible">
<a href="#" class="head widget-head terques-bg active clearfix">
<span class="pull-left">contact online (5)</span>
<span class="pull-right widget-collapse"><i class="ico-minus"></i></span>
</a>
<ul class="widget-container">
<li>
<div class="prog-row">
<div class="user-thumb">
<a href="#"><img src="images/avatar1_small.jpg" alt=""></a>
</div>
<div class="user-details">
<h4><a href="#">Jonathan Smith</a></h4>
<p>
Work for fun
</p>
</div>
<div class="user-status text-danger">
<i class="fa fa-comments-o"></i>
</div>
</div>
<div class="prog-row">
<div class="user-thumb">
<a href="#"><img src="images/avatar1.jpg" alt=""></a>
</div>
<div class="user-details">
<h4><a href="#">Anjelina Joe</a></h4>
<p>
Available
</p>
</div>
<div class="user-status text-success">
<i class="fa fa-comments-o"></i>
</div>
</div>
<div class="prog-row">
<div class="user-thumb">
<a href="#"><img src="images/chat-avatar2.jpg" alt=""></a>
</div>
<div class="user-details">
<h4><a href="#">John Doe</a></h4>
<p>
Away from Desk
</p>
</div>
<div class="user-status text-warning">
<i class="fa fa-comments-o"></i>
</div>
</div>
<div class="prog-row">
<div class="user-thumb">
<a href="#"><img src="images/avatar1_small.jpg" alt=""></a>
</div>
<div class="user-details">
<h4><a href="#">Mark Henry</a></h4>
<p>
working
</p>
</div>
<div class="user-status text-info">
<i class="fa fa-comments-o"></i>
</div>
</div>
<div class="prog-row">
<div class="user-thumb">
<a href="#"><img src="images/avatar1.jpg" alt=""></a>
</div>
<div class="user-details">
<h4><a href="#">Shila Jones</a></h4>
<p>
Work for fun
</p>
</div>
<div class="user-status text-danger">
<i class="fa fa-comments-o"></i>
</div>
</div>
<p class="text-center">
<a href="#" class="view-btn">View all Contacts</a>
</p>
</li>
</ul>
</li>
<li class="widget-collapsible">
<a href="#" class="head widget-head purple-bg active">
<span class="pull-left"> recent activity (3)</span>
<span class="pull-right widget-collapse"><i class="ico-minus"></i></span>
</a>
<ul class="widget-container">
<li>
<div class="prog-row">
<div class="user-thumb rsn-activity">
<i class="fa fa-clock-o"></i>
</div>
<div class="rsn-details ">
<p class="text-muted">
just now
</p>
<p>
<a href="#">Jim Doe </a>Purchased new equipments for zonal office setup
</p>
</div>
</div>
<div class="prog-row">
<div class="user-thumb rsn-activity">
<i class="fa fa-clock-o"></i>
</div>
<div class="rsn-details ">
<p class="text-muted">
2 min ago
</p>
<p>
<a href="#">Jane Doe </a>Purchased new equipments for zonal office setup
</p>
</div>
</div>
<div class="prog-row">
<div class="user-thumb rsn-activity">
<i class="fa fa-clock-o"></i>
</div>
<div class="rsn-details ">
<p class="text-muted">
1 day ago
</p>
<p>
<a href="#">Jim Doe </a>Purchased new equipments for zonal office setup
</p>
</div>
</div>
</li>
</ul>
</li>
<li class="widget-collapsible">
<a href="#" class="head widget-head yellow-bg active">
<span class="pull-left"> shipment status</span>
<span class="pull-right widget-collapse"><i class="ico-minus"></i></span>
</a>
<ul class="widget-container">
<li>
<div class="col-md-12">
<div class="prog-row">
<p>
Full sleeve baby wear (SL: 17665)
</p>
<div class="progress progress-xs mtop10">
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 40%">
<span class="sr-only">40% Complete</span>
</div>
</div>
</div>
<div class="prog-row">
<p>
Full sleeve baby wear (SL: 17665)
</p>
<div class="progress progress-xs mtop10">
<div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 70%">
<span class="sr-only">70% Completed</span>
</div>
</div>
</div>
</div>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!--right sidebar end-->
</section>
<!-- Placed js at the end of the document so the pages load faster -->
<!--Core js-->
<script src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.9.2.custom.min.js"></script>
<script src="bs3/js/bootstrap.min.js"></script>
<script class="include" type="text/javascript" src="js/jquery.dcjqaccordion.2.7.js"></script>
<script src="js/jquery.scrollTo.min.js"></script>
<script src="js/jQuery-slimScroll-1.3.0/jquery.slimscroll.js"></script>
<script src="js/jquery.nicescroll.js"></script>
<script src="js/fullcalendar/fullcalendar.min.js"></script>
<!--Easy Pie Chart-->
<script src="js/easypiechart/jquery.easypiechart.js"></script>
<!--Sparkline Chart-->
<script src="js/sparkline/jquery.sparkline.js"></script>
<!--jQuery Flot Chart-->
<script src="js/flot-chart/jquery.flot.js"></script>
<script src="js/flot-chart/jquery.flot.tooltip.min.js"></script>
<script src="js/flot-chart/jquery.flot.resize.js"></script>
<script src="js/flot-chart/jquery.flot.pie.resize.js"></script>
<!--common script init for all pages-->
<script src="js/scripts.js"></script>
<!--script for this page only-->
<script src="js/external-dragging-calendar.js"></script>
</body>
</html>
|
sahartak/bucket
|
html/calendar.html
|
HTML
|
gpl-2.0
| 29,849 |
import re
import urllib,time,xbmcaddon
import requests,base64
from ..common import clean_title,clean_search, random_agent,filter_host,send_log,error_log
from ..scraper import Scraper
dev_log = xbmcaddon.Addon('script.module.universalscrapers').getSetting("dev_log")
User_Agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36'
class couchtuner(Scraper):
domains = ['couchtuner']
name = "CouchTuner"
def __init__(self):
self.base_link = 'http://couchtuner.unblocked.lol'
self.sources = []
if dev_log=='true':
self.start_time = time.time()
def scrape_episode(self, title, show_year, year, season, episode, imdb, tvdb, debrid=False):
try:
scrape = clean_search(title.lower())
headers = {'User_Agent':User_Agent,'referer':self.base_link}
link = requests.get(self.base_link+'/tv-lists/', headers=headers,timeout=5).content
#print 'couch'+link
Regex = re.compile('<h2>Tv Listing</h2>(.+?)<div class="comments_part">',re.DOTALL).findall(link)
links = re.findall(r'<a href="([^"]+)".+?<strong>([^<>]*)</strong></a>', str(Regex), re.I|re.DOTALL)
for media_url, media_title in links:
if not clean_title(title).lower() == clean_title(media_title).lower():
continue
# print 'couchTUNER >>>> ' +media_url
self.get_sources(media_url,season, episode)
return self.sources
except Exception, argument:
if dev_log == 'true':
error_log(self.name,'Check Search')
return self.sources
def get_sources(self,media_url,season,episode):
print '::::::::::::::'+media_url
try:
epi_format = ('-season-%s-episode-%s-') %(season,episode)
epi_format2 = ('-s%s-e%s-') %(season,episode)
headers = {'User_Agent':User_Agent}
link = requests.get(media_url, headers=headers, timeout=10).content
episode_urls = re.compile('<li.+?strong><a href="([^"]+)"',re.DOTALL).findall(link)
for eps in episode_urls:
if epi_format in eps.lower() or epi_format2 in eps.lower():
#print 'This episode '+eps
headers = {'User_Agent':User_Agent}
EPISODE = requests.get(eps, headers=headers, timeout=10).content
holderpage = re.compile('<div class="entry".+?href="([^"]+)"',re.DOTALL).findall(EPISODE)[0]
#print 'HOLDERPAGE '+holderpage
headers = {'User_Agent':User_Agent}
final_page=requests.get(holderpage, headers=headers, timeout=10).content
sources = re.compile('<iframe src="([^"]+)"',re.DOTALL).findall(final_page)
count = 0
for final_url in sources:
host = final_url.split('//')[1].replace('www.','')
host = host.split('/')[0].lower()
if not filter_host(host):
continue
host = host.split('.')[0].title()
count +=1
self.sources.append({'source': host,'quality': 'DVD','scraper': self.name,'url': final_url,'direct': False})
if dev_log=='true':
end_time = time.time() - self.start_time
send_log(self.name,end_time,count)
except:pass
|
repotvsupertuga/tvsupertuga.repository
|
script.module.universalscrapers/lib/universalscrapers/scraperplugins/broken or need checking/couchtuner.py
|
Python
|
gpl-2.0
| 3,613 |
/* Copyright (c) 2010-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/interrupt.h>
#include <mach/msm_iomap.h>
#include <mach/msm_bus.h>
#include <mach/socinfo.h>
#include <mach/internal_power_rail.h>
#include "kgsl.h"
#include "kgsl_pwrscale.h"
#include "kgsl_device.h"
#include "kgsl_trace.h"
#define KGSL_PWRFLAGS_POWER_ON 0
#define KGSL_PWRFLAGS_CLK_ON 1
#define KGSL_PWRFLAGS_AXI_ON 2
#define KGSL_PWRFLAGS_IRQ_ON 3
#define UPDATE_BUSY_VAL 1000000
#define UPDATE_BUSY 50
void kgsl_pwrctrl_pwrlevel_change(struct kgsl_device *device,
unsigned int new_level)
{
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
if (new_level < (pwr->num_pwrlevels - 1) &&
new_level >= pwr->thermal_pwrlevel &&
new_level != pwr->active_pwrlevel) {
struct kgsl_pwrlevel *pwrlevel = &pwr->pwrlevels[new_level];
pwr->active_pwrlevel = new_level;
if ((test_bit(KGSL_PWRFLAGS_CLK_ON, &pwr->power_flags)) ||
(device->state == KGSL_STATE_NAP)) {
/*
* On some platforms, instability is caused on
* changing clock freq when the core is busy.
* Idle the gpu core before changing the clock freq.
*/
if (pwr->idle_needed == true)
device->ftbl->idle(device,
KGSL_TIMEOUT_DEFAULT);
clk_set_rate(pwr->grp_clks[0], pwrlevel->gpu_freq);
}
if (test_bit(KGSL_PWRFLAGS_AXI_ON, &pwr->power_flags)) {
if (pwr->pcl)
msm_bus_scale_client_update_request(pwr->pcl,
pwrlevel->bus_freq);
else if (pwr->ebi1_clk)
clk_set_rate(pwr->ebi1_clk, pwrlevel->bus_freq);
}
trace_kgsl_pwrlevel(device, pwr->active_pwrlevel,
pwrlevel->gpu_freq);
}
}
EXPORT_SYMBOL(kgsl_pwrctrl_pwrlevel_change);
static int __gpuclk_store(int max, struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{ int ret, i, delta = 5000000;
unsigned long val;
struct kgsl_device *device = kgsl_device_from_dev(dev);
struct kgsl_pwrctrl *pwr;
if (device == NULL)
return 0;
pwr = &device->pwrctrl;
ret = sscanf(buf, "%ld", &val);
if (ret != 1)
return count;
mutex_lock(&device->mutex);
for (i = 0; i < pwr->num_pwrlevels; i++) {
if (abs(pwr->pwrlevels[i].gpu_freq - val) < delta) {
if (max)
pwr->thermal_pwrlevel = i;
break;
}
}
if (i == pwr->num_pwrlevels)
goto done;
/*
* If the current or requested clock speed is greater than the
* thermal limit, bump down immediately.
*/
if (pwr->pwrlevels[pwr->active_pwrlevel].gpu_freq >
pwr->pwrlevels[pwr->thermal_pwrlevel].gpu_freq)
kgsl_pwrctrl_pwrlevel_change(device, pwr->thermal_pwrlevel);
else if (!max)
kgsl_pwrctrl_pwrlevel_change(device, i);
done:
mutex_unlock(&device->mutex);
return count;
}
static int kgsl_pwrctrl_max_gpuclk_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
return __gpuclk_store(1, dev, attr, buf, count);
}
static int kgsl_pwrctrl_max_gpuclk_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct kgsl_device *device = kgsl_device_from_dev(dev);
struct kgsl_pwrctrl *pwr;
if (device == NULL)
return 0;
pwr = &device->pwrctrl;
return snprintf(buf, PAGE_SIZE, "%d\n",
pwr->pwrlevels[pwr->thermal_pwrlevel].gpu_freq);
}
static int kgsl_pwrctrl_gpuclk_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
return __gpuclk_store(0, dev, attr, buf, count);
}
static int kgsl_pwrctrl_gpuclk_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct kgsl_device *device = kgsl_device_from_dev(dev);
struct kgsl_pwrctrl *pwr;
if (device == NULL)
return 0;
pwr = &device->pwrctrl;
return snprintf(buf, PAGE_SIZE, "%d\n",
pwr->pwrlevels[pwr->active_pwrlevel].gpu_freq);
}
static int kgsl_pwrctrl_pwrnap_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
char temp[20];
unsigned long val;
struct kgsl_device *device = kgsl_device_from_dev(dev);
struct kgsl_pwrctrl *pwr;
int rc;
if (device == NULL)
return 0;
pwr = &device->pwrctrl;
snprintf(temp, sizeof(temp), "%.*s",
(int)min(count, sizeof(temp) - 1), buf);
rc = strict_strtoul(temp, 0, &val);
if (rc)
return rc;
mutex_lock(&device->mutex);
if (val == 1)
pwr->nap_allowed = true;
else if (val == 0)
pwr->nap_allowed = false;
mutex_unlock(&device->mutex);
return count;
}
static int kgsl_pwrctrl_pwrnap_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct kgsl_device *device = kgsl_device_from_dev(dev);
if (device == NULL)
return 0;
return snprintf(buf, PAGE_SIZE, "%d\n", device->pwrctrl.nap_allowed);
}
static int kgsl_pwrctrl_idle_timer_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
char temp[20];
unsigned long val;
struct kgsl_device *device = kgsl_device_from_dev(dev);
struct kgsl_pwrctrl *pwr;
const long div = 1000/HZ;
static unsigned int org_interval_timeout = 1;
int rc;
if (device == NULL)
return 0;
pwr = &device->pwrctrl;
snprintf(temp, sizeof(temp), "%.*s",
(int)min(count, sizeof(temp) - 1), buf);
rc = strict_strtoul(temp, 0, &val);
if (rc)
return rc;
if (org_interval_timeout == 1)
org_interval_timeout = pwr->interval_timeout;
mutex_lock(&device->mutex);
/* Let the timeout be requested in ms, but convert to jiffies. */
val /= div;
if (val >= org_interval_timeout)
pwr->interval_timeout = val;
mutex_unlock(&device->mutex);
return count;
}
static int kgsl_pwrctrl_idle_timer_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct kgsl_device *device = kgsl_device_from_dev(dev);
if (device == NULL)
return 0;
return snprintf(buf, PAGE_SIZE, "%d\n",
device->pwrctrl.interval_timeout);
}
static int kgsl_pwrctrl_gpubusy_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
int ret;
struct kgsl_device *device = kgsl_device_from_dev(dev);
struct kgsl_busy *b = &device->pwrctrl.busy;
ret = snprintf(buf, 17, "%7d %7d\n",
b->on_time_old, b->time_old);
if (!test_bit(KGSL_PWRFLAGS_AXI_ON, &device->pwrctrl.power_flags)) {
b->on_time_old = 0;
b->time_old = 0;
}
return ret;
}
DEVICE_ATTR(gpuclk, 0644, kgsl_pwrctrl_gpuclk_show, kgsl_pwrctrl_gpuclk_store);
DEVICE_ATTR(max_gpuclk, 0644, kgsl_pwrctrl_max_gpuclk_show,
kgsl_pwrctrl_max_gpuclk_store);
DEVICE_ATTR(pwrnap, 0666, kgsl_pwrctrl_pwrnap_show, kgsl_pwrctrl_pwrnap_store);
DEVICE_ATTR(idle_timer, 0644, kgsl_pwrctrl_idle_timer_show,
kgsl_pwrctrl_idle_timer_store);
DEVICE_ATTR(gpubusy, 0644, kgsl_pwrctrl_gpubusy_show,
NULL);
static const struct device_attribute *pwrctrl_attr_list[] = {
&dev_attr_gpuclk,
&dev_attr_max_gpuclk,
&dev_attr_pwrnap,
&dev_attr_idle_timer,
&dev_attr_gpubusy,
NULL
};
int kgsl_pwrctrl_init_sysfs(struct kgsl_device *device)
{
return kgsl_create_device_sysfs_files(device->dev, pwrctrl_attr_list);
}
void kgsl_pwrctrl_uninit_sysfs(struct kgsl_device *device)
{
kgsl_remove_device_sysfs_files(device->dev, pwrctrl_attr_list);
}
/* Track the amount of time the gpu is on vs the total system time. *
* Regularly update the percentage of busy time displayed by sysfs. */
static void kgsl_pwrctrl_busy_time(struct kgsl_device *device, bool on_time)
{
struct kgsl_busy *b = &device->pwrctrl.busy;
int elapsed;
if (b->start.tv_sec == 0)
do_gettimeofday(&(b->start));
do_gettimeofday(&(b->stop));
elapsed = (b->stop.tv_sec - b->start.tv_sec) * 1000000;
elapsed += b->stop.tv_usec - b->start.tv_usec;
b->time += elapsed;
if (on_time)
b->on_time += elapsed;
/* Update the output regularly and reset the counters. */
if ((b->time > UPDATE_BUSY_VAL) ||
!test_bit(KGSL_PWRFLAGS_AXI_ON, &device->pwrctrl.power_flags)) {
b->on_time_old = b->on_time;
b->time_old = b->time;
b->on_time = 0;
b->time = 0;
}
do_gettimeofday(&(b->start));
}
void kgsl_pwrctrl_clk(struct kgsl_device *device, int state,
int requested_state)
{
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
int i = 0;
if (state == KGSL_PWRFLAGS_OFF) {
if (test_and_clear_bit(KGSL_PWRFLAGS_CLK_ON,
&pwr->power_flags)) {
trace_kgsl_clk(device, state);
for (i = KGSL_MAX_CLKS - 1; i > 0; i--)
if (pwr->grp_clks[i])
clk_disable(pwr->grp_clks[i]);
if ((pwr->pwrlevels[0].gpu_freq > 0) &&
(requested_state != KGSL_STATE_NAP))
clk_set_rate(pwr->grp_clks[0],
pwr->pwrlevels[pwr->num_pwrlevels - 1].
gpu_freq);
kgsl_pwrctrl_busy_time(device, true);
}
} else if (state == KGSL_PWRFLAGS_ON) {
if (!test_and_set_bit(KGSL_PWRFLAGS_CLK_ON,
&pwr->power_flags)) {
trace_kgsl_clk(device, state);
if ((pwr->pwrlevels[0].gpu_freq > 0) &&
(device->state != KGSL_STATE_NAP))
clk_set_rate(pwr->grp_clks[0],
pwr->pwrlevels[pwr->active_pwrlevel].
gpu_freq);
/* as last step, enable grp_clk
this is to let GPU interrupt to come */
for (i = KGSL_MAX_CLKS - 1; i > 0; i--)
if (pwr->grp_clks[i])
clk_enable(pwr->grp_clks[i]);
kgsl_pwrctrl_busy_time(device, false);
}
}
}
void kgsl_pwrctrl_axi(struct kgsl_device *device, int state)
{
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
if (state == KGSL_PWRFLAGS_OFF) {
if (test_and_clear_bit(KGSL_PWRFLAGS_AXI_ON,
&pwr->power_flags)) {
trace_kgsl_bus(device, state);
if (pwr->ebi1_clk) {
clk_set_rate(pwr->ebi1_clk, 0);
clk_disable(pwr->ebi1_clk);
}
if (pwr->pcl)
msm_bus_scale_client_update_request(pwr->pcl,
0);
}
} else if (state == KGSL_PWRFLAGS_ON) {
if (!test_and_set_bit(KGSL_PWRFLAGS_AXI_ON,
&pwr->power_flags)) {
trace_kgsl_bus(device, state);
if (pwr->ebi1_clk) {
clk_enable(pwr->ebi1_clk);
clk_set_rate(pwr->ebi1_clk,
pwr->pwrlevels[pwr->active_pwrlevel].
bus_freq);
}
if (pwr->pcl)
msm_bus_scale_client_update_request(pwr->pcl,
pwr->pwrlevels[pwr->active_pwrlevel].
bus_freq);
}
}
}
void kgsl_pwrctrl_pwrrail(struct kgsl_device *device, int state)
{
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
if (state == KGSL_PWRFLAGS_OFF) {
if (test_and_clear_bit(KGSL_PWRFLAGS_POWER_ON,
&pwr->power_flags)) {
internal_pwr_rail_ctl(pwr->pwr_rail, 0);
trace_kgsl_rail(device, state);
if (pwr->gpu_dig)
regulator_disable(pwr->gpu_dig);
if (pwr->gpu_reg)
regulator_disable(pwr->gpu_reg);
}
} else if (state == KGSL_PWRFLAGS_ON) {
if (!test_and_set_bit(KGSL_PWRFLAGS_POWER_ON,
&pwr->power_flags)) {
internal_pwr_rail_ctl(pwr->pwr_rail, 1);
trace_kgsl_rail(device, state);
if (pwr->gpu_reg) {
int status = regulator_enable(pwr->gpu_reg);
if (status)
KGSL_DRV_ERR(device,
"core regulator_enable "
"failed: %d\n",
status);
}
if (pwr->gpu_dig) {
int status = regulator_enable(pwr->gpu_dig);
if (status)
KGSL_DRV_ERR(device,
"cx regulator_enable "
"failed: %d\n",
status);
}
}
}
}
void kgsl_pwrctrl_irq(struct kgsl_device *device, int state)
{
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
if (state == KGSL_PWRFLAGS_ON) {
if (!test_and_set_bit(KGSL_PWRFLAGS_IRQ_ON,
&pwr->power_flags)) {
trace_kgsl_irq(device, state);
enable_irq(pwr->interrupt_num);
}
} else if (state == KGSL_PWRFLAGS_OFF) {
if (test_and_clear_bit(KGSL_PWRFLAGS_IRQ_ON,
&pwr->power_flags)) {
trace_kgsl_irq(device, state);
if (in_interrupt())
disable_irq_nosync(pwr->interrupt_num);
else
disable_irq(pwr->interrupt_num);
}
}
}
EXPORT_SYMBOL(kgsl_pwrctrl_irq);
int kgsl_pwrctrl_init(struct kgsl_device *device)
{
int i, result = 0;
struct clk *clk;
struct platform_device *pdev =
container_of(device->parentdev, struct platform_device, dev);
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
struct kgsl_device_platform_data *pdata = pdev->dev.platform_data;
const char *clk_names[KGSL_MAX_CLKS] = {pwr->src_clk_name,
pdata->clk.clk,
pdata->clk.pclk,
pdata->imem_clk_name.clk,
pdata->imem_clk_name.pclk};
/*acquire clocks */
for (i = 0; i < KGSL_MAX_CLKS; i++) {
if (clk_names[i]) {
clk = clk_get(&pdev->dev, clk_names[i]);
if (IS_ERR(clk))
goto clk_err;
pwr->grp_clks[i] = clk;
}
}
/* Make sure we have a source clk for freq setting */
if (pwr->grp_clks[0] == NULL)
pwr->grp_clks[0] = pwr->grp_clks[1];
/* put the AXI bus into asynchronous mode with the graphics cores */
if (pdata->set_grp_async != NULL)
pdata->set_grp_async();
if (pdata->num_levels > KGSL_MAX_PWRLEVELS) {
KGSL_PWR_ERR(device, "invalid power level count: %d\n",
pdata->num_levels);
result = -EINVAL;
goto done;
}
pwr->num_pwrlevels = pdata->num_levels;
pwr->active_pwrlevel = pdata->init_level;
for (i = 0; i < pdata->num_levels; i++) {
pwr->pwrlevels[i].gpu_freq =
(pdata->pwrlevel[i].gpu_freq > 0) ?
clk_round_rate(pwr->grp_clks[0],
pdata->pwrlevel[i].
gpu_freq) : 0;
pwr->pwrlevels[i].bus_freq =
pdata->pwrlevel[i].bus_freq;
pwr->pwrlevels[i].io_fraction =
pdata->pwrlevel[i].io_fraction;
}
/* Do not set_rate for targets in sync with AXI */
if (pwr->pwrlevels[0].gpu_freq > 0)
clk_set_rate(pwr->grp_clks[0], pwr->
pwrlevels[pwr->num_pwrlevels - 1].gpu_freq);
pwr->gpu_reg = regulator_get(NULL, pwr->regulator_name);
if (IS_ERR(pwr->gpu_reg))
pwr->gpu_reg = NULL;
if (pwr->gpu_reg) {
pwr->gpu_dig = regulator_get(&pdev->dev, "vdd_dig");
if (IS_ERR(pwr->gpu_dig))
pwr->gpu_dig = NULL;
} else
pwr->gpu_dig = NULL;
pwr->power_flags = 0;
pwr->nap_allowed = pdata->nap_allowed;
pwr->idle_needed = pdata->idle_needed;
pwr->interval_timeout = pdata->idle_timeout;
pwr->strtstp_sleepwake = pdata->strtstp_sleepwake;
if (internal_pwr_rail_mode(pwr->pwr_rail,
PWR_RAIL_CTL_MANUAL)) {
KGSL_PWR_ERR(device, "call internal_pwr_rail_mode failed\n");
result = -EINVAL;
goto done;
}
pwr->ebi1_clk = clk_get(NULL, "ebi1_kgsl_clk");
if (IS_ERR(pwr->ebi1_clk))
pwr->ebi1_clk = NULL;
else
clk_set_rate(pwr->ebi1_clk,
pwr->pwrlevels[pwr->active_pwrlevel].
bus_freq);
if (pdata->bus_scale_table != NULL) {
pwr->pcl = msm_bus_scale_register_client(pdata->
bus_scale_table);
if (!pwr->pcl) {
KGSL_PWR_ERR(device,
"msm_bus_scale_register_client failed: "
"id %d table %p", device->id,
pdata->bus_scale_table);
result = -EINVAL;
goto done;
}
}
/*acquire interrupt */
pwr->interrupt_num =
platform_get_irq_byname(pdev, pwr->irq_name);
if (pwr->interrupt_num <= 0) {
KGSL_PWR_ERR(device, "platform_get_irq_byname failed: %d\n",
pwr->interrupt_num);
result = -EINVAL;
goto done;
}
register_early_suspend(&device->display_off);
return result;
clk_err:
result = PTR_ERR(clk);
KGSL_PWR_ERR(device, "clk_get(%s) failed: %d\n",
clk_names[i], result);
done:
return result;
}
void kgsl_pwrctrl_close(struct kgsl_device *device)
{
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
int i;
KGSL_PWR_INFO(device, "close device %d\n", device->id);
unregister_early_suspend(&device->display_off);
if (pwr->interrupt_num > 0) {
if (pwr->have_irq) {
free_irq(pwr->interrupt_num, NULL);
pwr->have_irq = 0;
}
pwr->interrupt_num = 0;
}
clk_put(pwr->ebi1_clk);
if (pwr->pcl)
msm_bus_scale_unregister_client(pwr->pcl);
pwr->pcl = 0;
if (pwr->gpu_reg) {
regulator_put(pwr->gpu_reg);
pwr->gpu_reg = NULL;
}
if (pwr->gpu_dig) {
regulator_put(pwr->gpu_dig);
pwr->gpu_dig = NULL;
}
for (i = 1; i < KGSL_MAX_CLKS; i++)
if (pwr->grp_clks[i]) {
clk_put(pwr->grp_clks[i]);
pwr->grp_clks[i] = NULL;
}
pwr->grp_clks[0] = NULL;
pwr->power_flags = 0;
}
void kgsl_idle_check(struct work_struct *work)
{
struct kgsl_device *device = container_of(work, struct kgsl_device,
idle_check_ws);
WARN_ON(device == NULL);
if (device == NULL)
return;
mutex_lock(&device->mutex);
if (device->state & (KGSL_STATE_ACTIVE | KGSL_STATE_NAP)) {
if ((device->requested_state != KGSL_STATE_SLEEP) &&
(device->requested_state != KGSL_STATE_SLUMBER))
kgsl_pwrscale_idle(device);
if (kgsl_pwrctrl_sleep(device) != 0) {
mod_timer(&device->idle_timer,
jiffies +
device->pwrctrl.interval_timeout);
/* If the GPU has been too busy to sleep, make sure *
* that is acurately reflected in the % busy numbers. */
device->pwrctrl.busy.no_nap_cnt++;
if (device->pwrctrl.busy.no_nap_cnt > UPDATE_BUSY) {
kgsl_pwrctrl_busy_time(device, true);
device->pwrctrl.busy.no_nap_cnt = 0;
}
}
} else if (device->state & (KGSL_STATE_HUNG |
KGSL_STATE_DUMP_AND_RECOVER)) {
kgsl_pwrctrl_request_state(device, KGSL_STATE_NONE);
}
mutex_unlock(&device->mutex);
}
void kgsl_timer(unsigned long data)
{
struct kgsl_device *device = (struct kgsl_device *) data;
KGSL_PWR_INFO(device, "idle timer expired device %d\n", device->id);
if (device->requested_state != KGSL_STATE_SUSPEND) {
if (device->pwrctrl.restore_slumber ||
device->pwrctrl.strtstp_sleepwake)
kgsl_pwrctrl_request_state(device, KGSL_STATE_SLUMBER);
else
kgsl_pwrctrl_request_state(device, KGSL_STATE_SLEEP);
/* Have work run in a non-interrupt context. */
queue_work(device->work_queue, &device->idle_check_ws);
}
}
void kgsl_pre_hwaccess(struct kgsl_device *device)
{
BUG_ON(!mutex_is_locked(&device->mutex));
switch (device->state) {
case KGSL_STATE_ACTIVE:
return;
case KGSL_STATE_NAP:
case KGSL_STATE_SLEEP:
case KGSL_STATE_SLUMBER:
kgsl_pwrctrl_wake(device);
break;
case KGSL_STATE_SUSPEND:
kgsl_check_suspended(device);
break;
case KGSL_STATE_INIT:
case KGSL_STATE_HUNG:
case KGSL_STATE_DUMP_AND_RECOVER:
if (test_bit(KGSL_PWRFLAGS_CLK_ON,
&device->pwrctrl.power_flags))
break;
else
KGSL_PWR_ERR(device,
"hw access while clocks off from state %d\n",
device->state);
break;
default:
KGSL_PWR_ERR(device, "hw access while in unknown state %d\n",
device->state);
break;
}
}
EXPORT_SYMBOL(kgsl_pre_hwaccess);
void kgsl_check_suspended(struct kgsl_device *device)
{
if (device->requested_state == KGSL_STATE_SUSPEND ||
device->state == KGSL_STATE_SUSPEND) {
mutex_unlock(&device->mutex);
wait_for_completion(&device->hwaccess_gate);
mutex_lock(&device->mutex);
} else if (device->state == KGSL_STATE_DUMP_AND_RECOVER) {
mutex_unlock(&device->mutex);
wait_for_completion(&device->recovery_gate);
mutex_lock(&device->mutex);
} else if (device->state == KGSL_STATE_SLUMBER)
kgsl_pwrctrl_wake(device);
}
static int
_nap(struct kgsl_device *device)
{
switch (device->state) {
case KGSL_STATE_ACTIVE:
if (!device->ftbl->isidle(device)) {
kgsl_pwrctrl_request_state(device, KGSL_STATE_NONE);
return -EBUSY;
}
kgsl_pwrctrl_irq(device, KGSL_PWRFLAGS_OFF);
kgsl_pwrctrl_clk(device, KGSL_PWRFLAGS_OFF, KGSL_STATE_NAP);
kgsl_pwrctrl_set_state(device, KGSL_STATE_NAP);
if (device->idle_wakelock.name)
wake_unlock(&device->idle_wakelock);
case KGSL_STATE_NAP:
case KGSL_STATE_SLEEP:
case KGSL_STATE_SLUMBER:
break;
default:
kgsl_pwrctrl_request_state(device, KGSL_STATE_NONE);
break;
}
return 0;
}
static void
_sleep_accounting(struct kgsl_device *device)
{
kgsl_pwrctrl_busy_time(device, false);
device->pwrctrl.busy.start.tv_sec = 0;
device->pwrctrl.time = 0;
kgsl_pwrscale_sleep(device);
}
static int
_sleep(struct kgsl_device *device)
{
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
switch (device->state) {
case KGSL_STATE_ACTIVE:
if (!device->ftbl->isidle(device)) {
kgsl_pwrctrl_request_state(device, KGSL_STATE_NONE);
return -EBUSY;
}
/* fall through */
case KGSL_STATE_NAP:
kgsl_pwrctrl_irq(device, KGSL_PWRFLAGS_OFF);
kgsl_pwrctrl_axi(device, KGSL_PWRFLAGS_OFF);
if (pwr->pwrlevels[0].gpu_freq > 0)
clk_set_rate(pwr->grp_clks[0],
pwr->pwrlevels[pwr->num_pwrlevels - 1].
gpu_freq);
_sleep_accounting(device);
kgsl_pwrctrl_clk(device, KGSL_PWRFLAGS_OFF, KGSL_STATE_SLEEP);
kgsl_pwrctrl_set_state(device, KGSL_STATE_SLEEP);
if (device->idle_wakelock.name)
wake_unlock(&device->idle_wakelock);
break;
case KGSL_STATE_SLEEP:
case KGSL_STATE_SLUMBER:
break;
default:
KGSL_PWR_WARN(device, "unhandled state %s\n",
kgsl_pwrstate_to_str(device->state));
break;
}
return 0;
}
static int
_slumber(struct kgsl_device *device)
{
switch (device->state) {
case KGSL_STATE_ACTIVE:
if (!device->ftbl->isidle(device)) {
kgsl_pwrctrl_request_state(device, KGSL_STATE_NONE);
device->pwrctrl.restore_slumber = true;
return -EBUSY;
}
/* fall through */
case KGSL_STATE_NAP:
case KGSL_STATE_SLEEP:
del_timer_sync(&device->idle_timer);
if (!device->pwrctrl.strtstp_sleepwake)
kgsl_pwrctrl_pwrlevel_change(device,
KGSL_PWRLEVEL_NOMINAL);
device->ftbl->suspend_context(device);
device->ftbl->stop(device);
device->pwrctrl.restore_slumber = true;
_sleep_accounting(device);
kgsl_pwrctrl_set_state(device, KGSL_STATE_SLUMBER);
if (device->idle_wakelock.name)
wake_unlock(&device->idle_wakelock);
break;
case KGSL_STATE_SLUMBER:
break;
default:
KGSL_PWR_WARN(device, "unhandled state %s\n",
kgsl_pwrstate_to_str(device->state));
break;
}
return 0;
}
/******************************************************************/
/* Caller must hold the device mutex. */
int kgsl_pwrctrl_sleep(struct kgsl_device *device)
{
int status = 0;
KGSL_PWR_INFO(device, "sleep device %d\n", device->id);
/* Work through the legal state transitions */
switch (device->requested_state) {
case KGSL_STATE_NAP:
status = _nap(device);
break;
case KGSL_STATE_SLEEP:
status = _sleep(device);
break;
case KGSL_STATE_SLUMBER:
status = _slumber(device);
break;
default:
KGSL_PWR_INFO(device, "bad state request 0x%x\n",
device->requested_state);
kgsl_pwrctrl_request_state(device, KGSL_STATE_NONE);
status = -EINVAL;
break;
}
return status;
}
EXPORT_SYMBOL(kgsl_pwrctrl_sleep);
/******************************************************************/
/* Caller must hold the device mutex. */
void kgsl_pwrctrl_wake(struct kgsl_device *device)
{
int status;
kgsl_pwrctrl_request_state(device, KGSL_STATE_ACTIVE);
switch (device->state) {
case KGSL_STATE_SLUMBER:
status = device->ftbl->start(device, 0);
if (status) {
kgsl_pwrctrl_request_state(device, KGSL_STATE_NONE);
KGSL_DRV_ERR(device, "start failed %d\n", status);
break;
}
/* fall through */
case KGSL_STATE_SLEEP:
kgsl_pwrctrl_axi(device, KGSL_PWRFLAGS_ON);
kgsl_pwrscale_wake(device);
/* fall through */
case KGSL_STATE_NAP:
/* Turn on the core clocks */
kgsl_pwrctrl_clk(device, KGSL_PWRFLAGS_ON, KGSL_STATE_ACTIVE);
/* Enable state before turning on irq */
kgsl_pwrctrl_set_state(device, KGSL_STATE_ACTIVE);
kgsl_pwrctrl_irq(device, KGSL_PWRFLAGS_ON);
/* Re-enable HW access */
mod_timer(&device->idle_timer,
jiffies + device->pwrctrl.interval_timeout);
if (device->idle_wakelock.name)
wake_lock(&device->idle_wakelock);
case KGSL_STATE_ACTIVE:
break;
default:
KGSL_PWR_WARN(device, "unhandled state %s\n",
kgsl_pwrstate_to_str(device->state));
kgsl_pwrctrl_request_state(device, KGSL_STATE_NONE);
break;
}
}
EXPORT_SYMBOL(kgsl_pwrctrl_wake);
void kgsl_pwrctrl_enable(struct kgsl_device *device)
{
/* Order pwrrail/clk sequence based upon platform */
kgsl_pwrctrl_pwrrail(device, KGSL_PWRFLAGS_ON);
kgsl_pwrctrl_clk(device, KGSL_PWRFLAGS_ON, KGSL_STATE_ACTIVE);
kgsl_pwrctrl_axi(device, KGSL_PWRFLAGS_ON);
}
EXPORT_SYMBOL(kgsl_pwrctrl_enable);
void kgsl_pwrctrl_disable(struct kgsl_device *device)
{
/* Order pwrrail/clk sequence based upon platform */
kgsl_pwrctrl_axi(device, KGSL_PWRFLAGS_OFF);
kgsl_pwrctrl_clk(device, KGSL_PWRFLAGS_OFF, KGSL_STATE_SLEEP);
kgsl_pwrctrl_pwrrail(device, KGSL_PWRFLAGS_OFF);
}
EXPORT_SYMBOL(kgsl_pwrctrl_disable);
void kgsl_pwrctrl_set_state(struct kgsl_device *device, unsigned int state)
{
trace_kgsl_pwr_set_state(device, state);
device->state = state;
device->requested_state = KGSL_STATE_NONE;
}
EXPORT_SYMBOL(kgsl_pwrctrl_set_state);
void kgsl_pwrctrl_request_state(struct kgsl_device *device, unsigned int state)
{
if (state != KGSL_STATE_NONE && state != device->requested_state)
trace_kgsl_pwr_request_state(device, state);
device->requested_state = state;
}
EXPORT_SYMBOL(kgsl_pwrctrl_request_state);
const char *kgsl_pwrstate_to_str(unsigned int state)
{
switch (state) {
case KGSL_STATE_NONE:
return "NONE";
case KGSL_STATE_INIT:
return "INIT";
case KGSL_STATE_ACTIVE:
return "ACTIVE";
case KGSL_STATE_NAP:
return "NAP";
case KGSL_STATE_SLEEP:
return "SLEEP";
case KGSL_STATE_SUSPEND:
return "SUSPEND";
case KGSL_STATE_HUNG:
return "HUNG";
case KGSL_STATE_DUMP_AND_RECOVER:
return "DNR";
case KGSL_STATE_SLUMBER:
return "SLUMBER";
default:
break;
}
return "UNKNOWN";
}
EXPORT_SYMBOL(kgsl_pwrstate_to_str);
|
Evervolv/android_kernel_htc_msm7x30
|
drivers/gpu/msm/kgsl_pwrctrl.c
|
C
|
gpl-2.0
| 25,333 |
.timeline {
position: relative;
padding: 20px 0 20px;
list-style: none;
}
.timeline:before {
content: " ";
position: absolute;
top: 0;
bottom: 0;
left: 50%;
width: 3px;
margin-left: -1.5px;
background-color: #eeeeee;
}
.timeline > li {
position: relative;
margin-bottom: 20px;
/*list-style-type: none;*/
}
.timeline > li:before,
.timeline > li:after {
content: " ";
display: table;
}
.timeline > li:after {
clear: both;
}
.timeline > li:before,
.timeline > li:after {
content: " ";
display: table;
}
.timeline > li:after {
clear: both;
}
.timeline > li > .timeline-panel {
float: left;
position: relative;
width: 46%;
padding: 20px;
border: 1px solid #d4d4d4;
border-radius: 2px;
-webkit-box-shadow: 0 1px 6px rgba(0,0,0,0.175);
box-shadow: 0 1px 6px rgba(0,0,0,0.175);
}
.timeline > li > .timeline-panel:before {
content: " ";
display: inline-block;
position: absolute;
top: 26px;
right: -15px;
border-top: 15px solid transparent;
border-right: 0 solid #ccc;
border-bottom: 15px solid transparent;
border-left: 15px solid #ccc;
}
.timeline > li > .timeline-panel:after {
content: " ";
display: inline-block;
position: absolute;
top: 27px;
right: -14px;
border-top: 14px solid transparent;
border-right: 0 solid #fff;
border-bottom: 14px solid transparent;
border-left: 14px solid #fff;
}
.timeline > li > .timeline-badge {
z-index: 100;
position: absolute;
top: 16px;
left: 50%;
width: 50px;
height: 50px;
margin-left: -25px;
border-radius: 50% 50% 50% 50%;
text-align: center;
font-size: 1.4em;
line-height: 50px;
color: #fff;
background-color: #999999;
}
.timeline > li.timeline-inverted > .timeline-panel {
float: right;
}
.timeline > li.timeline-inverted > .timeline-panel:before {
right: auto;
left: -15px;
border-right-width: 15px;
border-left-width: 0;
}
.timeline > li.timeline-inverted > .timeline-panel:after {
right: auto;
left: -14px;
border-right-width: 14px;
border-left-width: 0;
}
.timeline-badge.primary {
background-color: #2e6da4 !important;
}
.timeline-badge.success {
background-color: #3f903f !important;
}
.timeline-badge.warning {
background-color: #f0ad4e !important;
}
.timeline-badge.danger {
background-color: #d9534f !important;
}
.timeline-badge.info {
background-color: #5bc0de !important;
}
.timeline-title {
margin-top: 0;
color: inherit;
}
.timeline-body > p,
.timeline-body > ul {
margin-bottom: 0;
}
.timeline-body > p + p {
margin-top: 5px;
}
@media(max-width:767px) {
ul.timeline:before {
left: 40px;
}
ul.timeline > li > .timeline-panel {
width: calc(100% - 90px);
width: -moz-calc(100% - 90px);
width: -webkit-calc(100% - 90px);
}
ul.timeline > li > .timeline-badge {
top: 16px;
left: 15px;
margin-left: 0;
}
ul.timeline > li > .timeline-panel {
float: right;
}
ul.timeline > li > .timeline-panel:before {
right: auto;
left: -15px;
border-right-width: 15px;
border-left-width: 0;
}
ul.timeline > li > .timeline-panel:after {
right: auto;
left: -14px;
border-right-width: 14px;
border-left-width: 0;
}
}
|
datasmurfen/CoreControl
|
web/resources/css/timeline.css
|
CSS
|
gpl-2.0
| 3,454 |
/*
* $Id$
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 2001 Gerald Combs
*
* 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "syntax-tree.h"
/* Keep track of sttype_t's via their sttype_id_t number */
static sttype_t* type_list[STTYPE_NUM_TYPES];
#define STNODE_MAGIC 0xe9b00b9e
void
sttype_init(void)
{
sttype_register_function();
sttype_register_integer();
sttype_register_pointer();
sttype_register_range();
sttype_register_string();
sttype_register_test();
}
void
sttype_cleanup(void)
{
/* nothing to do */
}
void
sttype_register(sttype_t *type)
{
sttype_id_t type_id;
type_id = type->id;
/* Check input */
g_assert(type_id < STTYPE_NUM_TYPES);
/* Don't re-register. */
g_assert(type_list[type_id] == NULL);
type_list[type_id] = type;
}
static sttype_t*
sttype_lookup(sttype_id_t type_id)
{
sttype_t *result;
/* Check input */
g_assert(type_id < STTYPE_NUM_TYPES);
result = type_list[type_id];
/* Check output. */
g_assert(result != NULL);
return result;
}
stnode_t*
stnode_new(sttype_id_t type_id, gpointer data)
{
sttype_t *type;
stnode_t *node;
node = g_new(stnode_t, 1);
node->magic = STNODE_MAGIC;
node->deprecated_token = NULL;
if (type_id == STTYPE_UNINITIALIZED) {
node->type = NULL;
node->data = NULL;
}
else {
type = sttype_lookup(type_id);
g_assert(type);
node->type = type;
if (type->func_new) {
node->data = type->func_new(data);
}
else {
node->data = data;
}
}
return node;
}
void
stnode_init(stnode_t *node, sttype_id_t type_id, gpointer data)
{
sttype_t *type;
assert_magic(node, STNODE_MAGIC);
g_assert(!node->type);
g_assert(!node->data);
type = sttype_lookup(type_id);
g_assert(type);
node->type = type;
if (type->func_new) {
node->data = type->func_new(data);
}
else {
node->data = data;
}
}
void
stnode_init_int(stnode_t *node, sttype_id_t type_id, gint32 value)
{
stnode_init(node, type_id, NULL);
node->value = value;
}
void
stnode_free(stnode_t *node)
{
assert_magic(node, STNODE_MAGIC);
if (node->type) {
if (node->type->func_free) {
node->type->func_free(node->data);
}
}
else {
g_assert(!node->data);
}
g_free(node);
}
const char*
stnode_type_name(stnode_t *node)
{
assert_magic(node, STNODE_MAGIC);
if (node->type)
return node->type->name;
else
return "UNINITIALIZED";
}
sttype_id_t
stnode_type_id(stnode_t *node)
{
assert_magic(node, STNODE_MAGIC);
if (node->type)
return node->type->id;
else
return STTYPE_UNINITIALIZED;
}
gpointer
stnode_data(stnode_t *node)
{
assert_magic(node, STNODE_MAGIC);
return node->data;
}
gint32
stnode_value(stnode_t *node)
{
assert_magic(node, STNODE_MAGIC);
return node->value;
}
const char *
stnode_deprecated(stnode_t *node)
{
if (!node) {
return NULL;
}
return node->deprecated_token;
}
|
giuliano108/wireshark-rtpmon
|
epan/dfilter/syntax-tree.c
|
C
|
gpl-2.0
| 3,623 |
/*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
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.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package org.jpc.emulator.execution.opcodes.rm;
import org.jpc.emulator.execution.*;
import org.jpc.emulator.execution.decoder.*;
import org.jpc.emulator.processor.*;
import org.jpc.emulator.processor.fpu64.*;
import static org.jpc.emulator.processor.Processor.*;
public class fxch_ST0_ST2 extends Executable
{
public fxch_ST0_ST2(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
int modrm = input.readU8();
}
public Branch execute(Processor cpu)
{
double tmp = cpu.fpu.ST(0);
cpu.fpu.setST(0, cpu.fpu.ST(2));
cpu.fpu.setST(2, tmp);
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
}
|
ianopolous/JPC
|
src/org/jpc/emulator/execution/opcodes/rm/fxch_ST0_ST2.java
|
Java
|
gpl-2.0
| 1,778 |
// **********************************************************************
//
// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
package IceInternal;
public final class ThreadPool
{
final class ShutdownWorkItem implements ThreadPoolWorkItem
{
@Override
public void execute(ThreadPoolCurrent current)
{
current.ioCompleted();
try
{
_instance.objectAdapterFactory().shutdown();
}
catch(Ice.CommunicatorDestroyedException ex)
{
}
}
}
static final class FinishedWorkItem implements ThreadPoolWorkItem
{
public
FinishedWorkItem(EventHandler handler, boolean close)
{
_handler = handler;
_close = close;
}
@Override
public void execute(ThreadPoolCurrent current)
{
_handler.finished(current, _close);
}
private final EventHandler _handler;
private final boolean _close;
}
static final class JoinThreadWorkItem implements ThreadPoolWorkItem
{
public
JoinThreadWorkItem(EventHandlerThread thread)
{
_thread = thread;
}
@Override
public void execute(ThreadPoolCurrent current)
{
// No call to ioCompleted, this shouldn't block (and we don't want to cause
// a new thread to be started).
try
{
_thread.join();
}
catch (InterruptedException e)
{
// Ignore.
}
}
private final EventHandlerThread _thread;
}
static final class InterruptWorkItem implements ThreadPoolWorkItem
{
@Override
public void execute(ThreadPoolCurrent current)
{
// Nothing to do, this is just used to interrupt the thread pool selector.
}
}
private static ThreadPoolWorkItem _interruptWorkItem = new InterruptWorkItem();
//
// Exception raised by the thread pool work queue when the thread pool
// is destroyed.
//
static final class DestroyedException extends RuntimeException
{
}
public
ThreadPool(Instance instance, String prefix, int timeout)
{
Ice.Properties properties = instance.initializationData().properties;
_instance = instance;
_dispatcher = instance.initializationData().dispatcher;
_destroyed = false;
_prefix = prefix;
_selector = new Selector(instance);
_threadIndex = 0;
_inUse = 0;
_inUseIO = 0;
_promote = true;
_serialize = properties.getPropertyAsInt(_prefix + ".Serialize") > 0;
_serverIdleTime = timeout;
_threadPrefix = Util.createThreadName(properties, _prefix);
int nProcessors = Runtime.getRuntime().availableProcessors();
//
// We use just one thread as the default. This is the fastest
// possible setting, still allows one level of nesting, and
// doesn't require to make the servants thread safe.
//
int size = properties.getPropertyAsIntWithDefault(_prefix + ".Size", 1);
if(size < 1)
{
String s = _prefix + ".Size < 1; Size adjusted to 1";
_instance.initializationData().logger.warning(s);
size = 1;
}
int sizeMax = properties.getPropertyAsIntWithDefault(_prefix + ".SizeMax", size);
if(sizeMax == -1)
{
sizeMax = nProcessors;
}
if(sizeMax < size)
{
String s = _prefix + ".SizeMax < " + _prefix + ".Size; SizeMax adjusted to Size (" + size + ")";
_instance.initializationData().logger.warning(s);
sizeMax = size;
}
int sizeWarn = properties.getPropertyAsInt(_prefix + ".SizeWarn");
if(sizeWarn != 0 && sizeWarn < size)
{
String s = _prefix + ".SizeWarn < " + _prefix + ".Size; adjusted SizeWarn to Size (" + size + ")";
_instance.initializationData().logger.warning(s);
sizeWarn = size;
}
else if(sizeWarn > sizeMax)
{
String s = _prefix + ".SizeWarn > " + _prefix + ".SizeMax; adjusted SizeWarn to SizeMax (" + sizeMax + ")";
_instance.initializationData().logger.warning(s);
sizeWarn = sizeMax;
}
int threadIdleTime = properties.getPropertyAsIntWithDefault(_prefix + ".ThreadIdleTime", 60);
if(threadIdleTime < 0)
{
String s = _prefix + ".ThreadIdleTime < 0; ThreadIdleTime adjusted to 0";
_instance.initializationData().logger.warning(s);
threadIdleTime = 0;
}
_size = size;
_sizeMax = sizeMax;
_sizeWarn = sizeWarn;
_sizeIO = Math.min(sizeMax, nProcessors);
_threadIdleTime = threadIdleTime;
int stackSize = properties.getPropertyAsInt( _prefix + ".StackSize");
if(stackSize < 0)
{
String s = _prefix + ".StackSize < 0; Size adjusted to JRE default";
_instance.initializationData().logger.warning(s);
stackSize = 0;
}
_stackSize = stackSize;
boolean hasPriority = properties.getProperty(_prefix + ".ThreadPriority").length() > 0;
int priority = properties.getPropertyAsInt(_prefix + ".ThreadPriority");
if(!hasPriority)
{
hasPriority = properties.getProperty("Ice.ThreadPriority").length() > 0;
priority = properties.getPropertyAsInt("Ice.ThreadPriority");
}
_hasPriority = hasPriority;
_priority = priority;
_workQueue = new ThreadPoolWorkQueue(_instance, this, _selector);
_nextHandler = _handlers.iterator();
if(_instance.traceLevels().threadPool >= 1)
{
String s = "creating " + _prefix + ": Size = " + _size + ", SizeMax = " + _sizeMax + ", SizeWarn = " +
_sizeWarn;
_instance.initializationData().logger.trace(_instance.traceLevels().threadPoolCat, s);
}
try
{
for(int i = 0; i < _size; i++)
{
EventHandlerThread thread = new EventHandlerThread(_threadPrefix + "-" + _threadIndex++);
if(_hasPriority)
{
thread.start(_priority);
}
else
{
thread.start(java.lang.Thread.NORM_PRIORITY);
}
_threads.add(thread);
}
}
catch(RuntimeException ex)
{
String s = "cannot create thread for `" + _prefix + "':\n" + Ex.toString(ex);
_instance.initializationData().logger.error(s);
destroy();
try
{
joinWithAllThreads();
}
catch (InterruptedException e)
{
throw new Ice.OperationInterruptedException();
}
throw ex;
}
}
@Override
protected synchronized void
finalize()
throws Throwable
{
try
{
IceUtilInternal.Assert.FinalizerAssert(_destroyed);
}
catch(java.lang.Exception ex)
{
}
finally
{
super.finalize();
}
}
public synchronized void
destroy()
{
if(_destroyed)
{
return;
}
_destroyed = true;
_workQueue.destroy();
}
public synchronized void
updateObservers()
{
for(EventHandlerThread thread : _threads)
{
thread.updateObserver();
}
}
public synchronized void
initialize(EventHandler handler)
{
assert(!_destroyed);
_selector.initialize(handler);
}
public void
register(EventHandler handler, int op)
{
update(handler, SocketOperation.None, op);
}
public synchronized void
update(EventHandler handler, int remove, int add)
{
assert(!_destroyed);
// Don't remove what needs to be added
remove &= ~add;
// Don't remove/add if already un-registered or registered
remove = handler._registered & remove;
add = ~handler._registered & add;
if(remove == add)
{
return;
}
_selector.update(handler, remove, add);
if((add & SocketOperation.Read) != 0 && handler._hasMoreData.value &&
(handler._disabled & SocketOperation.Read) == 0)
{
if(_pendingHandlers.isEmpty())
{
_workQueue.queue(_interruptWorkItem); // Interrupt select()
}
_pendingHandlers.add(handler);
}
else if((remove & SocketOperation.Read) != 0)
{
_pendingHandlers.remove(handler);
}
}
public void
unregister(EventHandler handler, int op)
{
update(handler, op, SocketOperation.None);
}
public synchronized boolean
finish(EventHandler handler, boolean closeNow)
{
assert(!_destroyed);
closeNow = _selector.finish(handler, closeNow);
_pendingHandlers.remove(handler);
_workQueue.queue(new FinishedWorkItem(handler, !closeNow));
return closeNow;
}
public void
dispatchFromThisThread(DispatchWorkItem workItem)
{
if(_dispatcher != null)
{
try
{
_dispatcher.dispatch(workItem, workItem.getConnection());
}
catch(java.lang.Exception ex)
{
if(_instance.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 1)
{
java.io.StringWriter sw = new java.io.StringWriter();
java.io.PrintWriter pw = new java.io.PrintWriter(sw);
ex.printStackTrace(pw);
pw.flush();
_instance.initializationData().logger.warning("dispatch exception:\n" + sw.toString());
}
}
}
else
{
workItem.run();
}
}
public void
dispatch(DispatchWorkItem workItem)
{
_workQueue.queue(workItem);
}
public void
joinWithAllThreads()
throws InterruptedException
{
//
// _threads is immutable after destroy() has been called,
// therefore no synchronization is needed. (Synchronization
// wouldn't be possible here anyway, because otherwise the
// other threads would never terminate.)
//
for(EventHandlerThread thread : _threads)
{
thread.join();
}
//
// Destroy the selector
//
_selector.destroy();
}
private void
run(EventHandlerThread thread)
{
ThreadPoolCurrent current = new ThreadPoolCurrent(_instance, this, thread);
boolean select = false;
while(true)
{
if(current._handler != null)
{
try
{
current._handler.message(current);
}
catch(DestroyedException ex)
{
return;
}
catch(java.lang.Exception ex)
{
String s = "exception in `" + _prefix + "':\n" + Ex.toString(ex);
s += "\nevent handler: " + current._handler.toString();
_instance.initializationData().logger.error(s);
}
}
else if(select)
{
if(_workQueue.size() == 0)
{
try
{
_selector.select(_serverIdleTime);
}
catch(Selector.TimeoutException ex)
{
synchronized(this)
{
if(!_destroyed && _inUse == 0)
{
_workQueue.queue(new ShutdownWorkItem()); // Select timed-out.
}
continue;
}
}
}
}
synchronized(this)
{
if(current._handler == null)
{
if(select)
{
_selector.finishSelect(_handlers);
_workQueue.update(_handlers);
select = false;
if(!_pendingHandlers.isEmpty())
{
for(EventHandlerOpPair pair : _handlers)
{
_pendingHandlers.remove(pair.handler);
}
for(EventHandler p : _pendingHandlers)
{
_handlers.add(new EventHandlerOpPair(p, SocketOperation.Read));
}
_pendingHandlers.clear();
}
_nextHandler = _handlers.iterator();
}
else if(!current._leader && followerWait(current))
{
return; // Wait timed-out.
}
}
else if(_sizeMax > 1)
{
if(!current._ioCompleted)
{
//
// The handler didn't call ioCompleted() so we take care of decreasing
// the IO thread count now.
//
--_inUseIO;
if(current._handler._hasMoreData.value &&
(current._handler._registered & SocketOperation.Read) != 0)
{
if(_pendingHandlers.isEmpty())
{
_workQueue.queue(_interruptWorkItem);
}
_pendingHandlers.add(current._handler);
}
}
else
{
//
// If the handler called ioCompleted(), we re-enable the handler in
// case it was disabled and we decrease the number of thread in use.
//
if(_serialize)
{
_selector.enable(current._handler, current.operation);
if(current._handler._hasMoreData.value &&
(current._handler._registered & SocketOperation.Read) != 0)
{
if(_pendingHandlers.isEmpty())
{
_workQueue.queue(_interruptWorkItem); // Interrupt select()
}
_pendingHandlers.add(current._handler);
}
}
assert(_inUse > 0);
--_inUse;
}
if(!current._leader && followerWait(current))
{
return; // Wait timed-out.
}
}
else if(current._handler._hasMoreData.value &&
(current._handler._registered & SocketOperation.Read) != 0)
{
if(_pendingHandlers.isEmpty())
{
_workQueue.queue(_interruptWorkItem); // Interrupt select()
}
_pendingHandlers.add(current._handler);
}
//
// Get the next ready handler.
//
EventHandlerOpPair next = null;
while(_nextHandler.hasNext())
{
EventHandlerOpPair n = _nextHandler.next();
if((n.op & n.handler._registered) != 0)
{
next = n;
break;
}
}
if(next != null)
{
current._ioCompleted = false;
current._handler = next.handler;
current.operation = next.op;
thread.setState(Ice.Instrumentation.ThreadState.ThreadStateInUseForIO);
}
else
{
current._handler = null;
}
if(current._handler == null)
{
//
// If there are no more ready handlers and there are still threads busy performing
// IO, we give up leadership and promote another follower (which will perform the
// select() only once all the IOs are completed). Otherwise, if there's no more
// threads peforming IOs, it's time to do another select().
//
if(_inUseIO > 0)
{
promoteFollower(current);
}
else
{
_handlers.clear();
_selector.startSelect();
select = true;
thread.setState(Ice.Instrumentation.ThreadState.ThreadStateIdle);
}
}
else if(_sizeMax > 1)
{
//
// Increment the IO thread count and if there's still threads available
// to perform IO and more handlers ready, we promote a follower.
//
++_inUseIO;
if(_nextHandler.hasNext() && _inUseIO < _sizeIO)
{
promoteFollower(current);
}
}
}
}
}
synchronized void
ioCompleted(ThreadPoolCurrent current)
{
current._ioCompleted = true; // Set the IO completed flag to specify that ioCompleted() has been called.
current._thread.setState(Ice.Instrumentation.ThreadState.ThreadStateInUseForUser);
if(_sizeMax > 1)
{
--_inUseIO;
if(!_destroyed)
{
if(_serialize)
{
_selector.disable(current._handler, current.operation);
// Make sure the handler isn't in the set of pending handlers (this can
// for example occur if the handler is has more data and its added by
// ThreadPool::update while we were processing IO).
_pendingHandlers.remove(current._handler);
}
else if(current._handler._hasMoreData.value &&
(current._handler._registered & SocketOperation.Read) != 0)
{
if(_pendingHandlers.isEmpty())
{
_workQueue.queue(_interruptWorkItem); // Interrupt select()
}
_pendingHandlers.add(current._handler);
}
}
if(current._leader)
{
//
// If this thread is still the leader, it's time to promote a new leader.
//
promoteFollower(current);
}
else if(_promote && (_nextHandler.hasNext() || _inUseIO == 0))
{
notify();
}
assert(_inUse >= 0);
++_inUse;
if(_inUse == _sizeWarn)
{
String s = "thread pool `" + _prefix + "' is running low on threads\n"
+ "Size=" + _size + ", " + "SizeMax=" + _sizeMax + ", " + "SizeWarn=" + _sizeWarn;
_instance.initializationData().logger.warning(s);
}
if(!_destroyed)
{
assert(_inUse <= _threads.size());
if(_inUse < _sizeMax && _inUse == _threads.size())
{
if(_instance.traceLevels().threadPool >= 1)
{
String s = "growing " + _prefix + ": Size=" + (_threads.size() + 1);
_instance.initializationData().logger.trace(_instance.traceLevels().threadPoolCat, s);
}
try
{
EventHandlerThread thread = new EventHandlerThread(_threadPrefix + "-" + _threadIndex++);
_threads.add(thread);
if(_hasPriority)
{
thread.start(_priority);
}
else
{
thread.start(java.lang.Thread.NORM_PRIORITY);
}
}
catch(RuntimeException ex)
{
String s = "cannot create thread for `" + _prefix + "':\n" + Ex.toString(ex);
_instance.initializationData().logger.error(s);
}
}
}
}
}
private synchronized void
promoteFollower(ThreadPoolCurrent current)
{
assert(!_promote && current._leader);
_promote = true;
if(_inUseIO < _sizeIO && (_nextHandler.hasNext() || _inUseIO == 0))
{
notify();
}
current._leader = false;
}
private synchronized boolean
followerWait(ThreadPoolCurrent current)
{
assert(!current._leader);
current._thread.setState(Ice.Instrumentation.ThreadState.ThreadStateIdle);
//
// It's important to clear the handler before waiting to make sure that
// resources for the handler are released now if it's finished. We also
// clear the per-thread stream.
//
current._handler = null;
current.stream.reset();
//
// Wait to be promoted and for all the IO threads to be done.
//
while(!_promote || _inUseIO == _sizeIO || (!_nextHandler.hasNext() && _inUseIO > 0))
{
if(_threadIdleTime > 0)
{
long before = IceInternal.Time.currentMonotonicTimeMillis();
boolean interrupted = false;
try
{
//
// If the wait is interrupted then we'll let the thread die as if it timed out.
//
wait(_threadIdleTime * 1000);
}
catch (InterruptedException e)
{
interrupted = true;
}
if(interrupted || IceInternal.Time.currentMonotonicTimeMillis() - before >= _threadIdleTime * 1000)
{
if(!_destroyed && (!_promote || _inUseIO == _sizeIO ||
(!_nextHandler.hasNext() && _inUseIO > 0)))
{
if(_instance.traceLevels().threadPool >= 1)
{
String s = "shrinking " + _prefix + ": Size=" + (_threads.size() - 1);
_instance.initializationData().logger.trace(_instance.traceLevels().threadPoolCat, s);
}
assert(_threads.size() > 1); // Can only be called by a waiting follower thread.
_threads.remove(current._thread);
_workQueue.queue(new JoinThreadWorkItem(current._thread));
return true;
}
}
}
else
{
try
{
wait();
}
catch (InterruptedException e)
{
//
// Eat the InterruptedException.
//
}
}
}
current._leader = true; // The current thread has become the leader.
_promote = false;
return false;
}
private final Instance _instance;
private final Ice.Dispatcher _dispatcher;
private final ThreadPoolWorkQueue _workQueue;
private boolean _destroyed;
private final String _prefix;
private final String _threadPrefix;
private final Selector _selector;
final class EventHandlerThread implements Runnable
{
EventHandlerThread(String name)
{
_name = name;
_state = Ice.Instrumentation.ThreadState.ThreadStateIdle;
updateObserver();
}
public void
updateObserver()
{
// Must be called with the thread pool mutex locked
Ice.Instrumentation.CommunicatorObserver obsv = _instance.initializationData().observer;
if(obsv != null)
{
_observer = obsv.getThreadObserver(_prefix, _name, _state, _observer);
if(_observer != null)
{
_observer.attach();
}
}
}
public void
setState(Ice.Instrumentation.ThreadState s)
{
// Must be called with the thread pool mutex locked
if(_observer != null)
{
if(_state != s)
{
_observer.stateChanged(_state, s);
}
}
_state = s;
}
public void
join()
throws InterruptedException
{
_thread.join();
}
public void
start(int priority)
{
_thread = new Thread(null, this, _name, _stackSize);
_thread.setPriority(priority);
_thread.start();
}
@Override
public void
run()
{
if(_instance.initializationData().threadHook != null)
{
try
{
_instance.initializationData().threadHook.start();
}
catch(java.lang.Exception ex)
{
String s = "thread hook start() method raised an unexpected exception in `";
s += _prefix + "' thread " + _name + ":\n" + Ex.toString(ex);
_instance.initializationData().logger.error(s);
}
}
try
{
ThreadPool.this.run(this);
}
catch(java.lang.Exception ex)
{
String s = "exception in `" + _prefix + "' thread " + _name + ":\n" + Ex.toString(ex);
_instance.initializationData().logger.error(s);
}
if(_observer != null)
{
_observer.detach();
}
if(_instance.initializationData().threadHook != null)
{
try
{
_instance.initializationData().threadHook.stop();
}
catch(java.lang.Exception ex)
{
String s = "thread hook stop() method raised an unexpected exception in `";
s += _prefix + "' thread " + _name + ":\n" + Ex.toString(ex);
_instance.initializationData().logger.error(s);
}
}
}
final private String _name;
private Thread _thread;
private Ice.Instrumentation.ThreadState _state;
private Ice.Instrumentation.ThreadObserver _observer;
}
private final int _size; // Number of threads that are pre-created.
private final int _sizeIO; // Number of threads that can concurrently perform IO.
private final int _sizeMax; // Maximum number of threads.
private final int _sizeWarn; // If _inUse reaches _sizeWarn, a "low on threads" warning will be printed.
private final boolean _serialize; // True if requests need to be serialized over the connection.
private final int _priority;
private final boolean _hasPriority;
private final long _serverIdleTime;
private final long _threadIdleTime;
private final int _stackSize;
private java.util.List<EventHandlerThread> _threads = new java.util.ArrayList<EventHandlerThread>();
private int _threadIndex; // For assigning thread names.
private int _inUse; // Number of threads that are currently in use.
private int _inUseIO; // Number of threads that are currently performing IO.
private java.util.List<EventHandlerOpPair> _handlers = new java.util.ArrayList<EventHandlerOpPair>();
private java.util.Iterator<EventHandlerOpPair> _nextHandler;
private java.util.HashSet<EventHandler> _pendingHandlers = new java.util.HashSet<EventHandler>();
private boolean _promote;
}
|
elijah513/ice
|
java/src/Ice/src/main/java/IceInternal/ThreadPool.java
|
Java
|
gpl-2.0
| 29,791 |
/* ----------------------------------------------------------------------------
* ATMEL Microcontroller Software Support
* ----------------------------------------------------------------------------
* Copyright (c) 2008, Atmel Corporation
*
* 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 disclaimer below.
*
* Atmel's name may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
* ----------------------------------------------------------------------------
*/
/*
Title: USBIrqHandler implementation
About: Purpose
Implementation of the USB Interrupt Handler.
*/
//------------------------------------------------------------------------------
// Headers
//------------------------------------------------------------------------------
#include <board.h>
#include <usb/device/core/USBD.h>
#include <exceptions.h>
//------------------------------------------------------------------------------
// Exported functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
/// Call Arbitrer, device and host interrupt handler.
/// The IRQ functions are defined with weak and can be surcharged if needed.
//------------------------------------------------------------------------------
void USB_IrqHandler( void )
{
// Most arbitrer interrupt
usb_general_interrupt();
// Device interrupt
USBD_IrqHandler();
// Host interrupt
usb_pipe_interrupt();
}
|
MikeBland/OpenRcBootloader
|
usb/common/core/USBIrqHandler.c
|
C
|
gpl-2.0
| 2,597 |
<?php
require_once(DIR_FS_EXTERNAL.'sofort/core/sofortLibAbstract.inc.php');
/**
* This class encapsulates retrieval of listed banks of the Netherlands
*
* @author SOFORT AG ([email protected])
*
* @copyright 2010-2014 SOFORT AG
*
* @license Released under the GNU LESSER GENERAL PUBLIC LICENSE (Version 3)
* @license http://www.gnu.org/licenses/lgpl.html
*
* @version SofortLib 2.1.1
*
* @link http://www.sofort.com/ official website
*/
class SofortLibIdealBanks extends SofortLibAbstract {
const IDEAL_BANKS_URL = 'https://www.sofort.com/payment/ideal/banks';
/**
* Array for the banks and Ids returned from the API
*
* @var array
*/
protected $_banks = array();
/**
* Constructor for SofortLibIDealBanks
*
* @param string $configKey
* @param string $apiUrl (optional)
* @return \SofortLibIdealBanks
*/
public function __construct($configKey, $apiUrl = '') {
$this->_rootTag = 'ideal';
if ($apiUrl == '') $apiUrl = (getenv('idealApiUrl') != '') ? getenv('idealApiUrl').'/banks' : self::IDEAL_BANKS_URL;
parent::__construct($configKey, $apiUrl);
}
/**
* Getter for bank list
*
* @return array
*/
public function getBanks() {
return $this->_banks;
}
/**
* Parse the xml (override)
*
* @see SofortLib_Abstract::_parse()
* @return void
*/
protected function _parse() {
if (isset($this->_response['ideal']['banks']['bank'][0]['code']['@data'])) {
foreach($this->_response['ideal']['banks']['bank'] as $key => $bank) {
$this->_banks[$key]['id'] = $bank['code']['@data'];
$this->_banks[$key]['text'] = $bank['name']['@data'];
}
}
}
}
|
ReichardtIT/modified-inkl-bootstrap-by-karl
|
includes/external/sofort/classes/sofortLibIdealBanks.inc.php
|
PHP
|
gpl-2.0
| 1,634 |
/* Test the `vld1f32' ARM Neon intrinsic. */
/* This file was autogenerated by neon-testgen. */
/* { dg-do assemble } */
/* { dg-require-effective-target arm_neon_ok } */
/* { dg-options "-save-temps -O0" } */
/* { dg-add-options arm_neon } */
#include "arm_neon.h"
void test_vld1f32 (void)
{
float32x2_t out_float32x2_t;
out_float32x2_t = vld1_f32 (0);
}
/* { dg-final { scan-assembler "vld1\.32\[ \]+((\\\{\[dD\]\[0-9\]+\\\})|(\[dD\]\[0-9\]+)), \\\[\[rR\]\[0-9\]+\\\]!?\(\[ \]+@.*\)?\n" } } */
/* { dg-final { cleanup-saved-temps } } */
|
ccompiler4pic32/pic32-gcc
|
gcc/testsuite/gcc.target/arm/neon/vld1f32.c
|
C
|
gpl-2.0
| 552 |
<?php
/*
Plugin Name: Easy SMTP Mail
Version: 1.0.4
Plugin URI: http://webriti.com/
Description: the wp_mail() function to use SMTP and set your SMTP settings or your wp_mail() function no need any configuration.
Author: harimaliya,priyanshu.mittal
Author URI: http://webriti.com/
License: GPL3
License URI: http://www.gnu.org/licenses/gpl.html
/*** The instantiated version of this plugin's class ***/
if (!function_exists('WebritiSmtpMail'))
{ class WebritiSmtpMail
{
/*** This plugin's identifier ***/
const ID = 'webriti-smtp-mail';
/*** This plugin's name ***/
const NAME = 'Webriti SMTP Mail';
/*** This plugin's version ***/
const VERSION = '1.0.1';
// Array of options and their default values
/*** Has the internationalization text domain been loaded? @var bool ***/
public $loaded_textdomain = false;
/*** Declares the WordPress action and filter callbacks ***/
public function __construct()
{
/** Define Directory Location Constants */
define('WEBRITI_PLUGIN_DIR_PATH_INC', plugin_dir_path(__FILE__).'inc');
/** Define https file Location Constants */
define('WEBRITI_PLUGIN_DIR_URL', plugin_dir_url( __FILE__ ));
// Webriti smtp plugin hook file
$this->load_plugin_hooks_file();
// Webriti smtp form
$this->webriti_smtp_form();
// Webriti smtp textdomain
$this->load_plugin_textdomain();
}
/*** plugin text domain
*/
public function load_plugin_textdomain() {
if (!$this->loaded_textdomain) {
load_plugin_textdomain('webritismtp', false, self::ID . '/lang');
}
}
public function load_plugin_hooks_file()
{
// This code is copied, from wp-includes/pluggable.php as at version 2.2.2
function webriti_phpmailer_init_smtp($phpmailer)
{ // Set the mailer type as per config above, this overrides the already called isMail method
$phpmailer->Mailer = get_option('mailer');
// Set the Sender (return-path) if required
if (get_option('mail_set_return_path'))
$phpmailer->Sender = $phpmailer->From;
// Set the SMTPSecure value, if set to none, leave this blank
$phpmailer->SMTPSecure = get_option('smtp_ssl') == 'none' ? '' : get_option('smtp_ssl');
// If we're sending via SMTP, // Set the other options
if (get_option('mailer') == "smtp")
{
// Set the SMTPSecure value, if set to none, leave this blank
$phpmailer->SMTPSecure = get_option('smtp_ssl') == 'none' ? '' : get_option('smtp_ssl');
$phpmailer->Host = get_option('smtp_host');
$phpmailer->Port = get_option('smtp_port');
// If we're using smtp auth, set the username & password
if (get_option('smtp_auth') == "true") {
$phpmailer->SMTPAuth = TRUE;
$phpmailer->Username = get_option('smtp_user');
$phpmailer->Password = get_option('smtp_pass');
}
}
$phpmailer = apply_filters('wp_mail_smtp_custom_options', $phpmailer);
} // End of phpmailer_init_smtp() function definition
// Webriti plugin option css and js
function load_webriti_smtpmail_css_js()
{
wp_enqueue_script('tab', WEBRITI_PLUGIN_DIR_URL .'js/option-panel-js.js');
wp_enqueue_style('option', WEBRITI_PLUGIN_DIR_URL .'css/style-option.css');
wp_enqueue_style('bootstrap', WEBRITI_PLUGIN_DIR_URL .'css/bootstrap.css');
}
// default data set plug-in activation
function webriti_smtp_activate()
{ $wpms_options = array (
'mail_from' => '',
'mail_from_name' => '',
'mailer' => 'smtp',
'mail_set_return_path' => 'false',
'smtp_host' => 'localhost',
'smtp_port' => 'port',
'smtp_ssl' => 'ssl',
'smtp_auth' => 'true',
'smtp_user' => '',
'smtp_pass' => ''
);
foreach ($wpms_options as $name => $val)
{
add_option($name,$val);
}
}
function webriti_smtp_mail_from ($orig)
{
if(is_email(get_option('mail_from')))
{ return get_option('mail_from'); }
else
{
// Get the site domain and get rid of www.
$sitename = strtolower( $_SERVER['SERVER_NAME'] );
if ( substr( $sitename, 0, 4 ) == 'www.' )
{ $sitename = substr( $sitename, 4 ); }
return $default_from = 'wordpress@' . $sitename;
die;
}
} // End of webriti_wp_mail_smtp_mail_from() function definition
function webriti_smtp_mail_from_name($orig)
{
if(get_option('mail_from_name'))
{ return get_option('mail_from_name'); }
else
{return "Wordpress"; }
}
// Add an action on phpmailer_init
add_action('phpmailer_init','webriti_phpmailer_init_smtp');
register_activation_hook(__FILE__,'webriti_smtp_activate');
// Add filters to replace the mail from name and emaila ddress
add_filter('wp_mail_from','webriti_smtp_mail_from');
add_filter('wp_mail_from_name','webriti_smtp_mail_from_name');
}
function webriti_smtp_form()
{
function webriti_smtp_mail_admin_menu()
{
$menu = add_options_page( __('Webriti SMTP Mail', 'webritismtp'), __('Webriti SMTP Mail', 'webritismtp'), 'manage_options', 'webriti_smtpmail_panels', 'webriti_smtpmail_options_panels_page');
add_action( 'admin_print_styles-' . $menu, 'load_webriti_smtpmail_css_js' );
}
// Wwbriti option page
function webriti_smtpmail_options_panels_page()
{
global $phpmailer;
if ( !is_object( $phpmailer ) || !is_a( $phpmailer, 'PHPMailer' ) )
{ require_once ABSPATH . WPINC . '/class-phpmailer.php';
require_once ABSPATH . WPINC . '/class-smtp.php';
$phpmailer = new PHPMailer( true );
}
require_once(WEBRITI_PLUGIN_DIR_PATH_INC .'/webriti_smtpmail_options.php');
}
// admin menu hook and function
add_action( 'admin_menu', 'webriti_smtp_mail_admin_menu');
}
}
}/// class end
$webritiSmtpMail = new WebritiSmtpMail;
?>
|
nicopenaredondo/UWC
|
wp-content/plugins/webriti-smtp-mail/webriti-smtp-mail.php
|
PHP
|
gpl-2.0
| 5,942 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>Loki: Member List</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.5.1-p1 -->
<div class="tabs">
<ul>
<li><a href="main.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li id="current"><a href="classes.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<form action="search.php" method="get">
<table cellspacing="0" cellpadding="0" border="0">
<tr>
<td><label> <u>S</u>earch for </label></td>
<td><input type="text" name="query" value="" size="20" accesskey="s"/></td>
</tr>
</table>
</form>
</li>
</ul></div>
<div class="tabs">
<ul>
<li><a href="classes.html"><span>Alphabetical List</span></a></li>
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul></div>
<h1>Loki::Private::IsMemberFunctionPointerRaw< T(S::*)(P01, P02, P03, P04, P05, P06, P07,...) volatile > Member List</h1>This is the complete list of members for <a class="el" href="a00400.html">Loki::Private::IsMemberFunctionPointerRaw< T(S::*)(P01, P02, P03, P04, P05, P06, P07,...) volatile ></a>, including all inherited members.<p><table>
</table><hr size="1"><address style="align: right;"><small>Generated on Sun Feb 25 16:53:00 2007 for Loki by
<a href="http://www.doxygen.org/index.html">
<img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.1-p1 </small></address>
</body>
</html>
|
gregorynicholas/houdini-ocean-toolkit
|
src/3rdparty/src/loki-0.1.6/doc/html/a01388.html
|
HTML
|
gpl-2.0
| 2,023 |
/*
* ProFTPD - mod_sftp traffic analysis protection
* Copyright (c) 2008-2009 TJ Saunders
*
* 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.
*
* As a special exemption, TJ Saunders and other respective copyright holders
* give permission to link this program with OpenSSL, and distribute the
* resulting executable, without including the source code for OpenSSL in the
* source distribution.
*
* $Id: tap.h,v 1.5 2009/08/26 05:23:28 castaglia Exp $
*/
#include "mod_sftp.h"
#ifndef MOD_SFTP_TAP_H
#define MOD_SFTP_TAP_H
int sftp_tap_have_policy(const char *);
/* May send an SSH2_MSG_IGNORE packet of random length, filled with random
* data to the client, depending on the selected policy. These messages can
* be injected into the SSH session in order to make traffic analysis harder.
* Returns -1 if there was an error while sending the packet, zero otherwise.
*/
int sftp_tap_send_packet(void);
/* Sets the traffic analysis protection (TAP) policy. Returns 0 if the given
* policy is acceptable, -1 otherwise.
*
* The list of policies is:
*
* "none" - send no SSH2_MSG_IGNORE packets
*
* "low" - 1 in 1000 chance of sending SSH2_MSG_IGNORE, with lengths of
* 64 to 256 bytes of random data.
*
* "medium" - 1 in 100 chance of sending SSH2_MSG_IGNORE, with lengths of
* 32 to 768 bytes of random data.
*
* "high" - 1 in 10 chance of sending SSH2_MSG_IGNORE, with lengths of
* 16 to 2048 bytes of random data.
*
* "paranoid" - always send SSH2_MSG_IGNORE packets, of lengths up to 8KB.
*
* Note that there is an additional TAP policy called 'rogaway'. This
* policy is automatically used if the negotiated server-to-client cipher
* is any of the CBC ciphers. The purpose of the 'rogaway' TAP policy is
* to implement the mitigation of the Rogaway CBC mode attack (see RFC4251,
* Section 9.3.1) via the use of IGNORE packets. The use of the 'rogaway'
* policy is hardcoded, and will override any configured TAP policy.
*/
int sftp_tap_set_policy(const char *);
#endif
|
paul-chambers/netgear-r7800
|
git_home/proftpd.git/contrib/mod_sftp/tap.h
|
C
|
gpl-2.0
| 2,719 |
/*
* Block driver for media (i.e., flash cards)
*
* Copyright 2002 Hewlett-Packard Company
* Copyright 2005-2008 Pierre Ossman
*
* Use consistent with the GNU GPL is permitted,
* provided that this copyright notice is
* preserved in its entirety in all copies and derived works.
*
* HEWLETT-PACKARD COMPANY MAKES NO WARRANTIES, EXPRESSED OR IMPLIED,
* AS TO THE USEFULNESS OR CORRECTNESS OF THIS CODE OR ITS
* FITNESS FOR ANY PARTICULAR PURPOSE.
*
* Many thanks to Alessandro Rubini and Jonathan Corbet!
*
* Author: Andrew Christian
* 28 May 2002
*/
#include <linux/moduleparam.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/hdreg.h>
#include <linux/kdev_t.h>
#include <linux/blkdev.h>
#include <linux/mutex.h>
#include <linux/scatterlist.h>
#include <linux/string_helpers.h>
#include <linux/delay.h>
#include <linux/capability.h>
#include <linux/compat.h>
#include <linux/mmc/ioctl.h>
#include <linux/mmc/card.h>
#include <linux/mmc/host.h>
#include <linux/mmc/mmc.h>
#include <linux/mmc/sd.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include "queue.h"
MODULE_ALIAS("mmc:block");
#ifdef MODULE_PARAM_PREFIX
#undef MODULE_PARAM_PREFIX
#endif
#define MODULE_PARAM_PREFIX "mmcblk."
#define INAND_CMD38_ARG_EXT_CSD 113
#define INAND_CMD38_ARG_ERASE 0x00
#define INAND_CMD38_ARG_TRIM 0x01
#define INAND_CMD38_ARG_SECERASE 0x80
#define INAND_CMD38_ARG_SECTRIM1 0x81
#define INAND_CMD38_ARG_SECTRIM2 0x88
static DEFINE_MUTEX(block_mutex);
/*
* The defaults come from config options but can be overriden by module
* or bootarg options.
*/
static int perdev_minors = CONFIG_MMC_BLOCK_MINORS;
/*
* We've only got one major, so number of mmcblk devices is
* limited to 256 / number of minors per device.
*/
static int max_devices;
/* 256 minors, so at most 256 separate devices */
static DECLARE_BITMAP(dev_use, 256);
static DECLARE_BITMAP(name_use, 256);
/*
* There is one mmc_blk_data per slot.
*/
struct mmc_blk_data {
spinlock_t lock;
struct gendisk *disk;
struct mmc_queue queue;
struct list_head part;
unsigned int flags;
#define MMC_BLK_CMD23 (1 << 0) /* Can do SET_BLOCK_COUNT for multiblock */
#define MMC_BLK_REL_WR (1 << 1) /* MMC Reliable write support */
unsigned int usage;
unsigned int read_only;
unsigned int part_type;
unsigned int name_idx;
unsigned int reset_done;
#define MMC_BLK_READ BIT(0)
#define MMC_BLK_WRITE BIT(1)
#define MMC_BLK_DISCARD BIT(2)
#define MMC_BLK_SECDISCARD BIT(3)
/*
* Only set in main mmc_blk_data associated
* with mmc_card with mmc_set_drvdata, and keeps
* track of the current selected device partition.
*/
unsigned int part_curr;
struct device_attribute force_ro;
};
static DEFINE_MUTEX(open_lock);
enum mmc_blk_status {
MMC_BLK_SUCCESS = 0,
MMC_BLK_PARTIAL,
MMC_BLK_CMD_ERR,
MMC_BLK_RETRY,
MMC_BLK_ABORT,
MMC_BLK_DATA_ERR,
MMC_BLK_ECC_ERR,
};
module_param(perdev_minors, int, 0444);
MODULE_PARM_DESC(perdev_minors, "Minors numbers to allocate per device");
static struct mmc_blk_data *mmc_blk_get(struct gendisk *disk)
{
struct mmc_blk_data *md;
mutex_lock(&open_lock);
md = disk->private_data;
if (md && md->usage == 0)
md = NULL;
if (md)
md->usage++;
mutex_unlock(&open_lock);
return md;
}
static inline int mmc_get_devidx(struct gendisk *disk)
{
int devidx = disk->first_minor / perdev_minors;
return devidx;
}
static void mmc_blk_put(struct mmc_blk_data *md)
{
mutex_lock(&open_lock);
md->usage--;
if (md->usage == 0) {
int devidx = mmc_get_devidx(md->disk);
blk_cleanup_queue(md->queue.queue);
__clear_bit(devidx, dev_use);
put_disk(md->disk);
kfree(md);
}
mutex_unlock(&open_lock);
}
static ssize_t force_ro_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
int ret;
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
ret = snprintf(buf, PAGE_SIZE, "%d",
get_disk_ro(dev_to_disk(dev)) ^
md->read_only);
mmc_blk_put(md);
return ret;
}
static ssize_t force_ro_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
int ret;
char *end;
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
unsigned long set = simple_strtoul(buf, &end, 0);
if (end == buf) {
ret = -EINVAL;
goto out;
}
set_disk_ro(dev_to_disk(dev), set || md->read_only);
ret = count;
out:
mmc_blk_put(md);
return ret;
}
static int mmc_blk_open(struct block_device *bdev, fmode_t mode)
{
struct mmc_blk_data *md = mmc_blk_get(bdev->bd_disk);
int ret = -ENXIO;
mutex_lock(&block_mutex);
if (md) {
if (md->usage == 2)
check_disk_change(bdev);
ret = 0;
if ((mode & FMODE_WRITE) && md->read_only) {
mmc_blk_put(md);
ret = -EROFS;
}
}
mutex_unlock(&block_mutex);
return ret;
}
static int mmc_blk_release(struct gendisk *disk, fmode_t mode)
{
struct mmc_blk_data *md = disk->private_data;
mutex_lock(&block_mutex);
mmc_blk_put(md);
mutex_unlock(&block_mutex);
return 0;
}
static int
mmc_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
{
geo->cylinders = get_capacity(bdev->bd_disk) / (4 * 16);
geo->heads = 4;
geo->sectors = 16;
return 0;
}
struct mmc_blk_ioc_data {
struct mmc_ioc_cmd ic;
unsigned char *buf;
u64 buf_bytes;
};
static struct mmc_blk_ioc_data *mmc_blk_ioctl_copy_from_user(
struct mmc_ioc_cmd __user *user)
{
struct mmc_blk_ioc_data *idata;
int err;
idata = kzalloc(sizeof(*idata), GFP_KERNEL);
if (!idata) {
err = -ENOMEM;
goto out;
}
if (copy_from_user(&idata->ic, user, sizeof(idata->ic))) {
err = -EFAULT;
goto idata_err;
}
idata->buf_bytes = (u64) idata->ic.blksz * idata->ic.blocks;
if (idata->buf_bytes > MMC_IOC_MAX_BYTES) {
err = -EOVERFLOW;
goto idata_err;
}
idata->buf = kzalloc(idata->buf_bytes, GFP_KERNEL);
if (!idata->buf) {
err = -ENOMEM;
goto idata_err;
}
if (copy_from_user(idata->buf, (void __user *)(unsigned long)
idata->ic.data_ptr, idata->buf_bytes)) {
err = -EFAULT;
goto copy_err;
}
return idata;
copy_err:
kfree(idata->buf);
idata_err:
kfree(idata);
out:
return ERR_PTR(err);
}
static int mmc_blk_ioctl_cmd(struct block_device *bdev,
struct mmc_ioc_cmd __user *ic_ptr)
{
struct mmc_blk_ioc_data *idata;
struct mmc_blk_data *md;
struct mmc_card *card;
struct mmc_command cmd = {0};
struct mmc_data data = {0};
struct mmc_request mrq = {NULL};
struct scatterlist sg;
int err;
/*
* The caller must have CAP_SYS_RAWIO, and must be calling this on the
* whole block device, not on a partition. This prevents overspray
* between sibling partitions.
*/
if ((!capable(CAP_SYS_RAWIO)) || (bdev != bdev->bd_contains))
return -EPERM;
idata = mmc_blk_ioctl_copy_from_user(ic_ptr);
if (IS_ERR(idata))
return PTR_ERR(idata);
cmd.opcode = idata->ic.opcode;
cmd.arg = idata->ic.arg;
cmd.flags = idata->ic.flags;
data.sg = &sg;
data.sg_len = 1;
data.blksz = idata->ic.blksz;
data.blocks = idata->ic.blocks;
sg_init_one(data.sg, idata->buf, idata->buf_bytes);
if (idata->ic.write_flag)
data.flags = MMC_DATA_WRITE;
else
data.flags = MMC_DATA_READ;
mrq.cmd = &cmd;
mrq.data = &data;
md = mmc_blk_get(bdev->bd_disk);
if (!md) {
err = -EINVAL;
goto cmd_done;
}
card = md->queue.card;
if (IS_ERR(card)) {
err = PTR_ERR(card);
goto cmd_done;
}
mmc_claim_host(card->host);
if (idata->ic.is_acmd) {
err = mmc_app_cmd(card->host, card);
if (err)
goto cmd_rel_host;
}
/* data.flags must already be set before doing this. */
mmc_set_data_timeout(&data, card);
/* Allow overriding the timeout_ns for empirical tuning. */
if (idata->ic.data_timeout_ns)
data.timeout_ns = idata->ic.data_timeout_ns;
if ((cmd.flags & MMC_RSP_R1B) == MMC_RSP_R1B) {
/*
* Pretend this is a data transfer and rely on the host driver
* to compute timeout. When all host drivers support
* cmd.cmd_timeout for R1B, this can be changed to:
*
* mrq.data = NULL;
* cmd.cmd_timeout = idata->ic.cmd_timeout_ms;
*/
data.timeout_ns = idata->ic.cmd_timeout_ms * 1000000;
}
mmc_wait_for_req(card->host, &mrq);
if (cmd.error) {
dev_err(mmc_dev(card->host), "%s: cmd error %d\n",
__func__, cmd.error);
err = cmd.error;
goto cmd_rel_host;
}
if (data.error) {
dev_err(mmc_dev(card->host), "%s: data error %d\n",
__func__, data.error);
err = data.error;
goto cmd_rel_host;
}
/*
* According to the SD specs, some commands require a delay after
* issuing the command.
*/
if (idata->ic.postsleep_min_us)
usleep_range(idata->ic.postsleep_min_us, idata->ic.postsleep_max_us);
if (copy_to_user(&(ic_ptr->response), cmd.resp, sizeof(cmd.resp))) {
err = -EFAULT;
goto cmd_rel_host;
}
if (!idata->ic.write_flag) {
if (copy_to_user((void __user *)(unsigned long) idata->ic.data_ptr,
idata->buf, idata->buf_bytes)) {
err = -EFAULT;
goto cmd_rel_host;
}
}
cmd_rel_host:
mmc_release_host(card->host);
cmd_done:
mmc_blk_put(md);
kfree(idata->buf);
kfree(idata);
return err;
}
static int mmc_blk_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
int ret = -EINVAL;
if (cmd == MMC_IOC_CMD)
ret = mmc_blk_ioctl_cmd(bdev, (struct mmc_ioc_cmd __user *)arg);
return ret;
}
#ifdef CONFIG_COMPAT
static int mmc_blk_compat_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
return mmc_blk_ioctl(bdev, mode, cmd, (unsigned long) compat_ptr(arg));
}
#endif
static const struct block_device_operations mmc_bdops = {
.open = mmc_blk_open,
.release = mmc_blk_release,
.getgeo = mmc_blk_getgeo,
.owner = THIS_MODULE,
.ioctl = mmc_blk_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = mmc_blk_compat_ioctl,
#endif
};
static inline int mmc_blk_part_switch(struct mmc_card *card,
struct mmc_blk_data *md)
{
int ret;
struct mmc_blk_data *main_md = mmc_get_drvdata(card);
if (main_md->part_curr == md->part_type)
return 0;
if (mmc_card_mmc(card)) {
u8 part_config = card->ext_csd.part_config;
part_config &= ~EXT_CSD_PART_CONFIG_ACC_MASK;
part_config |= md->part_type;
ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
EXT_CSD_PART_CONFIG, part_config,
card->ext_csd.part_time);
if (ret)
return ret;
card->ext_csd.part_config = part_config;
}
main_md->part_curr = md->part_type;
return 0;
}
static u32 mmc_sd_num_wr_blocks(struct mmc_card *card)
{
int err;
u32 result;
__be32 *blocks;
struct mmc_request mrq = {NULL};
struct mmc_command cmd = {0};
struct mmc_data data = {0};
unsigned int timeout_us;
struct scatterlist sg;
cmd.opcode = MMC_APP_CMD;
cmd.arg = card->rca << 16;
cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
err = mmc_wait_for_cmd(card->host, &cmd, 0);
if (err)
return (u32)-1;
if (!mmc_host_is_spi(card->host) && !(cmd.resp[0] & R1_APP_CMD))
return (u32)-1;
memset(&cmd, 0, sizeof(struct mmc_command));
cmd.opcode = SD_APP_SEND_NUM_WR_BLKS;
cmd.arg = 0;
cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
data.timeout_ns = card->csd.tacc_ns * 100;
data.timeout_clks = card->csd.tacc_clks * 100;
timeout_us = data.timeout_ns / 1000;
timeout_us += data.timeout_clks * 1000 /
(card->host->ios.clock / 1000);
if (timeout_us > 100000) {
data.timeout_ns = 100000000;
data.timeout_clks = 0;
}
data.blksz = 4;
data.blocks = 1;
data.flags = MMC_DATA_READ;
data.sg = &sg;
data.sg_len = 1;
mrq.cmd = &cmd;
mrq.data = &data;
blocks = kmalloc(4, GFP_KERNEL);
if (!blocks)
return (u32)-1;
sg_init_one(&sg, blocks, 4);
mmc_wait_for_req(card->host, &mrq);
result = ntohl(*blocks);
kfree(blocks);
if (cmd.error || data.error)
result = (u32)-1;
return result;
}
static int send_stop(struct mmc_card *card, u32 *status)
{
struct mmc_command cmd = {0};
int err;
cmd.opcode = MMC_STOP_TRANSMISSION;
cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
err = mmc_wait_for_cmd(card->host, &cmd, 5);
if (err == 0)
*status = cmd.resp[0];
return err;
}
static int get_card_status(struct mmc_card *card, u32 *status, int retries)
{
struct mmc_command cmd = {0};
int err;
cmd.opcode = MMC_SEND_STATUS;
if (!mmc_host_is_spi(card->host))
cmd.arg = card->rca << 16;
cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC;
err = mmc_wait_for_cmd(card->host, &cmd, retries);
if (err == 0)
*status = cmd.resp[0];
return err;
}
#define ERR_NOMEDIUM 3
#define ERR_RETRY 2
#define ERR_ABORT 1
#define ERR_CONTINUE 0
static int mmc_blk_cmd_error(struct request *req, const char *name, int error,
bool status_valid, u32 status)
{
switch (error) {
case -EILSEQ:
/* response crc error, retry the r/w cmd */
pr_err("%s: %s sending %s command, card status %#x\n",
req->rq_disk->disk_name, "response CRC error",
name, status);
return ERR_RETRY;
case -ETIMEDOUT:
pr_err("%s: %s sending %s command, card status %#x\n",
req->rq_disk->disk_name, "timed out", name, status);
/* If the status cmd initially failed, retry the r/w cmd */
if (!status_valid) {
pr_err("%s: status not valid, retrying timeout\n", req->rq_disk->disk_name);
return ERR_RETRY;
}
/*
* If it was a r/w cmd crc error, or illegal command
* (eg, issued in wrong state) then retry - we should
* have corrected the state problem above.
*/
if (status & (R1_COM_CRC_ERROR | R1_ILLEGAL_COMMAND)) {
pr_err("%s: command error, retrying timeout\n", req->rq_disk->disk_name);
return ERR_RETRY;
}
/* Otherwise abort the command */
pr_err("%s: not retrying timeout\n", req->rq_disk->disk_name);
return ERR_ABORT;
default:
/* We don't understand the error code the driver gave us */
pr_err("%s: unknown error %d sending read/write command, card status %#x\n",
req->rq_disk->disk_name, error, status);
return ERR_ABORT;
}
}
/*
* Initial r/w and stop cmd error recovery.
* We don't know whether the card received the r/w cmd or not, so try to
* restore things back to a sane state. Essentially, we do this as follows:
* - Obtain card status. If the first attempt to obtain card status fails,
* the status word will reflect the failed status cmd, not the failed
* r/w cmd. If we fail to obtain card status, it suggests we can no
* longer communicate with the card.
* - Check the card state. If the card received the cmd but there was a
* transient problem with the response, it might still be in a data transfer
* mode. Try to send it a stop command. If this fails, we can't recover.
* - If the r/w cmd failed due to a response CRC error, it was probably
* transient, so retry the cmd.
* - If the r/w cmd timed out, but we didn't get the r/w cmd status, retry.
* - If the r/w cmd timed out, and the r/w cmd failed due to CRC error or
* illegal cmd, retry.
* Otherwise we don't understand what happened, so abort.
*/
static int mmc_blk_cmd_recovery(struct mmc_card *card, struct request *req,
struct mmc_blk_request *brq, int *ecc_err)
{
bool prev_cmd_status_valid = true;
u32 status, stop_status = 0;
int err, retry;
if (mmc_card_removed(card))
return ERR_NOMEDIUM;
/*
* Try to get card status which indicates both the card state
* and why there was no response. If the first attempt fails,
* we can't be sure the returned status is for the r/w command.
*/
for (retry = 2; retry >= 0; retry--) {
err = get_card_status(card, &status, 0);
if (!err)
break;
prev_cmd_status_valid = false;
pr_err("%s: error %d sending status command, %sing\n",
req->rq_disk->disk_name, err, retry ? "retry" : "abort");
}
/* We couldn't get a response from the card. Give up. */
if (err) {
/* Check if the card is removed */
if (mmc_detect_card_removed(card->host))
return ERR_NOMEDIUM;
return ERR_ABORT;
}
/* Flag ECC errors */
if ((status & R1_CARD_ECC_FAILED) ||
(brq->stop.resp[0] & R1_CARD_ECC_FAILED) ||
(brq->cmd.resp[0] & R1_CARD_ECC_FAILED))
*ecc_err = 1;
/*
* Check the current card state. If it is in some data transfer
* mode, tell it to stop (and hopefully transition back to TRAN.)
*/
if (R1_CURRENT_STATE(status) == R1_STATE_DATA ||
R1_CURRENT_STATE(status) == R1_STATE_RCV) {
err = send_stop(card, &stop_status);
if (err)
pr_err("%s: error %d sending stop command\n",
req->rq_disk->disk_name, err);
/*
* If the stop cmd also timed out, the card is probably
* not present, so abort. Other errors are bad news too.
*/
if (err)
return ERR_ABORT;
if (stop_status & R1_CARD_ECC_FAILED)
*ecc_err = 1;
}
/* Check for set block count errors */
if (brq->sbc.error)
return mmc_blk_cmd_error(req, "SET_BLOCK_COUNT", brq->sbc.error,
prev_cmd_status_valid, status);
/* Check for r/w command errors */
if (brq->cmd.error)
return mmc_blk_cmd_error(req, "r/w cmd", brq->cmd.error,
prev_cmd_status_valid, status);
/* Data errors */
if (!brq->stop.error)
return ERR_CONTINUE;
/* Now for stop errors. These aren't fatal to the transfer. */
pr_err("%s: error %d sending stop command, original cmd response %#x, card status %#x\n",
req->rq_disk->disk_name, brq->stop.error,
brq->cmd.resp[0], status);
/*
* Subsitute in our own stop status as this will give the error
* state which happened during the execution of the r/w command.
*/
if (stop_status) {
brq->stop.resp[0] = stop_status;
brq->stop.error = 0;
}
return ERR_CONTINUE;
}
static int mmc_blk_reset(struct mmc_blk_data *md, struct mmc_host *host,
int type)
{
int err, retries;
if (md->reset_done & type)
{
printk("******* %s, md->reset_done:%d, type:%d, return -EEXIST *****\n", __func__, md->reset_done, type);
return -EEXIST;
}
md->reset_done |= type;
retries = 5;
do{
err = mmc_hw_reset(host);
}while(err && (err != -EOPNOTSUPP) && retries--);
/* Ensure we switch back to the correct partition */
if (err != -EOPNOTSUPP) {
struct mmc_blk_data *main_md = mmc_get_drvdata(host->card);
int part_err;
main_md->part_curr = main_md->part_type;
part_err = mmc_blk_part_switch(host->card, md);
if (part_err) {
/*
* We have failed to get back into the correct
* partition, so we need to abort the whole request.
*/
return -ENODEV;
}
}
return err;
}
static inline void mmc_blk_reset_success(struct mmc_blk_data *md, int type)
{
md->reset_done &= ~type;
}
static int mmc_blk_issue_discard_rq(struct mmc_queue *mq, struct request *req)
{
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
unsigned int from, nr, arg;
int err = 0, type = MMC_BLK_DISCARD;
if (!mmc_can_erase(card)) {
err = -EOPNOTSUPP;
goto out;
}
from = blk_rq_pos(req);
nr = blk_rq_sectors(req);
if (mmc_can_discard(card))
arg = MMC_DISCARD_ARG;
else if (mmc_can_trim(card))
arg = MMC_TRIM_ARG;
else
arg = MMC_ERASE_ARG;
retry:
if (card->quirks & MMC_QUIRK_INAND_CMD38) {
err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
INAND_CMD38_ARG_EXT_CSD,
arg == MMC_TRIM_ARG ?
INAND_CMD38_ARG_TRIM :
INAND_CMD38_ARG_ERASE,
0);
if (err)
goto out;
}
err = mmc_erase(card, from, nr, arg);
out:
if (err == -EIO && !mmc_blk_reset(md, card->host, type))
goto retry;
if (!err)
mmc_blk_reset_success(md, type);
spin_lock_irq(&md->lock);
__blk_end_request(req, err, blk_rq_bytes(req));
spin_unlock_irq(&md->lock);
return err ? 0 : 1;
}
static int mmc_blk_issue_secdiscard_rq(struct mmc_queue *mq,
struct request *req)
{
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
unsigned int from, nr, arg;
int err = 0, type = MMC_BLK_SECDISCARD;
if (!(mmc_can_secure_erase_trim(card) || mmc_can_sanitize(card))) {
err = -EOPNOTSUPP;
goto out;
}
/* The sanitize operation is supported at v4.5 only */
if (mmc_can_sanitize(card)) {
err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
EXT_CSD_SANITIZE_START, 1, 0);
goto out;
}
from = blk_rq_pos(req);
nr = blk_rq_sectors(req);
if (mmc_can_trim(card) && !mmc_erase_group_aligned(card, from, nr))
arg = MMC_SECURE_TRIM1_ARG;
else
arg = MMC_SECURE_ERASE_ARG;
retry:
if (card->quirks & MMC_QUIRK_INAND_CMD38) {
err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
INAND_CMD38_ARG_EXT_CSD,
arg == MMC_SECURE_TRIM1_ARG ?
INAND_CMD38_ARG_SECTRIM1 :
INAND_CMD38_ARG_SECERASE,
0);
if (err)
goto out;
}
err = mmc_erase(card, from, nr, arg);
if (!err && arg == MMC_SECURE_TRIM1_ARG) {
if (card->quirks & MMC_QUIRK_INAND_CMD38) {
err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
INAND_CMD38_ARG_EXT_CSD,
INAND_CMD38_ARG_SECTRIM2,
0);
if (err)
goto out;
}
err = mmc_erase(card, from, nr, MMC_SECURE_TRIM2_ARG);
}
out:
if (err == -EIO && !mmc_blk_reset(md, card->host, type))
goto retry;
if (!err)
mmc_blk_reset_success(md, type);
spin_lock_irq(&md->lock);
__blk_end_request(req, err, blk_rq_bytes(req));
spin_unlock_irq(&md->lock);
return err ? 0 : 1;
}
static int mmc_blk_issue_flush(struct mmc_queue *mq, struct request *req)
{
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
int ret = 0;
ret = mmc_flush_cache(card);
if (ret)
ret = -EIO;
spin_lock_irq(&md->lock);
__blk_end_request_all(req, ret);
spin_unlock_irq(&md->lock);
return ret ? 0 : 1;
}
/*
* Reformat current write as a reliable write, supporting
* both legacy and the enhanced reliable write MMC cards.
* In each transfer we'll handle only as much as a single
* reliable write can handle, thus finish the request in
* partial completions.
*/
static inline void mmc_apply_rel_rw(struct mmc_blk_request *brq,
struct mmc_card *card,
struct request *req)
{
if (!(card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN)) {
/* Legacy mode imposes restrictions on transfers. */
if (!IS_ALIGNED(brq->cmd.arg, card->ext_csd.rel_sectors))
brq->data.blocks = 1;
if (brq->data.blocks > card->ext_csd.rel_sectors)
brq->data.blocks = card->ext_csd.rel_sectors;
else if (brq->data.blocks < card->ext_csd.rel_sectors)
brq->data.blocks = 1;
}
}
#define CMD_ERRORS \
(R1_OUT_OF_RANGE | /* Command argument out of range */ \
R1_ADDRESS_ERROR | /* Misaligned address */ \
R1_BLOCK_LEN_ERROR | /* Transferred block length incorrect */\
R1_WP_VIOLATION | /* Tried to write to protected block */ \
R1_CC_ERROR | /* Card controller error */ \
R1_ERROR) /* General/unknown error */
static int mmc_blk_err_check(struct mmc_card *card,
struct mmc_async_req *areq)
{
struct mmc_queue_req *mq_mrq = container_of(areq, struct mmc_queue_req,
mmc_active);
struct mmc_blk_request *brq = &mq_mrq->brq;
struct request *req = mq_mrq->req;
int ecc_err = 0;
/*
* sbc.error indicates a problem with the set block count
* command. No data will have been transferred.
*
* cmd.error indicates a problem with the r/w command. No
* data will have been transferred.
*
* stop.error indicates a problem with the stop command. Data
* may have been transferred, or may still be transferring.
*/
if (brq->sbc.error || brq->cmd.error || brq->stop.error ||
brq->data.error) {
switch (mmc_blk_cmd_recovery(card, req, brq, &ecc_err)) {
case ERR_RETRY:
return MMC_BLK_RETRY;
case ERR_ABORT:
case ERR_NOMEDIUM:
return MMC_BLK_ABORT;
case ERR_CONTINUE:
break;
}
}
/*
* Check for errors relating to the execution of the
* initial command - such as address errors. No data
* has been transferred.
*/
if (brq->cmd.resp[0] & CMD_ERRORS) {
pr_err("%s: r/w command failed, status = %#x\n",
req->rq_disk->disk_name, brq->cmd.resp[0]);
return MMC_BLK_ABORT;
}
/*
* Everything else is either success, or a data error of some
* kind. If it was a write, we may have transitioned to
* program mode, which we have to wait for it to complete.
*/
if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ) {
u32 status;
unsigned long delay = jiffies + HZ;
do {
int err = get_card_status(card, &status, 5);
if (err) {
printk(KERN_ERR "%s: error %d requesting status\n",
req->rq_disk->disk_name, err);
return MMC_BLK_CMD_ERR;
}
/*
* Some cards mishandle the status bits,
* so make sure to check both the busy
* indication and the card state.
*/
if(status != 0x900)
printk("%s: check cards status: 0x%x\n", mmc_hostname(card->host), status);
if (time_after(jiffies, delay)){
printk("!!! %s, getting card status timeout\n", mmc_hostname(card->host));
break;
}
} while (!(status & R1_READY_FOR_DATA) ||
(R1_CURRENT_STATE(status) == R1_STATE_PRG));
}
if (brq->data.error) {
pr_err("%s: error %d transferring data, sector %u, nr %u, cmd response %#x, card status %#x\n",
req->rq_disk->disk_name, brq->data.error,
(unsigned)blk_rq_pos(req),
(unsigned)blk_rq_sectors(req),
brq->cmd.resp[0], brq->stop.resp[0]);
if (rq_data_dir(req) == READ) {
if (ecc_err)
return MMC_BLK_ECC_ERR;
return MMC_BLK_DATA_ERR;
} else {
return MMC_BLK_CMD_ERR;
}
}
if (!brq->data.bytes_xfered)
return MMC_BLK_RETRY;
if (blk_rq_bytes(req) != brq->data.bytes_xfered)
return MMC_BLK_PARTIAL;
return MMC_BLK_SUCCESS;
}
static void mmc_blk_rw_rq_prep(struct mmc_queue_req *mqrq,
struct mmc_card *card,
int disable_multi,
struct mmc_queue *mq)
{
u32 readcmd, writecmd;
struct mmc_blk_request *brq = &mqrq->brq;
struct request *req = mqrq->req;
struct mmc_blk_data *md = mq->data;
/*
* Reliable writes are used to implement Forced Unit Access and
* REQ_META accesses, and are supported only on MMCs.
*/
bool do_rel_wr = ((req->cmd_flags & REQ_FUA) ||
(req->cmd_flags & REQ_META)) &&
(rq_data_dir(req) == WRITE) &&
(md->flags & MMC_BLK_REL_WR);
memset(brq, 0, sizeof(struct mmc_blk_request));
brq->mrq.cmd = &brq->cmd;
brq->mrq.data = &brq->data;
brq->cmd.arg = blk_rq_pos(req);
if (!mmc_card_blockaddr(card))
brq->cmd.arg <<= 9;
brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
brq->data.blksz = 512;
brq->stop.opcode = MMC_STOP_TRANSMISSION;
brq->stop.arg = 0;
brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
brq->data.blocks = blk_rq_sectors(req);
/*
* The block layer doesn't support all sector count
* restrictions, so we need to be prepared for too big
* requests.
*/
if (brq->data.blocks > card->host->max_blk_count)
brq->data.blocks = card->host->max_blk_count;
if (brq->data.blocks > 1) {
/*
* After a read error, we redo the request one sector
* at a time in order to accurately determine which
* sectors can be read successfully.
*/
if (disable_multi)
brq->data.blocks = 1;
/* Some controllers can't do multiblock reads due to hw bugs */
if (card->host->caps2 & MMC_CAP2_NO_MULTI_READ &&
rq_data_dir(req) == READ)
brq->data.blocks = 1;
}
if (brq->data.blocks > 1 || do_rel_wr) {
/* SPI multiblock writes terminate using a special
* token, not a STOP_TRANSMISSION request.
*/
if (!mmc_host_is_spi(card->host) ||
rq_data_dir(req) == READ)
brq->mrq.stop = &brq->stop;
readcmd = MMC_READ_MULTIPLE_BLOCK;
writecmd = MMC_WRITE_MULTIPLE_BLOCK;
} else {
brq->mrq.stop = NULL;
readcmd = MMC_READ_SINGLE_BLOCK;
writecmd = MMC_WRITE_BLOCK;
}
if (rq_data_dir(req) == READ) {
brq->cmd.opcode = readcmd;
brq->data.flags |= MMC_DATA_READ;
} else {
brq->cmd.opcode = writecmd;
brq->data.flags |= MMC_DATA_WRITE;
}
if (do_rel_wr)
mmc_apply_rel_rw(brq, card, req);
/*
* Pre-defined multi-block transfers are preferable to
* open ended-ones (and necessary for reliable writes).
* However, it is not sufficient to just send CMD23,
* and avoid the final CMD12, as on an error condition
* CMD12 (stop) needs to be sent anyway. This, coupled
* with Auto-CMD23 enhancements provided by some
* hosts, means that the complexity of dealing
* with this is best left to the host. If CMD23 is
* supported by card and host, we'll fill sbc in and let
* the host deal with handling it correctly. This means
* that for hosts that don't expose MMC_CAP_CMD23, no
* change of behavior will be observed.
*
* N.B: Some MMC cards experience perf degradation.
* We'll avoid using CMD23-bounded multiblock writes for
* these, while retaining features like reliable writes.
*/
if ((md->flags & MMC_BLK_CMD23) &&
mmc_op_multi(brq->cmd.opcode) &&
(do_rel_wr || !(card->quirks & MMC_QUIRK_BLK_NO_CMD23))) {
brq->sbc.opcode = MMC_SET_BLOCK_COUNT;
brq->sbc.arg = brq->data.blocks |
(do_rel_wr ? (1 << 31) : 0);
brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC;
brq->mrq.sbc = &brq->sbc;
}
mmc_set_data_timeout(&brq->data, card);
brq->data.sg = mqrq->sg;
brq->data.sg_len = mmc_queue_map_sg(mq, mqrq);
/*
* Adjust the sg list so it is the same size as the
* request.
*/
if (brq->data.blocks != blk_rq_sectors(req)) {
int i, data_size = brq->data.blocks << 9;
struct scatterlist *sg;
for_each_sg(brq->data.sg, sg, brq->data.sg_len, i) {
data_size -= sg->length;
if (data_size <= 0) {
sg->length += data_size;
i++;
break;
}
}
brq->data.sg_len = i;
}
mqrq->mmc_active.mrq = &brq->mrq;
mqrq->mmc_active.err_check = mmc_blk_err_check;
mmc_queue_bounce_pre(mqrq);
}
static int mmc_blk_cmd_err(struct mmc_blk_data *md, struct mmc_card *card,
struct mmc_blk_request *brq, struct request *req,
int ret)
{
/*
* If this is an SD card and we're writing, we can first
* mark the known good sectors as ok.
*
* If the card is not SD, we can still ok written sectors
* as reported by the controller (which might be less than
* the real number of written sectors, but never more).
*/
if (mmc_card_sd(card)) {
u32 blocks;
blocks = mmc_sd_num_wr_blocks(card);
if (blocks != (u32)-1) {
spin_lock_irq(&md->lock);
/* do not end requset if cmd error */
/*ret = __blk_end_request(req, 0, blocks << 9);*/
ret = __blk_end_request(req, 0, 0);
spin_unlock_irq(&md->lock);
}
} else {
spin_lock_irq(&md->lock);
ret = __blk_end_request(req, 0, brq->data.bytes_xfered);
spin_unlock_irq(&md->lock);
}
return ret;
}
static void remove_sd_card(struct mmc_host *host)
{
printk(KERN_INFO "%s: %s\n", mmc_hostname(host), __func__);
if (!host->card || host->card->removed) {
printk(KERN_INFO "%s: card already removed\n",
mmc_hostname(host));
return;
}
if (!mmc_card_present(host->card)) {
printk(KERN_INFO "%s: card is not present\n",
mmc_hostname(host));
return;
}
mmc_schedule_card_removal_work(&host->remove, 0);
//host->card->removed = 1;
}
static int mmc_blk_issue_rw_rq(struct mmc_queue *mq, struct request *rqc)
{
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
struct mmc_blk_request *brq = &mq->mqrq_cur->brq;
int ret = 1, disable_multi = 0, retry = 0, type;
enum mmc_blk_status status;
struct mmc_queue_req *mq_rq;
struct request *req;
struct mmc_async_req *areq;
if (!rqc && !mq->mqrq_prev->req)
return 0;
do {
if (rqc) {
mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq);
areq = &mq->mqrq_cur->mmc_active;
} else
areq = NULL;
areq = mmc_start_req(card->host, areq, (int *) &status);
if (!areq)
return 0;
mq_rq = container_of(areq, struct mmc_queue_req, mmc_active);
brq = &mq_rq->brq;
req = mq_rq->req;
type = rq_data_dir(req) == READ ? MMC_BLK_READ : MMC_BLK_WRITE;
mmc_queue_bounce_post(mq_rq);
if(status)
printk("****** %s, transfer status:%d ****\n", __func__, status);
switch (status) {
case MMC_BLK_SUCCESS:
case MMC_BLK_PARTIAL:
/*
* A block was successfully transferred.
*/
mmc_blk_reset_success(md, type);
spin_lock_irq(&md->lock);
ret = __blk_end_request(req, 0,
brq->data.bytes_xfered);
spin_unlock_irq(&md->lock);
/*
* If the blk_end_request function returns non-zero even
* though all data has been transferred and no errors
* were returned by the host controller, it's a bug.
*/
if (status == MMC_BLK_SUCCESS && ret) {
printk(KERN_ERR "%s BUG rq_tot %d d_xfer %d\n",
__func__, blk_rq_bytes(req),
brq->data.bytes_xfered);
rqc = NULL;
goto cmd_abort;
}
break;
case MMC_BLK_CMD_ERR:
ret = mmc_blk_cmd_err(md, card, brq, req, ret);
if (!mmc_blk_reset(md, card->host, type))
break;
goto cmd_abort;
case MMC_BLK_RETRY:
if (retry++ < 5)
break;
/* Fall through */
case MMC_BLK_ABORT:
if (!mmc_blk_reset(md, card->host, type))
break;
goto cmd_abort;
case MMC_BLK_DATA_ERR: {
int err;
err = mmc_blk_reset(md, card->host, type);
if (!err)
break;
if (err == -ENODEV)
goto cmd_abort;
/* Fall through */
}
case MMC_BLK_ECC_ERR:
if (brq->data.blocks > 1) {
/* Redo read one sector at a time */
pr_warning("%s: retrying using single block read\n",
req->rq_disk->disk_name);
disable_multi = 1;
break;
}
/*
* After an error, we redo I/O one sector at a
* time, so we only reach here after trying to
* read a single sector.
*/
spin_lock_irq(&md->lock);
ret = __blk_end_request(req, -EIO,
brq->data.blksz);
spin_unlock_irq(&md->lock);
if (!ret)
goto start_new_req;
break;
}
if (ret) {
/*
* In case of a incomplete request
* prepare it again and resend.
*/
mmc_blk_rw_rq_prep(mq_rq, card, disable_multi, mq);
mmc_start_req(card->host, &mq_rq->mmc_active, NULL);
}
} while (ret);
return 1;
cmd_abort:
spin_lock_irq(&md->lock);
if (mmc_card_removed(card))
req->cmd_flags |= REQ_QUIET;
while (ret)
ret = __blk_end_request(req, -EIO, blk_rq_cur_bytes(req));
spin_unlock_irq(&md->lock);
/*
* reset host failed, give up, remove card
*/
if(mmc_card_sd(card))
remove_sd_card(card->host);
start_new_req:
if (rqc) {
mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq);
mmc_start_req(card->host, &mq->mqrq_cur->mmc_active, NULL);
}
return 0;
}
static int
mmc_blk_set_blksize(struct mmc_blk_data *md, struct mmc_card *card);
static int mmc_blk_issue_rq(struct mmc_queue *mq, struct request *req)
{
int ret;
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
#ifdef CONFIG_MMC_BLOCK_DEFERRED_RESUME
if (mmc_bus_needs_resume(card->host)) {
mmc_resume_bus(card->host);
mmc_blk_set_blksize(md, card);
}
#endif
if (req && !mq->mqrq_prev->req)
/* claim host only for the first request */
mmc_claim_host(card->host);
ret = mmc_blk_part_switch(card, md);
if (ret) {
if (req) {
spin_lock_irq(&md->lock);
__blk_end_request_all(req, -EIO);
spin_unlock_irq(&md->lock);
}
ret = 0;
goto out;
}
if (req && req->cmd_flags & REQ_DISCARD) {
/* complete ongoing async transfer before issuing discard */
if (card->host->areq)
mmc_blk_issue_rw_rq(mq, NULL);
if (req->cmd_flags & REQ_SECURE)
ret = mmc_blk_issue_secdiscard_rq(mq, req);
else
ret = mmc_blk_issue_discard_rq(mq, req);
} else if (req && req->cmd_flags & REQ_FLUSH) {
/* complete ongoing async transfer before issuing flush */
if (card->host->areq)
mmc_blk_issue_rw_rq(mq, NULL);
ret = mmc_blk_issue_flush(mq, req);
} else {
ret = mmc_blk_issue_rw_rq(mq, req);
}
out:
if (!req)
/* release host only when there are no more requests */
mmc_release_host(card->host);
return ret;
}
static inline int mmc_blk_readonly(struct mmc_card *card)
{
return mmc_card_readonly(card) ||
!(card->csd.cmdclass & CCC_BLOCK_WRITE);
}
static struct mmc_blk_data *mmc_blk_alloc_req(struct mmc_card *card,
struct device *parent,
sector_t size,
bool default_ro,
const char *subname)
{
struct mmc_blk_data *md;
int devidx, ret;
devidx = find_first_zero_bit(dev_use, max_devices);
if (devidx >= max_devices)
return ERR_PTR(-ENOSPC);
__set_bit(devidx, dev_use);
md = kzalloc(sizeof(struct mmc_blk_data), GFP_KERNEL);
if (!md) {
ret = -ENOMEM;
goto out;
}
/*
* !subname implies we are creating main mmc_blk_data that will be
* associated with mmc_card with mmc_set_drvdata. Due to device
* partitions, devidx will not coincide with a per-physical card
* index anymore so we keep track of a name index.
*/
if (!subname) {
md->name_idx = find_first_zero_bit(name_use, max_devices);
__set_bit(md->name_idx, name_use);
}
else
md->name_idx = ((struct mmc_blk_data *)
dev_to_disk(parent)->private_data)->name_idx;
/*
* Set the read-only status based on the supported commands
* and the write protect switch.
*/
md->read_only = mmc_blk_readonly(card);
md->disk = alloc_disk(perdev_minors);
if (md->disk == NULL) {
ret = -ENOMEM;
goto err_kfree;
}
spin_lock_init(&md->lock);
INIT_LIST_HEAD(&md->part);
md->usage = 1;
ret = mmc_init_queue(&md->queue, card, &md->lock, subname);
if (ret)
goto err_putdisk;
md->queue.issue_fn = mmc_blk_issue_rq;
md->queue.data = md;
md->disk->major = MMC_BLOCK_MAJOR;
md->disk->first_minor = devidx * perdev_minors;
md->disk->fops = &mmc_bdops;
md->disk->private_data = md;
md->disk->queue = md->queue.queue;
md->disk->driverfs_dev = &card->dev;
set_disk_ro(md->disk, md->read_only || default_ro);
md->disk->flags = GENHD_FL_EXT_DEVT;
/*
* As discussed on lkml, GENHD_FL_REMOVABLE should:
*
* - be set for removable media with permanent block devices
* - be unset for removable block devices with permanent media
*
* Since MMC block devices clearly fall under the second
* case, we do not set GENHD_FL_REMOVABLE. Userspace
* should use the block device creation/destruction hotplug
* messages to tell when the card is present.
*/
snprintf(md->disk->disk_name, sizeof(md->disk->disk_name),
"mmcblk%d%s", md->name_idx, subname ? subname : "");
blk_queue_logical_block_size(md->queue.queue, 512);
set_capacity(md->disk, size);
if (mmc_host_cmd23(card->host)) {
if (mmc_card_mmc(card) ||
(mmc_card_sd(card) &&
card->scr.cmds & SD_SCR_CMD23_SUPPORT))
md->flags |= MMC_BLK_CMD23;
}
if (mmc_card_mmc(card) &&
md->flags & MMC_BLK_CMD23 &&
((card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN) ||
card->ext_csd.rel_sectors)) {
md->flags |= MMC_BLK_REL_WR;
blk_queue_flush(md->queue.queue, REQ_FLUSH | REQ_FUA);
}
return md;
err_putdisk:
put_disk(md->disk);
err_kfree:
kfree(md);
out:
return ERR_PTR(ret);
}
static struct mmc_blk_data *mmc_blk_alloc(struct mmc_card *card)
{
sector_t size;
struct mmc_blk_data *md;
if (!mmc_card_sd(card) && mmc_card_blockaddr(card)) {
/*
* The EXT_CSD sector count is in number or 512 byte
* sectors.
*/
size = card->ext_csd.sectors;
} else {
/*
* The CSD capacity field is in units of read_blkbits.
* set_capacity takes units of 512 bytes.
*/
size = card->csd.capacity << (card->csd.read_blkbits - 9);
}
md = mmc_blk_alloc_req(card, &card->dev, size, false, NULL);
return md;
}
static int mmc_blk_alloc_part(struct mmc_card *card,
struct mmc_blk_data *md,
unsigned int part_type,
sector_t size,
bool default_ro,
const char *subname)
{
char cap_str[10];
struct mmc_blk_data *part_md;
part_md = mmc_blk_alloc_req(card, disk_to_dev(md->disk), size, default_ro,
subname);
if (IS_ERR(part_md))
return PTR_ERR(part_md);
part_md->part_type = part_type;
list_add(&part_md->part, &md->part);
string_get_size((u64)get_capacity(part_md->disk) << 9, STRING_UNITS_2,
cap_str, sizeof(cap_str));
printk(KERN_INFO "%s: %s %s partition %u %s\n",
part_md->disk->disk_name, mmc_card_id(card),
mmc_card_name(card), part_md->part_type, cap_str);
return 0;
}
static int mmc_blk_alloc_parts(struct mmc_card *card, struct mmc_blk_data *md)
{
int ret = 0;
if (!mmc_card_mmc(card))
return 0;
if (card->ext_csd.boot_size && mmc_boot_partition_access(card->host)) {
ret = mmc_blk_alloc_part(card, md, EXT_CSD_PART_CONFIG_ACC_BOOT0,
card->ext_csd.boot_size >> 9,
true,
"boot0");
if (ret)
return ret;
ret = mmc_blk_alloc_part(card, md, EXT_CSD_PART_CONFIG_ACC_BOOT1,
card->ext_csd.boot_size >> 9,
true,
"boot1");
if (ret)
return ret;
}
return ret;
}
static int
mmc_blk_set_blksize(struct mmc_blk_data *md, struct mmc_card *card)
{
int err;
if (mmc_card_blockaddr(card) || mmc_card_ddr_mode(card))
return 0;
mmc_claim_host(card->host);
err = mmc_set_blocklen(card, 512);
mmc_release_host(card->host);
if (err) {
printk(KERN_ERR "%s: unable to set block size to 512: %d\n",
md->disk->disk_name, err);
return -EINVAL;
}
return 0;
}
static void mmc_blk_remove_req(struct mmc_blk_data *md)
{
if (md) {
if (md->disk->flags & GENHD_FL_UP) {
device_remove_file(disk_to_dev(md->disk), &md->force_ro);
/* Stop new requests from getting into the queue */
del_gendisk_async(md->disk);
}
/* Then flush out any already in there */
mmc_cleanup_queue(&md->queue);
mmc_blk_put(md);
}
}
static void mmc_blk_remove_parts(struct mmc_card *card,
struct mmc_blk_data *md)
{
struct list_head *pos, *q;
struct mmc_blk_data *part_md;
__clear_bit(md->name_idx, name_use);
list_for_each_safe(pos, q, &md->part) {
part_md = list_entry(pos, struct mmc_blk_data, part);
list_del(pos);
mmc_blk_remove_req(part_md);
}
}
static int mmc_add_disk(struct mmc_blk_data *md)
{
int ret;
add_disk(md->disk);
md->force_ro.show = force_ro_show;
md->force_ro.store = force_ro_store;
sysfs_attr_init(&md->force_ro.attr);
md->force_ro.attr.name = "force_ro";
md->force_ro.attr.mode = S_IRUGO | S_IWUSR;
ret = device_create_file(disk_to_dev(md->disk), &md->force_ro);
if (ret)
del_gendisk(md->disk);
return ret;
}
static const struct mmc_fixup blk_fixups[] =
{
MMC_FIXUP("SEM02G", 0x2, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38),
MMC_FIXUP("SEM04G", 0x2, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38),
MMC_FIXUP("SEM08G", 0x2, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38),
MMC_FIXUP("SEM16G", 0x2, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38),
MMC_FIXUP("SEM32G", 0x2, 0x100, add_quirk, MMC_QUIRK_INAND_CMD38),
MMC_FIXUP("SD8GB", 0x41, 0x3432, add_quirk,MMC_QUIRK_BLK_NO_CMD23),
/*
* Some MMC cards experience performance degradation with CMD23
* instead of CMD12-bounded multiblock transfers. For now we'll
* black list what's bad...
* - Certain Toshiba cards.
*
* N.B. This doesn't affect SD cards.
*/
MMC_FIXUP("MMC08G", 0x11, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_BLK_NO_CMD23),
MMC_FIXUP("MMC16G", 0x11, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_BLK_NO_CMD23),
MMC_FIXUP("MMC32G", 0x11, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_BLK_NO_CMD23),
END_FIXUP
};
static int mmc_blk_probe(struct mmc_card *card)
{
struct mmc_blk_data *md, *part_md;
int err;
char cap_str[10];
/*
* Check that the card supports the command class(es) we need.
*/
if (!(card->csd.cmdclass & CCC_BLOCK_READ))
return -ENODEV;
md = mmc_blk_alloc(card);
if (IS_ERR(md))
return PTR_ERR(md);
err = mmc_blk_set_blksize(md, card);
if (err)
goto out;
string_get_size((u64)get_capacity(md->disk) << 9, STRING_UNITS_2,
cap_str, sizeof(cap_str));
printk(KERN_INFO "%s: %s %s %s %s\n",
md->disk->disk_name, mmc_card_id(card), mmc_card_name(card),
cap_str, md->read_only ? "(ro)" : "");
if (mmc_blk_alloc_parts(card, md))
goto out;
mmc_set_drvdata(card, md);
mmc_fixup_device(card, blk_fixups);
printk("%s: %s %s %s %s\n",
md->disk->disk_name, mmc_card_id(card), mmc_card_name(card),
cap_str, md->read_only ? "(ro)" : "");
#ifdef CONFIG_MMC_BLOCK_DEFERRED_RESUME
mmc_set_bus_resume_policy(card->host, 1);
#endif
if (mmc_add_disk(md))
goto out;
list_for_each_entry(part_md, &md->part, part) {
if (mmc_add_disk(part_md))
goto out;
}
return 0;
out:
mmc_blk_remove_parts(card, md);
mmc_blk_remove_req(md);
return err;
}
static void mmc_blk_remove(struct mmc_card *card)
{
struct mmc_blk_data *md = mmc_get_drvdata(card);
mmc_blk_remove_parts(card, md);
mmc_claim_host(card->host);
mmc_blk_part_switch(card, md);
mmc_release_host(card->host);
mmc_blk_remove_req(md);
mmc_set_drvdata(card, NULL);
#ifdef CONFIG_MMC_BLOCK_DEFERRED_RESUME
mmc_set_bus_resume_policy(card->host, 0);
#endif
}
#ifdef CONFIG_PM
static int mmc_blk_suspend(struct mmc_card *card)
{
struct mmc_blk_data *part_md;
struct mmc_blk_data *md = mmc_get_drvdata(card);
if (md) {
mmc_queue_suspend(&md->queue);
list_for_each_entry(part_md, &md->part, part) {
mmc_queue_suspend(&part_md->queue);
}
}
return 0;
}
static int mmc_blk_resume(struct mmc_card *card)
{
struct mmc_blk_data *part_md;
struct mmc_blk_data *md = mmc_get_drvdata(card);
if (md) {
#ifndef CONFIG_MMC_BLOCK_DEFERRED_RESUME
mmc_blk_set_blksize(md, card);
#endif
/*
* Resume involves the card going into idle state,
* so current partition is always the main one.
*/
md->part_curr = md->part_type;
mmc_queue_resume(&md->queue);
list_for_each_entry(part_md, &md->part, part) {
mmc_queue_resume(&part_md->queue);
}
}
return 0;
}
#else
#define mmc_blk_suspend NULL
#define mmc_blk_resume NULL
#endif
static struct mmc_driver mmc_driver = {
.drv = {
.name = "mmcblk",
},
.probe = mmc_blk_probe,
.remove = mmc_blk_remove,
.suspend = mmc_blk_suspend,
.resume = mmc_blk_resume,
};
static int __init mmc_blk_init(void)
{
int res;
if (perdev_minors != CONFIG_MMC_BLOCK_MINORS)
pr_info("mmcblk: using %d minors per device\n", perdev_minors);
max_devices = 256 / perdev_minors;
res = register_blkdev(MMC_BLOCK_MAJOR, "mmc");
if (res)
goto out;
res = mmc_register_driver(&mmc_driver);
if (res)
goto out2;
return 0;
out2:
unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
out:
return res;
}
static void __exit mmc_blk_exit(void)
{
mmc_unregister_driver(&mmc_driver);
unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
}
module_init(mmc_blk_init);
module_exit(mmc_blk_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Multimedia Card (MMC) block device driver");
|
voltagex/kernel-sprdb2g_gonk4.0_6821
|
drivers/mmc/card/block.c
|
C
|
gpl-2.0
| 46,161 |
#include "../src/gui/embedded/qkbddriverfactory_qws.h"
|
sunqueen/vlc-2.2.0-rc2.32-2013
|
win32/include/qt4.org/QtGui/qkbddriverfactory_qws.h
|
C
|
gpl-2.0
| 55 |
<?php
namespace Drupal\Tests\jsonapi\Kernel\Normalizer;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\file\Entity\File;
use Drupal\jsonapi\ResourceType\ResourceType;
use Drupal\jsonapi\LinkManager\LinkManager;
use Drupal\jsonapi\Normalizer\JsonApiDocumentTopLevelNormalizer;
use Drupal\jsonapi\Resource\JsonApiDocumentTopLevel;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
use Drupal\jsonapi\ResourceResponse;
use Drupal\taxonomy\Entity\Term;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\Tests\image\Kernel\ImageFieldCreationTrait;
use Drupal\Tests\jsonapi\Kernel\JsonapiKernelTestBase;
use Drupal\user\Entity\Role;
use Drupal\user\Entity\User;
use Drupal\user\RoleInterface;
use Prophecy\Argument;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Route;
/**
* @coversDefaultClass \Drupal\jsonapi\Normalizer\JsonApiDocumentTopLevelNormalizer
* @group jsonapi
*/
class JsonApiDocumentTopLevelNormalizerTest extends JsonapiKernelTestBase {
use ImageFieldCreationTrait;
/**
* {@inheritdoc}
*/
public static $modules = [
'jsonapi',
'field',
'node',
'serialization',
'system',
'taxonomy',
'text',
'user',
'file',
'image',
];
/**
* A node to normalize.
*
* @var \Drupal\Core\Entity\EntityInterface
*/
protected $node;
/**
* A user to normalize.
*
* @var \Drupal\user\Entity\User
*/
protected $user;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Add the entity schemas.
$this->installEntitySchema('node');
$this->installEntitySchema('user');
$this->installEntitySchema('taxonomy_term');
$this->installEntitySchema('file');
// Add the additional table schemas.
$this->installSchema('system', ['sequences']);
$this->installSchema('node', ['node_access']);
$this->installSchema('user', ['users_data']);
$this->installSchema('file', ['file_usage']);
$type = NodeType::create([
'type' => 'article',
]);
$type->save();
$this->createEntityReferenceField(
'node',
'article',
'field_tags',
'Tags',
'taxonomy_term',
'default',
['target_bundles' => ['tags']],
FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED
);
$this->createImageField('field_image', 'article');
$this->user = User::create([
'name' => 'user1',
'mail' => 'user@localhost',
]);
$this->user2 = User::create([
'name' => 'user2',
'mail' => 'user2@localhost',
]);
$this->user->save();
$this->user2->save();
$this->vocabulary = Vocabulary::create(['name' => 'Tags', 'vid' => 'tags']);
$this->vocabulary->save();
$this->term1 = Term::create([
'name' => 'term1',
'vid' => $this->vocabulary->id(),
]);
$this->term2 = Term::create([
'name' => 'term2',
'vid' => $this->vocabulary->id(),
]);
$this->term1->save();
$this->term2->save();
$this->file = File::create([
'uri' => 'public://example.png',
'filename' => 'example.png',
]);
$this->file->save();
$this->node = Node::create([
'title' => 'dummy_title',
'type' => 'article',
'uid' => 1,
'field_tags' => [
['target_id' => $this->term1->id()],
['target_id' => $this->term2->id()],
],
'field_image' => [
[
'target_id' => $this->file->id(),
'alt' => 'test alt',
'title' => 'test title',
'width' => 10,
'height' => 11,
],
],
]);
$this->node->save();
$link_manager = $this->prophesize(LinkManager::class);
$link_manager
->getEntityLink(Argument::any(), Argument::any(), Argument::type('array'), Argument::type('string'))
->willReturn('dummy_entity_link');
$link_manager
->getRequestLink(Argument::any())
->willReturn('dummy_document_link');
$this->container->set('jsonapi.link_manager', $link_manager->reveal());
$this->nodeType = NodeType::load('article');
Role::create([
'id' => RoleInterface::ANONYMOUS_ID,
'permissions' => [
'access content',
],
])->save();
}
/**
* {@inheritdoc}
*/
public function tearDown() {
if ($this->node) {
$this->node->delete();
}
if ($this->term1) {
$this->term1->delete();
}
if ($this->term2) {
$this->term2->delete();
}
if ($this->vocabulary) {
$this->vocabulary->delete();
}
if ($this->user) {
$this->user->delete();
}
if ($this->user2) {
$this->user2->delete();
}
}
/**
* @covers ::normalize
*/
public function testNormalize() {
list($request, $resource_type) = $this->generateProphecies('node', 'article');
$request->query = new ParameterBag([
'fields' => [
'node--article' => 'title,type,uid,field_tags,field_image',
'user--user' => 'name',
],
'include' => 'uid,field_tags,field_image',
]);
$response = new ResourceResponse();
$normalized = $this
->container
->get('serializer.normalizer.jsonapi_document_toplevel.jsonapi')
->normalize(
new JsonApiDocumentTopLevel($this->node),
'api_json',
[
'request' => $request,
'resource_type' => $resource_type,
'cacheable_metadata' => $response->getCacheableMetadata(),
]
);
$this->assertSame($normalized['data']['attributes']['title'], 'dummy_title');
$this->assertEquals($normalized['data']['id'], $this->node->uuid());
$this->assertSame([
'data' => [
'type' => 'node_type--node_type',
'id' => NodeType::load('article')->uuid(),
],
'links' => [
'self' => 'dummy_entity_link',
'related' => 'dummy_entity_link',
],
], $normalized['data']['relationships']['type']);
$this->assertTrue(!isset($normalized['data']['attributes']['created']));
$this->assertEquals([
'alt' => 'test alt',
'title' => 'test title',
'width' => 10,
'height' => 11,
], $normalized['data']['relationships']['field_image']['data']['meta']);
$this->assertSame('node--article', $normalized['data']['type']);
$this->assertEquals([
'data' => [
'type' => 'user--user',
'id' => $this->user->uuid(),
],
'links' => [
'self' => 'dummy_entity_link',
'related' => 'dummy_entity_link',
],
], $normalized['data']['relationships']['uid']);
$this->assertEquals(
"The current user is not allowed to GET the selected resource. The 'access user profiles' permission is required and the user must be active.",
$normalized['meta']['errors'][0]['detail']
);
$this->assertEquals(403, $normalized['meta']['errors'][0]['status']);
$this->assertEquals($this->term1->uuid(), $normalized['included'][0]['id']);
$this->assertEquals('taxonomy_term--tags', $normalized['included'][0]['type']);
$this->assertEquals($this->term1->label(), $normalized['included'][0]['attributes']['name']);
$this->assertTrue(!isset($normalized['included'][0]['attributes']['created']));
// Make sure that the cache tags for the includes and the requested entities
// are bubbling as expected.
$this->assertSame(
['file:1', 'node:1', 'taxonomy_term:1', 'taxonomy_term:2'],
$response->getCacheableMetadata()->getCacheTags()
);
$this->assertSame(
Cache::PERMANENT,
$response->getCacheableMetadata()->getCacheMaxAge()
);
}
/**
* @covers ::normalize
*/
public function testNormalizeRelated() {
list($request, $resource_type) = $this->generateProphecies('node', 'article', 'uid');
$request->query = new ParameterBag([
'fields' => [
'user--user' => 'name,roles',
],
'include' => 'roles',
]);
$document_wrapper = $this->prophesize(JsonApiDocumentTopLevel::class);
$author = $this->node->get('uid')->entity;
$document_wrapper->getData()->willReturn($author);
$response = new ResourceResponse();
$normalized = $this
->container
->get('serializer.normalizer.jsonapi_document_toplevel.jsonapi')
->normalize(
$document_wrapper->reveal(),
'api_json',
[
'request' => $request,
'resource_type' => $resource_type,
'cacheable_metadata' => $response->getCacheableMetadata(),
]
);
$this->assertSame($normalized['data']['attributes']['name'], 'user1');
$this->assertEquals($normalized['data']['id'], User::load(1)->uuid());
$this->assertEquals($normalized['data']['type'], 'user--user');
// Make sure that the cache tags for the includes and the requested entities
// are bubbling as expected.
$this->assertSame(['user:1'], $response->getCacheableMetadata()
->getCacheTags());
$this->assertSame(Cache::PERMANENT, $response->getCacheableMetadata()
->getCacheMaxAge());
}
/**
* @covers ::normalize
*/
public function testNormalizeUuid() {
list($request, $resource_type) = $this->generateProphecies('node', 'article', 'uuid');
$document_wrapper = $this->prophesize(JsonApiDocumentTopLevel::class);
$document_wrapper->getData()->willReturn($this->node);
$request->query = new ParameterBag([
'fields' => [
'node--article' => 'title,type,uid,field_tags',
'user--user' => 'name',
],
'include' => 'uid,field_tags',
]);
$response = new ResourceResponse();
$normalized = $this
->container
->get('serializer.normalizer.jsonapi_document_toplevel.jsonapi')
->normalize(
$document_wrapper->reveal(),
'api_json',
[
'request' => $request,
'resource_type' => $resource_type,
'cacheable_metadata' => $response->getCacheableMetadata(),
]
);
$this->assertStringMatchesFormat($this->node->uuid(), $normalized['data']['id']);
$this->assertEquals($this->node->type->entity->uuid(), $normalized['data']['relationships']['type']['data']['id']);
$this->assertEquals($this->user->uuid(), $normalized['data']['relationships']['uid']['data']['id']);
$this->assertFalse(empty($normalized['included'][0]['id']));
$this->assertFalse(empty($normalized['meta']['errors']));
$this->assertEquals($this->term1->uuid(), $normalized['included'][0]['id']);
// Make sure that the cache tags for the includes and the requested entities
// are bubbling as expected.
$this->assertSame(
['node:1', 'taxonomy_term:1', 'taxonomy_term:2'],
$response->getCacheableMetadata()->getCacheTags()
);
}
/**
* @covers ::normalize
*/
public function testNormalizeException() {
list($request, $resource_type) = $this->generateProphecies('node', 'article', 'id');
$document_wrapper = $this->prophesize(JsonApiDocumentTopLevel::class);
$document_wrapper->getData()->willReturn($this->node);
$request->query = new ParameterBag([
'fields' => [
'node--article' => 'title,type,uid',
'user--user' => 'name',
],
'include' => 'uid',
]);
$response = new ResourceResponse();
$normalized = $this
->container
->get('serializer')
->serialize(
new BadRequestHttpException('Lorem'),
'api_json',
[
'request' => $request,
'resource_type' => $resource_type,
'cacheable_metadata' => $response->getCacheableMetadata(),
'data_wrapper' => 'errors',
]
);
$normalized = Json::decode($normalized);
$this->assertNotEmpty($normalized['errors']);
$this->assertArrayNotHasKey('data', $normalized);
$this->assertEquals(400, $normalized['errors'][0]['status']);
$this->assertEquals('Lorem', $normalized['errors'][0]['detail']);
$this->assertEquals(['info' => 'http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1'], $normalized['errors'][0]['links']);
}
/**
* @covers ::normalize
*/
public function testNormalizeConfig() {
list($request, $resource_type) = $this->generateProphecies('node_type', 'node_type', 'id');
$document_wrapper = $this->prophesize(JsonApiDocumentTopLevel::class);
$document_wrapper->getData()->willReturn($this->nodeType);
$request->query = new ParameterBag([
'fields' => [
'node_type--node_type' => 'uuid,display_submitted',
],
'include' => NULL,
]);
$response = new ResourceResponse();
$normalized = $this
->container
->get('serializer.normalizer.jsonapi_document_toplevel.jsonapi')
->normalize($document_wrapper->reveal(), 'api_json', [
'request' => $request,
'resource_type' => $resource_type,
'cacheable_metadata' => $response->getCacheableMetadata(),
]);
$this->assertTrue(empty($normalized['data']['attributes']['type']));
$this->assertTrue(!empty($normalized['data']['attributes']['uuid']));
$this->assertSame($normalized['data']['attributes']['display_submitted'], TRUE);
$this->assertSame($normalized['data']['id'], NodeType::load('article')->uuid());
$this->assertSame($normalized['data']['type'], 'node_type--node_type');
// Make sure that the cache tags for the includes and the requested entities
// are bubbling as expected.
$this->assertSame(['config:node.type.article'], $response->getCacheableMetadata()
->getCacheTags());
}
/**
* Try to POST a node and check if it exists afterwards.
*
* @covers ::denormalize
*/
public function testDenormalize() {
$payload = '{"type":"article", "data":{"attributes":{"title":"Testing article"}}}';
list($request, $resource_type) = $this->generateProphecies('node', 'article', 'id');
$node = $this
->container
->get('serializer.normalizer.jsonapi_document_toplevel.jsonapi')
->denormalize(Json::decode($payload), JsonApiDocumentTopLevelNormalizer::class, 'api_json', [
'request' => $request,
'resource_type' => $resource_type,
]);
$this->assertInstanceOf('\Drupal\node\Entity\Node', $node);
$this->assertSame('Testing article', $node->getTitle());
}
/**
* Try to POST a node and check if it exists afterwards.
*
* @covers ::denormalize
*/
public function testDenormalizeUuid() {
$configurations = [
// Good data.
[
[
[$this->term2->uuid(), $this->term1->uuid()],
$this->user2->uuid(),
],
[
[$this->term2->id(), $this->term1->id()],
$this->user2->id(),
],
],
// Good data, without any tags.
[
[
[],
$this->user2->uuid(),
],
[
[],
$this->user2->id(),
],
],
// Bad data in first tag.
[
[
['invalid-uuid', $this->term1->uuid()],
$this->user2->uuid(),
],
[
[$this->term1->id()],
$this->user2->id(),
],
],
// Bad data in user and first tag.
[
[
['invalid-uuid', $this->term1->uuid()],
'also-invalid-uuid',
],
[
[$this->term1->id()],
NULL,
],
],
];
foreach ($configurations as $configuration) {
list($payload_data, $expected) = $this->denormalizeUuidProviderBuilder($configuration);
$payload = Json::encode($payload_data);
list($request, $resource_type) = $this->generateProphecies('node', 'article');
$this->container->get('request_stack')->push($request);
$node = $this
->container
->get('serializer.normalizer.jsonapi_document_toplevel.jsonapi')
->denormalize(Json::decode($payload), JsonApiDocumentTopLevelNormalizer::class, 'api_json', [
'request' => $request,
'resource_type' => $resource_type,
]);
/* @var \Drupal\node\Entity\Node $node */
$this->assertInstanceOf('\Drupal\node\Entity\Node', $node);
$this->assertSame('Testing article', $node->getTitle());
if (!empty($expected['user_id'])) {
$owner = $node->getOwner();
$this->assertEquals($expected['user_id'], $owner->id());
}
$tags = $node->get('field_tags')->getValue();
if (!empty($expected['tag_ids'][0])) {
$this->assertEquals($expected['tag_ids'][0], $tags[0]['target_id']);
}
else {
$this->assertArrayNotHasKey(0, $tags);
}
if (!empty($expected['tag_ids'][1])) {
$this->assertEquals($expected['tag_ids'][1], $tags[1]['target_id']);
}
else {
$this->assertArrayNotHasKey(1, $tags);
}
}
}
/**
* Try to POST a node with related resource of invalid type, as well as one
* with no type.
*/
public function testDenormalizeInvalidTypeAndNoType() {
$payload_data = [
'type' => 'node--article',
'data' => [
'attributes' => [
'title' => 'Testing article',
'id' => '33095485-70D2-4E51-A309-535CC5BC0115',
],
'relationships' => [
'uid' => [
'data' => [
'type' => 'user--user',
'id' => $this->user2->uuid(),
],
],
'field_tags' => [
'data' => [
[
'type' => 'foobar',
'id' => $this->term1->uuid(),
],
],
],
],
],
];
// Test relationship member with invalid type.
$payload = Json::encode($payload_data);
list($request, $resource_type) = $this->generateProphecies('node', 'article');
$this->container->get('request_stack')->push($request);
try {
$this->container->get('serializer.normalizer.jsonapi_document_toplevel.jsonapi')
->denormalize(Json::decode($payload), JsonApiDocumentTopLevelNormalizer::class, 'api_json', [
'request' => $request,
'resource_type' => $resource_type,
]);
$this->fail('No assertion thrown for invalid type');
}
catch (BadRequestHttpException $e) {
$this->assertEquals("Invalid type specified for related resource: 'foobar'", $e->getMessage());
}
// Test relationship member with no type.
unset($payload_data['data']['relationships']['field_tags']['data'][0]['type']);
$payload = Json::encode($payload_data);
list($request, $resource_type) = $this->generateProphecies('node', 'article');
$this->container->get('request_stack')->push($request);
try {
$this->container->get('serializer.normalizer.jsonapi_document_toplevel.jsonapi')
->denormalize(Json::decode($payload), JsonApiDocumentTopLevelNormalizer::class, 'api_json', [
'request' => $request,
'resource_type' => $resource_type,
]);
$this->fail('No assertion thrown for missing type');
}
catch (BadRequestHttpException $e) {
$this->assertEquals("No type specified for related resource", $e->getMessage());
}
}
/**
* We cannot use a PHPUnit data provider because our data depends on $this.
*
* @param array $options
*
* @return array
* The test data.
*/
protected function denormalizeUuidProviderBuilder($options) {
list($input, $expected) = $options;
list($input_tag_uuids, $input_user_uuid) = $input;
list($expected_tag_ids, $expected_user_id) = $expected;
$node = [
[
'type' => 'node--article',
'data' => [
'attributes' => [
'title' => 'Testing article',
'id' => '33095485-70D2-4E51-A309-535CC5BC0115',
],
'relationships' => [
'uid' => [
'data' => [
'type' => 'user--user',
'id' => $input_user_uuid,
],
],
'field_tags' => [
'data' => [],
],
],
],
],
[
'tag_ids' => $expected_tag_ids,
'user_id' => $expected_user_id,
],
];
if (isset($input_tag_uuids[0])) {
$node[0]['data']['relationships']['field_tags']['data'][0] = [
'type' => 'taxonomy_term--tags',
'id' => $input_tag_uuids[0],
];
}
if (isset($input_tag_uuids[1])) {
$node[0]['data']['relationships']['field_tags']['data'][1] = [
'type' => 'taxonomy_term--tags',
'id' => $input_tag_uuids[1],
];
}
return $node;
}
/**
* Generates the prophecies for the mocked entity request.
*
* @param string $entity_type_id
* The ID of the entity type. Ex: node.
* @param string $bundle
* The bundle. Ex: article.
*
* @return array
* A numeric array containing the request and the ResourceType.
*/
protected function generateProphecies($entity_type_id, $bundle, $related_property = NULL) {
$path = sprintf('/%s/%s', $entity_type_id, $bundle);
$path = $related_property ?
sprintf('%s/%s', $path, $related_property) :
$path;
$route = new Route($path, [
'_on_relationship' => NULL,
], [
'_entity_type' => $entity_type_id,
'_bundle' => $bundle,
]);
$request = new Request([], [], [
RouteObjectInterface::ROUTE_OBJECT => $route,
]);
/* @var \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager */
$entity_type_manager = $this->container->get('entity_type.manager');
$resource_type = new ResourceType(
$entity_type_id,
$bundle,
$entity_type_manager->getDefinition($entity_type_id)->getClass()
);
/* @var \Symfony\Component\HttpFoundation\RequestStack $request_stack */
$request_stack = $this->container->get('request_stack');
$request_stack->push($request);
$this->container->set('request_stack', $request_stack);
$this->container->get('serializer');
return [$request, $resource_type];
}
}
|
chriscalip/cdemo
|
web/modules/contrib/jsonapi/tests/src/Kernel/Normalizer/JsonApiDocumentTopLevelNormalizerTest.php
|
PHP
|
gpl-2.0
| 22,214 |
/* Definitions for LM32 running Linux-based GNU systems using ELF
Copyright (C) 1993-2021 Free Software Foundation, Inc.
Contributed by Philip Blundell <[email protected]>
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/>. */
/* elfos.h should have already been included. Now just override
any conflicting definitions and add any extras. */
/* The GNU C++ standard library requires that these macros be defined. */
#undef CPLUSPLUS_CPP_SPEC
#define CPLUSPLUS_CPP_SPEC "-D_GNU_SOURCE %(cpp)"
/* Now we define the strings used to build the spec file. */
#undef LIB_SPEC
#define LIB_SPEC \
"%{pthread:-lpthread} \
%{shared:-lc} \
%{!shared:-lc} "
#define LIBGCC_SPEC "-lgcc"
/* Provide a STARTFILE_SPEC appropriate for GNU/Linux. Here we add
the GNU/Linux magical crtbegin.o file (see crtstuff.c) which
provides part of the support for getting C++ file-scope static
object constructed before entering `main'. */
#undef STARTFILE_SPEC
#define STARTFILE_SPEC \
"%{!shared: \
%{pg:gcrt1.o%s} %{!pg:%{p:gcrt1.o%s} \
%{!p:%{profile:gcrt1.o%s} \
%{!profile:crt1.o%s}}}} \
crti.o%s %{!shared:crtbegin.o%s} %{shared:crtbeginS.o%s}"
/* Provide a ENDFILE_SPEC appropriate for GNU/Linux. Here we tack on
the GNU/Linux magical crtend.o file (see crtstuff.c) which
provides part of the support for getting C++ file-scope static
object constructed before entering `main', followed by a normal
GNU/Linux "finalizer" file, `crtn.o'. */
#undef ENDFILE_SPEC
#define ENDFILE_SPEC \
"%{!shared:crtend.o%s} %{shared:crtendS.o%s} crtn.o%s"
#undef LINK_SPEC
#define LINK_SPEC "%{h*} \
%{static:-Bstatic} \
%{shared:-shared} \
%{symbolic:-Bsymbolic} \
%{rdynamic:-export-dynamic} \
-dynamic-linker /lib/ld-linux.so.2"
#define TARGET_OS_CPP_BUILTINS() GNU_USER_TARGET_OS_CPP_BUILTINS()
#define LINK_GCC_C_SEQUENCE_SPEC \
"%{static|static-pie:--start-group} %G %{!nolibc:%L} \
%{static|static-pie:--end-group}%{!static:%{!static-pie:%G}}"
#undef CC1_SPEC
#define CC1_SPEC "%{G*} %{!fno-PIC:-fPIC}"
|
Gurgel100/gcc
|
gcc/config/lm32/uclinux-elf.h
|
C
|
gpl-2.0
| 2,714 |
<?php
if (!defined('MEDIAWIKI')) die();
/**
* MwRdf.php -- RDF framework for MediaWiki
* Copyright 2005,2006 Evan Prodromou <[email protected]>
* Copyright 2007 Mark Jaroski
*
* 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 *
* @author Evan Prodromou <[email protected]>
* @author Mark Jaroski <[email protected]>
* @package MediaWiki
* @subpackage Extensions
*/
class MwRdf_Vocabulary_Rdf extends MwRdf_Vocabulary {
//base uri
const RDF_NAMESPACE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
public function getNS() { return self::RDF_NAMESPACE; }
// Terms
public $Alt;
public $Bag;
public $Property;
public $Seq;
public $Statement;
public $List;
public $nil;
public $type;
public $rest;
public $first;
public $subject;
public $predicate;
public $object;
public $Description;
public $ID;
public $about;
public $aboutEach;
public $aboutEachPrefix;
public $bagID;
public $resource;
public $parseType;
public $Literal;
public $Resource;
public $li;
public $nodeID;
public $datatype;
public $seeAlso;
public $a;
// a special alias to be reassigned to type
public function __construct() {
parent::__construct();
$this->a = $this->type;
}
}
|
SuriyaaKudoIsc/wikia-app-test
|
extensions/RdfRedland/Vocabularies/Rdf.php
|
PHP
|
gpl-2.0
| 1,870 |
import shutil
import os
import mdtraj as md
from openmoltools.utils import import_, enter_temp_directory, run_antechamber, create_ffxml_file
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG, format="LOG: %(message)s")
# Note: We recommend having every function return *copies* of input, to avoid headaches associated with in-place changes
def get_charges(molecule, max_confs=800, strictStereo=True, keep_confs=None):
"""Generate charges for an OpenEye OEMol molecule.
Parameters
----------
molecule : OEMol
Molecule for which to generate conformers.
Omega will be used to generate max_confs conformations.
max_confs : int, optional, default=800
Max number of conformers to generate
strictStereo : bool, optional, default=True
If False, permits smiles strings with unspecified stereochemistry.
See https://docs.eyesopen.com/omega/usage.html
keep_confs : int, optional, default=None
If None, apply the charges to the provided conformation and return
this conformation. Otherwise, return some or all of the generated
conformations. If -1, all generated conformations are returned.
Otherwise, keep_confs = N will return an OEMol with up to N
generated conformations. Multiple conformations are still used to
*determine* the charges.
Returns
-------
charged_copy : OEMol
A molecule with OpenEye's recommended AM1BCC charge selection scheme.
Notes
-----
Roughly follows
http://docs.eyesopen.com/toolkits/cookbook/python/modeling/am1-bcc.html
"""
oechem = import_("openeye.oechem")
if not oechem.OEChemIsLicensed(): raise(ImportError("Need License for OEChem!"))
oequacpac = import_("openeye.oequacpac")
if not oequacpac.OEQuacPacIsLicensed(): raise(ImportError("Need License for oequacpac!"))
molecule = normalize_molecule(molecule)
charged_copy = generate_conformers(molecule, max_confs=max_confs, strictStereo=strictStereo) # Generate up to max_confs conformers
status = oequacpac.OEAssignPartialCharges(charged_copy, oequacpac.OECharges_AM1BCCSym) # AM1BCCSym recommended by Chris Bayly to KAB+JDC, Oct. 20 2014.
if not status:
raise(RuntimeError("OEAssignPartialCharges returned error code %d" % status))
#Determine conformations to return
if keep_confs == None:
#If returning original conformation
original = molecule.GetCoords()
#Delete conformers over 1
for k, conf in enumerate( charged_copy.GetConfs() ):
if k > 0:
charged_copy.DeleteConf(conf)
#Copy coordinates to single conformer
charged_copy.SetCoords( original )
elif keep_confs > 0:
#Otherwise if a number is provided, return this many confs if available
for k, conf in enumerate( charged_copy.GetConfs() ):
if k > keep_confs - 1:
charged_copy.DeleteConf(conf)
elif keep_confs == -1:
#If we want all conformations, continue
pass
else:
#Not a valid option to keep_confs
raise(ValueError('Not a valid option to keep_confs in get_charges.'))
return charged_copy
def normalize_molecule(molecule):
"""Normalize a copy of the molecule by checking aromaticity, adding explicit hydrogens, and renaming by IUPAC name.
Parameters
----------
molecule : OEMol
the molecule to be normalized.
Returns
-------
molcopy : OEMol
A (copied) version of the normalized molecule
"""
oechem = import_("openeye.oechem")
if not oechem.OEChemIsLicensed(): raise(ImportError("Need License for OEChem!"))
oeiupac = import_("openeye.oeiupac")
if not oeiupac.OEIUPACIsLicensed(): raise(ImportError("Need License for OEOmega!"))
molcopy = oechem.OEMol(molecule)
# Assign aromaticity.
oechem.OEAssignAromaticFlags(molcopy, oechem.OEAroModelOpenEye)
# Add hydrogens.
oechem.OEAddExplicitHydrogens(molcopy)
# Set title to IUPAC name.
name = oeiupac.OECreateIUPACName(molcopy)
molcopy.SetTitle(name)
# Check for any missing atom names, if found reassign all of them.
if any([atom.GetName() == '' for atom in molcopy.GetAtoms()]):
oechem.OETriposAtomNames(molcopy)
return molcopy
def iupac_to_oemol(iupac_name):
"""Create a OEMolBuilder from a iupac name.
Parameters
----------
iupac_name : str
IUPAC name of desired molecule.
Returns
-------
molecule : OEMol
A normalized molecule with desired iupac name
"""
oechem = import_("openeye.oechem")
if not oechem.OEChemIsLicensed(): raise(ImportError("Need License for OEChem!"))
oeiupac = import_("openeye.oeiupac")
if not oeiupac.OEIUPACIsLicensed(): raise(ImportError("Need License for OEOmega!"))
# Create an OEMol molecule from IUPAC name.
molecule = oechem.OEMol() # create a molecule
# Populate the MoleCule from the IUPAC name
if not oeiupac.OEParseIUPACName(molecule, iupac_name):
raise ValueError("The supplied IUPAC name '%s' could not be parsed." % iupac_name)
molecule = normalize_molecule(molecule)
return molecule
def smiles_to_oemol(smiles):
"""Create a OEMolBuilder from a smiles string.
Parameters
----------
smiles : str
SMILES representation of desired molecule.
Returns
-------
molecule : OEMol
A normalized molecule with desired smiles string.
"""
oechem = import_("openeye.oechem")
if not oechem.OEChemIsLicensed(): raise(ImportError("Need License for OEChem!"))
molecule = oechem.OEMol()
if not oechem.OEParseSmiles(molecule, smiles):
raise ValueError("The supplied SMILES '%s' could not be parsed." % smiles)
molecule = normalize_molecule(molecule)
return molecule
def generate_conformers(molecule, max_confs=800, strictStereo=True, ewindow=15.0, rms_threshold=1.0, strictTypes = True):
"""Generate conformations for the supplied molecule
Parameters
----------
molecule : OEMol
Molecule for which to generate conformers
max_confs : int, optional, default=800
Max number of conformers to generate. If None, use default OE Value.
strictStereo : bool, optional, default=True
If False, permits smiles strings with unspecified stereochemistry.
strictTypes : bool, optional, default=True
If True, requires that Omega have exact MMFF types for atoms in molecule; otherwise, allows the closest atom type of the same element to be used.
Returns
-------
molcopy : OEMol
A multi-conformer molecule with up to max_confs conformers.
Notes
-----
Roughly follows
http://docs.eyesopen.com/toolkits/cookbook/python/modeling/am1-bcc.html
"""
oechem = import_("openeye.oechem")
if not oechem.OEChemIsLicensed(): raise(ImportError("Need License for OEChem!"))
oeomega = import_("openeye.oeomega")
if not oeomega.OEOmegaIsLicensed(): raise(ImportError("Need License for OEOmega!"))
molcopy = oechem.OEMol(molecule)
omega = oeomega.OEOmega()
# These parameters were chosen to match http://docs.eyesopen.com/toolkits/cookbook/python/modeling/am1-bcc.html
omega.SetMaxConfs(max_confs)
omega.SetIncludeInput(True)
omega.SetCanonOrder(False)
omega.SetSampleHydrogens(True) # Word to the wise: skipping this step can lead to significantly different charges!
omega.SetEnergyWindow(ewindow)
omega.SetRMSThreshold(rms_threshold) # Word to the wise: skipping this step can lead to significantly different charges!
omega.SetStrictStereo(strictStereo)
omega.SetStrictAtomTypes(strictTypes)
omega.SetIncludeInput(False) # don't include input
if max_confs is not None:
omega.SetMaxConfs(max_confs)
status = omega(molcopy) # generate conformation
if not status:
raise(RuntimeError("omega returned error code %d" % status))
return molcopy
def get_names_to_charges(molecule):
"""Return a dictionary of atom names and partial charges, as well as a string representation.
Parameters
----------
molecule : OEMol
Molecule for which to grab charges
Returns
-------
data : dictionary
A dictinoary whose (key, val) pairs are the atom names and partial
charges, respectively.
molrepr : str
A string representation of data
"""
oechem = import_("openeye.oechem")
if not oechem.OEChemIsLicensed(): raise(ImportError("Need License for oechem!"))
molcopy = oechem.OEMol(molecule)
molrepr = ""
data = {}
for atom in molcopy.GetAtoms():
name = atom.GetName()
charge = atom.GetPartialCharge()
data[name] = charge
molrepr += "%s %f \n" % (name, charge)
return data, molrepr
def molecule_to_mol2(molecule, tripos_mol2_filename=None, conformer=0, residue_name="MOL"):
"""Convert OE molecule to tripos mol2 file.
Parameters
----------
molecule : openeye.oechem.OEGraphMol
The molecule to be converted.
tripos_mol2_filename : str, optional, default=None
Output filename. If None, will create a filename similar to
name.tripos.mol2, where name is the name of the OE molecule.
conformer : int, optional, default=0
Save this frame
residue_name : str, optional, default="MOL"
OpenEye writes mol2 files with <0> as the residue / ligand name.
This chokes many mol2 parsers, so we replace it with a string of
your choosing.
Returns
-------
tripos_mol2_filename : str
Filename of output tripos mol2 file
"""
oechem = import_("openeye.oechem")
if not oechem.OEChemIsLicensed(): raise(ImportError("Need License for oechem!"))
# Get molecule name.
molecule_name = molecule.GetTitle()
logger.debug(molecule_name)
# Write molecule as Tripos mol2.
if tripos_mol2_filename is None:
tripos_mol2_filename = molecule_name + '.tripos.mol2'
ofs = oechem.oemolostream(tripos_mol2_filename)
ofs.SetFormat(oechem.OEFormat_MOL2H)
for k, mol in enumerate(molecule.GetConfs()):
if k == conformer:
oechem.OEWriteMolecule(ofs, mol)
ofs.close()
# Replace <0> substructure names with valid text.
infile = open(tripos_mol2_filename, 'r')
lines = infile.readlines()
infile.close()
newlines = [line.replace('<0>', residue_name) for line in lines]
outfile = open(tripos_mol2_filename, 'w')
outfile.writelines(newlines)
outfile.close()
return molecule_name, tripos_mol2_filename
def oemols_to_ffxml(molecules, base_molecule_name="lig"):
"""Generate an OpenMM ffxml object and MDTraj trajectories from multiple OEMols
Parameters
----------
molecules : list(OEMole)
Molecules WITH CHARGES. Each can have multiple conformations.
WILL GIVE UNDEFINED RESULTS IF NOT CHARGED.
base_molecule_name : str, optional, default='lig'
Base name of molecule to use inside parameter files.
Returns
-------
trajectories : list(mdtraj.Trajectory)
List of MDTraj Trajectories for molecule. May contain multiple frames
ffxml : StringIO
StringIO representation of ffxml file.
Notes
-----
We allow multiple different molecules at once so that they can all be
included in a single ffxml file, which is currently the only recommended
way to simulate multiple GAFF molecules in a single simulation. For most
applications, you will have just a single molecule:
e.g. molecules = [my_oemol]
The resulting ffxml StringIO object can be directly input to OpenMM e.g.
`forcefield = app.ForceField(ffxml)`
This will generate a lot of temporary files, so you may want to use
utils.enter_temp_directory() to avoid clutter.
"""
all_trajectories = []
gaff_mol2_filenames = []
frcmod_filenames = []
print(os.getcwd())
for i, molecule in enumerate(molecules):
trajectories = []
for j in range(molecule.NumConfs()):
molecule_name = "%s-%d-%d" % (base_molecule_name, i, j)
mol2_filename = "./%s.mol2" % molecule_name
_unused = molecule_to_mol2(molecule, mol2_filename, conformer=j)
gaff_mol2_filename, frcmod_filename = run_antechamber(molecule_name, mol2_filename, charge_method=None) # It's redundant to run antechamber on each frame, fix me later.
traj = md.load(gaff_mol2_filename)
trajectories.append(traj)
if j == 0: # Only need 1 frame of forcefield files
gaff_mol2_filenames.append(gaff_mol2_filename)
frcmod_filenames.append(frcmod_filename)
# Create a trajectory with all frames of the current molecule
traj = trajectories[0].join(trajectories[1:])
all_trajectories.append(traj)
ffxml = create_ffxml_file(gaff_mol2_filenames, frcmod_filenames, override_mol2_residue_name=base_molecule_name)
return all_trajectories, ffxml
def smiles_to_antechamber(smiles_string, gaff_mol2_filename, frcmod_filename, residue_name="MOL", strictStereo=False):
"""Build a molecule from a smiles string and run antechamber,
generating GAFF mol2 and frcmod files from a smiles string. Charges
will be generated using the OpenEye QuacPac AM1-BCC implementation.
Parameters
----------
smiles_string : str
Smiles string of molecule to construct and charge
gaff_mol2_filename : str
Filename of mol2 file output of antechamber, with charges
created from openeye
frcmod_filename : str
Filename of frcmod file output of antechamber. Most likely
this file will be almost empty, at least for typical molecules.
residue_name : str, optional, default="MOL"
OpenEye writes mol2 files with <0> as the residue / ligand name.
This chokes many mol2 parsers, so we replace it with a string of
your choosing. This might be useful for downstream applications
if the residue names are required to be unique.
strictStereo : bool, optional, default=False
If False, permits smiles strings with unspecified stereochemistry.
See https://docs.eyesopen.com/omega/usage.html
"""
oechem = import_("openeye.oechem")
if not oechem.OEChemIsLicensed(): raise(ImportError("Need License for oechem!"))
# Get the absolute path so we can find these filenames from inside a temporary directory.
gaff_mol2_filename = os.path.abspath(gaff_mol2_filename)
frcmod_filename = os.path.abspath(frcmod_filename)
m = smiles_to_oemol(smiles_string)
m = get_charges(m, strictStereo=strictStereo, keep_confs=1)
with enter_temp_directory(): # Avoid dumping 50 antechamber files in local directory.
_unused = molecule_to_mol2(m, "./tmp.mol2", residue_name=residue_name)
net_charge = oechem.OENetCharge(m)
tmp_gaff_mol2_filename, tmp_frcmod_filename = run_antechamber("tmp", "./tmp.mol2", charge_method=None, net_charge=net_charge) # USE OE AM1BCC charges!
shutil.copy(tmp_gaff_mol2_filename, gaff_mol2_filename)
shutil.copy(tmp_frcmod_filename, frcmod_filename)
|
Clyde-fare/openmoltools
|
openmoltools/openeye.py
|
Python
|
gpl-2.0
| 15,515 |
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2013 Zbigniew Jędrzejewski-Szmek <[email protected]>
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 <Python.h>
#include <systemd/sd-messages.h>
#include "pyutil.h"
#include "log.h"
#include "util.h"
#include "macro.h"
PyDoc_STRVAR(module__doc__,
"Python interface to the libsystemd-id128 library.\n\n"
"Provides SD_MESSAGE_* constants and functions to query and generate\n"
"128-bit unique identifiers."
);
PyDoc_STRVAR(randomize__doc__,
"randomize() -> UUID\n\n"
"Return a new random 128-bit unique identifier.\n"
"Wraps sd_id128_randomize(3)."
);
PyDoc_STRVAR(get_machine__doc__,
"get_machine() -> UUID\n\n"
"Return a 128-bit unique identifier for this machine.\n"
"Wraps sd_id128_get_machine(3)."
);
PyDoc_STRVAR(get_boot__doc__,
"get_boot() -> UUID\n\n"
"Return a 128-bit unique identifier for this boot.\n"
"Wraps sd_id128_get_boot(3)."
);
static PyObject* make_uuid(sd_id128_t id) {
_cleanup_Py_DECREF_ PyObject
*uuid = NULL, *UUID = NULL, *bytes = NULL,
*args = NULL, *kwargs = NULL;
uuid = PyImport_ImportModule("uuid");
if (!uuid)
return NULL;
UUID = PyObject_GetAttrString(uuid, "UUID");
bytes = PyBytes_FromStringAndSize((const char*) &id.bytes, sizeof(id.bytes));
args = Py_BuildValue("()");
kwargs = PyDict_New();
if (!UUID || !bytes || !args || !kwargs)
return NULL;
if (PyDict_SetItemString(kwargs, "bytes", bytes) < 0)
return NULL;
return PyObject_Call(UUID, args, kwargs);
}
#define helper(name) \
static PyObject *name(PyObject *self, PyObject *args) { \
sd_id128_t id; \
int r; \
\
assert(args == NULL); \
\
r = sd_id128_##name(&id); \
if (r < 0) { \
errno = -r; \
return PyErr_SetFromErrno(PyExc_IOError); \
} \
\
return make_uuid(id); \
}
helper(randomize)
helper(get_machine)
helper(get_boot)
static PyMethodDef methods[] = {
{ "randomize", randomize, METH_NOARGS, randomize__doc__},
{ "get_machine", get_machine, METH_NOARGS, get_machine__doc__},
{ "get_boot", get_boot, METH_NOARGS, get_boot__doc__},
{ NULL, NULL, 0, NULL } /* Sentinel */
};
static int add_id(PyObject *module, const char* name, sd_id128_t id) {
PyObject *obj;
obj = make_uuid(id);
if (!obj)
return -1;
return PyModule_AddObject(module, name, obj);
}
#if PY_MAJOR_VERSION < 3
DISABLE_WARNING_MISSING_PROTOTYPES;
PyMODINIT_FUNC initid128(void) {
PyObject *m;
m = Py_InitModule3("id128", methods, module__doc__);
if (m == NULL)
return;
/* a series of lines like 'add_id() ;' follow */
#define JOINER ;
#include "id128-constants.h"
#undef JOINER
PyModule_AddStringConstant(m, "__version__", PACKAGE_VERSION);
}
REENABLE_WARNING;
#else
static struct PyModuleDef module = {
PyModuleDef_HEAD_INIT,
"id128", /* name of module */
module__doc__, /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module */
methods
};
DISABLE_WARNING_MISSING_PROTOTYPES;
PyMODINIT_FUNC PyInit_id128(void) {
PyObject *m;
m = PyModule_Create(&module);
if (m == NULL)
return NULL;
if ( /* a series of lines like 'add_id() ||' follow */
#define JOINER ||
#include "id128-constants.h"
#undef JOINER
PyModule_AddStringConstant(m, "__version__", PACKAGE_VERSION)) {
Py_DECREF(m);
return NULL;
}
return m;
}
REENABLE_WARNING;
#endif
|
flonatel/systemd-pne1
|
src/python-systemd/id128.c
|
C
|
gpl-2.0
| 5,258 |
#
# Makefile for the linux kernel.
#
obj-y := timer.o irq.o common.o serial.o clock.o
obj-y += dma.o gpiolib.o pm.o suspend.o
obj-$(CONFIG_MACH_PHY3250) += phy3250.o
obj-$(CONFIG_MACH_EA3250) += ea3250.o
obj-$(CONFIG_MACH_FDI3250) += fdi3250.o
|
dext3r/lpc3xxx-ea3250v2
|
arch/arm/mach-lpc32xx/Makefile
|
Makefile
|
gpl-2.0
| 247 |
package server.tasks;
import communication.Protocol;
import server.TaskManager;
import java.io.OutputStream;
import java.net.Socket;
import java.util.LinkedList;
public class ListTask extends TaskThread {
public ListTask(Socket connectionSocket, Protocol.ServerRequest request, TaskManager taskManager) {
super(connectionSocket, request, taskManager);
}
@Override
public void run() {
Protocol.ListTasksResponse.Builder submitTaskResponse = Protocol.ListTasksResponse.newBuilder();
try {
LinkedList<Protocol.ListTasksResponse.TaskDescription> tasks = taskManager.getTasks();
submitTaskResponse.addAllTasks(tasks).setStatus(Protocol.Status.OK);
} catch (Exception e) {
e.printStackTrace();
submitTaskResponse.setStatus(Protocol.Status.ERROR);
}
response.setListResponse(submitTaskResponse);
super.run();
}
}
|
dvolkow/hpcourse
|
csc/2016/jdv/src/main/java/server/tasks/ListTask.java
|
Java
|
gpl-2.0
| 935 |
/*
* include/linux/goodix_touch.h
*
* Copyright (C) 2010 - 2011 Goodix, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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.
*
*/
#ifndef _LINUX_GOODIX_TOUCH_H
#define _LINUX_GOODIX_TOUCH_H
#include <linux/earlysuspend.h>
#include <linux/hrtimer.h>
#include <linux/i2c.h>
#include <linux/input.h>
//#include <linux/51boardpcb.h>
//*************************TouchScreen Work Part*****************************
#define GOODIX_I2C_NAME "Goodix-TS"
//define default resolution of the touchscreen
//#define TOUCH_MAX_HEIGHT 800//1024//4096
//#define TOUCH_MAX_WIDTH 600//600//4096
/*
#define INT_PORT S3C64XX_GPL(10)//S3C64XX_GPN(15) //Int IO port S3C64XX_GPL(10)
#ifdef INT_PORT
#define TS_INT gpio_to_irq(INT_PORT) //Interrupt Number,EINT18(119)
#define INT_CFG S3C_GPIO_SFN(3)//(2) //IO configer as EINT
#else
#define TS_INT 0
#endif
*/
//whether need send cfg?
//#define DRIVER_SEND_CFG
//set trigger mode
#define INT_TRIGGER 0
#define POLL_TIME 10 //actual query spacing interval:POLL_TIME+6
#define GOODIX_MULTI_TOUCH
#ifdef GOODIX_MULTI_TOUCH
#define MAX_FINGER_NUM 8//10
#else
#define MAX_FINGER_NUM 1
#endif
//--------------------------- emdoor tp define -----------------------------------
#define DRIVER_SEND_CFG 1
#if defined(TP_GOODIX_EM7127_BM_81070027023_01)//em7127
#define TP_GOODIX_SIZE_7
#endif
#if defined(TP_GOODIX_EM73_HOTA_C113171A1)//em73
#define TP_GOODIX_SIZE_7 1
#define TP_GOODIX_REVERSE_X 1
#endif
#if defined(TP_GOODIX_EM86_DPT_N3371A)//em86
//#define TP_GOODIX_SIZE_8 1
#define HAVE_TOUCH_KEY 1
#define TOUCH_WITH_LIGHT_KEY 1
#endif
#if defined(TP_GOODIX_EM8127_BM_81080028A23_00)
#define TP_GOODIX_SIZE_8 1
#endif
#if defined(TP_GOODIX_EM1125_BM_81100026023_02)//em1125
#define TP_GOODIX_SIZE_101 1
#endif
#if defined(TP_GOODIX_EM101_TTCT097006_ZJFPC)
//#define TP_GOODIX_SIZE_10 1
#define TP_GOODIX_SWAP_X_Y 1
#define TP_GOODIX_REVERSE_Y 1
#define HAVE_TOUCH_KEY 1
#define TOUCH_WITH_LIGHT_KEY 1
#endif
#if defined(TP_GOODIX_EM101_300_L3512A_A00)
//#define TP_GOODIX_SIZE_10 1
//#define TP_GOODIX_SWAP_X_Y 1
//#define TP_GOODIX_REVERSE_Y 1
#define HAVE_TOUCH_KEY 1
#define TOUCH_WITH_LIGHT_KEY 1
#endif
//define default resolution of the touchscreen
#if defined(TP_GOODIX_SIZE_7)
#define TOUCH_MAX_HEIGHT 800
#define TOUCH_MAX_WIDTH 480
#elif defined(TP_GOODIX_SIZE_8)
#define TOUCH_MAX_HEIGHT 800
#define TOUCH_MAX_WIDTH 600
#elif defined(TP_GOODIX_SIZE_101)
#define TOUCH_MAX_HEIGHT 1024
#define TOUCH_MAX_WIDTH 600
#elif defined(TP_GOODIX_SIZE_10)
#define TOUCH_MAX_HEIGHT 1024
#define TOUCH_MAX_WIDTH 768
#elif defined(CONFIG_MACH_TCC8800)
#define TOUCH_MAX_HEIGHT 1024
#define TOUCH_MAX_WIDTH 768
#else
#define TOUCH_MAX_HEIGHT 4096
#define TOUCH_MAX_WIDTH 4096
#endif
#define TP_GOODIX_USE_IRQ 1
#if !defined(TP_NOT_USE_OFFON_BACKLIGHT) //for relsove some goodix touch can not use when off /on backlight
#define TP_GOODIX_USE_PW_CTRL 1
#endif
#define TP_GOODIX_CHECK_SUM 1//the new fw support check sum,but old fw not
#if defined(TP_GOODIX_CHECK_SUM)
#define CHECK_SUM_WITH_LOOP 1
#endif
#if defined(TP_GOODIX_USE_IRQ)
#define TS_INT INT_EI2 //Interrupt Number,INT_EI2 as 5
#define TP_GOODIX_USE_IRQ_WITH_HRTIMER 1
#else
#define TS_INT 0
#endif
//static const char *goodix_ts_name = "Goodix Capacitive TouchScreen";
//--------------------------- end emdoor tp define -------------------------------
//#define swap(x, y) do { typeof(x) z = x; x = y; y = z; } while (0)
struct goodix_ts_data {
uint16_t addr;
uint8_t bad_data;
struct i2c_client *client;
struct input_dev *input_dev;
int use_reset; //use RESET flag
int use_irq; //use EINT flag
int read_mode; //read moudle mode,20110221 by andrew
struct hrtimer timer;
struct work_struct work;
char phys[32];
int retry;
struct early_suspend early_suspend;
int (*power)(struct goodix_ts_data * ts, int on);
uint16_t abs_x_max;
uint16_t abs_y_max;
uint8_t max_touch_num;
uint8_t int_trigger_type;
uint8_t green_wake_mode;
};
static const char *goodix_ts_name = "tcc-ts-goodix-cap";
static struct workqueue_struct *goodix_wq;
struct i2c_client * i2c_connect_client = NULL;
static struct proc_dir_entry *goodix_proc_entry;
static struct kobject *goodix_debug_kobj;
#ifdef CONFIG_HAS_EARLYSUSPEND
static void goodix_ts_early_suspend(struct early_suspend *h);
static void goodix_ts_late_resume(struct early_suspend *h);
#endif
//*****************************End of Part I *********************************
//*************************Touchkey Surpport Part*****************************
//#define HAVE_TOUCH_KEY
#ifdef HAVE_TOUCH_KEY
#define READ_COOR_ADDR 0x00
#if defined(TP_GOODIX_EM101_TTCT097006_ZJFPC)
const uint16_t touch_key_array[]={
//KEY_MENU, //MENU
//KEY_HOME, //HOME
//KEY_SEND //CALL
KEY_HOME,
KEY_MENU,
KEY_BACK,
KEY_SEARCH,
};
#else
const uint16_t touch_key_array[]={
//KEY_MENU, //MENU
//KEY_HOME, //HOME
//KEY_SEND //CALL
KEY_SEARCH,
KEY_BACK,
KEY_MENU,
KEY_HOME,
};
#endif
#define MAX_KEY_NUM (sizeof(touch_key_array)/sizeof(touch_key_array[0]))
#else
#define READ_COOR_ADDR 0x01
#endif
//*****************************End of Part II*********************************
//*************************Firmware Update part*******************************
#define CONFIG_TOUCHSCREEN_GOODIX_IAP
#ifdef CONFIG_TOUCHSCREEN_GOODIX_IAP
#define UPDATE_NEW_PROTOCOL
unsigned int oldcrc32 = 0xFFFFFFFF;
unsigned int crc32_table[256];
unsigned int ulPolynomial = 0x04c11db7;
unsigned char rd_cfg_addr;
unsigned char rd_cfg_len;
unsigned char g_enter_isp = 0;
static int goodix_update_write(struct file *filp, const char __user *buff, unsigned long len, void *data);
static int goodix_update_read( char *page, char **start, off_t off, int count, int *eof, void *data );
#define PACK_SIZE 64 //update file package size
#define MAX_TIMEOUT 60000 //update time out conut
#define MAX_I2C_RETRIES 20 //i2c retry times
//I2C buf address
#define ADDR_CMD 80
#define ADDR_STA 81
#ifdef UPDATE_NEW_PROTOCOL
#define ADDR_DAT 0
#else
#define ADDR_DAT 82
#endif
//moudle state
#define NEW_UPDATE_START 0x01
#define UPDATE_START 0x02
#define SLAVE_READY 0x08
#define UNKNOWN_ERROR 0x00
#define FRAME_ERROR 0x10
#define CHECKSUM_ERROR 0x20
#define TRANSLATE_ERROR 0x40
#define FLASH_ERROR 0X80
//error no
#define ERROR_NO_FILE 2 //ENOENT
#define ERROR_FILE_READ 23 //ENFILE
#define ERROR_FILE_TYPE 21 //EISDIR
#define ERROR_GPIO_REQUEST 4 //EINTR
#define ERROR_I2C_TRANSFER 5 //EIO
#define ERROR_NO_RESPONSE 16 //EBUSY
#define ERROR_TIMEOUT 110 //ETIMEDOUT
//update steps
#define STEP_SET_PATH 1
#define STEP_CHECK_FILE 2
#define STEP_WRITE_SYN 3
#define STEP_WAIT_SYN 4
#define STEP_WRITE_LENGTH 5
#define STEP_WAIT_READY 6
#define STEP_WRITE_DATA 7
#define STEP_READ_STATUS 8
#define FUN_CLR_VAL 9
#define FUN_CMD 10
#define FUN_WRITE_CONFIG 11
//fun cmd
#define CMD_DISABLE_TP 0
#define CMD_ENABLE_TP 1
#define CMD_READ_VER 2
#define CMD_READ_RAW 3
#define CMD_READ_DIF 4
#define CMD_READ_CFG 5
#define CMD_SYS_REBOOT 101
//read mode
#define MODE_RD_VER 1
#define MODE_RD_RAW 2
#define MODE_RD_DIF 3
#define MODE_RD_CFG 4
#endif
//*****************************End of Part III********************************
struct goodix_i2c_platform_data {
uint32_t version; /* Use this entry for panels with */
//reservation
};
#endif /* _LINUX_GOODIX_TOUCH_H */
|
olexiyt/telechips-linux
|
drivers/input/touchscreen/goodix_touch_2chips.h
|
C
|
gpl-2.0
| 8,503 |
define(
"dijit/nls/fi/loading", ({
loadingState: "Lataus on meneillään...",
errorState: "On ilmennyt virhe."
})
);
|
hariomkumarmth/champaranexpress
|
wp-content/plugins/dojo/dijit/nls/fi/loading.js.uncompressed.js
|
JavaScript
|
gpl-2.0
| 125 |
/*
* This file is part of OpenTTD.
* OpenTTD 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.
* OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file settings_sl.cpp Handles the saveload part of the settings. */
#include "../stdafx.h"
#include "saveload.h"
#include "compat/settings_sl_compat.h"
#include "../settings_type.h"
#include "../settings_table.h"
#include "../network/network.h"
#include "../fios.h"
#include "../safeguards.h"
/**
* Prepare for reading and old diff_custom by zero-ing the memory.
*/
void PrepareOldDiffCustom()
{
memset(_old_diff_custom, 0, sizeof(_old_diff_custom));
}
/**
* Reading of the old diff_custom array and transforming it to the new format.
* @param savegame is it read from the config or savegame. In the latter case
* we are sure there is an array; in the former case we have
* to check that.
*/
void HandleOldDiffCustom(bool savegame)
{
/* Savegames before v4 didn't have "town_council_tolerance" in savegame yet. */
bool has_no_town_council_tolerance = savegame && IsSavegameVersionBefore(SLV_4);
uint options_to_load = GAME_DIFFICULTY_NUM - (has_no_town_council_tolerance ? 1 : 0);
if (!savegame) {
/* If we did read to old_diff_custom, then at least one value must be non 0. */
bool old_diff_custom_used = false;
for (uint i = 0; i < options_to_load && !old_diff_custom_used; i++) {
old_diff_custom_used = (_old_diff_custom[i] != 0);
}
if (!old_diff_custom_used) return;
}
/* Iterate over all the old difficulty settings, and convert the list-value to the new setting. */
uint i = 0;
for (const auto &name : _old_diff_settings) {
if (has_no_town_council_tolerance && name == "town_council_tolerance") continue;
std::string fullname = "difficulty." + name;
const SettingDesc *sd = GetSettingFromName(fullname);
/* Some settings are no longer in use; skip reading those. */
if (sd == nullptr) {
i++;
continue;
}
int32 value = (int32)((name == "max_loan" ? 1000 : 1) * _old_diff_custom[i++]);
sd->AsIntSetting()->MakeValueValidAndWrite(savegame ? &_settings_game : &_settings_newgame, value);
}
}
/**
* Get the SaveLoad description for the SettingTable.
* @param settings SettingDesc struct containing all information.
* @param is_loading True iff the SaveLoad table is for loading.
* @return Vector with SaveLoad entries for the SettingTable.
*/
static std::vector<SaveLoad> GetSettingsDesc(const SettingTable &settings, bool is_loading)
{
std::vector<SaveLoad> saveloads;
for (auto &desc : settings) {
const SettingDesc *sd = GetSettingDesc(desc);
if (sd->flags & SF_NOT_IN_SAVE) continue;
if (is_loading && (sd->flags & SF_NO_NETWORK_SYNC) && _networking && !_network_server) {
if (IsSavegameVersionBefore(SLV_TABLE_CHUNKS)) {
/* We don't want to read this setting, so we do need to skip over it. */
saveloads.push_back({sd->GetName(), sd->save.cmd, GetVarFileType(sd->save.conv) | SLE_VAR_NULL, sd->save.length, sd->save.version_from, sd->save.version_to, 0, nullptr, 0, nullptr});
}
continue;
}
saveloads.push_back(sd->save);
}
return saveloads;
}
/**
* Save and load handler for settings
* @param settings SettingDesc struct containing all information
* @param object can be either nullptr in which case we load global variables or
* a pointer to a struct which is getting saved
*/
static void LoadSettings(const SettingTable &settings, void *object, const SaveLoadCompatTable &slct)
{
const std::vector<SaveLoad> slt = SlCompatTableHeader(GetSettingsDesc(settings, true), slct);
if (!IsSavegameVersionBefore(SLV_RIFF_TO_ARRAY) && SlIterateArray() == -1) return;
SlObject(object, slt);
if (!IsSavegameVersionBefore(SLV_RIFF_TO_ARRAY) && SlIterateArray() != -1) SlErrorCorrupt("Too many settings entries");
/* Ensure all IntSettings are valid (min/max could have changed between versions etc). */
for (auto &desc : settings) {
const SettingDesc *sd = GetSettingDesc(desc);
if (sd->flags & SF_NOT_IN_SAVE) continue;
if ((sd->flags & SF_NO_NETWORK_SYNC) && _networking && !_network_server) continue;
if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
if (sd->IsIntSetting()) {
const IntSettingDesc *int_setting = sd->AsIntSetting();
int_setting->MakeValueValidAndWrite(object, int_setting->Read(object));
}
}
}
/**
* Save and load handler for settings
* @param settings SettingDesc struct containing all information
* @param object can be either nullptr in which case we load global variables or
* a pointer to a struct which is getting saved
*/
static void SaveSettings(const SettingTable &settings, void *object)
{
const std::vector<SaveLoad> slt = GetSettingsDesc(settings, false);
SlTableHeader(slt);
SlSetArrayIndex(0);
SlObject(object, slt);
}
struct OPTSChunkHandler : ChunkHandler {
OPTSChunkHandler() : ChunkHandler('OPTS', CH_READONLY) {}
void Load() const override
{
/* Copy over default setting since some might not get loaded in
* a networking environment. This ensures for example that the local
* autosave-frequency stays when joining a network-server */
PrepareOldDiffCustom();
LoadSettings(_old_gameopt_settings, &_settings_game, _gameopt_sl_compat);
HandleOldDiffCustom(true);
}
};
struct PATSChunkHandler : ChunkHandler {
PATSChunkHandler() : ChunkHandler('PATS', CH_TABLE) {}
/**
* Create a single table with all settings that should be stored/loaded
* in the savegame.
*/
SettingTable GetSettingTable() const
{
static const SettingTable saveload_settings_tables[] = {
_difficulty_settings,
_economy_settings,
_game_settings,
_linkgraph_settings,
_locale_settings,
_pathfinding_settings,
_script_settings,
_world_settings,
};
static std::vector<SettingVariant> settings_table;
if (settings_table.empty()) {
for (auto &saveload_settings_table : saveload_settings_tables) {
for (auto &saveload_setting : saveload_settings_table) {
settings_table.push_back(saveload_setting);
}
}
}
return settings_table;
}
void Load() const override
{
/* Copy over default setting since some might not get loaded in
* a networking environment. This ensures for example that the local
* currency setting stays when joining a network-server */
LoadSettings(this->GetSettingTable(), &_settings_game, _settings_sl_compat);
}
void LoadCheck(size_t) const override
{
LoadSettings(this->GetSettingTable(), &_load_check_data.settings, _settings_sl_compat);
}
void Save() const override
{
SaveSettings(this->GetSettingTable(), &_settings_game);
}
};
static const OPTSChunkHandler OPTS;
static const PATSChunkHandler PATS;
static const ChunkHandlerRef setting_chunk_handlers[] = {
OPTS,
PATS,
};
extern const ChunkHandlerTable _setting_chunk_handlers(setting_chunk_handlers);
|
pelya/openttd-android
|
src/saveload/settings_sl.cpp
|
C++
|
gpl-2.0
| 7,289 |
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'contextmenu', 'sr', {
options: 'Context Menu Options' // MISSING
} );
|
eastoncat/cm.eastoncat
|
sites/all/modules/contrib/civicrm/packages/ckeditor/plugins/contextmenu/lang/sr.js
|
JavaScript
|
gpl-2.0
| 251 |
/*
* Texture Filtering
* Version: 1.0
*
* Copyright (C) 2007 Hiroshi Morii All Rights Reserved.
* Email koolsmoky(at)users.sourceforge.net
* Web http://www.3dfxzone.it/koolsmoky
*
* this 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 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 GNU Make; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __TXUTIL_H__
#define __TXUTIL_H__
/* maximum number of CPU cores allowed */
#define MAX_NUMCORE 8
#include "TxInternal.h"
/* extension for cache files */
#define TEXCACHE_EXT wst("htc")
#include <vector>
class TxUtil
{
private:
static uint32 RiceCRC32(const uint8* src, int width, int height, int size, int rowStride);
static boolean RiceCRC32_CI4(const uint8* src, int width, int height, int rowStride,
uint32* crc32, uint32* cimax);
static boolean RiceCRC32_CI8(const uint8* src, int width, int height, int rowStride,
uint32* crc32, uint32* cimax);
public:
static int sizeofTx(int width, int height, uint16 format);
static uint32 checksumTx(uint8 *data, int width, int height, uint16 format);
#if 0 /* unused */
static uint32 chkAlpha(uint32* src, int width, int height);
#endif
static uint32 checksum(uint8 *src, int width, int height, int size, int rowStride);
static uint64 checksum64(uint8 *src, int width, int height, int size, int rowStride, uint8 *palette);
static int getNumberofProcessors();
};
class TxMemBuf
{
private:
uint8 *_tex[2];
uint32 _size[2];
std::vector< std::vector<uint32> > _bufs;
TxMemBuf();
public:
static TxMemBuf* getInstance() {
static TxMemBuf txMemBuf;
return &txMemBuf;
}
~TxMemBuf();
boolean init(int maxwidth, int maxheight);
void shutdown();
uint8 *get(uint32 num);
uint32 size_of(uint32 num);
uint32 *getThreadBuf(uint32 threadIdx, uint32 num, uint32 size);
};
void setTextureFormat(uint16 internalFormat, GHQTexInfo * info);
#endif /* __TXUTIL_H__ */
|
matthewharvey/GLideN64
|
src/GLideNHQ/TxUtil.h
|
C
|
gpl-2.0
| 2,424 |
/* tc-mn10300.c -- Assembler code for the Matsushita 10300
Copyright (C) 1996-2017 Free Software Foundation, Inc.
This file is part of GAS, the GNU Assembler.
GAS 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.
GAS 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 GAS; see the file COPYING. If not, write to
the Free Software Foundation, 51 Franklin Street - Fifth Floor,
Boston, MA 02110-1301, USA. */
#include "as.h"
#include "safe-ctype.h"
#include "subsegs.h"
#include "opcode/mn10300.h"
#include "dwarf2dbg.h"
#include "libiberty.h"
/* Structure to hold information about predefined registers. */
struct reg_name
{
const char *name;
int value;
};
/* Generic assembler global variables which must be defined by all
targets. */
/* Characters which always start a comment. */
const char comment_chars[] = "#";
/* Characters which start a comment at the beginning of a line. */
const char line_comment_chars[] = ";#";
/* Characters which may be used to separate multiple commands on a
single line. */
const char line_separator_chars[] = ";";
/* Characters which are used to indicate an exponent in a floating
point number. */
const char EXP_CHARS[] = "eE";
/* Characters which mean that a number is a floating point constant,
as in 0d1.0. */
const char FLT_CHARS[] = "dD";
const relax_typeS md_relax_table[] =
{
/* The plus values for the bCC and fBCC instructions in the table below
are because the branch instruction is translated into a jump
instruction that is now +2 or +3 bytes further on in memory, and the
correct size of jump instruction must be selected. */
/* bCC relaxing. */
{0x7f, -0x80, 2, 1},
{0x7fff + 2, -0x8000 + 2, 5, 2},
{0x7fffffff, -0x80000000, 7, 0},
/* bCC relaxing (uncommon cases for 3byte length instructions) */
{0x7f, -0x80, 3, 4},
{0x7fff + 3, -0x8000 + 3, 6, 5},
{0x7fffffff, -0x80000000, 8, 0},
/* call relaxing. */
{0x7fff, -0x8000, 5, 7},
{0x7fffffff, -0x80000000, 7, 0},
/* calls relaxing. */
{0x7fff, -0x8000, 4, 9},
{0x7fffffff, -0x80000000, 6, 0},
/* jmp relaxing. */
{0x7f, -0x80, 2, 11},
{0x7fff, -0x8000, 3, 12},
{0x7fffffff, -0x80000000, 5, 0},
/* fbCC relaxing. */
{0x7f, -0x80, 3, 14},
{0x7fff + 3, -0x8000 + 3, 6, 15},
{0x7fffffff, -0x80000000, 8, 0},
};
static int current_machine;
/* Fixups. */
#define MAX_INSN_FIXUPS 5
struct mn10300_fixup
{
expressionS exp;
int opindex;
bfd_reloc_code_real_type reloc;
};
struct mn10300_fixup fixups[MAX_INSN_FIXUPS];
static int fc;
/* We must store the value of each register operand so that we can
verify that certain registers do not match. */
int mn10300_reg_operands[MN10300_MAX_OPERANDS];
const char *md_shortopts = "";
struct option md_longopts[] =
{
{NULL, no_argument, NULL, 0}
};
size_t md_longopts_size = sizeof (md_longopts);
#define HAVE_AM33_2 (current_machine == AM33_2)
#define HAVE_AM33 (current_machine == AM33 || HAVE_AM33_2)
#define HAVE_AM30 (current_machine == AM30)
/* Opcode hash table. */
static struct hash_control *mn10300_hash;
/* This table is sorted. Suitable for searching by a binary search. */
static const struct reg_name data_registers[] =
{
{ "d0", 0 },
{ "d1", 1 },
{ "d2", 2 },
{ "d3", 3 },
};
static const struct reg_name address_registers[] =
{
{ "a0", 0 },
{ "a1", 1 },
{ "a2", 2 },
{ "a3", 3 },
};
static const struct reg_name r_registers[] =
{
{ "a0", 8 },
{ "a1", 9 },
{ "a2", 10 },
{ "a3", 11 },
{ "d0", 12 },
{ "d1", 13 },
{ "d2", 14 },
{ "d3", 15 },
{ "e0", 0 },
{ "e1", 1 },
{ "e10", 10 },
{ "e11", 11 },
{ "e12", 12 },
{ "e13", 13 },
{ "e14", 14 },
{ "e15", 15 },
{ "e2", 2 },
{ "e3", 3 },
{ "e4", 4 },
{ "e5", 5 },
{ "e6", 6 },
{ "e7", 7 },
{ "e8", 8 },
{ "e9", 9 },
{ "r0", 0 },
{ "r1", 1 },
{ "r10", 10 },
{ "r11", 11 },
{ "r12", 12 },
{ "r13", 13 },
{ "r14", 14 },
{ "r15", 15 },
{ "r2", 2 },
{ "r3", 3 },
{ "r4", 4 },
{ "r5", 5 },
{ "r6", 6 },
{ "r7", 7 },
{ "r8", 8 },
{ "r9", 9 },
};
static const struct reg_name xr_registers[] =
{
{ "mcrh", 2 },
{ "mcrl", 3 },
{ "mcvf", 4 },
{ "mdrq", 1 },
{ "sp", 0 },
{ "xr0", 0 },
{ "xr1", 1 },
{ "xr10", 10 },
{ "xr11", 11 },
{ "xr12", 12 },
{ "xr13", 13 },
{ "xr14", 14 },
{ "xr15", 15 },
{ "xr2", 2 },
{ "xr3", 3 },
{ "xr4", 4 },
{ "xr5", 5 },
{ "xr6", 6 },
{ "xr7", 7 },
{ "xr8", 8 },
{ "xr9", 9 },
};
static const struct reg_name float_registers[] =
{
{ "fs0", 0 },
{ "fs1", 1 },
{ "fs10", 10 },
{ "fs11", 11 },
{ "fs12", 12 },
{ "fs13", 13 },
{ "fs14", 14 },
{ "fs15", 15 },
{ "fs16", 16 },
{ "fs17", 17 },
{ "fs18", 18 },
{ "fs19", 19 },
{ "fs2", 2 },
{ "fs20", 20 },
{ "fs21", 21 },
{ "fs22", 22 },
{ "fs23", 23 },
{ "fs24", 24 },
{ "fs25", 25 },
{ "fs26", 26 },
{ "fs27", 27 },
{ "fs28", 28 },
{ "fs29", 29 },
{ "fs3", 3 },
{ "fs30", 30 },
{ "fs31", 31 },
{ "fs4", 4 },
{ "fs5", 5 },
{ "fs6", 6 },
{ "fs7", 7 },
{ "fs8", 8 },
{ "fs9", 9 },
};
static const struct reg_name double_registers[] =
{
{ "fd0", 0 },
{ "fd10", 10 },
{ "fd12", 12 },
{ "fd14", 14 },
{ "fd16", 16 },
{ "fd18", 18 },
{ "fd2", 2 },
{ "fd20", 20 },
{ "fd22", 22 },
{ "fd24", 24 },
{ "fd26", 26 },
{ "fd28", 28 },
{ "fd30", 30 },
{ "fd4", 4 },
{ "fd6", 6 },
{ "fd8", 8 },
};
/* We abuse the `value' field, that would be otherwise unused, to
encode the architecture on which (access to) the register was
introduced. FIXME: we should probably warn when we encounter a
register name when assembling for an architecture that doesn't
support it, before parsing it as a symbol name. */
static const struct reg_name other_registers[] =
{
{ "epsw", AM33 },
{ "mdr", 0 },
{ "pc", AM33 },
{ "psw", 0 },
{ "sp", 0 },
{ "ssp", 0 },
{ "usp", 0 },
};
#define OTHER_REG_NAME_CNT ARRAY_SIZE (other_registers)
/* Perform a binary search of the given register table REGS to see
if NAME is a valid regiter name. Returns the register number from
the array on success, or -1 on failure. */
static int
reg_name_search (const struct reg_name *regs,
int regcount,
const char *name)
{
int low, high;
low = 0;
high = regcount - 1;
do
{
int cmp, middle;
middle = (low + high) / 2;
cmp = strcasecmp (name, regs[middle].name);
if (cmp < 0)
high = middle - 1;
else if (cmp > 0)
low = middle + 1;
else
return regs[middle].value;
}
while (low <= high);
return -1;
}
/* Looks at the current position in the input line to see if it is
the name of a register in TABLE. If it is, then the name is
converted into an expression returned in EXPRESSIONP (with X_op
set to O_register and X_add_number set to the register number), the
input pointer is left pointing at the first non-blank character after
the name and the function returns TRUE. Otherwise the input pointer
is left alone and the function returns FALSE. */
static bfd_boolean
get_register_name (expressionS * expressionP,
const struct reg_name * table,
size_t table_length)
{
int reg_number;
char *name;
char *start;
char c;
/* Find the spelling of the operand. */
start = input_line_pointer;
c = get_symbol_name (&name);
reg_number = reg_name_search (table, table_length, name);
/* Put back the delimiting char. */
(void) restore_line_pointer (c);
/* Look to see if it's in the register table. */
if (reg_number >= 0)
{
expressionP->X_op = O_register;
expressionP->X_add_number = reg_number;
/* Make the rest nice. */
expressionP->X_add_symbol = NULL;
expressionP->X_op_symbol = NULL;
return TRUE;
}
/* Reset the line as if we had not done anything. */
input_line_pointer = start;
return FALSE;
}
static bfd_boolean
r_register_name (expressionS *expressionP)
{
return get_register_name (expressionP, r_registers, ARRAY_SIZE (r_registers));
}
static bfd_boolean
xr_register_name (expressionS *expressionP)
{
return get_register_name (expressionP, xr_registers, ARRAY_SIZE (xr_registers));
}
static bfd_boolean
data_register_name (expressionS *expressionP)
{
return get_register_name (expressionP, data_registers, ARRAY_SIZE (data_registers));
}
static bfd_boolean
address_register_name (expressionS *expressionP)
{
return get_register_name (expressionP, address_registers, ARRAY_SIZE (address_registers));
}
static bfd_boolean
float_register_name (expressionS *expressionP)
{
return get_register_name (expressionP, float_registers, ARRAY_SIZE (float_registers));
}
static bfd_boolean
double_register_name (expressionS *expressionP)
{
return get_register_name (expressionP, double_registers, ARRAY_SIZE (double_registers));
}
static bfd_boolean
other_register_name (expressionS *expressionP)
{
int reg_number;
char *name;
char *start;
char c;
/* Find the spelling of the operand. */
start = input_line_pointer;
c = get_symbol_name (&name);
reg_number = reg_name_search (other_registers, ARRAY_SIZE (other_registers), name);
/* Put back the delimiting char. */
(void) restore_line_pointer (c);
/* Look to see if it's in the register table. */
if (reg_number == 0
|| (reg_number == AM33 && HAVE_AM33))
{
expressionP->X_op = O_register;
expressionP->X_add_number = 0;
/* Make the rest nice. */
expressionP->X_add_symbol = NULL;
expressionP->X_op_symbol = NULL;
return TRUE;
}
/* Reset the line as if we had not done anything. */
input_line_pointer = start;
return FALSE;
}
void
md_show_usage (FILE *stream)
{
fprintf (stream, _("MN10300 assembler options:\n\
none yet\n"));
}
int
md_parse_option (int c ATTRIBUTE_UNUSED, const char *arg ATTRIBUTE_UNUSED)
{
return 0;
}
symbolS *
md_undefined_symbol (char *name ATTRIBUTE_UNUSED)
{
return 0;
}
const char *
md_atof (int type, char *litp, int *sizep)
{
return ieee_md_atof (type, litp, sizep, FALSE);
}
void
md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED,
asection *sec,
fragS *fragP)
{
static unsigned long label_count = 0;
char buf[40];
subseg_change (sec, 0);
if (fragP->fr_subtype == 0)
{
fix_new (fragP, fragP->fr_fix + 1, 1, fragP->fr_symbol,
fragP->fr_offset + 1, 1, BFD_RELOC_8_PCREL);
fragP->fr_var = 0;
fragP->fr_fix += 2;
}
else if (fragP->fr_subtype == 1)
{
/* Reverse the condition of the first branch. */
int offset = fragP->fr_fix;
int opcode = fragP->fr_literal[offset] & 0xff;
switch (opcode)
{
case 0xc8:
opcode = 0xc9;
break;
case 0xc9:
opcode = 0xc8;
break;
case 0xc0:
opcode = 0xc2;
break;
case 0xc2:
opcode = 0xc0;
break;
case 0xc3:
opcode = 0xc1;
break;
case 0xc1:
opcode = 0xc3;
break;
case 0xc4:
opcode = 0xc6;
break;
case 0xc6:
opcode = 0xc4;
break;
case 0xc7:
opcode = 0xc5;
break;
case 0xc5:
opcode = 0xc7;
break;
default:
abort ();
}
fragP->fr_literal[offset] = opcode;
/* Create a fixup for the reversed conditional branch. */
sprintf (buf, ".%s_%ld", FAKE_LABEL_NAME, label_count++);
fix_new (fragP, fragP->fr_fix + 1, 1,
symbol_new (buf, sec, 0, fragP->fr_next),
fragP->fr_offset + 1, 1, BFD_RELOC_8_PCREL);
/* Now create the unconditional branch + fixup to the
final target. */
fragP->fr_literal[offset + 2] = 0xcc;
fix_new (fragP, fragP->fr_fix + 3, 2, fragP->fr_symbol,
fragP->fr_offset + 1, 1, BFD_RELOC_16_PCREL);
fragP->fr_var = 0;
fragP->fr_fix += 5;
}
else if (fragP->fr_subtype == 2)
{
/* Reverse the condition of the first branch. */
int offset = fragP->fr_fix;
int opcode = fragP->fr_literal[offset] & 0xff;
switch (opcode)
{
case 0xc8:
opcode = 0xc9;
break;
case 0xc9:
opcode = 0xc8;
break;
case 0xc0:
opcode = 0xc2;
break;
case 0xc2:
opcode = 0xc0;
break;
case 0xc3:
opcode = 0xc1;
break;
case 0xc1:
opcode = 0xc3;
break;
case 0xc4:
opcode = 0xc6;
break;
case 0xc6:
opcode = 0xc4;
break;
case 0xc7:
opcode = 0xc5;
break;
case 0xc5:
opcode = 0xc7;
break;
default:
abort ();
}
fragP->fr_literal[offset] = opcode;
/* Create a fixup for the reversed conditional branch. */
sprintf (buf, ".%s_%ld", FAKE_LABEL_NAME, label_count++);
fix_new (fragP, fragP->fr_fix + 1, 1,
symbol_new (buf, sec, 0, fragP->fr_next),
fragP->fr_offset + 1, 1, BFD_RELOC_8_PCREL);
/* Now create the unconditional branch + fixup to the
final target. */
fragP->fr_literal[offset + 2] = 0xdc;
fix_new (fragP, fragP->fr_fix + 3, 4, fragP->fr_symbol,
fragP->fr_offset + 1, 1, BFD_RELOC_32_PCREL);
fragP->fr_var = 0;
fragP->fr_fix += 7;
}
else if (fragP->fr_subtype == 3)
{
fix_new (fragP, fragP->fr_fix + 2, 1, fragP->fr_symbol,
fragP->fr_offset + 2, 1, BFD_RELOC_8_PCREL);
fragP->fr_var = 0;
fragP->fr_fix += 3;
}
else if (fragP->fr_subtype == 4)
{
/* Reverse the condition of the first branch. */
int offset = fragP->fr_fix;
int opcode = fragP->fr_literal[offset + 1] & 0xff;
switch (opcode)
{
case 0xe8:
opcode = 0xe9;
break;
case 0xe9:
opcode = 0xe8;
break;
case 0xea:
opcode = 0xeb;
break;
case 0xeb:
opcode = 0xea;
break;
default:
abort ();
}
fragP->fr_literal[offset + 1] = opcode;
/* Create a fixup for the reversed conditional branch. */
sprintf (buf, ".%s_%ld", FAKE_LABEL_NAME, label_count++);
fix_new (fragP, fragP->fr_fix + 2, 1,
symbol_new (buf, sec, 0, fragP->fr_next),
fragP->fr_offset + 2, 1, BFD_RELOC_8_PCREL);
/* Now create the unconditional branch + fixup to the
final target. */
fragP->fr_literal[offset + 3] = 0xcc;
fix_new (fragP, fragP->fr_fix + 4, 2, fragP->fr_symbol,
fragP->fr_offset + 1, 1, BFD_RELOC_16_PCREL);
fragP->fr_var = 0;
fragP->fr_fix += 6;
}
else if (fragP->fr_subtype == 5)
{
/* Reverse the condition of the first branch. */
int offset = fragP->fr_fix;
int opcode = fragP->fr_literal[offset + 1] & 0xff;
switch (opcode)
{
case 0xe8:
opcode = 0xe9;
break;
case 0xea:
opcode = 0xeb;
break;
case 0xeb:
opcode = 0xea;
break;
default:
abort ();
}
fragP->fr_literal[offset + 1] = opcode;
/* Create a fixup for the reversed conditional branch. */
sprintf (buf, ".%s_%ld", FAKE_LABEL_NAME, label_count++);
fix_new (fragP, fragP->fr_fix + 2, 1,
symbol_new (buf, sec, 0, fragP->fr_next),
fragP->fr_offset + 2, 1, BFD_RELOC_8_PCREL);
/* Now create the unconditional branch + fixup to the
final target. */
fragP->fr_literal[offset + 3] = 0xdc;
fix_new (fragP, fragP->fr_fix + 4, 4, fragP->fr_symbol,
fragP->fr_offset + 1, 1, BFD_RELOC_32_PCREL);
fragP->fr_var = 0;
fragP->fr_fix += 8;
}
else if (fragP->fr_subtype == 6)
{
int offset = fragP->fr_fix;
fragP->fr_literal[offset] = 0xcd;
fix_new (fragP, fragP->fr_fix + 1, 2, fragP->fr_symbol,
fragP->fr_offset + 1, 1, BFD_RELOC_16_PCREL);
fragP->fr_var = 0;
fragP->fr_fix += 5;
}
else if (fragP->fr_subtype == 7)
{
int offset = fragP->fr_fix;
fragP->fr_literal[offset] = 0xdd;
fragP->fr_literal[offset + 5] = fragP->fr_literal[offset + 3];
fragP->fr_literal[offset + 6] = fragP->fr_literal[offset + 4];
fragP->fr_literal[offset + 3] = 0;
fragP->fr_literal[offset + 4] = 0;
fix_new (fragP, fragP->fr_fix + 1, 4, fragP->fr_symbol,
fragP->fr_offset + 1, 1, BFD_RELOC_32_PCREL);
fragP->fr_var = 0;
fragP->fr_fix += 7;
}
else if (fragP->fr_subtype == 8)
{
int offset = fragP->fr_fix;
fragP->fr_literal[offset] = 0xfa;
fragP->fr_literal[offset + 1] = 0xff;
fix_new (fragP, fragP->fr_fix + 2, 2, fragP->fr_symbol,
fragP->fr_offset + 2, 1, BFD_RELOC_16_PCREL);
fragP->fr_var = 0;
fragP->fr_fix += 4;
}
else if (fragP->fr_subtype == 9)
{
int offset = fragP->fr_fix;
fragP->fr_literal[offset] = 0xfc;
fragP->fr_literal[offset + 1] = 0xff;
fix_new (fragP, fragP->fr_fix + 2, 4, fragP->fr_symbol,
fragP->fr_offset + 2, 1, BFD_RELOC_32_PCREL);
fragP->fr_var = 0;
fragP->fr_fix += 6;
}
else if (fragP->fr_subtype == 10)
{
fragP->fr_literal[fragP->fr_fix] = 0xca;
fix_new (fragP, fragP->fr_fix + 1, 1, fragP->fr_symbol,
fragP->fr_offset + 1, 1, BFD_RELOC_8_PCREL);
fragP->fr_var = 0;
fragP->fr_fix += 2;
}
else if (fragP->fr_subtype == 11)
{
int offset = fragP->fr_fix;
fragP->fr_literal[offset] = 0xcc;
fix_new (fragP, fragP->fr_fix + 1, 2, fragP->fr_symbol,
fragP->fr_offset + 1, 1, BFD_RELOC_16_PCREL);
fragP->fr_var = 0;
fragP->fr_fix += 3;
}
else if (fragP->fr_subtype == 12)
{
int offset = fragP->fr_fix;
fragP->fr_literal[offset] = 0xdc;
fix_new (fragP, fragP->fr_fix + 1, 4, fragP->fr_symbol,
fragP->fr_offset + 1, 1, BFD_RELOC_32_PCREL);
fragP->fr_var = 0;
fragP->fr_fix += 5;
}
else if (fragP->fr_subtype == 13)
{
fix_new (fragP, fragP->fr_fix + 2, 1, fragP->fr_symbol,
fragP->fr_offset + 2, 1, BFD_RELOC_8_PCREL);
fragP->fr_var = 0;
fragP->fr_fix += 3;
}
else if (fragP->fr_subtype == 14)
{
/* Reverse the condition of the first branch. */
int offset = fragP->fr_fix;
int opcode = fragP->fr_literal[offset + 1] & 0xff;
switch (opcode)
{
case 0xd0:
opcode = 0xd1;
break;
case 0xd1:
opcode = 0xd0;
break;
case 0xd2:
opcode = 0xdc;
break;
case 0xd3:
opcode = 0xdb;
break;
case 0xd4:
opcode = 0xda;
break;
case 0xd5:
opcode = 0xd9;
break;
case 0xd6:
opcode = 0xd8;
break;
case 0xd7:
opcode = 0xdd;
break;
case 0xd8:
opcode = 0xd6;
break;
case 0xd9:
opcode = 0xd5;
break;
case 0xda:
opcode = 0xd4;
break;
case 0xdb:
opcode = 0xd3;
break;
case 0xdc:
opcode = 0xd2;
break;
case 0xdd:
opcode = 0xd7;
break;
default:
abort ();
}
fragP->fr_literal[offset + 1] = opcode;
/* Create a fixup for the reversed conditional branch. */
sprintf (buf, ".%s_%ld", FAKE_LABEL_NAME, label_count++);
fix_new (fragP, fragP->fr_fix + 2, 1,
symbol_new (buf, sec, 0, fragP->fr_next),
fragP->fr_offset + 2, 1, BFD_RELOC_8_PCREL);
/* Now create the unconditional branch + fixup to the
final target. */
fragP->fr_literal[offset + 3] = 0xcc;
fix_new (fragP, fragP->fr_fix + 4, 2, fragP->fr_symbol,
fragP->fr_offset + 1, 1, BFD_RELOC_16_PCREL);
fragP->fr_var = 0;
fragP->fr_fix += 6;
}
else if (fragP->fr_subtype == 15)
{
/* Reverse the condition of the first branch. */
int offset = fragP->fr_fix;
int opcode = fragP->fr_literal[offset + 1] & 0xff;
switch (opcode)
{
case 0xd0:
opcode = 0xd1;
break;
case 0xd1:
opcode = 0xd0;
break;
case 0xd2:
opcode = 0xdc;
break;
case 0xd3:
opcode = 0xdb;
break;
case 0xd4:
opcode = 0xda;
break;
case 0xd5:
opcode = 0xd9;
break;
case 0xd6:
opcode = 0xd8;
break;
case 0xd7:
opcode = 0xdd;
break;
case 0xd8:
opcode = 0xd6;
break;
case 0xd9:
opcode = 0xd5;
break;
case 0xda:
opcode = 0xd4;
break;
case 0xdb:
opcode = 0xd3;
break;
case 0xdc:
opcode = 0xd2;
break;
case 0xdd:
opcode = 0xd7;
break;
default:
abort ();
}
fragP->fr_literal[offset + 1] = opcode;
/* Create a fixup for the reversed conditional branch. */
sprintf (buf, ".%s_%ld", FAKE_LABEL_NAME, label_count++);
fix_new (fragP, fragP->fr_fix + 2, 1,
symbol_new (buf, sec, 0, fragP->fr_next),
fragP->fr_offset + 2, 1, BFD_RELOC_8_PCREL);
/* Now create the unconditional branch + fixup to the
final target. */
fragP->fr_literal[offset + 3] = 0xdc;
fix_new (fragP, fragP->fr_fix + 4, 4, fragP->fr_symbol,
fragP->fr_offset + 1, 1, BFD_RELOC_32_PCREL);
fragP->fr_var = 0;
fragP->fr_fix += 8;
}
else
abort ();
}
valueT
md_section_align (asection *seg, valueT addr)
{
int align = bfd_get_section_alignment (stdoutput, seg);
return ((addr + (1 << align) - 1) & -(1 << align));
}
void
md_begin (void)
{
const char *prev_name = "";
const struct mn10300_opcode *op;
mn10300_hash = hash_new ();
/* Insert unique names into hash table. The MN10300 instruction set
has many identical opcode names that have different opcodes based
on the operands. This hash table then provides a quick index to
the first opcode with a particular name in the opcode table. */
op = mn10300_opcodes;
while (op->name)
{
if (strcmp (prev_name, op->name))
{
prev_name = (char *) op->name;
hash_insert (mn10300_hash, op->name, (char *) op);
}
op++;
}
/* Set the default machine type. */
#ifdef TE_LINUX
if (!bfd_set_arch_mach (stdoutput, bfd_arch_mn10300, AM33_2))
as_warn (_("could not set architecture and machine"));
current_machine = AM33_2;
#else
if (!bfd_set_arch_mach (stdoutput, bfd_arch_mn10300, MN103))
as_warn (_("could not set architecture and machine"));
current_machine = MN103;
#endif
/* Set linkrelax here to avoid fixups in most sections. */
linkrelax = 1;
}
static symbolS *GOT_symbol;
static inline int
mn10300_PIC_related_p (symbolS *sym)
{
expressionS *exp;
if (! sym)
return 0;
if (sym == GOT_symbol)
return 1;
exp = symbol_get_value_expression (sym);
return (exp->X_op == O_PIC_reloc
|| mn10300_PIC_related_p (exp->X_add_symbol)
|| mn10300_PIC_related_p (exp->X_op_symbol));
}
static inline int
mn10300_check_fixup (struct mn10300_fixup *fixup)
{
expressionS *exp = &fixup->exp;
repeat:
switch (exp->X_op)
{
case O_add:
case O_subtract: /* If we're sufficiently unlucky that the label
and the expression that references it happen
to end up in different frags, the subtract
won't be simplified within expression(). */
/* The PIC-related operand must be the first operand of a sum. */
if (exp != &fixup->exp || mn10300_PIC_related_p (exp->X_op_symbol))
return 1;
if (exp->X_add_symbol && exp->X_add_symbol == GOT_symbol)
fixup->reloc = BFD_RELOC_32_GOT_PCREL;
exp = symbol_get_value_expression (exp->X_add_symbol);
goto repeat;
case O_symbol:
if (exp->X_add_symbol && exp->X_add_symbol == GOT_symbol)
fixup->reloc = BFD_RELOC_32_GOT_PCREL;
break;
case O_PIC_reloc:
fixup->reloc = exp->X_md;
exp->X_op = O_symbol;
if (fixup->reloc == BFD_RELOC_32_PLT_PCREL
&& fixup->opindex >= 0
&& (mn10300_operands[fixup->opindex].flags
& MN10300_OPERAND_RELAX))
return 1;
break;
default:
return (mn10300_PIC_related_p (exp->X_add_symbol)
|| mn10300_PIC_related_p (exp->X_op_symbol));
}
return 0;
}
void
mn10300_cons_fix_new (fragS *frag, int off, int size, expressionS *exp,
bfd_reloc_code_real_type r ATTRIBUTE_UNUSED)
{
struct mn10300_fixup fixup;
fixup.opindex = -1;
fixup.exp = *exp;
fixup.reloc = BFD_RELOC_UNUSED;
mn10300_check_fixup (&fixup);
if (fixup.reloc == BFD_RELOC_MN10300_GOT32)
switch (size)
{
case 2:
fixup.reloc = BFD_RELOC_MN10300_GOT16;
break;
case 3:
fixup.reloc = BFD_RELOC_MN10300_GOT24;
break;
case 4:
break;
default:
goto error;
}
else if (fixup.reloc == BFD_RELOC_UNUSED)
switch (size)
{
case 1:
fixup.reloc = BFD_RELOC_8;
break;
case 2:
fixup.reloc = BFD_RELOC_16;
break;
case 3:
fixup.reloc = BFD_RELOC_24;
break;
case 4:
fixup.reloc = BFD_RELOC_32;
break;
default:
goto error;
}
else if (size != 4)
{
error:
as_bad (_("unsupported BFD relocation size %u"), size);
fixup.reloc = BFD_RELOC_UNUSED;
}
fix_new_exp (frag, off, size, &fixup.exp, 0, fixup.reloc);
}
static bfd_boolean
check_operand (const struct mn10300_operand *operand,
offsetT val)
{
/* No need to check 32bit operands for a bit. Note that
MN10300_OPERAND_SPLIT is an implicit 32bit operand. */
if (operand->bits != 32
&& (operand->flags & MN10300_OPERAND_SPLIT) == 0)
{
long min, max;
offsetT test;
int bits;
bits = operand->bits;
if (operand->flags & MN10300_OPERAND_24BIT)
bits = 24;
if ((operand->flags & MN10300_OPERAND_SIGNED) != 0)
{
max = (1 << (bits - 1)) - 1;
min = - (1 << (bits - 1));
}
else
{
max = (1 << bits) - 1;
min = 0;
}
test = val;
if (test < (offsetT) min || test > (offsetT) max)
return FALSE;
}
return TRUE;
}
/* Insert an operand value into an instruction. */
static void
mn10300_insert_operand (unsigned long *insnp,
unsigned long *extensionp,
const struct mn10300_operand *operand,
offsetT val,
char *file,
unsigned int line,
unsigned int shift)
{
/* No need to check 32bit operands for a bit. Note that
MN10300_OPERAND_SPLIT is an implicit 32bit operand. */
if (operand->bits != 32
&& (operand->flags & MN10300_OPERAND_SPLIT) == 0)
{
long min, max;
offsetT test;
int bits;
bits = operand->bits;
if (operand->flags & MN10300_OPERAND_24BIT)
bits = 24;
if ((operand->flags & MN10300_OPERAND_SIGNED) != 0)
{
max = (1 << (bits - 1)) - 1;
min = - (1 << (bits - 1));
}
else
{
max = (1 << bits) - 1;
min = 0;
}
test = val;
if (test < (offsetT) min || test > (offsetT) max)
as_warn_value_out_of_range (_("operand"), test, (offsetT) min, (offsetT) max, file, line);
}
if ((operand->flags & MN10300_OPERAND_SPLIT) != 0)
{
*insnp |= (val >> (32 - operand->bits)) & ((1 << operand->bits) - 1);
*extensionp |= ((val & ((1 << (32 - operand->bits)) - 1))
<< operand->shift);
}
else if ((operand->flags & MN10300_OPERAND_24BIT) != 0)
{
*insnp |= (val >> (24 - operand->bits)) & ((1 << operand->bits) - 1);
*extensionp |= ((val & ((1 << (24 - operand->bits)) - 1))
<< operand->shift);
}
else if ((operand->flags & (MN10300_OPERAND_FSREG | MN10300_OPERAND_FDREG)))
{
/* See devo/opcodes/m10300-opc.c just before #define FSM0 for an
explanation of these variables. Note that FMT-implied shifts
are not taken into account for FP registers. */
unsigned long mask_low, mask_high;
int shl_low, shr_high, shl_high;
switch (operand->bits)
{
case 5:
/* Handle regular FP registers. */
if (operand->shift >= 0)
{
/* This is an `m' register. */
shl_low = operand->shift;
shl_high = 8 + (8 & shl_low) + (shl_low & 4) / 4;
}
else
{
/* This is an `n' register. */
shl_low = -operand->shift;
shl_high = shl_low / 4;
}
mask_low = 0x0f;
mask_high = 0x10;
shr_high = 4;
break;
case 3:
/* Handle accumulators. */
shl_low = -operand->shift;
shl_high = 0;
mask_low = 0x03;
mask_high = 0x04;
shr_high = 2;
break;
default:
abort ();
}
*insnp |= ((((val & mask_high) >> shr_high) << shl_high)
| ((val & mask_low) << shl_low));
}
else if ((operand->flags & MN10300_OPERAND_EXTENDED) == 0)
{
*insnp |= (((long) val & ((1 << operand->bits) - 1))
<< (operand->shift + shift));
if ((operand->flags & MN10300_OPERAND_REPEATED) != 0)
*insnp |= (((long) val & ((1 << operand->bits) - 1))
<< (operand->shift + shift + operand->bits));
}
else
{
*extensionp |= (((long) val & ((1 << operand->bits) - 1))
<< (operand->shift + shift));
if ((operand->flags & MN10300_OPERAND_REPEATED) != 0)
*extensionp |= (((long) val & ((1 << operand->bits) - 1))
<< (operand->shift + shift + operand->bits));
}
}
void
md_assemble (char *str)
{
char *s;
struct mn10300_opcode *opcode;
struct mn10300_opcode *next_opcode;
const unsigned char *opindex_ptr;
int next_opindex, relaxable;
unsigned long insn, extension, size = 0;
char *f;
int i;
int match;
/* Get the opcode. */
for (s = str; *s != '\0' && !ISSPACE (*s); s++)
;
if (*s != '\0')
*s++ = '\0';
/* Find the first opcode with the proper name. */
opcode = (struct mn10300_opcode *) hash_find (mn10300_hash, str);
if (opcode == NULL)
{
as_bad (_("Unrecognized opcode: `%s'"), str);
return;
}
str = s;
while (ISSPACE (*str))
++str;
input_line_pointer = str;
for (;;)
{
const char *errmsg;
int op_idx;
char *hold;
int extra_shift = 0;
errmsg = _("Invalid opcode/operands");
/* Reset the array of register operands. */
memset (mn10300_reg_operands, -1, sizeof (mn10300_reg_operands));
relaxable = 0;
fc = 0;
match = 0;
next_opindex = 0;
insn = opcode->opcode;
extension = 0;
/* If the instruction is not available on the current machine
then it can not possibly match. */
if (opcode->machine
&& !(opcode->machine == AM33_2 && HAVE_AM33_2)
&& !(opcode->machine == AM33 && HAVE_AM33)
&& !(opcode->machine == AM30 && HAVE_AM30))
goto error;
for (op_idx = 1, opindex_ptr = opcode->operands;
*opindex_ptr != 0;
opindex_ptr++, op_idx++)
{
const struct mn10300_operand *operand;
expressionS ex;
if (next_opindex == 0)
{
operand = &mn10300_operands[*opindex_ptr];
}
else
{
operand = &mn10300_operands[next_opindex];
next_opindex = 0;
}
while (*str == ' ' || *str == ',')
++str;
if (operand->flags & MN10300_OPERAND_RELAX)
relaxable = 1;
/* Gather the operand. */
hold = input_line_pointer;
input_line_pointer = str;
if (operand->flags & MN10300_OPERAND_PAREN)
{
if (*input_line_pointer != ')' && *input_line_pointer != '(')
{
input_line_pointer = hold;
str = hold;
goto error;
}
input_line_pointer++;
goto keep_going;
}
/* See if we can match the operands. */
else if (operand->flags & MN10300_OPERAND_DREG)
{
if (!data_register_name (&ex))
{
input_line_pointer = hold;
str = hold;
goto error;
}
}
else if (operand->flags & MN10300_OPERAND_AREG)
{
if (!address_register_name (&ex))
{
input_line_pointer = hold;
str = hold;
goto error;
}
}
else if (operand->flags & MN10300_OPERAND_SP)
{
char *start;
char c = get_symbol_name (&start);
if (strcasecmp (start, "sp") != 0)
{
(void) restore_line_pointer (c);
input_line_pointer = hold;
str = hold;
goto error;
}
(void) restore_line_pointer (c);
goto keep_going;
}
else if (operand->flags & MN10300_OPERAND_RREG)
{
if (!r_register_name (&ex))
{
input_line_pointer = hold;
str = hold;
goto error;
}
}
else if (operand->flags & MN10300_OPERAND_XRREG)
{
if (!xr_register_name (&ex))
{
input_line_pointer = hold;
str = hold;
goto error;
}
}
else if (operand->flags & MN10300_OPERAND_FSREG)
{
if (!float_register_name (&ex))
{
input_line_pointer = hold;
str = hold;
goto error;
}
}
else if (operand->flags & MN10300_OPERAND_FDREG)
{
if (!double_register_name (&ex))
{
input_line_pointer = hold;
str = hold;
goto error;
}
}
else if (operand->flags & MN10300_OPERAND_FPCR)
{
char *start;
char c = get_symbol_name (&start);
if (strcasecmp (start, "fpcr") != 0)
{
(void) restore_line_pointer (c);
input_line_pointer = hold;
str = hold;
goto error;
}
(void) restore_line_pointer (c);
goto keep_going;
}
else if (operand->flags & MN10300_OPERAND_USP)
{
char *start;
char c = get_symbol_name (&start);
if (strcasecmp (start, "usp") != 0)
{
(void) restore_line_pointer (c);
input_line_pointer = hold;
str = hold;
goto error;
}
(void) restore_line_pointer (c);
goto keep_going;
}
else if (operand->flags & MN10300_OPERAND_SSP)
{
char *start;
char c = get_symbol_name (&start);
if (strcasecmp (start, "ssp") != 0)
{
(void) restore_line_pointer (c);
input_line_pointer = hold;
str = hold;
goto error;
}
(void) restore_line_pointer (c);
goto keep_going;
}
else if (operand->flags & MN10300_OPERAND_MSP)
{
char *start;
char c = get_symbol_name (&start);
if (strcasecmp (start, "msp") != 0)
{
(void) restore_line_pointer (c);
input_line_pointer = hold;
str = hold;
goto error;
}
(void) restore_line_pointer (c);
goto keep_going;
}
else if (operand->flags & MN10300_OPERAND_PC)
{
char *start;
char c = get_symbol_name (&start);
if (strcasecmp (start, "pc") != 0)
{
(void) restore_line_pointer (c);
input_line_pointer = hold;
str = hold;
goto error;
}
(void) restore_line_pointer (c);
goto keep_going;
}
else if (operand->flags & MN10300_OPERAND_EPSW)
{
char *start;
char c = get_symbol_name (&start);
if (strcasecmp (start, "epsw") != 0)
{
(void) restore_line_pointer (c);
input_line_pointer = hold;
str = hold;
goto error;
}
(void) restore_line_pointer (c);
goto keep_going;
}
else if (operand->flags & MN10300_OPERAND_PLUS)
{
if (*input_line_pointer != '+')
{
input_line_pointer = hold;
str = hold;
goto error;
}
input_line_pointer++;
goto keep_going;
}
else if (operand->flags & MN10300_OPERAND_PSW)
{
char *start;
char c = get_symbol_name (&start);
if (strcasecmp (start, "psw") != 0)
{
(void) restore_line_pointer (c);
input_line_pointer = hold;
str = hold;
goto error;
}
(void) restore_line_pointer (c);
goto keep_going;
}
else if (operand->flags & MN10300_OPERAND_MDR)
{
char *start;
char c = get_symbol_name (&start);
if (strcasecmp (start, "mdr") != 0)
{
(void) restore_line_pointer (c);
input_line_pointer = hold;
str = hold;
goto error;
}
(void) restore_line_pointer (c);
goto keep_going;
}
else if (operand->flags & MN10300_OPERAND_REG_LIST)
{
unsigned int value = 0;
if (*input_line_pointer != '[')
{
input_line_pointer = hold;
str = hold;
goto error;
}
/* Eat the '['. */
input_line_pointer++;
/* We used to reject a null register list here; however,
we accept it now so the compiler can emit "call"
instructions for all calls to named functions.
The linker can then fill in the appropriate bits for the
register list and stack size or change the instruction
into a "calls" if using "call" is not profitable. */
while (*input_line_pointer != ']')
{
char *start;
char c;
if (*input_line_pointer == ',')
input_line_pointer++;
c = get_symbol_name (&start);
if (strcasecmp (start, "d2") == 0)
{
value |= 0x80;
(void) restore_line_pointer (c);
}
else if (strcasecmp (start, "d3") == 0)
{
value |= 0x40;
(void) restore_line_pointer (c);
}
else if (strcasecmp (start, "a2") == 0)
{
value |= 0x20;
(void) restore_line_pointer (c);
}
else if (strcasecmp (start, "a3") == 0)
{
value |= 0x10;
(void) restore_line_pointer (c);
}
else if (strcasecmp (start, "other") == 0)
{
value |= 0x08;
(void) restore_line_pointer (c);
}
else if (HAVE_AM33
&& strcasecmp (start, "exreg0") == 0)
{
value |= 0x04;
(void) restore_line_pointer (c);
}
else if (HAVE_AM33
&& strcasecmp (start, "exreg1") == 0)
{
value |= 0x02;
(void) restore_line_pointer (c);
}
else if (HAVE_AM33
&& strcasecmp (start, "exother") == 0)
{
value |= 0x01;
(void) restore_line_pointer (c);
}
else if (HAVE_AM33
&& strcasecmp (start, "all") == 0)
{
value |= 0xff;
(void) restore_line_pointer (c);
}
else
{
input_line_pointer = hold;
str = hold;
goto error;
}
}
input_line_pointer++;
mn10300_insert_operand (& insn, & extension, operand,
value, NULL, 0, 0);
goto keep_going;
}
else if (data_register_name (&ex))
{
input_line_pointer = hold;
str = hold;
goto error;
}
else if (address_register_name (&ex))
{
input_line_pointer = hold;
str = hold;
goto error;
}
else if (other_register_name (&ex))
{
input_line_pointer = hold;
str = hold;
goto error;
}
else if (HAVE_AM33 && r_register_name (&ex))
{
input_line_pointer = hold;
str = hold;
goto error;
}
else if (HAVE_AM33 && xr_register_name (&ex))
{
input_line_pointer = hold;
str = hold;
goto error;
}
else if (HAVE_AM33_2 && float_register_name (&ex))
{
input_line_pointer = hold;
str = hold;
goto error;
}
else if (HAVE_AM33_2 && double_register_name (&ex))
{
input_line_pointer = hold;
str = hold;
goto error;
}
else if (*str == ')' || *str == '(')
{
input_line_pointer = hold;
str = hold;
goto error;
}
else
{
expression (&ex);
}
switch (ex.X_op)
{
case O_illegal:
errmsg = _("illegal operand");
goto error;
case O_absent:
errmsg = _("missing operand");
goto error;
case O_register:
{
int mask;
mask = MN10300_OPERAND_DREG | MN10300_OPERAND_AREG;
if (HAVE_AM33)
mask |= MN10300_OPERAND_RREG | MN10300_OPERAND_XRREG;
if (HAVE_AM33_2)
mask |= MN10300_OPERAND_FSREG | MN10300_OPERAND_FDREG;
if ((operand->flags & mask) == 0)
{
input_line_pointer = hold;
str = hold;
goto error;
}
if (opcode->format == FMT_D1 || opcode->format == FMT_S1)
extra_shift = 8;
else if (opcode->format == FMT_D2
|| opcode->format == FMT_D4
|| opcode->format == FMT_S2
|| opcode->format == FMT_S4
|| opcode->format == FMT_S6
|| opcode->format == FMT_D5)
extra_shift = 16;
else if (opcode->format == FMT_D7)
extra_shift = 8;
else if (opcode->format == FMT_D8 || opcode->format == FMT_D9)
extra_shift = 8;
else
extra_shift = 0;
mn10300_insert_operand (& insn, & extension, operand,
ex.X_add_number, NULL,
0, extra_shift);
/* And note the register number in the register array. */
mn10300_reg_operands[op_idx - 1] = ex.X_add_number;
break;
}
case O_constant:
/* If this operand can be promoted, and it doesn't
fit into the allocated bitfield for this insn,
then promote it (ie this opcode does not match). */
if (operand->flags
& (MN10300_OPERAND_PROMOTE | MN10300_OPERAND_RELAX)
&& !check_operand (operand, ex.X_add_number))
{
input_line_pointer = hold;
str = hold;
goto error;
}
mn10300_insert_operand (& insn, & extension, operand,
ex.X_add_number, NULL, 0, 0);
break;
default:
/* If this operand can be promoted, then this opcode didn't
match since we can't know if it needed promotion! */
if (operand->flags & MN10300_OPERAND_PROMOTE)
{
input_line_pointer = hold;
str = hold;
goto error;
}
/* We need to generate a fixup for this expression. */
if (fc >= MAX_INSN_FIXUPS)
as_fatal (_("too many fixups"));
fixups[fc].exp = ex;
fixups[fc].opindex = *opindex_ptr;
fixups[fc].reloc = BFD_RELOC_UNUSED;
if (mn10300_check_fixup (& fixups[fc]))
goto error;
++fc;
break;
}
keep_going:
str = input_line_pointer;
input_line_pointer = hold;
while (*str == ' ' || *str == ',')
++str;
}
/* Make sure we used all the operands! */
if (*str != ',')
match = 1;
/* If this instruction has registers that must not match, verify
that they do indeed not match. */
if (opcode->no_match_operands)
{
/* Look at each operand to see if it's marked. */
for (i = 0; i < MN10300_MAX_OPERANDS; i++)
{
if ((1 << i) & opcode->no_match_operands)
{
int j;
/* operand I is marked. Check that it does not match any
operands > I which are marked. */
for (j = i + 1; j < MN10300_MAX_OPERANDS; j++)
{
if (((1 << j) & opcode->no_match_operands)
&& mn10300_reg_operands[i] == mn10300_reg_operands[j])
{
errmsg = _("Invalid register specification.");
match = 0;
goto error;
}
}
}
}
}
error:
if (match == 0)
{
next_opcode = opcode + 1;
if (!strcmp (next_opcode->name, opcode->name))
{
opcode = next_opcode;
continue;
}
as_bad ("%s", errmsg);
return;
}
break;
}
while (ISSPACE (*str))
++str;
if (*str != '\0')
as_bad (_("junk at end of line: `%s'"), str);
input_line_pointer = str;
/* Determine the size of the instruction. */
if (opcode->format == FMT_S0)
size = 1;
if (opcode->format == FMT_S1 || opcode->format == FMT_D0)
size = 2;
if (opcode->format == FMT_S2 || opcode->format == FMT_D1)
size = 3;
if (opcode->format == FMT_D6)
size = 3;
if (opcode->format == FMT_D7 || opcode->format == FMT_D10)
size = 4;
if (opcode->format == FMT_D8)
size = 6;
if (opcode->format == FMT_D9)
size = 7;
if (opcode->format == FMT_S4)
size = 5;
if (opcode->format == FMT_S6 || opcode->format == FMT_D5)
size = 7;
if (opcode->format == FMT_D2)
size = 4;
if (opcode->format == FMT_D3)
size = 5;
if (opcode->format == FMT_D4)
size = 6;
if (relaxable && fc > 0)
{
/* On a 64-bit host the size of an 'int' is not the same
as the size of a pointer, so we need a union to convert
the opindex field of the fr_cgen structure into a char *
so that it can be stored in the frag. We do not have
to worry about losing accuracy as we are not going to
be even close to the 32bit limit of the int. */
union
{
int opindex;
char * ptr;
}
opindex_converter;
int type;
/* We want to anchor the line info to the previous frag (if
there isn't one, create it), so that, when the insn is
resized, we still get the right address for the beginning of
the region. */
f = frag_more (0);
dwarf2_emit_insn (0);
/* bCC */
if (size == 2)
{
/* Handle bra specially. Basically treat it like jmp so
that we automatically handle 8, 16 and 32 bit offsets
correctly as well as jumps to an undefined address.
It is also important to not treat it like other bCC
instructions since the long forms of bra is different
from other bCC instructions. */
if (opcode->opcode == 0xca00)
type = 10;
else
type = 0;
}
/* call */
else if (size == 5)
type = 6;
/* calls */
else if (size == 4)
type = 8;
/* jmp */
else if (size == 3 && opcode->opcode == 0xcc0000)
type = 10;
else if (size == 3 && (opcode->opcode & 0xfff000) == 0xf8d000)
type = 13;
/* bCC (uncommon cases) */
else
type = 3;
opindex_converter.opindex = fixups[0].opindex;
f = frag_var (rs_machine_dependent, 8, 8 - size, type,
fixups[0].exp.X_add_symbol,
fixups[0].exp.X_add_number,
opindex_converter.ptr);
/* This is pretty hokey. We basically just care about the
opcode, so we have to write out the first word big endian.
The exception is "call", which has two operands that we
care about.
The first operand (the register list) happens to be in the
first instruction word, and will be in the right place if
we output the first word in big endian mode.
The second operand (stack size) is in the extension word,
and we want it to appear as the first character in the extension
word (as it appears in memory). Luckily, writing the extension
word in big endian format will do what we want. */
number_to_chars_bigendian (f, insn, size > 4 ? 4 : size);
if (size > 8)
{
number_to_chars_bigendian (f + 4, extension, 4);
number_to_chars_bigendian (f + 8, 0, size - 8);
}
else if (size > 4)
number_to_chars_bigendian (f + 4, extension, size - 4);
}
else
{
/* Allocate space for the instruction. */
f = frag_more (size);
/* Fill in bytes for the instruction. Note that opcode fields
are written big-endian, 16 & 32bit immediates are written
little endian. Egad. */
if (opcode->format == FMT_S0
|| opcode->format == FMT_S1
|| opcode->format == FMT_D0
|| opcode->format == FMT_D6
|| opcode->format == FMT_D7
|| opcode->format == FMT_D10
|| opcode->format == FMT_D1)
{
number_to_chars_bigendian (f, insn, size);
}
else if (opcode->format == FMT_S2
&& opcode->opcode != 0xdf0000
&& opcode->opcode != 0xde0000)
{
/* A format S2 instruction that is _not_ "ret" and "retf". */
number_to_chars_bigendian (f, (insn >> 16) & 0xff, 1);
number_to_chars_littleendian (f + 1, insn & 0xffff, 2);
}
else if (opcode->format == FMT_S2)
{
/* This must be a ret or retf, which is written entirely in
big-endian format. */
number_to_chars_bigendian (f, insn, 3);
}
else if (opcode->format == FMT_S4
&& opcode->opcode != 0xdc000000)
{
/* This must be a format S4 "call" instruction. What a pain. */
unsigned long temp = (insn >> 8) & 0xffff;
number_to_chars_bigendian (f, (insn >> 24) & 0xff, 1);
number_to_chars_littleendian (f + 1, temp, 2);
number_to_chars_bigendian (f + 3, insn & 0xff, 1);
number_to_chars_bigendian (f + 4, extension & 0xff, 1);
}
else if (opcode->format == FMT_S4)
{
/* This must be a format S4 "jmp" instruction. */
unsigned long temp = ((insn & 0xffffff) << 8) | (extension & 0xff);
number_to_chars_bigendian (f, (insn >> 24) & 0xff, 1);
number_to_chars_littleendian (f + 1, temp, 4);
}
else if (opcode->format == FMT_S6)
{
unsigned long temp = ((insn & 0xffffff) << 8)
| ((extension >> 16) & 0xff);
number_to_chars_bigendian (f, (insn >> 24) & 0xff, 1);
number_to_chars_littleendian (f + 1, temp, 4);
number_to_chars_bigendian (f + 5, (extension >> 8) & 0xff, 1);
number_to_chars_bigendian (f + 6, extension & 0xff, 1);
}
else if (opcode->format == FMT_D2
&& opcode->opcode != 0xfaf80000
&& opcode->opcode != 0xfaf00000
&& opcode->opcode != 0xfaf40000)
{
/* A format D2 instruction where the 16bit immediate is
really a single 16bit value, not two 8bit values. */
number_to_chars_bigendian (f, (insn >> 16) & 0xffff, 2);
number_to_chars_littleendian (f + 2, insn & 0xffff, 2);
}
else if (opcode->format == FMT_D2)
{
/* A format D2 instruction where the 16bit immediate
is really two 8bit immediates. */
number_to_chars_bigendian (f, insn, 4);
}
else if (opcode->format == FMT_D3)
{
number_to_chars_bigendian (f, (insn >> 16) & 0xffff, 2);
number_to_chars_littleendian (f + 2, insn & 0xffff, 2);
number_to_chars_bigendian (f + 4, extension & 0xff, 1);
}
else if (opcode->format == FMT_D4)
{
unsigned long temp = ((insn & 0xffff) << 16) | (extension & 0xffff);
number_to_chars_bigendian (f, (insn >> 16) & 0xffff, 2);
number_to_chars_littleendian (f + 2, temp, 4);
}
else if (opcode->format == FMT_D5)
{
unsigned long temp = (((insn & 0xffff) << 16)
| ((extension >> 8) & 0xffff));
number_to_chars_bigendian (f, (insn >> 16) & 0xffff, 2);
number_to_chars_littleendian (f + 2, temp, 4);
number_to_chars_bigendian (f + 6, extension & 0xff, 1);
}
else if (opcode->format == FMT_D8)
{
unsigned long temp = ((insn & 0xff) << 16) | (extension & 0xffff);
number_to_chars_bigendian (f, (insn >> 8) & 0xffffff, 3);
number_to_chars_bigendian (f + 3, (temp & 0xff), 1);
number_to_chars_littleendian (f + 4, temp >> 8, 2);
}
else if (opcode->format == FMT_D9)
{
unsigned long temp = ((insn & 0xff) << 24) | (extension & 0xffffff);
number_to_chars_bigendian (f, (insn >> 8) & 0xffffff, 3);
number_to_chars_littleendian (f + 3, temp, 4);
}
/* Create any fixups. */
for (i = 0; i < fc; i++)
{
const struct mn10300_operand *operand;
int reloc_size;
operand = &mn10300_operands[fixups[i].opindex];
if (fixups[i].reloc != BFD_RELOC_UNUSED
&& fixups[i].reloc != BFD_RELOC_32_GOT_PCREL
&& fixups[i].reloc != BFD_RELOC_32_GOTOFF
&& fixups[i].reloc != BFD_RELOC_32_PLT_PCREL
&& fixups[i].reloc != BFD_RELOC_MN10300_TLS_GD
&& fixups[i].reloc != BFD_RELOC_MN10300_TLS_LD
&& fixups[i].reloc != BFD_RELOC_MN10300_TLS_LDO
&& fixups[i].reloc != BFD_RELOC_MN10300_TLS_GOTIE
&& fixups[i].reloc != BFD_RELOC_MN10300_TLS_IE
&& fixups[i].reloc != BFD_RELOC_MN10300_TLS_LE
&& fixups[i].reloc != BFD_RELOC_MN10300_GOT32)
{
reloc_howto_type *reloc_howto;
int offset;
reloc_howto = bfd_reloc_type_lookup (stdoutput,
fixups[i].reloc);
if (!reloc_howto)
abort ();
reloc_size = bfd_get_reloc_size (reloc_howto);
if (reloc_size < 1 || reloc_size > 4)
abort ();
offset = 4 - size;
fix_new_exp (frag_now, f - frag_now->fr_literal + offset,
reloc_size, &fixups[i].exp,
reloc_howto->pc_relative,
fixups[i].reloc);
}
else
{
int reloc, pcrel, offset;
fixS *fixP;
reloc = BFD_RELOC_NONE;
if (fixups[i].reloc != BFD_RELOC_UNUSED)
reloc = fixups[i].reloc;
/* How big is the reloc? Remember SPLIT relocs are
implicitly 32bits. */
if ((operand->flags & MN10300_OPERAND_SPLIT) != 0)
reloc_size = 32;
else if ((operand->flags & MN10300_OPERAND_24BIT) != 0)
reloc_size = 24;
else
reloc_size = operand->bits;
/* Is the reloc pc-relative? */
pcrel = (operand->flags & MN10300_OPERAND_PCREL) != 0;
if (reloc != BFD_RELOC_NONE)
pcrel = bfd_reloc_type_lookup (stdoutput, reloc)->pc_relative;
offset = size - (reloc_size + operand->shift) / 8;
/* Choose a proper BFD relocation type. */
if (reloc != BFD_RELOC_NONE)
;
else if (pcrel)
{
if (reloc_size == 32)
reloc = BFD_RELOC_32_PCREL;
else if (reloc_size == 16)
reloc = BFD_RELOC_16_PCREL;
else if (reloc_size == 8)
reloc = BFD_RELOC_8_PCREL;
else
abort ();
}
else
{
if (reloc_size == 32)
reloc = BFD_RELOC_32;
else if (reloc_size == 16)
reloc = BFD_RELOC_16;
else if (reloc_size == 8)
reloc = BFD_RELOC_8;
else
abort ();
}
fixP = fix_new_exp (frag_now, f - frag_now->fr_literal + offset,
reloc_size / 8, &fixups[i].exp, pcrel,
((bfd_reloc_code_real_type) reloc));
if (pcrel)
fixP->fx_offset += offset;
}
}
dwarf2_emit_insn (size);
}
/* Label this frag as one that contains instructions. */
frag_now->tc_frag_data = TRUE;
}
/* If while processing a fixup, a reloc really needs to be created
then it is done here. */
arelent **
tc_gen_reloc (asection *seg ATTRIBUTE_UNUSED, fixS *fixp)
{
static arelent * no_relocs = NULL;
static arelent * relocs[MAX_RELOC_EXPANSION + 1];
arelent *reloc;
reloc = XNEW (arelent);
reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
if (reloc->howto == NULL)
{
as_bad_where (fixp->fx_file, fixp->fx_line,
_("reloc %d not supported by object file format"),
(int) fixp->fx_r_type);
free (reloc);
return & no_relocs;
}
reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
relocs[0] = reloc;
relocs[1] = NULL;
if (fixp->fx_subsy
&& S_GET_SEGMENT (fixp->fx_subsy) == absolute_section)
{
fixp->fx_offset -= S_GET_VALUE (fixp->fx_subsy);
fixp->fx_subsy = NULL;
}
if (fixp->fx_addsy && fixp->fx_subsy)
{
asection *asec, *ssec;
asec = S_GET_SEGMENT (fixp->fx_addsy);
ssec = S_GET_SEGMENT (fixp->fx_subsy);
/* If we have a difference between two (non-absolute) symbols we must
generate two relocs (one for each symbol) and allow the linker to
resolve them - relaxation may change the distances between symbols,
even local symbols defined in the same section. */
if (ssec != absolute_section || asec != absolute_section)
{
arelent * reloc2 = XNEW (arelent);
relocs[0] = reloc2;
relocs[1] = reloc;
reloc2->address = reloc->address;
reloc2->howto = bfd_reloc_type_lookup (stdoutput, BFD_RELOC_MN10300_SYM_DIFF);
reloc2->addend = - S_GET_VALUE (fixp->fx_subsy);
reloc2->sym_ptr_ptr = XNEW (asymbol *);
*reloc2->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_subsy);
reloc->addend = fixp->fx_offset;
if (asec == absolute_section)
{
reloc->addend += S_GET_VALUE (fixp->fx_addsy);
reloc->sym_ptr_ptr = bfd_abs_section_ptr->symbol_ptr_ptr;
}
else
{
reloc->sym_ptr_ptr = XNEW (asymbol *);
*reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
}
fixp->fx_pcrel = 0;
fixp->fx_done = 1;
return relocs;
}
else
{
char *fixpos = fixp->fx_where + fixp->fx_frag->fr_literal;
reloc->addend = (S_GET_VALUE (fixp->fx_addsy)
- S_GET_VALUE (fixp->fx_subsy) + fixp->fx_offset);
switch (fixp->fx_r_type)
{
case BFD_RELOC_8:
md_number_to_chars (fixpos, reloc->addend, 1);
break;
case BFD_RELOC_16:
md_number_to_chars (fixpos, reloc->addend, 2);
break;
case BFD_RELOC_24:
md_number_to_chars (fixpos, reloc->addend, 3);
break;
case BFD_RELOC_32:
md_number_to_chars (fixpos, reloc->addend, 4);
break;
default:
reloc->sym_ptr_ptr
= (asymbol **) bfd_abs_section_ptr->symbol_ptr_ptr;
return relocs;
}
free (reloc);
return & no_relocs;
}
}
else
{
reloc->sym_ptr_ptr = XNEW (asymbol *);
*reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
reloc->addend = fixp->fx_offset;
}
return relocs;
}
/* Returns true iff the symbol attached to the frag is at a known location
in the given section, (and hence the relocation to it can be relaxed by
the assembler). */
static inline bfd_boolean
has_known_symbol_location (fragS * fragp, asection * sec)
{
symbolS * sym = fragp->fr_symbol;
return sym != NULL
&& S_IS_DEFINED (sym)
&& ! S_IS_WEAK (sym)
&& S_GET_SEGMENT (sym) == sec;
}
int
md_estimate_size_before_relax (fragS *fragp, asection *seg)
{
if (fragp->fr_subtype == 6
&& ! has_known_symbol_location (fragp, seg))
fragp->fr_subtype = 7;
else if (fragp->fr_subtype == 8
&& ! has_known_symbol_location (fragp, seg))
fragp->fr_subtype = 9;
else if (fragp->fr_subtype == 10
&& ! has_known_symbol_location (fragp, seg))
fragp->fr_subtype = 12;
if (fragp->fr_subtype == 13)
return 3;
if (fragp->fr_subtype >= sizeof (md_relax_table) / sizeof (md_relax_table[0]))
abort ();
return md_relax_table[fragp->fr_subtype].rlx_length;
}
long
md_pcrel_from (fixS *fixp)
{
if (fixp->fx_addsy != (symbolS *) NULL
&& (!S_IS_DEFINED (fixp->fx_addsy) || S_IS_WEAK (fixp->fx_addsy)))
/* The symbol is undefined or weak. Let the linker figure it out. */
return 0;
return fixp->fx_frag->fr_address + fixp->fx_where;
}
void
md_apply_fix (fixS * fixP, valueT * valP, segT seg)
{
char * fixpos = fixP->fx_where + fixP->fx_frag->fr_literal;
int size = 0;
int value = (int) * valP;
gas_assert (fixP->fx_r_type < BFD_RELOC_UNUSED);
/* This should never happen. */
if (seg->flags & SEC_ALLOC)
abort ();
/* The value we are passed in *valuep includes the symbol values.
If we are doing this relocation the code in write.c is going to
call bfd_install_relocation, which is also going to use the symbol
value. That means that if the reloc is fully resolved we want to
use *valuep since bfd_install_relocation is not being used.
However, if the reloc is not fully resolved we do not want to use
*valuep, and must use fx_offset instead. However, if the reloc
is PC relative, we do want to use *valuep since it includes the
result of md_pcrel_from. */
if (fixP->fx_addsy != NULL && ! fixP->fx_pcrel)
value = fixP->fx_offset;
/* If the fix is relative to a symbol which is not defined, or not
in the same segment as the fix, we cannot resolve it here. */
if (fixP->fx_addsy != NULL
&& (! S_IS_DEFINED (fixP->fx_addsy)
|| (S_GET_SEGMENT (fixP->fx_addsy) != seg)))
{
fixP->fx_done = 0;
return;
}
switch (fixP->fx_r_type)
{
case BFD_RELOC_8:
case BFD_RELOC_8_PCREL:
size = 1;
break;
case BFD_RELOC_16:
case BFD_RELOC_16_PCREL:
size = 2;
break;
case BFD_RELOC_32:
case BFD_RELOC_32_PCREL:
size = 4;
break;
case BFD_RELOC_VTABLE_INHERIT:
case BFD_RELOC_VTABLE_ENTRY:
fixP->fx_done = 0;
return;
case BFD_RELOC_MN10300_ALIGN:
fixP->fx_done = 1;
return;
case BFD_RELOC_NONE:
default:
as_bad_where (fixP->fx_file, fixP->fx_line,
_("Bad relocation fixup type (%d)"), fixP->fx_r_type);
}
md_number_to_chars (fixpos, value, size);
/* If a symbol remains, pass the fixup, as a reloc, onto the linker. */
if (fixP->fx_addsy == NULL)
fixP->fx_done = 1;
}
/* Return zero if the fixup in fixp should be left alone and not
adjusted. */
bfd_boolean
mn10300_fix_adjustable (struct fix *fixp)
{
if (fixp->fx_pcrel)
{
if (TC_FORCE_RELOCATION_LOCAL (fixp))
return FALSE;
}
/* Non-relative relocs can (and must) be adjusted if they do
not meet the criteria below, or the generic criteria. */
else if (TC_FORCE_RELOCATION (fixp))
return FALSE;
/* Do not adjust relocations involving symbols in code sections,
because it breaks linker relaxations. This could be fixed in the
linker, but this fix is simpler, and it pretty much only affects
object size a little bit. */
if (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_CODE)
return FALSE;
/* Likewise, do not adjust symbols that won't be merged, or debug
symbols, because they too break relaxation. We do want to adjust
other mergable symbols, like .rodata, because code relaxations
need section-relative symbols to properly relax them. */
if (! (S_GET_SEGMENT (fixp->fx_addsy)->flags & SEC_MERGE))
return FALSE;
if (strncmp (S_GET_SEGMENT (fixp->fx_addsy)->name, ".debug", 6) == 0)
return FALSE;
return TRUE;
}
static void
set_arch_mach (int mach)
{
if (!bfd_set_arch_mach (stdoutput, bfd_arch_mn10300, mach))
as_warn (_("could not set architecture and machine"));
current_machine = mach;
}
static inline char *
mn10300_end_of_match (char *cont, const char *what)
{
int len = strlen (what);
if (strncmp (cont, what, strlen (what)) == 0
&& ! is_part_of_name (cont[len]))
return cont + len;
return NULL;
}
int
mn10300_parse_name (char const *name,
expressionS *exprP,
enum expr_mode mode,
char *nextcharP)
{
char *next = input_line_pointer;
char *next_end;
int reloc_type;
segT segment;
exprP->X_op_symbol = NULL;
if (strcmp (name, GLOBAL_OFFSET_TABLE_NAME) == 0)
{
if (! GOT_symbol)
GOT_symbol = symbol_find_or_make (name);
exprP->X_add_symbol = GOT_symbol;
no_suffix:
/* If we have an absolute symbol or a reg,
then we know its value now. */
segment = S_GET_SEGMENT (exprP->X_add_symbol);
if (mode != expr_defer && segment == absolute_section)
{
exprP->X_op = O_constant;
exprP->X_add_number = S_GET_VALUE (exprP->X_add_symbol);
exprP->X_add_symbol = NULL;
}
else if (mode != expr_defer && segment == reg_section)
{
exprP->X_op = O_register;
exprP->X_add_number = S_GET_VALUE (exprP->X_add_symbol);
exprP->X_add_symbol = NULL;
}
else
{
exprP->X_op = O_symbol;
exprP->X_add_number = 0;
}
return 1;
}
exprP->X_add_symbol = symbol_find_or_make (name);
if (*nextcharP != '@')
goto no_suffix;
else if ((next_end = mn10300_end_of_match (next + 1, "GOTOFF")))
reloc_type = BFD_RELOC_32_GOTOFF;
else if ((next_end = mn10300_end_of_match (next + 1, "GOT")))
reloc_type = BFD_RELOC_MN10300_GOT32;
else if ((next_end = mn10300_end_of_match (next + 1, "PLT")))
reloc_type = BFD_RELOC_32_PLT_PCREL;
else if ((next_end = mn10300_end_of_match (next + 1, "tlsgd")))
reloc_type = BFD_RELOC_MN10300_TLS_GD;
else if ((next_end = mn10300_end_of_match (next + 1, "tlsldm")))
reloc_type = BFD_RELOC_MN10300_TLS_LD;
else if ((next_end = mn10300_end_of_match (next + 1, "dtpoff")))
reloc_type = BFD_RELOC_MN10300_TLS_LDO;
else if ((next_end = mn10300_end_of_match (next + 1, "gotntpoff")))
reloc_type = BFD_RELOC_MN10300_TLS_GOTIE;
else if ((next_end = mn10300_end_of_match (next + 1, "indntpoff")))
reloc_type = BFD_RELOC_MN10300_TLS_IE;
else if ((next_end = mn10300_end_of_match (next + 1, "tpoff")))
reloc_type = BFD_RELOC_MN10300_TLS_LE;
else
goto no_suffix;
*input_line_pointer = *nextcharP;
input_line_pointer = next_end;
*nextcharP = *input_line_pointer;
*input_line_pointer = '\0';
exprP->X_op = O_PIC_reloc;
exprP->X_add_number = 0;
exprP->X_md = reloc_type;
return 1;
}
/* The target specific pseudo-ops which we support. */
const pseudo_typeS md_pseudo_table[] =
{
{ "am30", set_arch_mach, AM30 },
{ "am33", set_arch_mach, AM33 },
{ "am33_2", set_arch_mach, AM33_2 },
{ "mn10300", set_arch_mach, MN103 },
{NULL, 0, 0}
};
/* Returns FALSE if there is some mn10300 specific reason why the
subtraction of two same-section symbols cannot be computed by
the assembler. */
bfd_boolean
mn10300_allow_local_subtract (expressionS * left, expressionS * right, segT section)
{
bfd_boolean result;
fragS * left_frag;
fragS * right_frag;
fragS * frag;
/* If we are not performing linker relaxation then we have nothing
to worry about. */
if (linkrelax == 0)
return TRUE;
/* If the symbols are not in a code section then they are OK. */
if ((section->flags & SEC_CODE) == 0)
return TRUE;
/* Otherwise we have to scan the fragments between the two symbols.
If any instructions are found then we have to assume that linker
relaxation may change their size and so we must delay resolving
the subtraction until the final link. */
left_frag = symbol_get_frag (left->X_add_symbol);
right_frag = symbol_get_frag (right->X_add_symbol);
if (left_frag == right_frag)
return ! left_frag->tc_frag_data;
result = TRUE;
for (frag = left_frag; frag != NULL; frag = frag->fr_next)
{
if (frag->tc_frag_data)
result = FALSE;
if (frag == right_frag)
break;
}
if (frag == NULL)
for (frag = right_frag; frag != NULL; frag = frag->fr_next)
{
if (frag->tc_frag_data)
result = FALSE;
if (frag == left_frag)
break;
}
if (frag == NULL)
/* The two symbols are on disjoint fragment chains
- we cannot possibly compute their difference. */
return FALSE;
return result;
}
/* When relaxing, we need to output a reloc for any .align directive
that requests alignment to a two byte boundary or larger. */
void
mn10300_handle_align (fragS *frag)
{
if (linkrelax
&& (frag->fr_type == rs_align
|| frag->fr_type == rs_align_code)
&& frag->fr_address + frag->fr_fix > 0
&& frag->fr_offset > 1
&& now_seg != bss_section
/* Do not create relocs for the merging sections - such
relocs will prevent the contents from being merged. */
&& (bfd_get_section_flags (now_seg->owner, now_seg) & SEC_MERGE) == 0)
/* Create a new fixup to record the alignment request. The symbol is
irrelevant but must be present so we use the absolute section symbol.
The offset from the symbol is used to record the power-of-two alignment
value. The size is set to 0 because the frag may already be aligned,
thus causing cvt_frag_to_fill to reduce the size of the frag to zero. */
fix_new (frag, frag->fr_fix, 0, & abs_symbol, frag->fr_offset, FALSE,
BFD_RELOC_MN10300_ALIGN);
}
bfd_boolean
mn10300_force_relocation (struct fix * fixp)
{
if (linkrelax
&& (fixp->fx_pcrel
|| fixp->fx_r_type == BFD_RELOC_MN10300_ALIGN))
return TRUE;
return generic_force_reloc (fixp);
}
|
habemus-papadum/binutils-gdb
|
gas/config/tc-mn10300.c
|
C
|
gpl-2.0
| 66,228 |
<?php
/**
* @package JINC
* @subpackage Graphics
* @copyright Copyright (C) 2010 - Lhacky
* @license GNU/GPL http://www.gnu.org/licenses/gpl-2.0.html
* This file is part of JINC.
*
* JINC 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.
*
* JINC 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 JINC. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Requiring PHP libraries and defining constants
*/
require_once 'compositegraph.php';
require_once 'gpoint.php';
/**
* GCircledPoint class, defining a graphical circled poing.
*
* @package JINC
* @subpackage Graphics
* @since 0.6
*/
class GCircledPoint extends CompositeGraph {
/**
* X value
*
* @var int
*/
var $_x1;
/**
* Y value
*
* @var int
*/
var $_y1;
/**
* Point color. Red intensity
*
* @var int
*/
var $_background_r_color;
/**
* Point color. Green intensity
*
* @var int
*/
var $_background_g_color;
/**
* Point color. Blue intensity
*
* @var int
*/
var $_background_b_color;
/**
* GCircledPoint constructor.
*/
function GCircledPoint() {
parent::CompositeGraph();
$this->setBackgroundColor(255, 255, 255);
}
/**
* Point coordinates setter.
*
* @param integer $x1
* @param integer $y1
*/
function setCoordinates($x1, $y1) {
$this->_x1 = (int) $x1;
$this->_y1 = (int) $y1;
}
/**
* Background color setter.
*
* @param integer $r Red intensity background color
* @param integer $g Green intensity background color
* @param integer $b Blue intensity background color
*/
function setBackgroundColor($r, $g, $b) {
$this->_background_r_color = (int) $r;
$this->_background_g_color = (int) $g;
$this->_background_b_color = (int) $b;
}
/**
* Predisplay function
*
* @return void
*/
function prepare() {
$p1 = new GPoint();
$p1->setCoordinates($this->_x1, $this->_y1);
$bsize = ((int) ($this->getSize() / 3)) + 1;
$p1->setSize($this->getSize() + $bsize);
$p1->setColor($this->_background_r_color, $this->_background_g_color, $this->_background_b_color);
$this->addElement($p1);
$p2 = new GPoint();
$p2->setCoordinates($this->_x1, $this->_y1);
$p2->setSize($this->getSize());
$p2->setColor($this->_r_color, $this->_g_color, $this->_b_color);
$this->addElement($p2);
}
}
?>
|
thiyagarajan/newschool
|
administrator/components/com_jinc/classes/graphics/gcircledpoint.php
|
PHP
|
gpl-2.0
| 3,091 |
<?php
/**
* @version 2.9.x
* @package K2
* @author JoomlaWorks https://www.joomlaworks.net
* @copyright Copyright (c) 2006 - 2018 JoomlaWorks Ltd. All rights reserved.
* @license GNU/GPL license: http://www.gnu.org/copyleft/gpl.html
*/
// no direct access
defined('_JEXEC') or die;
?>
<?php if($this->mainframe->isSite()): ?>
<!-- Frontend Item Editing (Modal View) -->
<div id="k2ModalContainer">
<div id="k2ModalHeader">
<h2 id="k2ModalLogo"><?php echo (JRequest::getInt('cid')) ? JText::_('K2_EDIT_ITEM') : JText::_('K2_ADD_ITEM'); ?></h2>
<table id="k2ModalToolbar" cellpadding="2" cellspacing="4">
<tr>
<td id="toolbar-save" class="button">
<a href="#" onclick="Joomla.submitbutton('save');return false;">
<i class="fa fa-check" aria-hidden="true"></i> <?php echo JText::_('K2_SAVE'); ?>
</a>
</td>
<td id="toolbar-cancel" class="button">
<a href="#">
<i class="fa fa-times-circle" aria-hidden="true"></i> <?php echo JText::_('K2_CLOSE'); ?>
</a>
</td>
</tr>
</table>
</div>
<?php endif; ?>
<form action="<?php echo JRoute::_('index.php'); ?>" enctype="multipart/form-data" method="post" name="adminForm" id="adminForm">
<?php if($this->mainframe->isSite() && !$this->permissions->get('publish')): ?>
<div id="k2ModalPermissionsNotice">
<p><?php echo JText::_('K2_FRONTEND_PERMISSIONS_NOTICE'); ?></p>
</div>
<?php endif; ?>
<!-- Top Nav Tabs START here -->
<div id="k2FormTopNav" class="k2Tabs">
<?php if($this->row->id): ?>
<div id="k2ID"><strong><?php echo JText::_('K2_ID'); ?></strong> <?php echo $this->row->id; ?></div>
<?php endif; ?>
<ul class="k2NavTabs">
<li id="tabContent"><a href="#k2TabBasic"><i class="fa fa-home"></i><?php echo JText::_('K2_BASIC'); ?></a></li>
<li id="tabContent"><a href="#k2TabPubAndMeta"><i class="fa fa-info-circle"></i><?php echo JText::_('K2_PUBLISHING_AND_METADATA'); ?></a></li>
<?php if($this->mainframe->isAdmin()): ?>
<li id="tabContent"><a href="#k2TabDisplaySet"><i class="fa fa-desktop"></i><?php echo JText::_('K2_DISPLAY_SETTINGS'); ?></a></li>
<?php endif; ?>
</ul>
<!-- Top Nav Tabs content -->
<div class="k2NavTabContent" id="k2TabBasic">
<div class="k2Table">
<div class="k2TableLabel">
<label for="title"><?php echo JText::_('K2_TITLE'); ?></label>
</div>
<div class="k2TableValue">
<input class="text_area k2TitleBox" type="text" name="title" id="title" maxlength="250" value="<?php echo $this->row->title; ?>" />
</div>
<div class="k2TableLabel">
<label for="alias"><?php echo JText::_('K2_TITLE_ALIAS'); ?></label>
</div>
<div class="k2TableValue">
<input class="text_area k2TitleAliasBox" type="text" name="alias" id="alias" maxlength="250" value="<?php echo $this->row->alias; ?>" />
</div>
<div class="k2TableLabel">
<label><?php echo JText::_('K2_CATEGORY'); ?></label>
</div>
<div class="k2TableValue">
<?php echo $this->lists['categories']; ?>
<?php if($this->mainframe->isAdmin() || ($this->mainframe->isSite() && $this->permissions->get('publish'))): ?>
<div class="k2SubTable k2TableRight k2TableRightTop">
<div class="k2SubTableLabel">
<label for="featured"><?php echo JText::_('K2_IS_IT_FEATURED'); ?></label>
</div>
<div class="k2SubTableValue">
<?php echo $this->lists['featured']; ?>
</div>
<div class="k2SubTableLabel">
<label><?php echo JText::_('K2_PUBLISHED'); ?></label>
</div>
<div class="k2SubTableValue">
<?php echo $this->lists['published']; ?>
</div>
</div>
<?php endif; ?>
</div>
<div class="k2TableLabel">
<label for="tags"><?php echo JText::_('K2_TAGS'); ?></label>
</div>
<div class="k2TableValue">
<?php if($this->params->get('taggingSystem')): ?>
<!-- Free tagging -->
<ul class="tags">
<?php if(isset($this->row->tags) && count($this->row->tags)): ?>
<?php foreach($this->row->tags as $tag): ?>
<li class="tagAdded">
<?php echo $tag->name; ?>
<span title="<?php echo JText::_('K2_CLICK_TO_REMOVE_TAG'); ?>" class="tagRemove">×</span>
<input type="hidden" name="tags[]" value="<?php echo $tag->name; ?>" />
</li>
<?php endforeach; ?>
<?php endif; ?>
<li class="tagAdd">
<input type="text" id="search-field" />
</li>
<li class="clr"></li>
</ul>
<p class="k2TagsNotice">
<?php echo JText::_('K2_WRITE_A_TAG_AND_PRESS_RETURN_OR_COMMA_TO_ADD_IT'); ?>
</p>
<?php else: ?>
<!-- Selection based tagging -->
<?php if( !$this->params->get('lockTags') || $this->user->gid>23): ?>
<div style="float:left;">
<input type="text" name="tag" id="tag" />
<input type="button" id="newTagButton" value="<?php echo JText::_('K2_ADD'); ?>" />
</div>
<div id="tagsLog"></div>
<div class="clr"></div>
<span class="k2Note">
<?php echo JText::_('K2_WRITE_A_TAG_AND_PRESS_ADD_TO_INSERT_IT_TO_THE_AVAILABLE_TAGS_LISTNEW_TAGS_ARE_APPENDED_AT_THE_BOTTOM_OF_THE_AVAILABLE_TAGS_LIST_LEFT'); ?>
</span>
<?php endif; ?>
<table cellspacing="0" cellpadding="0" border="0" id="tagLists">
<tr>
<td id="tagListsLeft">
<span><?php echo JText::_('K2_AVAILABLE_TAGS'); ?></span> <?php echo $this->lists['tags']; ?>
</td>
<td id="tagListsButtons">
<input type="button" id="addTagButton" value="<?php echo JText::_('K2_ADD'); ?> »" />
<br />
<br />
<input type="button" id="removeTagButton" value="« <?php echo JText::_('K2_REMOVE'); ?>" />
</td>
<td id="tagListsRight">
<span><?php echo JText::_('K2_SELECTED_TAGS'); ?></span> <?php echo $this->lists['selectedTags']; ?>
</td>
</tr>
</table>
<?php endif; ?>
</div>
<div class="k2TableLabel">
<label><?php echo JText::_('K2_AUTHOR'); ?></label>
</div>
<div class="k2TableValue">
<div class="k2SubTable k2TableInline">
<div class="k2SubTableValue">
<span id="k2Author">
<?php echo $this->row->author; ?>
<input type="hidden" name="created_by" value="<?php echo $this->row->created_by; ?>" />
</span>
<?php if($this->mainframe->isAdmin() || ($this->mainframe->isSite() && $this->permissions->get('editAll'))): ?>
<a data-k2-modal="iframe" class="k2Selector" href="index.php?option=com_k2&view=users&tmpl=component&context=modalselector&fid=k2Author&fname=created_by">
<i class="fa fa-pencil"></i>
</a>
<?php endif; ?>
</div>
<div class="k2SubTableLabel">
<label><?php echo JText::_('K2_AUTHOR_ALIAS'); ?></label>
</div>
<div class="k2SubTableValue">
<input class="text_area" type="text" name="created_by_alias" maxlength="250" value="<?php echo $this->row->created_by_alias; ?>" />
</div>
</div>
<div class="k2SubTable k2ItemTableRight k2ItemTableRightPad">
<div class="k2SubTableLabel">
<label><?php echo JText::_('K2_ACCESS_LEVEL'); ?></label>
</div>
<div class="k2SubTableValue">
<?php echo $this->lists['access']; ?>
</div>
<?php if(isset($this->lists['language'])): ?>
<div class="k2SubTableLabel">
<label><?php echo JText::_('K2_LANGUAGE'); ?></label>
</div>
<div class="k2SubTableValue">
<?php echo $this->lists['language']; ?>
</div>
<?php endif; ?>
</div>
</div>
</div>
<!-- Required extra field warning -->
<div id="k2ExtraFieldsValidationResults">
<h3><?php echo JText::_('K2_THE_FOLLOWING_FIELDS_ARE_REQUIRED'); ?></h3>
<ul id="k2ExtraFieldsMissing">
<li><?php echo JText::_('K2_LOADING'); ?></li>
</ul>
</div>
<!-- Tabs start here -->
<div class="k2Tabs" id="k2Tabs">
<ul class="k2TabsNavigation">
<li id="tabContent"><a href="#k2TabContent"><i class="fa fa-file-text-o"></i><?php echo JText::_('K2_CONTENT'); ?></a></li>
<?php if ($this->params->get('showImageTab')): ?>
<li id="tabImage"><a href="#k2TabImage"><i class="fa fa-camera"></i><?php echo JText::_('K2_IMAGE'); ?></a></li>
<?php endif; ?>
<?php if ($this->params->get('showImageGalleryTab')): ?>
<li id="tabImageGallery"><a href="#k2TabImageGallery"><i class="fa fa-file-image-o"></i><?php echo JText::_('K2_IMAGE_GALLERY'); ?></a></li>
<?php endif; ?>
<?php if ($this->params->get('showVideoTab')): ?>
<li id="tabVideo"><a href="#k2TabMedia"><i class="fa fa-file-video-o"></i><?php echo JText::_('K2_MEDIA'); ?></a></li>
<?php endif; ?>
<?php if ($this->params->get('showExtraFieldsTab')): ?>
<li id="tabExtraFields"><a href="#k2TabExtraFields"><i class="fa fa-gear"></i><?php echo JText::_('K2_EXTRA_FIELDS'); ?></a></li>
<?php endif; ?>
<?php if ($this->params->get('showAttachmentsTab')): ?>
<li id="tabAttachments"><a href="#k2TabAttachments"><i class="fa fa-file-o"></i><?php echo JText::_('K2_ATTACHMENTS'); ?></a></li>
<?php endif; ?>
<?php if(count(array_filter($this->K2PluginsItemOther)) && $this->params->get('showK2Plugins')): ?>
<li id="tabPlugins"><a href="#k2TabPlugins"><i class="fa fa-wrench"></i><?php echo JText::_('K2_PLUGINS'); ?></a></li>
<?php endif; ?>
</ul>
<!-- Tab content -->
<div class="k2TabsContent" id="k2TabContent">
<?php if($this->params->get('mergeEditors')): ?>
<div class="k2ItemFormEditor">
<?php echo $this->text; ?>
<div class="dummyHeight"></div>
<div class="clr"></div>
</div>
<?php else: ?>
<div class="k2ItemFormEditor">
<span class="k2ItemFormEditorTitle"><?php echo JText::_('K2_INTROTEXT_TEASER_CONTENTEXCERPT'); ?></span>
<?php echo $this->introtext; ?>
<div class="dummyHeight"></div>
<div class="clr"></div>
</div>
<div class="k2ItemFormEditor">
<span class="k2ItemFormEditorTitle"><?php echo JText::_('K2_FULLTEXT_MAIN_CONTENT'); ?></span>
<?php echo $this->fulltext; ?>
<div class="dummyHeight"></div>
<div class="clr"></div>
</div>
<?php endif; ?>
<?php if (count($this->K2PluginsItemContent)): ?>
<div class="itemPlugins itemPluginsContent">
<?php foreach($this->K2PluginsItemContent as $K2Plugin): ?>
<?php if(!is_null($K2Plugin)): ?>
<div class="itemAdditionalField">
<legend><?php echo $K2Plugin->name; ?></legend>
<div class="itemAdditionalData">
<?php echo $K2Plugin->fields; ?>
</div>
</div>
<?php endif; ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
<div class="clr"></div>
</div>
<?php if ($this->params->get('showImageTab')): ?>
<!-- Tab image -->
<div class="k2TabsContent k2TabsContentLower" id="k2TabImage">
<div class="itemAdditionalField">
<div class="k2FLeft k2Right itemAdditionalValue">
<label><?php echo JText::_('K2_ITEM_IMAGE'); ?></label>
</div>
<div class="itemAdditionalData">
<input type="file" name="image" class="fileUpload" />
<i>(<?php echo JText::_('K2_MAX_UPLOAD_SIZE'); ?>: <?php echo ini_get('upload_max_filesize'); ?>)</i>
<span class="sep"><?php echo JText::_('K2_OR'); ?></span>
<input type="text" name="existingImage" id="existingImageValue" class="text_area" readonly />
<input type="button" value="<?php echo JText::_('K2_BROWSE_SERVER'); ?>" id="k2ImageBrowseServer" />
</div>
</div>
<?php if (!empty($this->row->image)): ?>
<div class="itemAdditionalField">
<div class="k2FLeft k2Right itemAdditionalValue">
<label><?php echo JText::_('K2_ITEM_IMAGE_PREVIEW'); ?></label>
</div>
<div class="itemAdditionalData">
<a data-fancybox="images" data-caption="<?php echo $this->row->title; ?>" href="<?php echo $this->row->image; ?>" title="<?php echo JText::_('K2_CLICK_ON_IMAGE_TO_PREVIEW_IN_ORIGINAL_SIZE'); ?>">
<img class="k2AdminImage" src="<?php echo $this->row->thumb; ?>" alt="<?php echo $this->row->title; ?>" />
</a>
<input type="checkbox" name="del_image" id="del_image" />
<label for="del_image"><?php echo JText::_('K2_CHECK_THIS_BOX_TO_DELETE_CURRENT_IMAGE_OR_JUST_UPLOAD_A_NEW_IMAGE_TO_REPLACE_THE_EXISTING_ONE'); ?></label>
</div>
</div>
<?php endif; ?>
<div class="itemAdditionalField">
<div class="k2FLeft k2Right itemAdditionalValue">
<label><?php echo JText::_('K2_ITEM_IMAGE_CAPTION'); ?></label>
</div>
<div class="itemAdditionalData">
<input type="text" name="image_caption" size="30" class="text_area" value="<?php echo $this->row->image_caption; ?>" />
</div>
</div>
<div class="itemAdditionalField">
<div class="k2FLeft k2Right itemAdditionalValue">
<label><?php echo JText::_('K2_ITEM_IMAGE_CREDITS'); ?></label>
</div>
<div class="itemAdditionalData">
<input type="text" name="image_credits" size="30" class="text_area" value="<?php echo $this->row->image_credits; ?>" />
</div>
</div>
<?php if (count($this->K2PluginsItemImage)): ?>
<div class="itemPlugins">
<?php foreach($this->K2PluginsItemImage as $K2Plugin): ?>
<?php if(!is_null($K2Plugin)): ?>
<div class="itemAdditionalField">
<fieldset>
<div class="k2FLeft k2Right itemAdditionalValue">
<label><?php echo $K2Plugin->name; ?></label>
</div>
<div class="itemAdditionalData">
<?php echo $K2Plugin->fields; ?>
</div>
</fieldset>
</div>
<?php endif; ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
<?php if ($this->params->get('showImageGalleryTab')): ?>
<!-- Tab image gallery -->
<div class="k2TabsContent k2TabsContentLower" id="k2TabImageGallery">
<?php if ($this->lists['checkSIG']): ?>
<div id="item_gallery_content" class="itemAdditionalField">
<?php if($this->sigPro): ?>
<div class="itemGalleryBlock">
<label><?php echo JText::_('K2_COM_BE_ITEM_SIGPRO_UPLOAD_NOTE'); ?></label>
<a class="k2Button modal" rel="{handler: 'iframe', size: {x: 940, y: 560}}" href="index.php?option=com_sigpro&view=galleries&task=create&newFolder=<?php echo $this->sigProFolder; ?>&type=k2&tmpl=component">
<?php echo JText::_('K2_COM_BE_ITEM_SIGPRO_UPLOAD'); ?>
</a>
<br />
<input name="sigProFolder" type="hidden" value="<?php echo $this->sigProFolder; ?>" />
</div>
<div class="itemGalleryBlock separator">
<?php echo JText::_('K2_OR'); ?>
</div>
<?php endif; ?>
<div class="itemGalleryBlock">
<label><?php echo JText::_('K2_UPLOAD_A_ZIP_FILE_WITH_IMAGES'); ?></label>
<input type="file" name="gallery" class="fileUpload" />
<span class="hasTip k2GalleryNotice" title="
<?php echo JText::_('K2_UPLOAD_A_ZIP_FILE_HELP_HEADER'); ?>::<?php echo JText::_('K2_UPLOAD_A_ZIP_FILE_HELP_TEXT'); ?>">
<?php echo JText::_('K2_UPLOAD_A_ZIP_FILE_HELP'); ?>
</span>
<label><?php echo JText::_('K2_MAX_UPLOAD_SIZE'); ?>: <?php echo ini_get('upload_max_filesize'); ?></label>
</div>
<div class="itemGalleryBlock separator">
<?php echo JText::_('K2_OR'); ?>
</div>
<div class="itemGalleryBlock">
<label><?php echo JText::_('K2_OR_ENTER_A_FLICKR_SET_URL'); ?></label>
<input type="text" name="flickrGallery" size="50" value="<?php echo ($this->row->galleryType == 'flickr') ? $this->row->galleryValue : ''; ?>" />
<span class="hasTip k2GalleryNotice" title="<?php echo JText::_('K2_VALID_FLICK_API_KEY_HELP_HEADER'); ?>::<?php echo JText::_('K2_VALID_FLICK_API_KEY_HELP_TEXT'); ?>">
<?php echo JText::_('K2_UPLOAD_A_ZIP_FILE_HELP'); ?>
</span>
</div>
<?php if (!empty($this->row->gallery)): ?>
<!-- Preview -->
<div id="itemGallery" class="itemGalleryBlock">
<?php echo $this->row->gallery; ?>
<div class="clr"></div>
<input type="checkbox" name="del_gallery" id="del_gallery" />
<label for="del_gallery"><?php echo JText::_('K2_CHECK_THIS_BOX_TO_DELETE_CURRENT_IMAGE_GALLERY_OR_JUST_UPLOAD_A_NEW_IMAGE_GALLERY_TO_REPLACE_THE_EXISTING_ONE'); ?></label>
</div>
<?php endif; ?>
</div>
<?php
// SIGPro is not present
else: ?>
<?php if (K2_JVERSION == '15'): ?>
<dl id="system-message">
<dt class="notice"><?php echo JText::_('K2_NOTICE'); ?></dt>
<dd class="notice message fade">
<ul>
<li><?php echo JText::_('K2_NOTICE_PLEASE_INSTALL_JOOMLAWORKS_SIMPLE_IMAGE_GALLERY_PRO_PLUGIN_IF_YOU_WANT_TO_USE_THE_IMAGE_GALLERY_FEATURES_OF_K2'); ?></li>
</ul>
</dd>
</dl>
<?php elseif(K2_JVERSION == '25'): ?>
<div id="system-message-container">
<dl id="system-message">
<dt class="notice"><?php echo JText::_('K2_NOTICE'); ?></dt>
<dd class="notice message">
<ul>
<li><?php echo JText::_('K2_NOTICE_PLEASE_INSTALL_JOOMLAWORKS_SIMPLE_IMAGE_GALLERY_PRO_PLUGIN_IF_YOU_WANT_TO_USE_THE_IMAGE_GALLERY_FEATURES_OF_K2'); ?></li>
</ul>
</dd>
</dl>
</div>
<?php else: ?>
<div class="alert">
<h4 class="alert-heading"><?php echo JText::_('K2_NOTICE'); ?></h4>
<div><p><?php echo JText::_('K2_NOTICE_PLEASE_INSTALL_JOOMLAWORKS_SIMPLE_IMAGE_GALLERY_PRO_PLUGIN_IF_YOU_WANT_TO_USE_THE_IMAGE_GALLERY_FEATURES_OF_K2'); ?></p></div>
</div>
<?php endif; ?>
<?php endif; ?>
<?php if (count($this->K2PluginsItemGallery)): ?>
<div class="itemPlugins">
<?php foreach($this->K2PluginsItemGallery as $K2Plugin): ?>
<?php if(!is_null($K2Plugin)): ?>
<div class="itemAdditionalField">
<fieldset>
<legend><?php echo $K2Plugin->name; ?></legend>
<div class="itemAdditionalData">
<?php echo $K2Plugin->fields; ?>
</div>
</fieldset>
</div>
<?php endif; ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
<?php if ($this->params->get('showVideoTab')): ?>
<!-- Tab video -->
<div class="k2TabsContent k2TabsContentLower" id="k2TabMedia">
<?php if ($this->lists['checkAllVideos']): ?>
<div id="item_video_content">
<div class="itemAdditionalField">
<div class="k2FLeft k2Right itemAdditionalValue">
<label><?php echo JText::_('K2_MEDIA_SOURCE'); ?></label>
</div>
<div class="itemAdditionalData">
<div id="k2MediaTabs" class="k2Tabs">
<ul class="k2TabsNavigation">
<li><a href="#k2MediaTab1"><?php echo JText::_('K2_UPLOAD'); ?></a></li>
<li><a href="#k2MediaTab2"><?php echo JText::_('K2_BROWSE_SERVERUSE_REMOTE_MEDIA'); ?></a></li>
<li><a href="#k2MediaTab3"><?php echo JText::_('K2_MEDIA_USE_ONLINE_VIDEO_SERVICE'); ?></a></li>
<li><a href="#k2MediaTab4"><?php echo JText::_('K2_EMBED'); ?></a></li>
</ul>
<div id="k2MediaTab1" class="k2TabsContent k2TabsContentLower">
<div class="panel" id="Upload_video">
<input type="file" name="video" class="fileUpload" />
<i>(<?php echo JText::_('K2_MAX_UPLOAD_SIZE'); ?>: <?php echo ini_get('upload_max_filesize'); ?>)</i>
</div>
</div>
<div id="k2MediaTab2" class="k2TabsContent k2TabsContentLower">
<div class="panel" id="Remote_video">
<div class="itemAdditionalBlock">
<a id="k2MediaBrowseServer" class="k2Button" href="index.php?option=com_k2&view=media&type=video&tmpl=component&fieldID=remoteVideo">
<?php echo JText::_('K2_BROWSE_VIDEOS_ON_SERVER')?>
</a>
</div>
<div class="itemAdditionalBlock sep">
<label><?php echo JText::_('K2_OR'); ?></label>
</div>
<div class="itemAdditionalBlock">
<label><?php echo JText::_('K2_PASTE_REMOTE_VIDEO_URL'); ?></label>
</div>
<div class="itemAdditionalBlock">
<input type="text" size="50" name="remoteVideo" id="remoteVideo" value="<?php echo $this->lists['remoteVideo'] ?>" />
</div>
</div>
</div>
<div id="k2MediaTab3" class="k2TabsContent k2TabsContentLower">
<div class="panel" id="Video_from_provider">
<div class="itemAdditionalBlock">
<label><?php echo JText::_('K2_SELECT_VIDEO_PROVIDER'); ?></label>
</div>
<div class="itemAdditionalBlock">
<?php echo $this->lists['providers']; ?>
</div>
<div class="itemAdditionalBlock">
<label><?php echo JText::_('K2_AND_ENTER_VIDEO_ID'); ?></label>
</div>
<div class="itemAdditionalBlock">
<input type="text" size="50" name="videoID" value="<?php echo $this->lists['providerVideo'] ?>" />
</div>
<div class="k2Right k2DocLink">
<a data-k2-modal="iframe" href="https://www.joomlaworks.net/allvideos-documentation">
<i class="fa fa-info"></i>
<span><?php echo JText::_('K2_READ_THE_ALLVIDEOS_DOCUMENTATION_FOR_MORE'); ?></span>
</a>
</div>
</div>
</div>
<div id="k2MediaTab4" class="k2TabsContent k2TabsContentLower">
<div class="itemAdditionalField panel" id="embedVideo">
<div class="k2FLeft k2Right itemAdditionalValue">
<label><?php echo JText::_('K2_PASTE_HTML_EMBED_CODE_BELOW'); ?></label>
</div>
<div class="itemAdditionalData">
<textarea name="embedVideo" rows="5" cols="50" class="textarea"><?php echo $this->lists['embedVideo']; ?></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
<?php if($this->row->video): ?>
<div class="itemAdditionalField">
<div class="k2FLeft k2Right itemAdditionalValue">
<label><?php echo JText::_('K2_MEDIA_PREVIEW'); ?></label>
</div>
<div class="itemAdditionalData">
<?php echo $this->row->video; ?>
<div class="clr"></div>
<input type="checkbox" name="del_video" id="del_video" />
<label for="del_video"><?php echo JText::_('K2_CHECK_THIS_BOX_TO_DELETE_CURRENT_VIDEO_OR_USE_THE_FORM_ABOVE_TO_REPLACE_THE_EXISTING_ONE'); ?></label>
</div>
</div>
<?php endif; ?>
<div class="itemAdditionalField">
<div class="k2FLeft k2Right itemAdditionalValue">
<label><?php echo JText::_('K2_MEDIA_CAPTION'); ?></label>
</div>
<div class="itemAdditionalData">
<input type="text" name="video_caption" size="50" class="text_area" value="<?php echo $this->row->video_caption; ?>" />
</div>
</div>
<div class="itemAdditionalField">
<div class="k2FLeft k2Right itemAdditionalValue">
<label><?php echo JText::_('K2_MEDIA_CREDITS'); ?></label>
</div>
<div class="itemAdditionalData">
<input type="text" name="video_credits" size="50" class="text_area" value="<?php echo $this->row->video_credits; ?>" />
</div>
</div>
</div>
<?php
// No AllVideos - Show default fields
else: ?>
<!-- No AllVideos alert goes here -->
<?php if (K2_JVERSION == '15'): ?>
<dl id="system-message">
<dt class="notice"><?php echo JText::_('K2_NOTICE'); ?></dt>
<dd class="notice message fade">
<ul>
<li><?php echo JText::_('K2_NOTICE_PLEASE_INSTALL_JOOMLAWORKS_ALLVIDEOS_PLUGIN_IF_YOU_WANT_TO_USE_THE_FULL_VIDEO_FEATURES_OF_K2'); ?></li>
</ul>
</dd>
</dl>
<?php elseif(K2_JVERSION == '25'): ?>
<div id="system-message-container">
<dl id="system-message">
<dt class="notice"><?php echo JText::_('K2_NOTICE'); ?></dt>
<dd class="notice message">
<ul>
<li><?php echo JText::_('K2_NOTICE_PLEASE_INSTALL_JOOMLAWORKS_ALLVIDEOS_PLUGIN_IF_YOU_WANT_TO_USE_THE_FULL_VIDEO_FEATURES_OF_K2'); ?></li>
</ul>
</dd>
</dl>
</div>
<?php else: ?>
<div class="alert">
<h4 class="alert-heading"><?php echo JText::_('K2_NOTICE'); ?></h4>
<div><p><?php echo JText::_('K2_NOTICE_PLEASE_INSTALL_JOOMLAWORKS_ALLVIDEOS_PLUGIN_IF_YOU_WANT_TO_USE_THE_FULL_VIDEO_FEATURES_OF_K2'); ?></p></div>
</div>
<?php endif; ?>
<!-- End of the alert -->
<div id="k2MediaTabs" class="k2Tabs">
<ul class="k2TabsNavigation">
<li><a href="#k2MediaTab4"><?php echo JText::_('K2_EMBED'); ?></a></li>
</ul>
<div class="k2TabsContent" id="k2MediaTab4">
<div class="panel" id="embedVideo">
<?php echo JText::_('K2_PASTE_HTML_EMBED_CODE_BELOW'); ?>
<br />
<textarea name="embedVideo" rows="5" cols="50" class="textarea"><?php echo $this->lists['embedVideo']; ?></textarea>
</div>
</div>
</div>
<?php if($this->row->video): ?>
<div class="itemAdditionalField">
<div class="k2FLeft k2Right itemAdditionalValue">
<label><?php echo JText::_('K2_MEDIA_PREVIEW'); ?></label>
</div>
<div class="itemAdditionalData">
<?php echo $this->row->video; ?>
<input type="checkbox" name="del_video" id="del_video" />
<label for="del_video"><?php echo JText::_('K2_USE_THE_FORM_ABOVE_TO_REPLACE_THE_EXISTING_VIDEO_OR_CHECK_THIS_BOX_TO_DELETE_CURRENT_VIDEO'); ?></label>
</div>
</div>
<?php endif; ?>
<div class="itemAdditionalField">
<div class="k2FLeft k2Right itemAdditionalValue">
<label><?php echo JText::_('K2_MEDIA_CAPTION'); ?></label>
</div>
<div class="itemAdditionalData">
<input type="text" name="video_caption" size="50" class="text_area" value="<?php echo $this->row->video_caption; ?>" />
</div>
</div>
<div class="itemAdditionalField">
<div class="k2FLeft k2Right itemAdditionalValue">
<label><?php echo JText::_('K2_MEDIA_CREDITS'); ?></label>
</div>
<div class="itemAdditionalData">
<input type="text" name="video_credits" size="50" class="text_area" value="<?php echo $this->row->video_credits; ?>" />
</div>
</div>
<?php endif; ?>
<!-- END of the AllVideos check -->
<?php if (count($this->K2PluginsItemVideo)): ?>
<div class="itemPlugins">
<?php foreach($this->K2PluginsItemVideo as $K2Plugin): ?>
<?php if(!is_null($K2Plugin)): ?>
<div class="itemAdditionalField">
<legend><?php echo $K2Plugin->name; ?></legend>
<div class="itemAdditionalData">
<?php echo $K2Plugin->fields; ?>
</div>
</div>
<?php endif; ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
<?php if ($this->params->get('showExtraFieldsTab')): ?>
<!-- Tab extra fields -->
<div class="k2TabsContent k2TabsContentLower" id="k2TabExtraFields">
<div id="extraFieldsContainer">
<?php if (count($this->extraFields)): ?>
<div id="extraFields">
<?php foreach($this->extraFields as $extraField): ?>
<div class="itemAdditionalField">
<?php if($extraField->type == 'header'): ?>
<h4 class="k2ExtraFieldHeader"><?php echo $extraField->name; ?></h4>
<?php else: ?>
<div class="k2Right k2FLeft itemAdditionalValue">
<label for="K2ExtraField_<?php echo $extraField->id; ?>"><?php echo $extraField->name; ?></label>
</div>
<div class="itemAdditionalData">
<?php echo $extraField->element; ?>
</div>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
<?php else: ?>
<?php if (K2_JVERSION == '15'): ?>
<dl id="system-message">
<dt class="notice"><?php echo JText::_('K2_NOTICE'); ?></dt>
<dd class="notice message fade">
<ul>
<li><?php echo JText::_('K2_PLEASE_SELECT_A_CATEGORY_FIRST_TO_RETRIEVE_ITS_RELATED_EXTRA_FIELDS'); ?></li>
</ul>
</dd>
</dl>
<?php elseif (K2_JVERSION == '25'): ?>
<div id="system-message-container">
<dl id="system-message">
<dt class="notice"><?php echo JText::_('K2_NOTICE'); ?></dt>
<dd class="notice message">
<ul>
<li><?php echo JText::_('K2_PLEASE_SELECT_A_CATEGORY_FIRST_TO_RETRIEVE_ITS_RELATED_EXTRA_FIELDS'); ?></li>
</ul>
</dd>
</dl>
</div>
<?php else: ?>
<div class="alert">
<h4 class="alert-heading"><?php echo JText::_('K2_NOTICE'); ?></h4>
<div>
<p><?php echo JText::_('K2_PLEASE_SELECT_A_CATEGORY_FIRST_TO_RETRIEVE_ITS_RELATED_EXTRA_FIELDS'); ?></p>
</div>
</div>
<?php endif; ?>
<?php endif; ?>
</div>
<?php if (count($this->K2PluginsItemExtraFields)): ?>
<div class="itemPlugins">
<?php foreach($this->K2PluginsItemExtraFields as $K2Plugin): ?>
<?php if(!is_null($K2Plugin)): ?>
<div class="itemAdditionalField">
<legend><?php echo $K2Plugin->name; ?></legend>
<div class="itemAdditionalData"><?php echo $K2Plugin->fields; ?></div>
</div>
<?php endif; ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
<?php if ($this->params->get('showAttachmentsTab')): ?>
<!-- Tab attachements -->
<div class="k2TabsContent k2TabsContentLower" id="k2TabAttachments">
<div class="itemAttachments table-responsive">
<?php if (count($this->row->attachments)): ?>
<table class="itemAttachmentsTable">
<tr>
<th>
<?php echo JText::_('K2_FILENAME'); ?>
</th>
<th>
<?php echo JText::_('K2_TITLE'); ?>
</th>
<th>
<?php echo JText::_('K2_TITLE_ATTRIBUTE'); ?>
</th>
<th>
<?php echo JText::_('K2_DOWNLOADS'); ?>
</th>
<th class="k2Center">
<?php echo JText::_('K2_OPERATIONS'); ?>
</th>
</tr>
<?php foreach($this->row->attachments as $attachment): ?>
<tr>
<td class="attachment_entry">
<?php echo $attachment->filename; ?>
</td>
<td>
<?php echo $attachment->title; ?>
</td>
<td>
<?php echo $attachment->titleAttribute; ?>
</td>
<td>
<?php echo $attachment->hits; ?>
</td>
<td class="k2Center">
<a class="downloadAttachmentButton" href="<?php echo $attachment->link; ?>" title="<?php echo JText::_('K2_DOWNLOAD'); ?>">
<i class="fa fa-download"></i>
<span class="hidden"><?php echo JText::_('K2_DOWNLOAD'); ?></span>
</a>
<a class="deleteAttachmentButton" title="<?php echo JText::_('K2_DELETE'); ?>" href="<?php echo JURI::base(true); ?>/index.php?option=com_k2&view=item&task=deleteAttachment&id=<?php echo $attachment->id?>&cid=<?php echo $this->row->id; ?>">
<i class="fa fa-remove"></i>
<span class="hidden"><?php echo JText::_('K2_DELETE'); ?></span>
</a>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
</div>
<div id="addAttachment">
<input type="button" id="addAttachmentButton" class="k2Selector k2Button" value="<?php echo JText::_('K2_ADD_ATTACHMENT_FIELD'); ?>" />
<i>(<?php echo JText::_('K2_MAX_UPLOAD_SIZE'); ?>: <?php echo ini_get('upload_max_filesize'); ?>)</i>
</div>
<div id="itemAttachments"></div>
<?php if (count($this->K2PluginsItemAttachments)): ?>
<div class="itemPlugins">
<?php foreach($this->K2PluginsItemAttachments as $K2Plugin): ?>
<?php if(!is_null($K2Plugin)): ?>
<div class="itemAdditionalField">
<legend><?php echo $K2Plugin->name; ?></legend>
<div class="itemAdditionalData"><?php echo $K2Plugin->fields; ?></div>
</div>
<?php endif; ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
<?php if(count(array_filter($this->K2PluginsItemOther)) && $this->params->get('showK2Plugins')): ?>
<!-- Tab other plugins -->
<div class="k2TabsContent k2TabsContentLower" id="k2TabPlugins">
<div class="itemPlugins">
<?php foreach($this->K2PluginsItemOther as $K2Plugin): ?>
<?php if(!is_null($K2Plugin)): ?>
<fieldset>
<legend><?php echo $K2Plugin->name; ?></legend>
<?php echo $K2Plugin->fields; ?>
</fieldset>
<?php endif; ?>
<?php endforeach; ?>
</div>
</div>
<?php endif; ?>
</div>
<!-- Lower Tabs end here -->
<input type="hidden" name="isSite" value="<?php echo (int) $this->mainframe->isSite(); ?>" />
<?php if($this->mainframe->isSite()): ?>
<input type="hidden" name="lang" value="<?php echo JRequest::getCmd('lang'); ?>" />
<?php endif; ?>
<input type="hidden" name="id" value="<?php echo $this->row->id; ?>" />
<input type="hidden" name="option" value="com_k2" />
<input type="hidden" name="view" value="item" />
<input type="hidden" name="task" value="<?php echo JRequest::getVar('task'); ?>" />
<input type="hidden" name="Itemid" value="<?php echo JRequest::getInt('Itemid'); ?>" />
<?php echo JHTML::_('form.token'); ?>
</div>
<!-- End of the basic parameters -->
<div class="k2NavTabContent" id="k2TabPubAndMeta">
<ul class="k2ScrollSpyMenu">
<?php if($this->row->id): ?>
<li><a href="#iteminfo"><?php echo JText::_('K2_ITEM_INFO'); ?></a></li>
<?php endif; ?>
<li><a href="#publishing"><?php echo JText::_('K2_PUBLISHING'); ?></a></li>
<li><a href="#metadata"><?php echo JText::_('K2_METADATA'); ?></a></li>
</ul>
<div class="k2ScrollingContent">
<?php if($this->row->id): ?>
<h3><?php echo JText::_('K2_ITEM_INFO'); ?></h3>
<div class="row-resposive">
<div class="col col6">
<a id="iteminfo"></a>
<ul class="additionalParams">
<li>
<label class="k2FLeft"><?php echo JText::_('K2_ITEM_ID'); ?></label>
<label class="k2FRight"><?php echo $this->row->id; ?></label>
</li>
<li>
<label class="k2FLeft"><?php echo JText::_('K2_PUBLISHED'); ?></label>
<label class="k2FRight"><?php echo ($this->row->published > 0) ? JText::_('K2_YES') : JText::_('K2_NO'); ?></label>
</li>
<li>
<label class="k2FLeft"><?php echo JText::_('K2_FEATURED'); ?></label>
<label class="k2FRight"><?php echo ($this->row->featured > 0) ? JText::_('K2_YES'): JText::_('K2_NO'); ?></label>
</li>
<li>
<label class="k2FLeft"><?php echo JText::_('K2_CREATED_DATE'); ?></label>
<label class="k2FRight"><?php echo $this->lists['created']; ?></label>
</li>
<li>
<label class="k2FLeft"><?php echo JText::_('K2_CREATED_BY'); ?></label>
<label class="k2FRight"><?php echo $this->row->author; ?></label>
</li>
<li>
<label class="k2FLeft"><?php echo JText::_('K2_MODIFIED_DATE'); ?></label>
<label class="k2FRight"><?php echo $this->lists['modified']; ?></label>
</li>
<?php if($this->row->moderator): ?>
<li>
<label class="k2FLeft"><?php echo JText::_('K2_MODIFIED_BY'); ?></label>
<label class="k2FRight"><?php echo $this->row->moderator; ?></label>
</li>
<?php endif; ?>
</ul>
</div>
<div class="col col3">
<div class="itemHits">
<?php echo JText::_('K2_HITS'); ?>
<span><?php echo $this->row->hits; ?></span>
<?php if($this->row->hits): ?>
<div class="itemHitsReset">
<input id="resetHitsButton" type="button" value="<?php echo JText::_('K2_RESET'); ?>" class="button" name="resetHits" />
</div>
<?php endif; ?>
</div>
</div>
<div class="col col3">
<div class="itemRating">
<?php echo JText::_('K2_RATING'); ?>
<?php if($this->row->ratingCount): ?>
<span><?php echo number_format(($this->row->ratingSum/$this->row->ratingCount), 2); ?>/5.00</span>
<?php else: ?>
<span>0.00/5.00</span>
<?php endif; ?>
<?php echo $this->row->ratingCount; ?> <?php echo ($this->row->ratingCount == 1) ? JText::_('K2_VOTE') : JText::_('K2_VOTES'); ?>
<div class="itemRatingReset">
<input id="resetRatingButton" type="button" value="<?php echo JText::_('K2_RESET'); ?>" class="button" name="resetRating" />
</div>
</div>
</div>
</div>
<?php endif; ?>
<div class="xmlParamsFields">
<a id="publishing"></a>
<h3><?php echo JText::_('K2_PUBLISHING'); ?></h3>
<ul class="adminformlist">
<li>
<div class="paramLabel">
<label><?php echo JText::_('K2_CREATION_DATE'); ?></label>
</div>
<div class="paramValue k2DateTimePickerControl">
<input type="text" data-k2-datetimepicker id="created" name="created" value="<?php echo $this->lists['createdCalendar']; ?>" autocomplete="off" />
<i class="fa fa-calendar" aria-hidden="true"></i>
</div>
<li>
<div class="paramLabel">
<label><?php echo JText::_('K2_START_PUBLISHING'); ?></label>
</div>
<div class="paramValue k2DateTimePickerControl">
<input type="text" data-k2-datetimepicker id="publish_up" name="publish_up" value="<?php echo $this->lists['publish_up']; ?>" autocomplete="off" />
<i class="fa fa-calendar" aria-hidden="true"></i>
</div>
</li>
<li>
<div class="paramLabel">
<label><?php echo JText::_('K2_FINISH_PUBLISHING'); ?></label>
</div>
<div class="paramValue k2DateTimePickerControl">
<input type="text" data-k2-datetimepicker id="publish_down" name="publish_down" value="<?php echo $this->lists['publish_down']; ?>" autocomplete="off" />
<i class="fa fa-calendar" aria-hidden="true"></i>
</div>
</li>
</ul>
<div class="clr"></div>
<a id="metadata"></a>
<h3><?php echo JText::_('K2_METADATA'); ?></h3>
<ul class="adminformlist">
<li>
<div class="paramLabel">
<label><?php echo JText::_('K2_DESCRIPTION'); ?></label>
</div>
<div class="paramValue">
<textarea name="metadesc" rows="5" cols="20" data-k2-chars="160"><?php echo $this->row->metadesc; ?></textarea>
</div>
</li>
<li>
<div class="paramLabel">
<label><?php echo JText::_('K2_KEYWORDS'); ?></label>
</div>
<div class="paramValue">
<textarea name="metakey" rows="5" cols="20"><?php echo $this->row->metakey; ?></textarea>
</div>
</li>
<li>
<div class="paramLabel">
<label><?php echo JText::_('K2_ROBOTS'); ?></label>
</div>
<div class="paramValue">
<?php echo $this->lists['metarobots']; ?>
</div>
</li>
<li>
<div class="paramLabel">
<label><?php echo JText::_('K2_AUTHOR'); ?></label>
</div>
<div class="paramValue">
<input type="text" name="meta[author]" value="<?php echo $this->lists['metadata']->get('author'); ?>" />
</div>
</li>
<ul>
</div>
</div>
</div>
<?php if($this->mainframe->isAdmin()): ?>
<div class="k2NavTabContent" id="k2TabDisplaySet">
<ul class="k2ScrollSpyMenu">
<li><a href="#catViewOptions"><?php echo JText::_('K2_ITEM_VIEW_OPTIONS_IN_CATEGORY_LISTINGS'); ?></a></li>
<li><a href="#itemViewOptions"><?php echo JText::_('K2_ITEM_VIEW_OPTIONS'); ?></a></li>
</ul>
<div class="k2ScrollingContent">
<a id="catViewOptions"></a>
<h3><?php echo JText::_('K2_ITEM_VIEW_OPTIONS_IN_CATEGORY_LISTINGS'); ?></h3>
<div class="xmlParamsFields">
<fieldset class="panelform">
<ul class="adminformlist">
<?php if(version_compare( JVERSION, '1.6.0', 'ge' )): ?>
<?php foreach($this->form->getFieldset('item-view-options-listings') as $field): ?>
<li<?php if($field->type=='header') echo ' class="headerElement"'; ?>>
<?php if($field->type=='header'): ?>
<div class="paramValueHeader"><?php echo $field->input; ?></div>
<?php elseif($field->type=='Spacer'): ?>
<div class="paramValueSpacer"> </div>
<div class="clr"></div>
<?php else: ?>
<div class="paramLabel"><?php echo $field->label; ?></div>
<div class="paramValue"><?php echo $field->input; ?></div>
<div class="clr"></div>
<?php endif; ?>
</li>
<?php endforeach; ?>
<?php else: ?>
<?php foreach($this->form->getParams('params', 'item-view-options-listings') as $param): ?>
<li<?php if((string)$param[1]=='' || $param[5] == '') echo ' class="headerElement"'; ?>>
<?php if((string)$param[1]=='' || $param[5] == ''): ?>
<div class="paramValueHeader"><?php echo $param[1]; ?></div>
<?php else: ?>
<div class="paramLabel"><?php echo $param[0]; ?></div>
<div class="paramValue"><?php echo $param[1]; ?></div>
<div class="clr"></div>
<?php endif; ?>
</li>
<?php endforeach; ?>
<?php endif; ?>
</ul>
</fieldset>
</div>
<a id="itemViewOptions"></a>
<h3><?php echo JText::_('K2_ITEM_VIEW_OPTIONS'); ?></h3>
<div class="xmlParamsFields">
<fieldset class="panelform">
<ul class="adminformlist">
<?php if(version_compare( JVERSION, '1.6.0', 'ge' )): ?>
<?php foreach($this->form->getFieldset('item-view-options') as $field): ?>
<li<?php if($field->type=='header') echo ' class="headerElement"'; ?>>
<?php if($field->type=='header'): ?>
<div class="paramValueHeader"><?php echo $field->input; ?></div>
<?php elseif($field->type=='Spacer'): ?>
<div class="paramValueSpacer"> </div>
<div class="clr"></div>
<?php else: ?>
<div class="paramLabel"><?php echo $field->label; ?></div>
<div class="paramValue"><?php echo $field->input; ?></div>
<div class="clr"></div>
<?php endif; ?>
</li>
<?php endforeach; ?>
<?php else: ?>
<?php foreach($this->form->getParams('params', 'item-view-options') as $param): ?>
<li<?php if((string)$param[1]=='' || $param[5] == '') echo ' class="headerElement"'; ?>>
<?php if((string)$param[1]=='' || $param[5] == ''): ?>
<div class="paramValueHeader"><?php echo $param[1]; ?></div>
<?php else: ?>
<div class="paramLabel"><?php echo $param[0]; ?></div>
<div class="paramValue"><?php echo $param[1]; ?></div>
<div class="clr"></div>
<?php endif; ?>
</li>
<?php endforeach; ?>
<?php endif; ?>
</ul>
</fieldset>
</div>
</div>
</div>
<?php endif; ?>
</div>
<!-- Top Nav Tabs END here -->
</form>
<?php if($this->mainframe->isSite()): ?>
</div>
<?php endif; ?>
|
renebentes/joomla-3.x
|
administrator/components/com_k2/views/item/tmpl/default.php
|
PHP
|
gpl-2.0
| 43,343 |
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
#subtext {
font: 9px normal Helvetica, Arial, sans-serif;
}
a {
color: orange;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid orange;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid orange;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
input {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#body{
margin: 0 15px 0 15px;
}
p.footer{
text-align: right;
font-size: 11px;
border-top: 1px solid orange;
line-height: 32px;
padding: 0 10px 0 10px;
margin: 20px 0 0 0;
}
#container{
margin: 10px;
border: 1px solid orange;
-webkit-box-shadow: 0 0 20px #D0D0D0;
}
|
alideny/AquaFlameCMS_Trinity
|
install/css/FlameCMS.css
|
CSS
|
gpl-2.0
| 1,226 |
/*****************************************************************************\
* workingcluster.h - definitions dealing with the working cluster
******************************************************************************
* Copyright (C) 2010 Lawrence Livermore National Security.
* Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
* Written by Danny Auble [email protected], et. al.
* CODE-OCEC-09-009. All rights reserved.
*
* This file is part of SLURM, a resource management program.
* For details, see <http://www.schedmd.com/slurmdocs/>.
* Please also read the included file: DISCLAIMER.
*
* SLURM 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.
*
* In addition, as a special exception, the copyright holders give permission
* to link the code of portions of this program with the OpenSSL library under
* certain conditions as described in each individual source file, and
* distribute linked combinations including the two. You must obey the GNU
* General Public License in all respects for all of the code used other than
* OpenSSL. If you modify file(s) with this exception, you may extend this
* exception to your version of the file(s), but you are not obligated to do
* so. If you do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source files in
* the program, then also delete it here.
*
* SLURM 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 SLURM; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
\*****************************************************************************/
#ifndef _WORKINGCLUSTER_H
#define _WORKINGCLUSTER_H
/* Return the number of dimensions in the current working cluster */
extern uint16_t slurmdb_setup_cluster_dims(void);
/* Return the size of each dimensions in the current working cluster.
* Returns NULL if information not available or not applicable. */
extern int * slurmdb_setup_cluster_dim_size(void);
/* Return the number of digits required in the numeric suffix of hostnames
* in the current working cluster */
extern uint16_t slurmdb_setup_cluster_name_dims(void);
/* Return true if the working cluster is a native Cray system */
extern bool is_cray_system(void);
/* Return the architecture flags in the current working cluster */
extern uint32_t slurmdb_setup_cluster_flags(void);
/* Translate architecture flag strings to their equivalent bitmaps */
extern uint32_t slurmdb_str_2_cluster_flags(char *flags_in);
/*
* Translate architecture flag bitmaps to their equivalent comma-delimited
* string
*
* NOTE: Call xfree() to release memory allocated to the return value
*/
extern char *slurmdb_cluster_flags_2_str(uint32_t flags_in);
#endif
|
chaos/slurm
|
src/common/working_cluster.h
|
C
|
gpl-2.0
| 3,278 |
/*
* Header for code common to all OMAP2+ machines.
*
* 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 SOFTWARE IS PROVIDED ``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 AUTHOR 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.
*
* 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.
*/
#ifndef __ARCH_ARM_MACH_OMAP2PLUS_COMMON_H
#define __ARCH_ARM_MACH_OMAP2PLUS_COMMON_H
#ifndef __ASSEMBLER__
#include <linux/irq.h>
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/i2c/twl.h>
#include <linux/i2c-omap.h>
#include <linux/reboot.h>
#include <linux/irqchip/irq-omap-intc.h>
#include <asm/proc-fns.h>
#include <asm/hardware/cache-l2x0.h>
#include "i2c.h"
#include "serial.h"
#include "usb.h"
#define OMAP_INTC_START NR_IRQS
#if defined(CONFIG_PM) && defined(CONFIG_ARCH_OMAP2)
int omap2_pm_init(void);
#else
static inline int omap2_pm_init(void)
{
return 0;
}
#endif
#if defined(CONFIG_PM) && defined(CONFIG_ARCH_OMAP3)
int omap3_pm_init(void);
#else
static inline int omap3_pm_init(void)
{
return 0;
}
#endif
#if defined(CONFIG_PM) && (defined(CONFIG_ARCH_OMAP4) || defined(CONFIG_SOC_OMAP5) || defined(CONFIG_SOC_DRA7XX))
int omap4_pm_init(void);
int omap4_pm_init_early(void);
#else
static inline int omap4_pm_init(void)
{
return 0;
}
static inline int omap4_pm_init_early(void)
{
return 0;
}
#endif
#ifdef CONFIG_OMAP_MUX
int omap_mux_late_init(void);
#else
static inline int omap_mux_late_init(void)
{
return 0;
}
#endif
extern void omap2_init_common_infrastructure(void);
extern void omap2_sync32k_timer_init(void);
extern void omap3_sync32k_timer_init(void);
extern void omap3_secure_sync32k_timer_init(void);
extern void omap3_gptimer_timer_init(void);
extern void omap4_local_timer_init(void);
#ifdef CONFIG_CACHE_L2X0
int omap_l2_cache_init(void);
#define OMAP_L2C_AUX_CTRL (L2C_AUX_CTRL_SHARED_OVERRIDE | \
L310_AUX_CTRL_DATA_PREFETCH | \
L310_AUX_CTRL_INSTR_PREFETCH)
void omap4_l2c310_write_sec(unsigned long val, unsigned reg);
#else
static inline int omap_l2_cache_init(void)
{
return 0;
}
#define OMAP_L2C_AUX_CTRL 0
#define omap4_l2c310_write_sec NULL
#endif
extern void omap5_realtime_timer_init(void);
void omap2420_init_early(void);
void omap2430_init_early(void);
void omap3430_init_early(void);
void omap35xx_init_early(void);
void omap3630_init_early(void);
void omap3_init_early(void); /* Do not use this one */
void am33xx_init_early(void);
void am35xx_init_early(void);
void ti81xx_init_early(void);
void am33xx_init_early(void);
void am43xx_init_early(void);
void am43xx_init_late(void);
void omap4430_init_early(void);
void omap5_init_early(void);
void omap3_init_late(void); /* Do not use this one */
void omap4430_init_late(void);
void omap2420_init_late(void);
void omap2430_init_late(void);
void omap3430_init_late(void);
void omap35xx_init_late(void);
void omap3630_init_late(void);
void am35xx_init_late(void);
void ti81xx_init_late(void);
void am33xx_init_late(void);
void omap5_init_late(void);
int omap2_common_pm_late_init(void);
void dra7xx_init_early(void);
void dra7xx_init_late(void);
#ifdef CONFIG_SOC_BUS
void omap_soc_device_init(void);
#else
static inline void omap_soc_device_init(void)
{
}
#endif
#if defined(CONFIG_SOC_OMAP2420) || defined(CONFIG_SOC_OMAP2430)
void omap2xxx_restart(enum reboot_mode mode, const char *cmd);
#else
static inline void omap2xxx_restart(enum reboot_mode mode, const char *cmd)
{
}
#endif
#ifdef CONFIG_SOC_AM33XX
void am33xx_restart(enum reboot_mode mode, const char *cmd);
#else
static inline void am33xx_restart(enum reboot_mode mode, const char *cmd)
{
}
#endif
#ifdef CONFIG_ARCH_OMAP3
void omap3xxx_restart(enum reboot_mode mode, const char *cmd);
#else
static inline void omap3xxx_restart(enum reboot_mode mode, const char *cmd)
{
}
#endif
#if defined(CONFIG_ARCH_OMAP4) || defined(CONFIG_SOC_OMAP5) || \
defined(CONFIG_SOC_DRA7XX) || defined(CONFIG_SOC_AM43XX)
void omap44xx_restart(enum reboot_mode mode, const char *cmd);
#else
static inline void omap44xx_restart(enum reboot_mode mode, const char *cmd)
{
}
#endif
/* This gets called from mach-omap2/io.c, do not call this */
void __init omap2_set_globals_tap(u32 class, void __iomem *tap);
void __init omap242x_map_io(void);
void __init omap243x_map_io(void);
void __init omap3_map_io(void);
void __init am33xx_map_io(void);
void __init omap4_map_io(void);
void __init omap5_map_io(void);
void __init ti81xx_map_io(void);
/* omap_barriers_init() is OMAP4 only */
void omap_barriers_init(void);
/**
* omap_test_timeout - busy-loop, testing a condition
* @cond: condition to test until it evaluates to true
* @timeout: maximum number of microseconds in the timeout
* @index: loop index (integer)
*
* Loop waiting for @cond to become true or until at least @timeout
* microseconds have passed. To use, define some integer @index in the
* calling code. After running, if @index == @timeout, then the loop has
* timed out.
*/
#define omap_test_timeout(cond, timeout, index) \
({ \
for (index = 0; index < timeout; index++) { \
if (cond) \
break; \
udelay(1); \
} \
})
extern struct device *omap2_get_mpuss_device(void);
extern struct device *omap2_get_iva_device(void);
extern struct device *omap2_get_l3_device(void);
extern struct device *omap4_get_dsp_device(void);
unsigned int omap4_xlate_irq(unsigned int hwirq);
void omap_gic_of_init(void);
#ifdef CONFIG_CACHE_L2X0
extern void __iomem *omap4_get_l2cache_base(void);
#endif
struct device_node;
#ifdef CONFIG_SMP
extern void __iomem *omap4_get_scu_base(void);
#else
static inline void __iomem *omap4_get_scu_base(void)
{
return NULL;
}
#endif
extern void gic_dist_disable(void);
extern void gic_dist_enable(void);
extern bool gic_dist_disabled(void);
extern void gic_timer_retrigger(void);
extern void omap_smc1(u32 fn, u32 arg);
extern void __iomem *omap4_get_sar_ram_base(void);
extern void omap_do_wfi(void);
#ifdef CONFIG_SMP
/* Needed for secondary core boot */
extern void omap4_secondary_startup(void);
extern void omap4460_secondary_startup(void);
extern u32 omap_modify_auxcoreboot0(u32 set_mask, u32 clear_mask);
extern void omap_auxcoreboot_addr(u32 cpu_addr);
extern u32 omap_read_auxcoreboot0(void);
extern void omap4_cpu_die(unsigned int cpu);
extern struct smp_operations omap4_smp_ops;
extern void omap5_secondary_startup(void);
extern void omap5_secondary_hyp_startup(void);
#endif
#if defined(CONFIG_SMP) && defined(CONFIG_PM)
extern int omap4_mpuss_init(void);
extern int omap4_enter_lowpower(unsigned int cpu, unsigned int power_state);
extern int omap4_finish_suspend(unsigned long cpu_state);
extern void omap4_cpu_resume(void);
extern int omap4_hotplug_cpu(unsigned int cpu, unsigned int power_state);
#else
static inline int omap4_enter_lowpower(unsigned int cpu,
unsigned int power_state)
{
cpu_do_idle();
return 0;
}
static inline int omap4_hotplug_cpu(unsigned int cpu, unsigned int power_state)
{
cpu_do_idle();
return 0;
}
static inline int omap4_mpuss_init(void)
{
return 0;
}
static inline int omap4_finish_suspend(unsigned long cpu_state)
{
return 0;
}
static inline void omap4_cpu_resume(void)
{}
#endif
void pdata_quirks_init(const struct of_device_id *);
void omap_auxdata_legacy_init(struct device *dev);
void omap_pcs_legacy_init(int irq, void (*rearm)(void));
struct omap_sdrc_params;
extern void omap_sdrc_init(struct omap_sdrc_params *sdrc_cs0,
struct omap_sdrc_params *sdrc_cs1);
struct omap2_hsmmc_info;
extern void omap_reserve(void);
struct omap_hwmod;
extern int omap_dss_reset(struct omap_hwmod *);
/* SoC specific clock initializer */
int omap_clk_init(void);
int __init omapdss_init_of(void);
void __init omapdss_early_init_of(void);
#endif /* __ASSEMBLER__ */
#endif /* __ARCH_ARM_MACH_OMAP2PLUS_COMMON_H */
|
klock-android/linux
|
arch/arm/mach-omap2/common.h
|
C
|
gpl-2.0
| 8,741 |
/*
* This file is part of OpenTTD.
* OpenTTD 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.
* OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file network_func.h Network functions used by other parts of OpenTTD. */
#ifndef NETWORK_FUNC_H
#define NETWORK_FUNC_H
/**
* Uncomment the following define to enable command replaying.
* See docs/desync.txt for details.
*/
// #define DEBUG_DUMP_COMMANDS
// #define DEBUG_FAILED_DUMP_COMMANDS
#include "network_type.h"
#include "../console_type.h"
#include "../gfx_type.h"
#include "../openttd.h"
#include "../company_type.h"
#include "../string_type.h"
extern NetworkCompanyState *_network_company_states;
extern ClientID _network_own_client_id;
extern ClientID _redirect_console_to_client;
extern uint8 _network_reconnect;
extern StringList _network_bind_list;
extern StringList _network_host_list;
extern StringList _network_ban_list;
byte NetworkSpectatorCount();
bool NetworkIsValidClientName(const std::string_view client_name);
bool NetworkValidateOurClientName();
bool NetworkValidateClientName(std::string &client_name);
bool NetworkValidateServerName(std::string &server_name);
void NetworkUpdateClientName(const std::string &client_name);
void NetworkUpdateServerGameType();
bool NetworkCompanyHasClients(CompanyID company);
std::string NetworkChangeCompanyPassword(CompanyID company_id, std::string password);
void NetworkReboot();
void NetworkDisconnect(bool blocking = false, bool close_admins = true);
void NetworkGameLoop();
void NetworkBackgroundLoop();
std::string_view ParseFullConnectionString(const std::string &connection_string, uint16 &port, CompanyID *company_id = nullptr);
void NetworkStartDebugLog(const std::string &connection_string);
void NetworkPopulateCompanyStats(NetworkCompanyStats *stats);
void NetworkUpdateClientInfo(ClientID client_id);
void NetworkClientsToSpectators(CompanyID cid);
bool NetworkClientConnectGame(const std::string &connection_string, CompanyID default_company, const std::string &join_server_password = "", const std::string &join_company_password = "");
void NetworkClientJoinGame();
void NetworkClientRequestMove(CompanyID company, const std::string &pass = "");
void NetworkClientSendRcon(const std::string &password, const std::string &command);
void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const std::string &msg, int64 data = 0);
bool NetworkClientPreferTeamChat(const NetworkClientInfo *cio);
bool NetworkCompanyIsPassworded(CompanyID company_id);
bool NetworkMaxCompaniesReached();
void NetworkPrintClients();
void NetworkHandlePauseChange(PauseMode prev_mode, PauseMode changed_mode);
/*** Commands ran by the server ***/
void NetworkServerDailyLoop();
void NetworkServerMonthlyLoop();
void NetworkServerYearlyLoop();
void NetworkServerSendConfigUpdate();
void NetworkServerUpdateGameInfo();
void NetworkServerShowStatusToConsole();
bool NetworkServerStart();
void NetworkServerNewCompany(const Company *company, NetworkClientInfo *ci);
bool NetworkServerChangeClientName(ClientID client_id, const std::string &new_name);
void NetworkServerDoMove(ClientID client_id, CompanyID company_id);
void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, const std::string &string);
void NetworkServerSendChat(NetworkAction action, DestType type, int dest, const std::string &msg, ClientID from_id, int64 data = 0, bool from_admin = false);
void NetworkServerSendExternalChat(const std::string &source, TextColour colour, const std::string &user, const std::string &msg);
void NetworkServerKickClient(ClientID client_id, const std::string &reason);
uint NetworkServerKickOrBanIP(ClientID client_id, bool ban, const std::string &reason);
uint NetworkServerKickOrBanIP(const std::string &ip, bool ban, const std::string &reason);
void NetworkInitChatMessage();
void CDECL NetworkAddChatMessage(TextColour colour, uint duration, const std::string &message);
void NetworkUndrawChatMessage();
void NetworkChatMessageLoop();
void NetworkAfterNewGRFScan();
#endif /* NETWORK_FUNC_H */
|
pelya/openttd-android
|
src/network/network_func.h
|
C
|
gpl-2.0
| 4,484 |
/* packet-ndmp.h
*
* $Id$
*
* (c) 2007 Ronnie Sahlberg
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* 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 __PACKET_NDMP_H__
#define __PACKET_NDMP_H__
extern gboolean check_if_ndmp(tvbuff_t *tvb, packet_info *pinfo);
#endif /* packet-ndmp.h */
|
hb9cwp/wireshark-jdsu
|
epan/dissectors/packet-ndmp.h
|
C
|
gpl-2.0
| 1,046 |
from django.core.management.base import NoArgsCommand
from ganeti_webmgr.clusters.models import Cluster
from ganeti_webmgr.nodes.models import Node
from ganeti_webmgr.virtualmachines.models import VirtualMachine
from ganeti_webmgr.utils.client import GanetiApiError
class Command(NoArgsCommand):
help = "Refreshes the Cache for Clusters, Nodes and Virtual Machines."
def handle_noargs(self, **options):
self.refresh_objects(**options)
def refresh_objects(self, **options):
"""
This was originally the code in the 0009
and then 0010 'force_object_refresh' migration
Force a refresh of all Cluster, Nodes, and VirtualMachines, and
import any new Nodes.
"""
write = self.stdout.write
flush = self.stdout.flush
def wf(str, newline=False, verbosity=1):
if (verbosity > 0):
if newline:
write('\n')
write(str)
flush()
verbosity = int(options.get('verbosity'))
wf('- Refreshing Cached Cluster Objects', verbosity=verbosity)
wf('> Synchronizing Cluster Nodes ', True, verbosity=verbosity)
flush()
Cluster.objects.all().update(mtime=None)
for cluster in Cluster.objects.all().iterator():
try:
cluster.sync_nodes()
wf('.', verbosity=verbosity)
except GanetiApiError:
wf('E', verbosity=verbosity)
Node.objects.all().update(mtime=None)
wf('> Refreshing Node Caches ', True, verbosity=verbosity)
for node in Node.objects.all().iterator():
try:
wf('.', verbosity=verbosity)
except GanetiApiError:
wf('E', verbosity=verbosity)
VirtualMachine.objects.all().update(mtime=None)
wf('> Refreshing Instance Caches ', True, verbosity=verbosity)
for instance in VirtualMachine.objects.all().iterator():
try:
wf('.', verbosity=verbosity)
except GanetiApiError:
wf('E', verbosity=verbosity)
wf('\n', verbosity=verbosity)
|
dmS0Zq/ganeti_webmgr
|
ganeti_webmgr/ganeti_web/management/commands/refreshcache.py
|
Python
|
gpl-2.0
| 2,172 |
<?php
/**
* EXHIBIT A. Common Public Attribution License Version 1.0
* The contents of this file are subject to the Common Public Attribution License Version 1.0 (the “License”);
* you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://www.oxwall.org/license. The License is based on the Mozilla Public License Version 1.1
* but Sections 14 and 15 have been added to cover use of software over a computer network and provide for
* limited attribution for the Original Developer. In addition, Exhibit A has been modified to be consistent
* with Exhibit B. Software distributed under the License is distributed on an “AS IS” basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language
* governing rights and limitations under the License. The Original Code is Oxwall software.
* The Initial Developer of the Original Code is Oxwall Foundation (http://www.oxwall.org/foundation).
* All portions of the code written by Oxwall Foundation are Copyright (c) 2011. All Rights Reserved.
* EXHIBIT B. Attribution Information
* Attribution Copyright Notice: Copyright 2011 Oxwall Foundation. All rights reserved.
* Attribution Phrase (not exceeding 10 words): Powered by Oxwall community software
* Attribution URL: http://www.oxwall.org/
* Graphic Image as provided in the Covered Code.
* Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work
* which combines Covered Code or portions thereof with code not governed by the terms of the CPAL.
*/
/**
* Singleton. Language Data Access Object
*
* @author Aybat Duyshokov <[email protected]>
* @package ow_system_plugins.base.bol
* @since 1.0
*/
class BOL_LanguageDao extends OW_BaseDao
{
/**
* Class constructor
*
*/
protected function __construct()
{
parent::__construct();
}
/**
* Class instance
*
* @var BOL_LanguageDao
*/
private static $classInstance;
/**
* Returns class instance
*
* @return BOL_LanguageDao
*/
public static function getInstance()
{
if ( !isset(self::$classInstance) )
self::$classInstance = new self();
return self::$classInstance;
}
/**
* @see OW_BaseDao::getDtoClassName()
*
*/
public function getDtoClassName()
{
return 'BOL_Language';
}
/**
* @see OW_BaseDao::getTableName()
*
*/
public function getTableName()
{
return OW_DB_PREFIX . 'base_language';
}
/**
* Enter description here...
*
* @param string $tag
* @return BOL_Language
*/
public function findByTag( $tag )
{
$example = new OW_Example();
$example->andFieldEqual('tag', trim($tag));
return $this->findObjectByExample($example);
}
public function findMaxOrder()
{
return $this->dbo->queryForColumn('SELECT MAX(`order`) FROM ' . $this->getTableName());
}
public function getCurrent()
{
$ex = new OW_Example();
$ex->setOrder('`order` ASC')->setLimitClause(0, 1);
return $this->findObjectByExample($ex);
}
public function countActiveLanguages()
{
$ex = new OW_Example();
$ex->andFieldEqual('status', 'active');
return $this->countByExample($ex);
}
public function findActiveList()
{
$ex = new OW_Example();
$ex->andFieldEqual('status', 'active');
return $this->findListByExample($ex);
}
}
|
seret/oxtebafu
|
ow_system_plugins/base/bol/language_dao.php
|
PHP
|
gpl-2.0
| 3,621 |
/*
Copyright (C) 2015 Datto Inc.
This file is part of dattobd.
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.
*/
#include "../../includes.h"
static inline void dummy(void){
struct hd_struct hd;
part_nr_sects_read(&hd);
}
|
xtavras/dattobd
|
src/configure-tests/feature-tests/part_nr_sects_read.c
|
C
|
gpl-2.0
| 379 |
#ifndef __CONFIG_M8_K200_V1_H__
#define __CONFIG_M8_K200_V1_H__
//#define AML_UBOOT_LOG_PROFILE 1
#define CONFIG_AML_MESON_8 1
#define CONFIG_MACH_MESON8_K200_V1 // generate M8 K200 machid number
#define CONFIG_SECURITYKEY
#ifndef CONFIG_M8
#define CONFIG_M8
#endif // ifndef CONFIG_M8
//#define CONFIG_VLSI_EMULATOR 1
//#define TEST_UBOOT_BOOT_SPEND_TIME
// cart type of each port
#define PORT_A_CARD_TYPE CARD_TYPE_UNKNOWN
#define PORT_B_CARD_TYPE CARD_TYPE_UNKNOWN
#define PORT_C_CARD_TYPE CARD_TYPE_MMC // otherwise CARD_TYPE_SD
//UART Sectoion
#define CONFIG_CONS_INDEX 2
//UART A Section
//#define CONFIG_UART_A_FUNCTION_ADD
//#define CONFIG_SECURESTORAGEKEY
#ifdef CONFIG_SECURESTORAGEKEY
#ifndef CONFIG_RANDOM_GENERATE
#define CONFIG_RANDOM_GENERATE
#endif
#endif
//#define CONFIG_SECURITYKEY
#ifdef CONFIG_SECURITYKEY
#define CONFIG_AML_NAND_KEY
#endif
#define CONFIG_AML_GATE_INIT 1
#define CONFIG_NEXT_NAND
//#define CONFIG_SECURE_NAND 1
//support "boot,bootd"
//#define CONFIG_CMD_BOOTD 1
//Enable HDMI Tx
//#define CONFIG_VIDEO_AMLTVOUT 1
//Enable LCD output
//#define CONFIG_VIDEO_AMLLCD
#define LCD_BPP LCD_COLOR16
#define CONFIG_ACS
#ifdef CONFIG_ACS
#define CONFIG_DDR_SIZE_IND_ADDR 0xD9000000 //pass memory size, spl->uboot
#endif
#ifdef CONFIG_NEXT_NAND
#define CONFIG_CMD_IMGREAD 1 //read the actual size of boot.img/recovery.img/logo.img use cmd 'imgread'
#define CONFIG_AML_V2_USBTOOL 1
#endif//#ifdef CONFIG_NEXT_NAND
#define CONFIG_CMD_CPU_TEMP
#if CONFIG_AML_V2_USBTOOL
#define CONFIG_SHA1
#define CONFIG_AUTO_START_SD_BURNING 1//1 then auto detect whether or not jump into sdc_burning when boot from external mmc card
#define CONFIG_SD_BURNING_SUPPORT_LED 1//1 then using led flickering states changing to show burning states when sdcard burning
#define CONFIG_POWER_KEY_NOT_SUPPORTED_FOR_BURN 1//power key and poweroff can't work
#define CONFIG_SD_BURNING_SUPPORT_UI 1//have bmp display to indicate burning state when sdcard burning
#ifdef CONFIG_ACS
#define CONFIG_TPL_BOOT_ID_ADDR (0xD9000000U + 4)//pass boot_id, spl->uboot
#else
#define CONFIG_TPL_BOOT_ID_ADDR (&reboot_mode)//pass boot_id, spl->uboot
#endif// #ifdef CONFIG_ACS
#endif// #if CONFIG_AML_V2_USBTOOL
#define CONFIG_UNIFY_KEY_MANAGE 1
#define CONFIG_CMD_PWM 1
//#define CONFIG_CMD_IMGREAD_FOR_SECU_BOOT_V2 1 //open this macro if need read encrypted kernel/dtb with whole part size
//Enable storage devices
#define CONFIG_CMD_NAND 1
#define CONFIG_VIDEO_AML 1
#define CONFIG_CMD_BMP 1
#define CONFIG_VIDEO_AMLTVOUT 1
#define CONFIG_AML_HDMI_TX 1
#define CONFIG_OSD_SCALE_ENABLE 1
#if defined(CONFIG_VIDEO_AMLTVOUT)
#define CONFIG_CVBS_PERFORMANCE_COMPATIBILITY_SUPPORT 1
#define CONFIG_CVBS_CHINASARFT 0x0
#define CONFIG_CVBS_CHINATELECOM 0x1
#define CONFIG_CVBS_CHINAMOBILE 0x2
#define CONFIG_CVBS_PERFORMANCE_ACTIVED CONFIG_CVBS_CHINASARFT
#endif
//Enable storage devices
#define CONFIG_CMD_SF 1
#if defined(CONFIG_CMD_SF)
#define SPI_WRITE_PROTECT 1
#define CONFIG_CMD_MEMORY 1
#endif /*CONFIG_CMD_SF*/
//Amlogic SARADC support
#define CONFIG_SARADC 1
#define CONFIG_CMD_SARADC
#define CONFIG_EFUSE 1
//#define CONFIG_MACHID_CHECK 1
#define CONFIG_CMD_SUSPEND 1
//#define CONFIG_IR_REMOTE 1
#define CONFIG_L2_OFF 1
#define CONFIG_CMD_NET 1
#if defined(CONFIG_CMD_NET)
#define CONFIG_AML_ETHERNET 1
#define CONFIG_NET_MULTI 1
#define CONFIG_CMD_PING 1
#define CONFIG_CMD_DHCP 1
#define CONFIG_CMD_RARP 1
#define RMII_PHY_INTERFACE 1
//#define CONFIG_NET_RGMII
//#define CONFIG_NET_RMII_CLK_EXTERNAL //use external 50MHz clock source
#define CONFIG_AML_ETHERNET 1 /*to link /driver/net/aml_ethernet.c*/
#define IP101PHY 1 /*to link /driver/net/aml_ethernet.c*/
//#define KSZ8091 1 /*to link /driver/net/aml_ethernet.c*/
#define CONFIG_HOSTNAME arm_m8
#define CONFIG_ETHADDR 00:15:18:01:81:31 /* Ethernet address */
#define CONFIG_IPADDR 10.18.9.97 /* Our ip address */
#define CONFIG_GATEWAYIP 10.18.9.1 /* Our getway ip address */
#define CONFIG_SERVERIP 10.18.9.113 /* Tftp server ip address */
#define CONFIG_NETMASK 255.255.255.0
#endif /* (CONFIG_CMD_NET) */
//I2C definitions
#define CONFIG_AML_I2C 1
#ifdef CONFIG_AML_I2C
#define CONFIG_CMD_I2C 1
#define HAS_AO_MODULE
#define CONFIG_SYS_I2C_SPEED 400000
#endif //#ifdef CONFIG_AML_I2C
#define CONFIG_CMD_AML
#define CONFIG_CMD_CPU_TEMP
/*
* PMU definitions, all PMU devices must be include involved
* in CONFIG_PLATFORM_HAS_PMU
*/
//#define CONFIG_PLATFORM_HAS_PMU
#ifdef CONFIG_PLATFORM_HAS_PMU
#define CONFIG_RN5T618
#ifdef CONFIG_RN5T618
//#define CONFIG_UBOOT_BATTERY_PARAMETER_TEST // uboot can do battery curve test
//#define CONFIG_UBOOT_BATTERY_PARAMETERS // uboot can get battery parameters from dts
#define CONFIG_ALWAYS_POWER_ON // if platform without battery, must have
#define CONFIG_DISABLE_POWER_KEY_OFF // disable power off PMU by long press power key
/*
* under some cases default voltage of PMU output is
* not suitable for application, so you should take care
* of the following macros which defined initial voltage
* of each power domain when in SPL stage of uboot.
*/
#define CONFIG_POWER_SPL // init power for all domians, must have
#define CONFIG_VCCK_VOLTAGE 1100 // CPU core voltage when boot, must have
#define CONFIG_VDDAO_VOLTAGE 1150 // VDDAO voltage when boot, must have
#define CONFIG_DDR_VOLTAGE 1500 // DDR voltage when boot, must have
#define CONFIG_VDDIO_AO28 2900 // VDDIO_AO28 voltage when boot, option
#define CONFIG_VDDIO_AO18 1800 // VDDIO_AO18 voltage when boot, option
#define CONFIG_RTC_0V9 900 // RTC_0V9 voltage when boot, option
#define CONFIG_VDD_LDO 2700 // VDD_LDO voltage when boot, option
#define CONFIG_VCC1V8 1800 // VCC1.8v voltage when boot, option
#define CONFIG_VCC2V8 2850 // VCC2.8v voltage when boot, option
#define CONFIG_AVDD1V8 1800 // AVDD1.8V voltage when boot, option
/*
* set to 1 if you want decrease voltage of VDDAO when suspend
*/
#define CONFIG_VDDAO_VOLTAGE_CHANGE 1
#ifdef CONFIG_VDDAO_VOLTAGE_CHANGE
#define CONFIG_VDDAO_SUSPEND_VOLTAGE 825 // voltage of VDDAO when suspend
#endif /* CONFIG_VDDAO_VOLTAGE_CHANGE */
/*
* DCDC mode switch when suspend
*/
#define CONFIG_DCDC_PFM_PMW_SWITCH 1
#define CONFIG_POWEROFF_VCCX2
#endif /* CONFIG_RN5T618 */
#else
#define CONFIG_PWM_POWER 1
#define CONFIG_NO_32K_XTAL 1
#define CONFIG_POWER_SPL
#define CONFIG_PWM_VDDEE_VOLTAGE 1100 //VDDEE voltage when boot, must have
#define CONFIG_PWM_VDDEE_SUSPEND_VOLTAGE 1100 //VDDEE voltage when suspend, must have
#endif /* CONFIG_PLATFORM_HAS_PMU */
#define CONFIG_SDIO_B1 1
#define CONFIG_SDIO_A 1
#define CONFIG_SDIO_B 1
#define CONFIG_SDIO_C 1
#define CONFIG_ENABLE_EXT_DEVICE_RETRY 1
#define CONFIG_MMU 1
#define CONFIG_PAGE_OFFSET 0xc0000000
#define CONFIG_SYS_LONGHELP 1
/* USB
* Enable CONFIG_MUSB_HCD for Host functionalities MSC, keyboard
* Enable CONFIG_MUSB_UDD for Device functionalities.
*/
/* #define CONFIG_MUSB_UDC 1 */
#define CONFIG_CMD_USB 1
#if defined(CONFIG_CMD_USB)
#define CONFIG_M8_USBPORT_BASE_A 0xC9040000
#define CONFIG_M8_USBPORT_BASE_B 0xC90C0000
#define CONFIG_USB_STORAGE 1
#define CONFIG_USB_DWC_OTG_HCD 1
#define CONFIG_USB_DWC_OTG_294 1
#endif //#if defined(CONFIG_CMD_USB)
#define CONFIG_ENABLE_CVBS 1
#define CONFIG_UCL 1
#define CONFIG_SELF_COMPRESS
//#define CONFIG_PREBOOT "mw da004004 80000510;mw c81000014 4000;mw c1109900 0"
#define CONFIG_CMD_AUTOSCRIPT
#define CONFIG_CMD_REBOOT 1
#define CONFIG_PREBOOT
/* Environment information */
#define CONFIG_BOOTDELAY 1
#define CONFIG_BOOTFILE boot.img
#define CONFIG_EXTRA_ENV_SETTINGS \
"us_delay_step=1\0" \
"loadaddr=0x12000000\0" \
"loadaddr_logo=0x13000000\0" \
"testaddr=0x12400000\0" \
"console=ttyS0,115200n8\0" \
"bootm_low=0x00000000\0" \
"bootm_size=0x80000000\0" \
"boardname=m8_board\0" \
"chipname=8726m8\0" \
"get_dt=checkhw\0" \
"initrd_high=60000000\0" \
"hdmimode=1080p\0" \
"cvbsmode=576cvbs\0" \
"outputmode=1080p\0" \
"vdac_config=0x10\0" \
"initargs=init=/init console=ttyS0,115200n8 no_console_suspend ramoops.mem_address=0x04e00000 ramoops.mem_size=0x100000 ramoops.record_size=0x8000 ramoops.console_size=0x4000\0" \
"preloaddtb=imgread dtb boot ${loadaddr}\0" \
"video_dev=tvout\0" \
"display_width=1920\0" \
"display_height=1080\0" \
"display_bpp=16\0" \
"display_color_format_index=16\0" \
"display_layer=osd2\0" \
"display_color_fg=0xffff\0" \
"display_color_bg=0\0" \
"fb_addr=0x15100000\0" \
"fb_width=1280\0"\
"fb_height=720\0"\
"partnum=2\0" \
"p0start=1000000\0" \
"p0size=400000\0" \
"p0path=uImage\0" \
"p1start=1400000\0" \
"p1size=8000000\0" \
"p1path=android.rootfs\0" \
"bootstart=0\0" \
"bootsize=100000\0" \
"bootpath=u-boot.bin\0" \
"sdcburncfg=aml_sdc_burn.ini\0"\
"normalstart=1000000\0" \
"normalsize=400000\0" \
"upgrade_step=0\0" \
"firstboot=1\0" \
"store=0\0"\
"wipe_data=success\0"\
"cvbs_drv=0\0"\
"preboot="\
"if itest ${upgrade_step} == 3; then run prepare; run storeargs; run update; fi; "\
"if itest ${upgrade_step} == 1; then "\
"defenv_reserve_env; setenv upgrade_step 2; saveenv;"\
"fi; "\
"run prepare;"\
"run storeargs;"\
"get_rebootmode; clear_rebootmode; echo reboot_mode=${reboot_mode};" \
"run update_key; " \
"run switch_bootmode\0" \
\
"update_key="\
"saradc open 0; " \
"if saradc get_in_range 0 0x50; then " \
"msleep 50; " \
"if saradc get_in_range 0 0x50; then echo update by key...; run update; fi;" \
"fi\0" \
\
"update="\
/*first try usb burning, second sdc_burn, third autoscr, last recovery*/\
"run usb_burning; "\
"if mmcinfo; then "\
"if fatexist mmc 0 ${sdcburncfg}; then "\
"run sdc_burning; "\
"else "\
"if fatload mmc 0 ${loadaddr} aml_autoscript; then autoscr ${loadaddr}; fi;"\
"run recovery;"\
"fi;"\
"else "\
"run recovery;"\
"fi;\0"\
\
"storeargs="\
"setenv bootargs ${initargs} cvbsdrv=${cvbs_drv} vdaccfg=${vdac_config} logo=osd1,loaded,${fb_addr},${outputmode},full hdmimode=${hdmimode} cvbsmode=${cvbsmode} androidboot.firstboot=${firstboot} hdmitx=${cecconfig}\0"\
\
"switch_bootmode="\
"if test ${reboot_mode} = factory_reset; then "\
"run recovery;"\
"else if test ${reboot_mode} = update; then "\
"run update;"\
"else if test ${reboot_mode} = usb_burning; then "\
"run usb_burning;"\
"else if test ${wipe_data} = failed; then "\
"echo wipe_data=${wipe_data}; run recovery;"\
"else " \
" "\
"fi;fi;fi;fi\0" \
\
"prepare="\
"logo size ${outputmode}; video open; video clear; video dev open ${outputmode};"\
"imgread pic logo bootup ${loadaddr_logo}; "\
"bmp display ${bootup_offset}; bmp scale;"\
"\0"\
\
"storeboot="\
"secukey auto;" \
"secukey write keyexample 1234567890; "\
"echo Booting...; "\
"if unifykey get usid; then "\
"setenv bootargs ${bootargs} androidboot.serialno=${usid};"\
"fi;"\
"imgread kernel boot ${loadaddr};"\
"bootm;"\
"run recovery\0" \
\
"recovery="\
"echo enter recovery;"\
"if mmcinfo; then "\
"if fatload mmc 0 ${loadaddr} recovery.img; then bootm;fi;"\
"fi; "\
"if usb start 0; then "\
"if fatload usb 0 ${loadaddr} recovery.img; then bootm; fi;"\
"fi;"\
"if imgread kernel recovery ${loadaddr}; then "\
"bootm; "\
"else "\
"echo no recovery in flash; "\
"fi;\0" \
\
"usb_burning=update 1000\0" \
"sdc_burning=sdc_burn ${sdcburncfg}\0"
#define CONFIG_BOOTCOMMAND "run storeboot"
#define CONFIG_AUTO_COMPLETE 1
#define CONFIG_ENV_SIZE (64*1024)
#define CONFIG_STORE_COMPATIBLE
#ifdef CONFIG_STORE_COMPATIBLE
//spi
#define CONFIG_ENV_OVERWRITE
#define CONFIG_CMD_SAVEENV
#define CONFIG_ENV_SECT_SIZE 0x1000
#define CONFIG_ENV_IN_SPI_OFFSET 0x100000
//nand
#define CONFIG_ENV_IN_NAND_OFFSET 0x400000
#define CONFIG_ENV_BLOCK_NUM 2
//emmc
#define CONFIG_SYS_MMC_ENV_DEV 1
#define CONFIG_ENV_IN_EMMC_OFFSET 0x80000
#else
#define CONFIG_SPI_BOOT 1
//#define CONFIG_MMC_BOOT
//#define CONFIG_NAND_BOOT 1
#ifdef CONFIG_NAND_BOOT
#define CONFIG_AMLROM_NANDBOOT 1
#endif
#ifdef CONFIG_SPI_BOOT
#define CONFIG_ENV_OVERWRITE
#define CONFIG_ENV_IS_IN_SPI_FLASH
#define CONFIG_CMD_SAVEENV
#define CONFIG_ENV_SECT_SIZE 0x10000
#define CONFIG_ENV_OFFSET 0x1f0000
#elif defined CONFIG_NAND_BOOT
#define CONFIG_ENV_IS_IN_AML_NAND
#define CONFIG_CMD_SAVEENV
#define CONFIG_ENV_OVERWRITE
#define CONFIG_ENV_OFFSET 0x400000
#define CONFIG_ENV_BLOCK_NUM 2
#elif defined CONFIG_MMC_BOOT
#define CONFIG_ENV_IS_IN_MMC
#define CONFIG_CMD_SAVEENV
#define CONFIG_SYS_MMC_ENV_DEV 0
#define CONFIG_ENV_OFFSET 0x1000000
#else
#define CONFIG_ENV_IS_NOWHERE 1
#endif
#endif
//wifi wake up
//#define CONFIG_WIFI_WAKEUP 1
//#define CONFIG_NET_WIFI
//----------------------------------------------------------------------
//Please set the M8 CPU clock(unit: MHz)
//legal value: 600, 792, 996, 1200,1440
#define M8_CPU_CLK (1200)
#define CONFIG_SYS_CPU_CLK (M8_CPU_CLK)
//----------------------------------------------------------------------
//-----------------------------------------------------------------------
//DDR setting
//For DDR PUB training not check the VT done flag
#define CONFIG_NO_DDR_PUB_VT_CHECK 1
//For DDR clock gating disable
#define CONFIG_GATEACDDRCLK_DISABLE 1
//For DDR low power feature disable
//#define CONFIG_DDR_LOW_POWER_DISABLE 1
//For DDR PUB WL/WD/RD/RG-LVT, WD/RD-BVT disable
#define CONFIG_PUB_WLWDRDRGLVTWDRDBVT_DISABLE 1
//current DDR clock range (408~804)MHz with fixed step 12MHz
#define CONFIG_DDR_CLK 792 //696 //768 //792// (636)
#define CONFIG_DDR_MODE CFG_DDR_BUS_WIDTH_32BIT //m8 doesn't support
#define CONFIG_DDR_CHANNEL_SET CFG_DDR_TWO_CHANNEL_SWITCH_BIT_12
//On board DDR capacity
/*DDR capactiy support 512MB, 1GB, 1.5GB, 2GB, 3GB*/
#define CONFIG_DDR_SIZE 1024 //MB. Legal value: 512, 1024, 1536, 2048, 3072
#ifdef CONFIG_ACS
//#define CONFIG_DDR_CHANNEL_AUTO_DETECT //ddr channel setting auto detect
//#define CONFIG_DDR_MODE_AUTO_DETECT //ddr bus-width auto detection. m8 doesn't support.
#define CONFIG_DDR_SIZE_AUTO_DETECT //ddr size auto detection
#endif
#ifdef CONFIG_DDR_SIZE_AUTO_DETECT
#define CONFIG_AUTO_SET_MULTI_DT_ID //if wanna pass mem=xx to kernel, pls disable this config
#ifndef CONFIG_AUTO_SET_MULTI_DT_ID
#define CONFIG_AUTO_SET_BOOTARGS_MEM
#endif
#endif
#define CONFIG_DUMP_DDR_INFO 1
#define CONFIG_ENABLE_WRITE_LEVELING 1
//#define DDR_SCRAMBE_ENABLE 1
#define CONFIG_SYS_MEMTEST_START 0x10000000 /* memtest works on */
#define CONFIG_SYS_MEMTEST_END 0x18000000 /* 0 ... 128 MB in DRAM */
//#define CONFIG_ENABLE_MEM_DEVICE_TEST 1
#define CONFIG_NR_DRAM_BANKS 1 /* CS1 may or may not be populated */
/* Pass open firmware flat tree*/
#define CONFIG_OF_LIBFDT 1
#define CONFIG_DT_PRELOAD 1
#define CONFIG_SYS_BOOTMAPSZ PHYS_MEMORY_SIZE /* Initial Memory map for Linux */
#define CONFIG_ANDROID_IMG 1
#define CONFIG_CMD_IMGPACK 1
//M8 secure boot disable
//#define CONFIG_AML_DISABLE_CRYPTO_UBOOT 1
//M8 L1 cache enable for uboot decompress speed up
#define CONFIG_AML_SPL_L1_CACHE_ON 1
/*-----------------------------------------------------------------------
* power down
*/
//#define CONFIG_CMD_RUNARC 1 /* runarc */
#define CONFIG_AML_SUSPEND 1
#define CONFIG_CMD_LOGO
/*
* CPU switch test for uboot
*/
//#define CONFIG_M8_TEST_CPU_SWITCH 1
/*
* Secure OS
*/
#ifdef CONFIG_MESON_TRUSTZONE
#define CONFIG_MESON_SECUREARGS 1
//#define CONFIG_MESON_SECURE_HDCP 1
#define CONFIG_JOIN_UBOOT_SECUREOS 1
#define SECUREOS_KEY_BASE_ADDR 0x06100000
#define SECURE_OS_DECOMPRESS_ADDR 0x06200000
#define CONFIG_SECURE_STORAGE_BURNED
#ifdef CONFIG_SECURE_STORAGE_BURNED
#define CONFIG_MESON_STORAGE_BURN 1
#define CONFIG_MESON_STORAGE_DEBUG
#define CONFIG_SECURESTORAGEKEY
#define CONFIG_RANDOM_GENERATE
#define CONFIG_CMD_SECURESTORE
#define CONFIG_CMD_RANDOM
/* secure storage support both spi and emmc */
#define CONFIG_SECURE_MMC
//#define CONFIG_SPI_NOR_SECURE_STORAGE
#endif // CONFIG_SECURE_STORAGE_BURNED
#endif //CONFIG_MESON_TRUSTZONE
#endif //__CONFIG_M8_K200_V1_H__
|
superdjc/tbdg773b_uboot
|
board/amlogic/configs/m8_n200C_v1.h
|
C
|
gpl-2.0
| 17,202 |
/* purple
*
* Purple 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 02111-1301 USA
*/
#include "internal.h"
#include <string.h>
#include "http.h"
struct _FbHttpConns
{
GHashTable *cons;
gboolean canceled;
};
GQuark
fb_http_error_quark(void)
{
static GQuark q = 0;
if (G_UNLIKELY(q == 0)) {
q = g_quark_from_static_string("fb-http-error-quark");
}
return q;
}
FbHttpConns *
fb_http_conns_new(void)
{
FbHttpConns *cons;
cons = g_new0(FbHttpConns, 1);
cons->cons = g_hash_table_new(g_direct_hash, g_direct_equal);
return cons;
}
void
fb_http_conns_free(FbHttpConns *cons)
{
g_return_if_fail(cons != NULL);
g_hash_table_destroy(cons->cons);
g_free(cons);
}
void
fb_http_conns_cancel_all(FbHttpConns *cons)
{
GHashTableIter iter;
gpointer con;
g_return_if_fail(cons != NULL);
g_return_if_fail(!cons->canceled);
cons->canceled = TRUE;
g_hash_table_iter_init(&iter, cons->cons);
while (g_hash_table_iter_next(&iter, &con, NULL)) {
g_hash_table_iter_remove(&iter);
purple_http_conn_cancel(con);
}
}
gboolean
fb_http_conns_is_canceled(FbHttpConns *cons)
{
g_return_val_if_fail(cons != NULL, TRUE);
return cons->canceled;
}
void
fb_http_conns_add(FbHttpConns *cons, PurpleHttpConnection *con)
{
g_return_if_fail(cons != NULL);
g_return_if_fail(!cons->canceled);
g_hash_table_replace(cons->cons, con, con);
}
void
fb_http_conns_remove(FbHttpConns *cons, PurpleHttpConnection *con)
{
g_return_if_fail(cons != NULL);
g_return_if_fail(!cons->canceled);
g_hash_table_remove(cons->cons, con);
}
void
fb_http_conns_reset(FbHttpConns *cons)
{
g_return_if_fail(cons != NULL);
cons->canceled = FALSE;
g_hash_table_remove_all(cons->cons);
}
gboolean
fb_http_error_chk(PurpleHttpResponse *res, GError **error)
{
const gchar *msg;
gint code;
if (purple_http_response_is_successful(res)) {
return TRUE;
}
msg = purple_http_response_get_error(res);
code = purple_http_response_get_code(res);
g_set_error(error, FB_HTTP_ERROR, code, "%s", msg);
return FALSE;
}
FbHttpParams *
fb_http_params_new(void)
{
return g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
}
FbHttpParams *
fb_http_params_new_parse(const gchar *data, gboolean isurl)
{
const gchar *tail;
gchar *key;
gchar **ps;
gchar *val;
guint i;
FbHttpParams *params;
params = fb_http_params_new();
if (data == NULL) {
return params;
}
if (isurl) {
data = strchr(data, '?');
if (data == NULL) {
return params;
}
tail = strchr(++data, '#');
if (tail != NULL) {
data = g_strndup(data, tail - data);
} else {
data = g_strdup(data);
}
}
ps = g_strsplit(data, "&", 0);
for (i = 0; ps[i] != NULL; i++) {
key = ps[i];
val = strchr(ps[i], '=');
if (val == NULL) {
continue;
}
*(val++) = 0;
key = g_uri_unescape_string(key, NULL);
val = g_uri_unescape_string(val, NULL);
g_hash_table_replace(params, key, val);
}
if (isurl) {
g_free((gchar *) data);
}
g_strfreev(ps);
return params;
}
void
fb_http_params_free(FbHttpParams *params)
{
g_hash_table_destroy(params);
}
gchar *
fb_http_params_close(FbHttpParams *params, const gchar *url)
{
GHashTableIter iter;
gpointer key;
gpointer val;
GString *ret;
g_hash_table_iter_init(&iter, params);
ret = g_string_new(NULL);
while (g_hash_table_iter_next(&iter, &key, &val)) {
if (val == NULL) {
g_hash_table_iter_remove(&iter);
continue;
}
if (ret->len > 0) {
g_string_append_c(ret, '&');
}
g_string_append_uri_escaped(ret, key, NULL, TRUE);
g_string_append_c(ret, '=');
g_string_append_uri_escaped(ret, val, NULL, TRUE);
}
if (url != NULL) {
g_string_prepend_c(ret, '?');
g_string_prepend(ret, url);
}
fb_http_params_free(params);
return g_string_free(ret, FALSE);
}
static const gchar *
fb_http_params_get(FbHttpParams *params, const gchar *name, GError **error)
{
const gchar *ret;
ret = g_hash_table_lookup(params, name);
if (ret == NULL) {
g_set_error(error, FB_HTTP_ERROR, FB_HTTP_ERROR_NOMATCH,
_("No matches for %s"), name);
return NULL;
}
return ret;
}
gboolean
fb_http_params_get_bool(FbHttpParams *params, const gchar *name,
GError **error)
{
const gchar *val;
val = fb_http_params_get(params, name, error);
if (val == NULL) {
return FALSE;
}
return g_ascii_strcasecmp(val, "TRUE") == 0;
}
gdouble
fb_http_params_get_dbl(FbHttpParams *params, const gchar *name,
GError **error)
{
const gchar *val;
val = fb_http_params_get(params, name, error);
if (val == NULL) {
return 0.0;
}
return g_ascii_strtod(val, NULL);
}
gint64
fb_http_params_get_int(FbHttpParams *params, const gchar *name,
GError **error)
{
const gchar *val;
val = fb_http_params_get(params, name, error);
if (val == NULL) {
return 0;
}
return g_ascii_strtoll(val, NULL, 10);
}
const gchar *
fb_http_params_get_str(FbHttpParams *params, const gchar *name,
GError **error)
{
return fb_http_params_get(params, name, error);
}
gchar *
fb_http_params_dup_str(FbHttpParams *params, const gchar *name,
GError **error)
{
const gchar *str;
str = fb_http_params_get(params, name, error);
return g_strdup(str);
}
static void
fb_http_params_set(FbHttpParams *params, const gchar *name, gchar *value)
{
gchar *key;
key = g_strdup(name);
g_hash_table_replace(params, key, value);
}
void
fb_http_params_set_bool(FbHttpParams *params, const gchar *name,
gboolean value)
{
gchar *val;
val = g_strdup(value ? "true" : "false");
fb_http_params_set(params, name, val);
}
void
fb_http_params_set_dbl(FbHttpParams *params, const gchar *name, gdouble value)
{
gchar *val;
val = g_strdup_printf("%f", value);
fb_http_params_set(params, name, val);
}
void
fb_http_params_set_int(FbHttpParams *params, const gchar *name, gint64 value)
{
gchar *val;
val = g_strdup_printf("%" G_GINT64_FORMAT, value);
fb_http_params_set(params, name, val);
}
void
fb_http_params_set_str(FbHttpParams *params, const gchar *name,
const gchar *value)
{
gchar *val;
val = g_strdup(value);
fb_http_params_set(params, name, val);
}
void
fb_http_params_set_strf(FbHttpParams *params, const gchar *name,
const gchar *format, ...)
{
gchar *val;
va_list ap;
va_start(ap, format);
val = g_strdup_vprintf(format, ap);
va_end(ap);
fb_http_params_set(params, name, val);
}
gboolean
fb_http_urlcmp(const gchar *url1, const gchar *url2, gboolean protocol)
{
const gchar *str1;
const gchar *str2;
gboolean ret = TRUE;
gint int1;
gint int2;
guint i;
PurpleHttpURL *purl1;
PurpleHttpURL *purl2;
static const const gchar * (*funcs[]) (const PurpleHttpURL *url) = {
/* Always first so it can be skipped */
purple_http_url_get_protocol,
purple_http_url_get_fragment,
purple_http_url_get_host,
purple_http_url_get_password,
purple_http_url_get_path,
purple_http_url_get_username
};
if ((url1 == NULL) || (url2 == NULL)) {
return url1 == url2;
}
purl1 = purple_http_url_parse(url1);
if (purl1 == NULL) {
return g_ascii_strcasecmp(url1, url2) == 0;
}
purl2 = purple_http_url_parse(url2);
if (purl2 == NULL) {
purple_http_url_free(purl1);
return g_ascii_strcasecmp(url1, url2) == 0;
}
for (i = protocol ? 0 : 1; i < G_N_ELEMENTS(funcs); i++) {
str1 = funcs[i](purl1);
str2 = funcs[i](purl2);
if (!purple_strequal(str1, str2)) {
ret = FALSE;
break;
}
}
if (ret && protocol) {
int1 = purple_http_url_get_port(purl1);
int2 = purple_http_url_get_port(purl2);
if (int1 != int2) {
ret = FALSE;
}
}
purple_http_url_free(purl1);
purple_http_url_free(purl2);
return ret;
}
|
N8Fear/purple-facebook
|
pidgin/libpurple/protocols/facebook/http.c
|
C
|
gpl-2.0
| 8,553 |
/*
* Copyright (C) 2007 Apple, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
extern int WebViewCount;
extern int WebDataSourceCount;
extern int WebFrameCount;
extern int WebHTMLRepresentationCount;
extern int WebFrameViewCount;
|
Debian/openjfx
|
modules/web/src/main/native/Source/WebKit/win/WebKitStatisticsPrivate.h
|
C
|
gpl-2.0
| 1,711 |
/*
* Copyright (c) 2009, 2012, 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.
*/
package com.oracle.graal.lir;
import static com.oracle.graal.api.code.ValueUtil.*;
import static com.oracle.graal.lir.LIRValueUtil.*;
import java.util.*;
import com.oracle.graal.api.code.*;
import com.oracle.graal.api.meta.*;
import com.oracle.graal.debug.*;
import com.oracle.graal.graph.*;
import com.oracle.graal.lir.LIRInstruction.OperandFlag;
import com.oracle.graal.lir.LIRInstruction.OperandMode;
import com.oracle.graal.lir.LIRInstruction.ValueProcedure;
import com.oracle.graal.nodes.cfg.*;
public final class LIRVerifier {
private final LIR lir;
private final FrameMap frameMap;
private final boolean beforeRegisterAllocation;
private final BitSet[] blockLiveOut;
private final Object[] variableDefinitions;
private BitSet liveOutFor(Block block) {
return blockLiveOut[block.getId()];
}
private void setLiveOutFor(Block block, BitSet liveOut) {
blockLiveOut[block.getId()] = liveOut;
}
private int maxRegisterNum() {
return frameMap.target.arch.getRegisters().length;
}
private boolean isAllocatableRegister(Value value) {
return isRegister(value) && frameMap.registerConfig.getAttributesMap()[asRegister(value).number].isAllocatable();
}
public static boolean verify(final LIRInstruction op) {
ValueProcedure allowedProc = new ValueProcedure() {
@Override
public Value doValue(Value value, OperandMode mode, EnumSet<OperandFlag> flags) {
return allowed(op, value, mode, flags);
}
};
op.forEachInput(allowedProc);
op.forEachAlive(allowedProc);
op.forEachState(allowedProc);
op.forEachTemp(allowedProc);
op.forEachOutput(allowedProc);
op.verify();
return true;
}
public static boolean verify(boolean beforeRegisterAllocation, LIR lir, FrameMap frameMap) {
LIRVerifier verifier = new LIRVerifier(beforeRegisterAllocation, lir, frameMap);
verifier.verify();
return true;
}
private LIRVerifier(boolean beforeRegisterAllocation, LIR lir, FrameMap frameMap) {
this.beforeRegisterAllocation = beforeRegisterAllocation;
this.lir = lir;
this.frameMap = frameMap;
this.blockLiveOut = new BitSet[lir.linearScanOrder().size()];
this.variableDefinitions = new Object[lir.numVariables()];
}
private BitSet curVariablesLive;
private Value[] curRegistersLive;
private Block curBlock;
private Object curInstruction;
private BitSet curRegistersDefined;
private void verify() {
ValueProcedure useProc = new ValueProcedure() {
@Override
public Value doValue(Value value, OperandMode mode, EnumSet<OperandFlag> flags) {
return use(value, mode, flags);
}
};
ValueProcedure defProc = new ValueProcedure() {
@Override
public Value doValue(Value value, OperandMode mode, EnumSet<OperandFlag> flags) {
return def(value, mode, flags);
}
};
int maxRegisterNum = maxRegisterNum();
curRegistersDefined = new BitSet();
for (Block block : lir.linearScanOrder()) {
curBlock = block;
curVariablesLive = new BitSet();
curRegistersLive = new Value[maxRegisterNum];
if (block.getDominator() != null) {
curVariablesLive.or(liveOutFor(block.getDominator()));
}
assert lir.lir(block).get(0) instanceof StandardOp.LabelOp : "block must start with label";
if (block.getSuccessorCount() > 0) {
LIRInstruction last = lir.lir(block).get(lir.lir(block).size() - 1);
assert last instanceof StandardOp.JumpOp : "block with successor must end with unconditional jump";
}
for (LIRInstruction op : lir.lir(block)) {
curInstruction = op;
op.forEachInput(useProc);
if (op.destroysCallerSavedRegisters()) {
for (Register register : frameMap.registerConfig.getCallerSaveRegisters()) {
curRegistersLive[register.number] = null;
}
}
curRegistersDefined.clear();
op.forEachAlive(useProc);
op.forEachState(useProc);
op.forEachTemp(defProc);
op.forEachOutput(defProc);
curInstruction = null;
}
setLiveOutFor(block, curVariablesLive);
}
}
private Value use(Value value, OperandMode mode, EnumSet<OperandFlag> flags) {
allowed(curInstruction, value, mode, flags);
if (isVariable(value)) {
assert beforeRegisterAllocation;
int variableIdx = asVariable(value).index;
if (!curVariablesLive.get(variableIdx)) {
TTY.println("block %s instruction %s", curBlock, curInstruction);
TTY.println("live variables: %s", curVariablesLive);
if (variableDefinitions[variableIdx] != null) {
TTY.println("definition of %s: %s", value, variableDefinitions[variableIdx]);
}
TTY.println("ERROR: Use of variable %s that is not defined in dominator", value);
throw GraalInternalError.shouldNotReachHere();
}
} else if (isAllocatableRegister(value)) {
int regNum = asRegister(value).number;
if (mode == OperandMode.ALIVE) {
curRegistersDefined.set(regNum);
}
if (beforeRegisterAllocation && !curRegistersLive[regNum].equals(value)) {
TTY.println("block %s instruction %s", curBlock, curInstruction);
TTY.println("live registers: %s", Arrays.toString(curRegistersLive));
TTY.println("ERROR: Use of fixed register %s that is not defined in this block", value);
throw GraalInternalError.shouldNotReachHere();
}
}
return value;
}
private Value def(Value value, OperandMode mode, EnumSet<OperandFlag> flags) {
allowed(curInstruction, value, mode, flags);
if (isVariable(value)) {
assert beforeRegisterAllocation;
int variableIdx = asVariable(value).index;
if (variableDefinitions[variableIdx] != null) {
TTY.println("block %s instruction %s", curBlock, curInstruction);
TTY.println("live variables: %s", curVariablesLive);
TTY.println("definition of %s: %s", value, variableDefinitions[variableIdx]);
TTY.println("ERROR: Variable %s defined multiple times", value);
throw GraalInternalError.shouldNotReachHere();
}
assert curInstruction != null;
variableDefinitions[variableIdx] = curInstruction;
assert !curVariablesLive.get(variableIdx);
if (mode == OperandMode.DEF) {
curVariablesLive.set(variableIdx);
}
} else if (isAllocatableRegister(value)) {
int regNum = asRegister(value).number;
if (curRegistersDefined.get(regNum)) {
TTY.println("block %s instruction %s", curBlock, curInstruction);
TTY.println("ERROR: Same register defined twice in the same instruction: %s", value);
throw GraalInternalError.shouldNotReachHere();
}
curRegistersDefined.set(regNum);
if (beforeRegisterAllocation) {
if (mode == OperandMode.DEF) {
curRegistersLive[regNum] = value;
} else {
curRegistersLive[regNum] = null;
}
}
}
return value;
}
// @formatter:off
private static Value allowed(Object op, Value value, OperandMode mode, EnumSet<OperandFlag> flags) {
if ((isVariable(value) && flags.contains(OperandFlag.REG)) ||
(isRegister(value) && flags.contains(OperandFlag.REG)) ||
(isStackSlot(value) && flags.contains(OperandFlag.STACK)) ||
(isConstant(value) && flags.contains(OperandFlag.CONST) && mode != OperandMode.DEF) ||
(isIllegal(value) && flags.contains(OperandFlag.ILLEGAL))) {
return value;
}
throw new GraalInternalError("Invalid LIR%n Instruction: %s%n Mode: %s%n Flags: %s%n Unexpected value: %s %s",
op, mode, flags, value.getClass().getSimpleName(), value);
}
// @formatter:on
}
|
arodchen/MaxSim
|
graal/graal/com.oracle.graal.lir/src/com/oracle/graal/lir/LIRVerifier.java
|
Java
|
gpl-2.0
| 9,736 |
#!/usr/bin/env php
<?php
/**
* @copyright Copyright (C) 1999-2013 eZ Systems AS. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
* @version //autogentag//
* @package kernel
*/
require 'autoload.php';
$cli = eZCLI::instance();
$script = eZScript::instance( array( 'description' => ( "eZ Publish Country update script\n\n" .
"Upgrades db table in addition with upgrade from 3.9.2 to 3.9.3\n" .
"Fixes bug with aplying VAT rules" ),
'use-session' => false,
'use-modules' => true,
'use-extensions' => true ) );
$script->startup();
$options = $script->getOptions( );
$script->initialize();
$db = eZDB::instance();
$countries = $db->arrayQuery( "SELECT country_code from ezvatrule;" );
$iniCountries = eZCountryType::fetchCountryList();
$updatedRules = 0;
foreach ( $countries as $country )
{
foreach ( $iniCountries as $iniCountry )
{
if ( $iniCountry['Name'] == $country['country_code'] )
{
$countryName = $country['country_code'];
$countryCode = $iniCountry['Alpha2'];
$db->query( "UPDATE ezvatrule SET country_code='" . $db->escapeString( $countryCode ) . "' WHERE country_code='" . $db->escapeString( $countryName ) . "'" );
$updatedRules++;
}
}
}
$cli->output( 'Updated VAT rules: ' . $updatedRules );
$script->shutdown();
?>
|
lexxksb/shumoff
|
update/common/scripts/4.0/updatevatcountries.php
|
PHP
|
gpl-2.0
| 1,607 |
<?php
function add_group_meta_box() {
global $bp;
?>
<fieldset>
<legend class="screen-reader-text"><span><?php _e('Core Group Options', 'bp-group-organizer') ?></span></legend>
<p><label for="group_name">
<?php _e('Group Name', 'bp-group-organizer'); ?><input id="group_name" type="text" name="group_name" value="" />
</label></p>
<p><label for="group_slug">
<?php _e('Group Slug', 'bp-group-organizer'); ?>
<input id="group_slug" type="text" name="group_slug" value="" />
</label></p>
<p><label for="group_desc">
<?php _e('Group Description', 'bp-group-organizer'); ?>
<input id="group_desc" type="text" name="group_desc" value="" />
</label></p>
</fieldset>
<fieldset>
<legend class="screen-reader-text"><span><?php _e('Advanced Group Options', 'bp-group-organizer') ?></span></legend>
<p><label for="group_status">
<?php _e( 'Privacy Options', 'buddypress' ); ?>
<select id="group_status" name="group_status">
<?php foreach($bp->groups->valid_status as $status) : ?>
<option value="<?php echo $status ?>"><?php echo ucfirst($status) ?></option>
<?php endforeach; ?>
</select>
</label></p>
<?php if ( bp_is_active( 'forums' ) && ( function_exists( 'bp_forums_is_installed_correctly' ) && bp_forums_is_installed_correctly() ) ) : ?>
<p><label for="group_forum">
<?php _e('Enable discussion forum', 'buddypress'); ?>
<input id="group_forum" type="checkbox" name="group_forum" checked />
</label></p>
<?php elseif( function_exists( 'bbp_is_group_forums_active' ) && bbp_is_group_forums_active() ) : ?>
<p><label for="group_forum">
<?php _e('Enable bbPress discussion forum', 'bp-group-organizer'); ?>
<input id="group_forum" type="checkbox" name="group_forum" checked />
</label></p>
<?php endif; ?>
<p><label for="group_creator">
<?php _e('Group Creator', 'bp-group-organizer'); ?>
<input id="group_creator" type="text" name="group_creator" value="" />
</label></p>
</fieldset>
<?php if( defined( 'BP_GROUP_HIERARCHY_IS_INSTALLED' ) ) : ?>
<fieldset><legend class="screen-reader-text"><span><?php _e('Group Hierarchy Options') ?></span></legend>
<?php if(method_exists('BP_Groups_Hierarchy','get_tree')) : ?>
<p><label for="group_parent">
<?php _e( 'Parent Group', 'bp-group-hierarchy' ); ?>
<?php $all_groups = BP_Groups_Hierarchy::get_tree(); ?>
<select name="group_parent" id="group_parent">
<option value="0"><?php _e('Site Root','bp-group-hierarchy') ?></option>
<?php foreach($all_groups as $group) : ?>
<option value="<?php echo $group->id ?>"><?php echo esc_html( stripslashes( $group->name ) ) ?> (<?php echo $group->slug ?>)</option>
<?php endforeach; ?>
</select>
</label></p>
<?php else: ?>
<p><?php _e('Your version of BuddyPress Group Hierarchy is too old to use with the organizer. Please upgrade to version <code>1.2.1</code> or higher.', 'bp-group-organizer'); ?></p>
<?php endif; ?>
</fieldset>
<?php endif; ?>
<?php do_action( 'bp_group_organizer_display_new_group_options' ); ?>
<p><?php _e('Create a group to add to your site.', 'bp-group-organizer'); ?></p>
<p class="button-controls">
<?php submit_button( __( 'Add' ), 'button-primary primary right', 'group-organizer-create', false ); ?>
<span class="spinner"></span>
</p>
<?php
}
add_meta_box('add_group_meta_box', __('Create a Group', 'bp-group-organizer'), 'add_group_meta_box', 'group-organizer', 'side');
?>
|
BODA82/MaineLearning
|
wp-content/plugins/bp-group-organizer/includes/group-meta-boxes.php
|
PHP
|
gpl-2.0
| 3,521 |
<?php
namespace Google\AdsApi\Dfp\v201611;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class RichMediaStudioChildAssetPropertyType
{
const FLASH = 'FLASH';
const VIDEO = 'VIDEO';
const IMAGE = 'IMAGE';
const DATA = 'DATA';
}
|
renshuki/dfp-manager
|
vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201611/RichMediaStudioChildAssetPropertyType.php
|
PHP
|
gpl-2.0
| 261 |
<?php
/**
* @author JoomlaShine.com Team
* @copyright JoomlaShine.com
* @link joomlashine.com
* @package JSN ImageShow - Theme Classic
* @version $Id: jsn_is_thememedia.php 6649 2011-06-08 10:29:57Z giangnd $
* @license GNU/GPL v2 http://www.gnu.org/licenses/gpl-2.0.html
*/
defined('_JEXEC') or die( 'Restricted access' );
JSNISFactory::importFile('classes.jsn_is_mediamanager');
class JSNISThemeMedia extends JSNISMediaManager
{
var $_showcaseThemeName = 'themeclassic';
var $_showcaseThemeType = 'jsnimageshow';
public static function getInstance()
{
static $instanceThemeMedia;
if ($instanceThemeMedia == null)
{
$instanceThemeMedia = new JSNISThemeMedia();
}
return $instanceThemeMedia;
}
function setMediaBasePath()
{
$act = JRequest::getCmd('act','custom');
if ($act == 'custom')
{
$this->setPath(JPATH_ROOT.DS.'images', JURI::root().'images');
}
if ($act == 'background')
{
$this->setPath(JPATH_COMPONENT_SITE.DS.'assets'.DS.'images'.DS.'bg-images', JURI::root().'components/com_imageshow/assets/images/bg-images');
}
if ($act == 'pattern')
{
$this->setPath(JPATH_PLUGINS.DS.$this->_showcaseThemeType.DS.$this->_showcaseThemeName.DS.$this->_showcaseThemeName.DS.'assets'.DS.'images'.DS.'bg-patterns', JURI::root().'plugins/'.$this->_showcaseThemeType.'/'.$this->_showcaseThemeName.'/'.$this->_showcaseThemeName.'/assets/images/bg-patterns');
}
if ($act == 'watermark')
{
$this->setPath(JPATH_ROOT.DS.'images', JURI::root().'images');
}
}
}
|
chakrinamo/Projet_LPSIL
|
plugins/jsnimageshow/themeclassic/themeclassic/classes/jsn_is_thememedia.php
|
PHP
|
gpl-2.0
| 1,528 |
<?php
namespace Typoheads\Formhandler\Validator\ErrorCheck;
/* *
* This script is part of the TYPO3 project - inspiring people to share! *
* *
* TYPO3 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 script is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- *
* TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General *
* Public License for more details. *
* */
/**
* Validates that a specified field's value matches the generated word of the extension "jm_recaptcha"
*
* @author Reinhard Führicht <[email protected]>
* @package Tx_Formhandler
* @subpackage ErrorChecks
*/
class JmRecaptcha extends AbstractErrorCheck
{
public function check()
{
$checkFailed = '';
if (\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('jm_recaptcha')) {
require_once(\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('jm_recaptcha') . 'class.tx_jmrecaptcha.php');
$this->recaptcha = new \tx_jmrecaptcha();
$status = $this->recaptcha->validateReCaptcha();
if (!$status['verified']) {
$checkFailed = $this->getCheckFailed();
}
}
return $checkFailed;
}
}
|
hnadler/typo3-formhandler
|
Classes/Validator/ErrorCheck/JmRecaptcha.php
|
PHP
|
gpl-2.0
| 1,853 |
/*
* This file is part of the UCB release of Plan 9. It is subject to the license
* terms in the LICENSE file found in the top-level directory of this
* distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
* part of the UCB release of Plan 9, including this file, may be copied,
* modified, propagated, or distributed except according to the terms contained
* in the LICENSE file.
*/
#include <u.h>
#include <libc.h>
/*
* Return pointer to first occurrence of s2 in s1,
* 0 if none
*/
char*
strstr(char *s1, char *s2)
{
char *p, *pa, *pb;
int c0, c;
c0 = *s2;
if(c0 == 0)
return s1;
s2++;
for(p=strchr(s1, c0); p; p=strchr(p+1, c0)) {
pa = p;
for(pb=s2;; pb++) {
c = *pb;
if(c == 0)
return p;
if(c != *++pa)
break;
}
}
return 0;
}
|
brho/plan9
|
sys/src/libc/port/strstr.c
|
C
|
gpl-2.0
| 798 |
namespace Server.Items
{
public class DaemonClaw : Item, ICommodity
{
[Constructable]
public DaemonClaw()
: this(1)
{
}
[Constructable]
public DaemonClaw(int amount)
: base(0x5721)
{
Stackable = true;
Amount = amount;
}
public DaemonClaw(Serial serial)
: base(serial)
{
}
TextDefinition ICommodity.Description => LabelNumber;
bool ICommodity.IsDeedable => true;
public override int LabelNumber => 1113330;// daemon claw
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write(0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
}
|
Argalep/ServUO
|
Scripts/Items/Resource/DaemonClaw.cs
|
C#
|
gpl-2.0
| 937 |
--[[
Copyright (C) 2010-2014 <reyalp (at) gmail dot com>
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--]]
local cli = {
cmds={},
names={},
finished = false,
source_level = 0, -- number of nested execfile calls
}
--[[
info printf - message to be printed at normal verbosity
]]
cli.infomsg = util.make_msgf( function() return prefs.cli_verbose end, 1)
cli.dbgmsg = util.make_msgf( function() return prefs.cli_verbose end, 2)
--[[
get command args of the form -a[=value] -bar[=value] .. [wordarg1] [wordarg2] [wordarg...]
--]]
local argparser = { }
cli.argparser = argparser
-- trim leading spaces
function argparser:trimspace(str)
local s, e = string.find(str,'^[%c%s]*')
return string.sub(str,e+1)
end
--[[
get a 'word' argument, either a sequence of non-white space characters, or a quoted string
inside " \ is treated as an escape character
return word, end position on success or false, error message
]]
function argparser:get_word(str)
local result = ''
local esc = false
local qchar = false
local pos = 1
while pos <= string.len(str) do
local c = string.sub(str,pos,pos)
-- in escape, append next character unconditionally
if esc then
result = result .. c
esc = false
-- inside double quote, start escape and discard backslash
elseif qchar == '"' and c == '\\' then
esc = true
-- character is the current quote char, close quote and discard
elseif c == qchar then
qchar = false
-- not hit a space and not inside a quote, end
elseif not qchar and string.match(c,"[%c%s]") then
break
-- hit a quote and not inside a quote, enter quote and discard
elseif not qchar and c == '"' or c == "'" then
qchar = c
-- anything else, copy
else
result = result .. c
end
pos = pos + 1
end
if esc then
return false,"unexpected \\"
end
if qchar then
return false,"unclosed " .. qchar
end
return result,pos
end
function argparser:parse_words(str)
local words={}
str = self:trimspace(str)
while string.len(str) > 0 do
local w,pos = self:get_word(str)
if not w then
return false,pos -- pos is error string
end
table.insert(words,w)
str = string.sub(str,pos)
str = self:trimspace(str)
end
return words
end
--[[
parse a command string into switches and word arguments
switches are in the form -swname[=value]
word arguments are anything else
any portion of the string may be quoted with '' or ""
inside "", \ is treated as an escape
on success returns table with args as array elements and switches as named elements
on failure returns false, error
defs defines the valid switches and their default values. Can also define default values of numeric args
TODO enforce switch values, number of args, integrate with help
]]
function argparser:parse(str)
-- default values
local results=util.extend_table({},self.defs)
local words,errmsg=self:parse_words(str)
if not words then
return false,errmsg
end
for i, w in ipairs(words) do
-- look for -name
local s,e,swname=string.find(w,'^-(%a[%w_-]*)')
-- found a switch
if s then
if type(self.defs[swname]) == 'nil' then
return false,'unknown switch '..swname
end
local swval
-- no value
if e == string.len(w) then
swval = true
elseif string.sub(w,e+1,e+1) == '=' then
-- note, may be empty string but that's ok
swval = string.sub(w,e+2)
else
return false,"invalid switch value "..string.sub(w,e+1)
end
results[swname]=swval
else
table.insert(results,w)
end
end
return results
end
-- a default for comands that want the raw string
argparser.nop = {
parse =function(self,str)
return str
end
}
function argparser.create(defs)
local r={ defs=defs }
return util.mt_inherit(r,argparser)
end
cli.cmd_proto = {
get_help = function(self)
local namestr = self.names[1]
if #self.names > 1 then
namestr = namestr .. " (" .. self.names[2]
for i=3,#self.names do
namestr = namestr .. "," .. self.names[i]
end
namestr = namestr .. ")"
end
return string.format("%-12s %-12s: - %s\n",namestr,self.arghelp,self.help)
end,
get_help_detail = function(self)
local msg=self:get_help()
if self.help_detail then
msg = msg..self.help_detail..'\n'
end
return msg
end,
}
cli.cmd_meta = {
__index = function(cmd, key)
return cli.cmd_proto[key]
end,
}
function cli:add_commands(cmds)
for i = 1, #cmds do
cmd = cmds[i]
table.insert(self.cmds,cmd)
if not cmd.arghelp then
cmd.arghelp = ''
end
if not cmd.args then
cmd.args = argparser.nop
end
for _,name in ipairs(cmd.names) do
if self.names[name] then
warnf("duplicate command name %s\n",name)
else
self.names[name] = cmd
end
end
setmetatable(cmd,cli.cmd_meta)
end
end
function cli:get_prompt()
if con:is_connected() then
local script_id = con:get_script_id()
if script_id then
return string.format("con %d> ",script_id)
else
return "con> "
end
else
return "___> "
end
end
function cli:prompt()
printf("%s",self:get_prompt())
end
-- execute command given by a single line
-- returns status,message
-- message is an error message or printable value
function cli:execute(line)
-- single char shortcuts
local s,e,cmd = string.find(line,'^[%c%s]*([!.#=])[%c%s]*')
if not cmd then
s,e,cmd = string.find(line,'^[%c%s]*([%w_]+)[%c%s]*')
end
if s then
local args = string.sub(line,e+1)
if self.names[cmd] then
local status,msg
args,msg = self.names[cmd].args:parse(args)
if not args then
return false,msg
end
local cstatus
local t0=ustime.new()
con:reset_counters()
if self.names[cmd].noxpcall then
cstatus = true
status,msg = self.names[cmd]:func(args)
else
cstatus,status,msg = xpcall(
function()
return self.names[cmd]:func(args)
end,
errutil.format)
end
local tdiff = ustime.diff(t0)/1000000;
if prefs.cli_time then
printf("time %.4f\n",tdiff)
end
if prefs.cli_xferstats then
local xferstats = con:get_counters();
local rbps,wbps
if tdiff == 0 then
rbps = "-"
wbps = "-"
else
-- note these are based on total command execution time, not just transfer
rbps = string.format("%d",xferstats.read/tdiff)
wbps = string.format("%d",xferstats.write/tdiff)
end
printf("r %d %s/s w %d %s/s\n",xferstats.read,rbps,xferstats.write,wbps)
end
if not cstatus then
return false,status
end
if not status and not msg then
msg=cmd .. " failed"
end
return status,msg
else
return false,string.format("unknown command '%s'\n",cmd)
end
elseif string.find(line,'[^%c%s]') then
return false, string.format("bad input '%s'\n",line)
end
-- blank input is OK
return true,""
end
function cli:execfile(filename)
if cli.source_level == prefs.cli_source_max then
return false, 'too many nested source calls'
end
cli.source_level = cli.source_level + 1
local fh, err = io.open(filename,'rb')
if not fh then
return false, 'failed to open file: '..tostring(err)
end
-- empty file is OK
local status = true
local lnum = 1
for line in fh:lines() do
local msg
status, msg = self:execute(line)
self:print_status(status,msg)
-- TODO pref to continue on errors
if self.finished or not status then
break
end
lnum = lnum + 1
end
fh:close()
cli.source_level = cli.source_level - 1
if not status then
return false, string.format('error on line %d',lnum)
end
return true
end
function cli:print_status(status,msg)
if not status then
errf("%s\n",tostring(msg))
elseif msg then
msg = tostring(msg) -- ensure error object is converted
if string.len(msg) ~= 0 then
printf("%s",msg)
if string.sub(msg,-1,-1) ~= '\n' then
printf("\n")
end
end
end
return status,msg
end
if readline then
cli.readline = readline.line
cli.add_history = readline.add_history
else
function cli.readline(prompt)
printf("%s",prompt)
return io.read()
end
-- noop
function cli.add_history(line)
end
end
function cli:run()
while true do
line = cli.readline(self:get_prompt())
if not line then
break
end
if line:len() > 0 then
cli.add_history(line)
end
self:print_status(self:execute(line))
if self.finished then
break
end
end
end
-- update gui for cli commands
-- TODO should be a generic event system
function cli:connection_status_change()
if gui then
gui.update_connection_status()
end
end
function cli:mode_change()
if gui then
gui.update_mode_list()
end
end
--[[
process options common to shoot and remoteshoot
]]
function cli:get_shoot_common_opts(args)
if not con:is_connected() then
return false, 'not connected'
end
if not util.in_table({'s','a','96'},args.u) then
return false,"invalid units"
end
if args.sv and args.svm then
return false, "both sv and svm given"
end
local opts={}
if args.u == 's' then
if args.av then
opts.av=exp.f_to_av96(args.av)
end
if args.sv then
opts.sv=exp.iso_to_sv96(args.sv)
end
if args.svm then
opts.svm=exp.iso_to_sv96(args.svm)
end
if args.tv then
local n,d = string.match(args.tv,'^([%d]+)/([%d.]+)$')
if n then
n = tonumber(n)
d = tonumber(d)
if not n or not d or n == 0 or d == 0 then
return false, 'invalid tv fraction'
end
opts.tv = exp.shutter_to_tv96(n/d)
else
n = tonumber(args.tv)
if not n then
return false, 'invalid tv value'
end
opts.tv = exp.shutter_to_tv96(n)
end
end
elseif args.u == 'a' then
if args.av then
opts.av = util.round(args.av*96)
end
if args.sv then
opts.sv = util.round(args.sv*96)
end
if args.svm then
opts.svm = util.round(args.svm*96)
end
if args.tv then
opts.tv = util.round(args.tv*96)
end
else
if args.av then
opts.av=tonumber(args.av)
end
if args.sv then
opts.sv=tonumber(args.sv)
end
if args.svm then
opts.svm=tonumber(args.svm)
end
if args.tv then
opts.tv=tonumber(args.tv)
end
end
if args.isomode then
if opts.sv or opts.svm then
return false,'set only one of sv, svm or isomode!'
end
opts.isomode = tonumber(args.isomode)
end
if args.nd then
local val = ({['in']=1,out=2})[args.nd]
if not val then
return false,'invalid ND state '..tostring(args.nd)
end
opts.nd = val
end
if args.sd then
local sd,units=string.match(args.sd,'(%d+)(%a*)')
local convert={
mm=1,
cm=100,
m=1000,
ft=304.8,
['in']=25.4,
}
if units == '' then
units = 'm'
end
if not convert[units] then
return false,string.format('invalid sd units %s',tostring(units))
end
opts.sd = util.round(sd*convert[units])
end
-- hack for CHDK override bug that ignores APEX 0
-- only used for CHDK 1.1 (API 2.4 and earlier)
if opts.tv == 0 and not con:is_ver_compatible(2,5) then
opts.tv = 1
end
return opts
end
--[[
return a single character status,formatted text listing for a single device specified by desc, or throw an error
]]
function cli.list_dev_single(desc)
local lcon = chdku.connection(desc)
local tempcon = false
local con_status = "+"
if not lcon:is_connected() then
tempcon = true
con_status = "-"
lcon:connect()
else
-- existing con wrapped in new object won't have info set
lcon.update_connection_info(lcon)
end
if con_status == '+' and lcon._con == con._con then
con_status = "*"
end
local msg=string.format("%s b=%s d=%s v=0x%x p=0x%x s=%s",
tostring(lcon.ptpdev.model),
lcon.condev.bus, lcon.condev.dev,
tostring(lcon.condev.vendor_id),
tostring(lcon.condev.product_id),
tostring(lcon.ptpdev.serial_number))
if tempcon then
lcon:disconnect()
end
return con_status,msg
end
--[[
helper function to setup lvdumpimg files
]]
function cli.init_lvdumpimg_file_opts(which,args,subst)
local opts={}
local pipeopt, ext, write_fn
if which == 'vp' then
pipeopt = 'pipevp'
ext='ppm'
write_fn = chdku.live_dump_vp_pbm
elseif which == 'bm' then
pipeopt = 'pipebm'
ext='pam'
write_fn = chdku.live_dump_bm_pam
else
errlib.throw{etype='bad_arg',msg='invalid type '..tostring(which)}
end
local filespec
if args[which] == true then
if args[pipeopt] then
errlib.throw{etype='bad_arg',msg='must specify command with '..tostring(pipeopt)}
end
filespec = which..'_${time,%014.3f}.'..ext
else
filespec = args[which]
end
if args[pipeopt] then
opts.pipe = true
if args[pipeopt] == 'oneproc' then
opts.pipe_oneproc = true
end
end
opts.write = function(frame)
if not args.nosubst then
opts.filename = subst:run(filespec)
else
opts.filename = filespec
end
write_fn(frame,opts)
if not args.quiet then
if opts.pipe_oneproc then
cli.infomsg('frame %d\n',subst.state.frame)
else
cli.infomsg('%s\n',opts.filename)
end
end
end
return opts
end
cli.download_overwrite_opts={
n=false,
y=true,
old=function(lcon,lopts,finfo,st,src,dst)
return chdku.ts_cam2pc(finfo.st.mtime) > st.modification
end,
ask=function(lcon,lopts,finfo,st,src,dst)
while true do
printf("existing: %s %d bytes modified %s\n",dst,st.size,os.date('%c',st.modification))
printf("new: %s %d bytes modified %s\n",src,finfo.st.size,os.date('%c',chdku.ts_cam2pc(finfo.st.mtime)))
local line = cli.readline('overwrite y / n / a (abort)? ')
if line == 'y' then
return true
end
if line == 'n' then
return false
end
if line == 'a' then
errlib.throw{etype='user_abort',msg='aborted by user'}
end
end
end,
}
function cli.get_download_overwrite_opt(val)
if type(val) == 'string' then
local ow = cli.download_overwrite_opts[val]
if ow == nil then
errlib.throw{etype='bad_arg',msg='unrecognized overwrite option '..val}
end
return ow
else
errlib.throw{etype='bad_arg',msg='unrecognized overwrite option '..tostring(val)}
end
end
-- TODO should have a system to split up command code
local rsint=require'rsint'
rsint.register_rlib()
cli:add_commands{
{
names={'help','h'},
arghelp='[cmd]|[-v]',
args=argparser.create{v=false},
help='help on [cmd] or all commands',
help_detail=[[
help -v gives full help on all commands, otherwise as summary is printed
]],
func=function(self,args)
cmd = args[1]
if cmd and cli.names[cmd] then
return true, cli.names[cmd]:get_help_detail()
end
if cmd then
return false, string.format("unknown command '%s'\n",cmd)
end
msg = ""
for i,c in ipairs(cli.cmds) do
if args.v then
msg = msg .. c:get_help_detail()
else
msg = msg .. c:get_help()
end
end
return true, msg
end,
},
{
names={'#'},
help='comment',
func=function(self,args)
return true
end,
},
{
names={'exec','!'},
help='execute local lua',
arghelp='<lua code>',
help_detail=[[
Execute lua in chdkptp.
The global variable con accesses the current CLI connection.
Return values are printed in the console.
]],
func=function(self,args)
local f,r = loadstring(args)
if not f then
return false, string.format("compile failed:%s\n",r)
end
r={xpcall(f,errutil.format)} -- TODO would be nice to be able to force backtrace or not per call
if not r[1] then
return false, string.format("call failed:%s\n",r[2])
end
local s
local sopts={pretty=true,err_type=false,err_cycle=false,forceint=false,fix_bignum=false}
if #r > 1 then
s='=' .. serialize(r[2],sopts)
for i = 3, #r do
s = s .. ',' .. serialize(r[i],sopts)
end
end
return true, s
end,
},
{
names={'set'},
help='show or set option',
arghelp='[-v|-c] [option[=value]]',
args=argparser.create{
v=false,
c=false,
},
help_detail=[[
Use set with no options to see a list
-v show desciption when showing value
-c output as set command
]],
func=function(self,args)
local mode
if args.v then
mode='full'
end
if args.c then
mode='cmd'
end
if #args == 0 then
local r={}
for name,pref in prefs._each() do
local status, desc = prefs._describe(name,mode)
-- desc will be error if we somehow get invalid in here
table.insert(r,desc)
end
return true,table.concat(r,'\n')
end
if #args > 1 then
return false, 'unexpected args'
end
local name,value = string.match(args[1],'^([%a_][%w%a_]+)=(.*)$')
if not name then
return prefs._describe(args[1],mode)
end
return prefs._set(name,value)
end,
},
{
names={'quit','q'},
help='quit program',
func=function()
cli.finished = true
return true
end,
},
{
names={'source'},
help='execute cli commands from file',
arghelp='<file>',
args=argparser.create{ },
func=function(self,args)
return cli:execfile(args[1])
end,
},
{
names={'lua','.'},
help='execute remote lua',
arghelp='<lua code>',
help_detail=[[
Execute Lua code on the camera.
Returns immediately after the script is started.
Return values or error messages can be retrieved with getm after the script is completed.
]],
func=function(self,args)
con:exec(args)
return true
end,
},
{
names={'getm'},
help='get messages',
func=function(self,args)
local msgs=''
local msg,err
while true do
msg=con:read_msg()
if msg.type == 'none' then
return true,msgs
end
msgs = msgs .. chdku.format_script_msg(msg) .. "\n"
end
end,
},
{
names={'putm'},
help='send message',
arghelp='<msg string>',
func=function(self,args)
con:write_msg(args)
return true
end,
},
{
names={'luar','='},
help='execute remote lua, wait for result',
arghelp='<lua code>',
help_detail=[[
Execute Lua code on the camera, waiting for the script to end.
Return values or error messages are printed after the script completes.
]],
func=function(self,args)
local rets={}
local msgs={}
con:execwait(args,{rets=rets,msgs=msgs})
local r=''
for i=1,#msgs do
r=r .. chdku.format_script_msg(msgs[i]) .. '\n'
end
for i=1,table.maxn(rets) do
r=r .. chdku.format_script_msg(rets[i]) .. '\n'
end
return true,r
end,
},
{
names={'killscript'},
help='kill running remote script',
args=argparser.create{
noflush=false,
force=false,
},
arghelp='[-noflush][-force][-nowait]',
help_detail=[[
Terminate any running script on the camera
-noflush: don't discard script messages
-force: force kill even if camera does not support (crash / memory leaks likely!)
]],
func=function(self,args)
if not con:is_ver_compatible(2,6) then
if not args.force then
return false,'camera does not support clean kill, use -force if you are sure'
end
warnf("camera does not support clean kill, crashes likely\n")
end
-- execute an empty script with kill options set
-- wait ensures it will be all done
local flushmsgs = not args.noflush;
con:exec("",{
flush_cam_msgs=flushmsgs,
flush_host_msgs=flushmsgs,
clobber=true})
-- use standalone wait_status because we don't want execwait message handling
con:wait_status{run=false}
return true
end,
},
{
names={'rmem'},
help='read memory',
args=argparser.create{i32=false}, -- word
arghelp='<address> [count] [-i32[=fmt]]',
help_detail=[[
Dump <count> bytes or words starting at <address>
-i32 display as 32 bit words rather than byte oriented hex dump
-i32=<fmt> use printf format string fmt to display
]],
func=function(self,args)
local addr = tonumber(args[1])
local count = tonumber(args[2])
if not addr then
return false, "bad args"
end
if not count then
count = 1
end
if args.i32 then
count = count * 4
end
local r = con:getmem(addr,count)
if args.i32 then
local fmt
if type(args.i32) == 'string' then
fmt = args.i32
end
r=util.hexdump_words(r,addr,fmt)
else
r=util.hexdump(r,addr)
end
return true, string.format("0x%08x %u\n",addr,count)..r
end,
},
{
names={'list'},
help='list USB devices',
help_detail=[[
Lists all recognized PTP devices in the following format on success
<status><num>:<modelname> b=<bus> d=<device> v=<usb vendor> p=<usb pid> s=<serial number>
or on error
<status><num> b=<bus> d=<device> ERROR: <error message>
status values
* connected, current target for CLI commands (con global variable)
+ connected, not CLI target
- not connected
! error querying status
serial numbers are not available from all models, nil will be shown if not available
]],
func=function()
local msg = ''
-- TODO usb only, will not show connected PTP/IP
local devs = chdk.list_usb_devices()
for i,desc in ipairs(devs) do
local status,con_status,str = pcall(cli.list_dev_single,desc)
if status then
msg = msg .. string.format("%s%d:%s\n",con_status,i,str)
else
-- use the requested dev/bus here, since the lcon data may not be set
msg = msg .. string.format('!%d: b=%s d=%s ERROR: %s\n',i,desc.bus, desc.dev,tostring(con_status))
end
end
return true,msg
end,
},
{
names={'upload','u'},
help='upload a file to the camera',
arghelp="[-nolua] <local> [remote]",
args=argparser.create{nolua=false},
help_detail=[[
<local> file to upload
[remote] destination
If not specified, file is uploaded to A/
If remote is a directory or ends in / uploaded to remote/<local file name>
-nolua skip lua based checks on remote
Allows upload while running script
Prevents detecting if remote is a directory
Some cameras have problems with paths > 32 characters
Dryos cameras do not handle non 8.3 filenames well
]],
func=function(self,args)
local src = args[1]
if not src then
return false, "missing source"
end
if lfs.attributes(src,'mode') ~= 'file' then
return false, 'src is not a file: '..src
end
local dst_dir
local dst = args[2]
-- no dst, use filename of source
if dst then
dst = fsutil.make_camera_path(dst)
if string.find(dst,'[\\/]$') then
-- trailing slash, append filename of source
dst = string.sub(dst,1,-2)
if not args.nolua then
local st,err = con:stat(dst)
if not st then
return false, 'stat dest '..dst..' failed: ' .. err
end
if not st.is_dir then
return false, 'not a directory: '..dst
end
end
dst = fsutil.joinpath(dst,fsutil.basename(src))
else
if not args.nolua then
local st = con:stat(dst)
if st and st.is_dir then
dst = fsutil.joinpath(dst,fsutil.basename(src))
end
end
end
else
dst = fsutil.make_camera_path(fsutil.basename(src))
end
local msg=string.format("%s->%s\n",src,dst)
con:upload(src,dst)
return true, msg
end,
},
{
names={'download','d'},
help='download a file from the camera',
arghelp="[-nolua] <remote> [local]",
args=argparser.create{nolua=false},
help_detail=[[
<remote> file to download
A/ is prepended if not present
[local] destination
If not specified, the file will be downloaded to the current directory
If a directory, the file will be downloaded into it
-nolua skip lua based checks on remote
Allows download while running script
]],
func=function(self,args)
local src = args[1]
if not src then
return false, "missing source"
end
local dst = args[2]
if not dst then
-- no dest, use final component of source path
dst = fsutil.basename(src)
-- if target is a directory or has explicit trailing / download into it
elseif lfs.attributes(dst,'mode') == 'directory' or fsutil.is_dir_sep(string.sub(dst,-1,-1)) then
dst = fsutil.joinpath(dst,fsutil.basename(src))
end
-- ensure target dir exists
fsutil.mkdir_parent(dst)
src = fsutil.make_camera_path(src)
if not args.nolua then
local src_st,err = con:stat(src)
if not src_st then
return false, 'stat source '..src..' failed: ' .. err
end
if not src_st.is_file then
return false, src..' is not a file'
end
end
local msg=string.format("%s->%s\n",src,dst)
con:download(src,dst)
return true, msg
end,
},
{
names={'imdl'},
help='download images from the camera',
arghelp="[options] [src ...]",
args=argparser.create{
d='${subdir}/${name}',
ddir=false,
last=false,
imin=false,
imax=false,
dmin=false,
dmax=false,
fmatch='%a%a%a_%d%d%d%d%.%w%w%w',
rmatch=false,
maxdepth=2, -- dcim/subdir
pretend=false,
nomtime=false,
batchsize=20,
dbgmem=false,
overwrite='ask',
quiet=false,
rm=false,
},
help_detail=[[
[src] source directories, default A/DCIM.
Specifying directories which do not follow normal image directory naming will
limit available substitution patterns.
options:
-d=<dest spec> destination spec, using substitutions described below
default ${subdir}/${name} which mirrors the DCIM image
subdirectories into current working directory or ddir
-ddir=<path> directory path to prepend to dest, default none
-last=n download last N images based on file counter
-imin=n download images number n or greater
-imax=n download images number n or less
-dmin=n download images from directory number n or greater
-dmax=n download images from directory number n or less
-fmatch=<pattern> download only file with path/name matching <pattern>
-rmatch=<pattern> only recurse into directories with path/name matching <pattern>
-maxdepth=n only recurse into N levels of directory, default 2
-pretend print actions instead of doing them
-nomtime don't preserve modification time of remote files
-batchsize=n lower = slower, less memory used
-dbgmem print memory usage info
-overwrite=<str> overwrite existing files (y|n|old|ask), default ask
-quiet don't display actions
-rm delete files after downloading
note <pattern> is a lua pattern, not a filesystem glob like *.JPG
Substitutions
${serial,strfmt} camera serial number, or empty if not available, default format %s
${pid,strfmt} camera platform ID, default format %x
${ldate,datefmt} PC clock date, os.date format, default %Y%m%d_%H%M%S
${lts,strfmt} PC clock date as unix timestamp + microseconds, default format %f
${lms,strfmt} PC clock milliseconds part, default format %03d
${mdate,datefmt} Camera file modified date, converted to PC time, os.date format, default %Y%m%d_%H%M%S
${mts,strfmt} Camera file modified date, as unix timestamp converted to PC time, default format %d
${name} Image full name, like IMG_1234.JPG
${basename} Image name without extension, like IMG_1234
${ext} Image extension, like .JPG
${subdir} Image DCIM subdirectory, like 100CANON or 100___01 or 100_0101
${imgnum} Image number like 1234
${dirnum} Image directory number like 101
${dirmonth} Image DCIM subdirectory month, like 01, date folder naming cameras only
${dirday} Image DCIM subdirectory day, like 01, date folder naming cameras only
Unavailable values (e.g. ${dirday} without daily folders) result in an empty string
PC clock times are set to the start of download, not per image
]],
func=function(self,args)
-- some names need translating
local opts={
dst=args.d,
dstdir=args.ddir,
lastimg=args.last,
imgnum_min=args.imin,
imgnum_max=args.imax,
dirnum_min=args.dmin,
dirnum_max=args.dmax,
fmatch=args.fmatch,
rmatch=args.rmatch,
maxdepth=tonumber(args.maxdepth),
pretend=args.pretend,
mtime=not args.nomtime,
batchsize=tonumber(args.batchsize),
dbgmem=args.dbgmem,
verbose=not args.quiet,
overwrite=cli.get_download_overwrite_opt(args.overwrite),
}
if #args > 0 then
opts.start_paths={}
for i,v in ipairs(args) do
opts.start_paths[i]=fsutil.make_camera_path(v)
end
end
local files=con:imglist(opts)
con:imglist_download(files,opts)
if args.rm then
con:imglist_delete(files,opts)
end
return true
end,
},
{
names={'imrm'},
help='delete images from the camera',
arghelp="[options] [path ...]",
args=argparser.create{
last=false,
imin=false,
imax=false,
dmin=false,
dmax=false,
fmatch='%a%a%a_%d%d%d%d%.%w%w%w',
rmatch=false,
maxdepth=2, -- dcim/subdir
pretend=false,
batchsize=20,
dbgmem=false,
quiet=false,
},
help_detail=[[
[path] directories to delete from, default A/DCIM.
options:
-last=n delete last N images based on file counter
-imin=n delete images number n or greater
-imax=n delete images number n or less
-dmin=n delete images from directory number n or greater
-dmax=n delete images from directory number n or less
-fmatch=<pattern> delete only file with path/name matching <pattern>
-rmatch=<pattern> only recurse into directories with path/name matching <pattern>
-maxdepth=n only recurse into N levels of directory, default 2
-pretend print actions instead of doing them
-batchsize=n lower = slower, less memory used
-dbgmem print memory usage info
-quiet don't display actions
note <pattern> is a lua pattern, not a filesystem glob like *.JPG
file selection options are equivalent to imdl
]],
func=function(self,args)
-- some names need translating
local opts={
lastimg=args.last,
imgnum_min=args.imin,
imgnum_max=args.imax,
dirnum_min=args.dmin,
dirnum_max=args.dmax,
fmatch=args.fmatch,
rmatch=args.rmatch,
maxdepth=tonumber(args.maxdepth),
pretend=args.pretend,
mtime=not args.nomtime,
batchsize=tonumber(args.batchsize),
dbgmem=args.dbgmem,
verbose=not args.quiet
}
if #args > 0 then
opts.start_paths={}
for i,v in ipairs(args) do
opts.start_paths[i]=fsutil.make_camera_path(v)
end
end
local files=con:imglist(opts)
con:imglist_delete(files,opts)
return true
end,
},
{
names={'imls'},
help='list images on the camera',
arghelp="[options] [path ...]",
args=argparser.create{
last=false,
imin=false,
imax=false,
dmin=false,
dmax=false,
fmatch='%a%a%a_%d%d%d%d%.%w%w%w',
rmatch=false,
maxdepth=2, -- dcim/subdir
sort='path',
r=false,
batchsize=20,
dbgmem=false,
quiet=false,
},
help_detail=[[
[path] directories to list from, default A/DCIM.
options:
-last=n list last N images based on file counter
-imin=n list images number n or greater
-imax=n list images number n or less
-dmin=n list images from directory number n or greater
-dmax=n list images from directory number n or less
-fmatch=<pattern> list only files with path/name matching <pattern>
-rmatch=<pattern> only recurse into directories with path/name matching <pattern>
-maxdepth=n only recurse into N levels of directory, default 2
-sort=order where order is one of 'path','name','date','size' default 'path'
-r sort descending instead of ascending
-batchsize=n lower = slower, less memory used
-dbgmem print memory usage info
-quiet don't display actions
note <pattern> is a lua pattern, not a filesystem glob like *.JPG
file selection options are equivalent to imdl
]],
func=function(self,args)
-- some names need translating
local opts={
lastimg=args.last,
imgnum_min=args.imin,
imgnum_max=args.imax,
dirnum_min=args.dmin,
dirnum_max=args.dmax,
fmatch=args.fmatch,
rmatch=args.rmatch,
maxdepth=tonumber(args.maxdepth),
pretend=args.pretend,
mtime=not args.nomtime,
batchsize=tonumber(args.batchsize),
dbgmem=args.dbgmem,
verbose=not args.quiet
}
local sortopts={
path={'full'},
name={'name'},
date={'st','mtime'},
size={'st','size'},
}
local sortpath = sortopts[args.sort]
if not sortpath then
return false,'invalid sort '..tostring(args.sort)
end
if #args > 0 then
opts.start_paths={}
for i,v in ipairs(args) do
opts.start_paths[i]=fsutil.make_camera_path(v)
end
end
local files=con:imglist(opts)
if args.r then
util.table_path_sort(files,sortpath,'des')
else
util.table_path_sort(files,sortpath,'asc')
end
local r=''
for i,finfo in ipairs(files) do
local size = finfo.st.size
r = r .. string.format("%s %10s %s\n",
os.date('%c',chdku.ts_cam2pc(finfo.st.mtime)),
tostring(finfo.st.size),
finfo.full)
end
return true, r
end,
},
{
names={'mdownload','mdl'},
help='download file/directories from the camera',
arghelp="[options] <remote, remote, ...> <target dir>",
args=argparser.create{
fmatch=false,
dmatch=false,
rmatch=false,
nodirs=false,
maxdepth=100,
pretend=false,
nomtime=false,
batchsize=20,
dbgmem=false,
overwrite='ask',
},
help_detail=[[
<remote...> files/directories to download
<target dir> directory to download into
options:
-fmatch=<pattern> download only file with path/name matching <pattern>
-dmatch=<pattern> only create directories with path/name matching <pattern>
-rmatch=<pattern> only recurse into directories with path/name matching <pattern>
-nodirs only create directories needed to download file
-maxdepth=n only recurse into N levels of directory
-pretend print actions instead of doing them
-nomtime don't preserve modification time of remote files
-batchsize=n lower = slower, less memory used
-dbgmem print memory usage info
-overwrite=<str> overwrite existing files (y|n|old|ask), default ask
note <pattern> is a lua pattern, not a filesystem glob like *.JPG
]],
func=function(self,args)
if #args < 2 then
return false,'expected source(s) and destination'
end
local dst=table.remove(args)
local srcs={}
for i,v in ipairs(args) do
srcs[i]=fsutil.make_camera_path(v)
end
-- TODO some of these need translating, so can't pass direct
local opts={
fmatch=args.fmatch,
dmatch=args.dmatch,
rmatch=args.rmatch,
dirs=not args.nodirs,
maxdepth=tonumber(args.maxdepth),
pretend=args.pretend,
mtime=not args.nomtime,
batchsize=tonumber(args.batchsize),
dbgmem=args.dbgmem,
overwrite=cli.get_download_overwrite_opt(args.overwrite),
}
con:mdownload(srcs,dst,opts)
return true
end,
},
{
names={'mupload','mup'},
help='upload file/directories to the camera',
arghelp="[options] <local, local, ...> <target dir>",
args=argparser.create{
fmatch=false,
dmatch=false,
rmatch=false,
nodirs=false,
maxdepth=100,
pretend=false,
nomtime=false,
},
help_detail=[[
<local...> files/directories to upload
<target dir> directory to upload into
options:
-fmatch=<pattern> upload only file with path/name matching <pattern>
-dmatch=<pattern> only create directories with path/name matching <pattern>
-rmatch=<pattern> only recurse into directories with path/name matching <pattern>
-nodirs only create directories needed to upload file
-maxdepth=n only recurse into N levels of directory
-pretend print actions instead of doing them
-nomtime don't preserve local modification time
note <pattern> is a lua pattern, not a filesystem glob like *.JPG
]],
func=function(self,args)
if #args < 2 then
return false,'expected source(s) and destination'
end
local dst=fsutil.make_camera_path(table.remove(args))
local srcs={}
-- args has other stuff in it, copy array parts
srcs={unpack(args)}
-- TODO some of these need translating, so can't pass direct
local opts={
fmatch=args.fmatch,
dmatch=args.dmatch,
rmatch=args.rmatch,
dirs=not args.nodirs,
maxdepth=tonumber(args.maxdepth),
pretend=args.pretend,
mtime=not args.nomtime,
}
con:mupload(srcs,dst,opts)
return true
end,
},
{
names={'delete','rm'},
help='delete file/directories from the camera',
arghelp="[options] <target, target,...>",
args=argparser.create{
fmatch=false,
dmatch=false,
rmatch=false,
nodirs=false,
maxdepth=100,
pretend=false,
ignore_errors=false,
skip_topdirs=false,
},
help_detail=[[
<target...> files/directories to remote
options:
-fmatch=<pattern> upload only file with names matching <pattern>
-dmatch=<pattern> only delete directories with names matching <pattern>
-rmatch=<pattern> only recurse into directories with names matching <pattern>
-nodirs don't delete drictories recursed into, only files
-maxdepth=n only recurse into N levels of directory
-pretend print actions instead of doing them
-ignore_errors don't abort if delete fails, continue to next item
-skip_topdirs don't delete directories given in command line, only contents
note <pattern> is a lua pattern, not a filesystem glob like *.JPG
]],
func=function(self,args)
if #args < 1 then
return false,'expected at least one target'
end
-- args has other stuff in it, copy array parts
local tgts={}
for i,v in ipairs(args) do
tgts[i]=fsutil.make_camera_path(v)
end
-- TODO some of these need translating, so can't pass direct
local opts={
fmatch=args.fmatch,
dmatch=args.dmatch,
rmatch=args.rmatch,
dirs=not args.nodirs,
maxdepth=tonumber(args.maxdepth),
pretend=args.pretend,
ignore_errors=args.ignore_errors,
skip_topdirs=args.skip_topdirs,
}
-- TODO use msg_handler to print as they are deleted instead of all at the end
local results = con:mdelete(tgts,opts)
for i,v in ipairs(results) do
-- TODO success should not be displayed at low verbosity
printf("%s: ",v.file)
if v.status then
printf('OK')
else
printf('FAILED')
end
if v.msg then
printf(": %s",v.msg)
end
printf('\n')
end
return true
end,
},
{
names={'mkdir'},
help='create directories on camera',
arghelp="<directory>",
args=argparser.create{ },
help_detail=[[
<directory> directory to create. Intermediate directories will be created as needed
]],
func=function(self,args)
if #args ~= 1 then
return false,'expected exactly one arg'
end
return con:mkdir_m(fsutil.make_camera_path(args[1]))
end
},
{
names={'version','ver'},
help='print API and program versions',
args=argparser.create{
p=false,
l=false,
},
arghelp="[-p][-l]",
help_detail=[[
-p print program version
-l print library versions
]],
func=function(self,args)
local host_ver = string.format("host:%d.%d cam:",chdku.apiver.MAJOR,chdku.apiver.MINOR)
local status = true
local r
if con:is_connected() then
-- TODO could just use con cached versions
local cam_major, cam_minor = con:camera_api_version()
if cam_major then
r = host_ver .. string.format("%d.%d",cam_major,cam_minor)
else
status = false
r = host_ver .. string.format("error %s",cam_minor)
end
else
r = host_ver .. "not connected"
end
if args.p then
r = string.format('chdkptp %d.%d.%d-%s built %s %s\n%s',
chdku.ver.MAJOR,chdku.ver.MINOR,chdku.ver.BUILD,chdku.ver.DESC,
chdku.ver.DATE,chdku.ver.TIME,r)
end
if args.l then
r = r .. '\n'.._VERSION -- Lua version
-- note these will only show up if actually running gui
if iup then
r = r .. '\nIUP '..iup._VERSION
end
if cd then
r = r .. '\nCD '..cd._VERSION
end
end
return status,r
end,
},
{
names={'connect','c'},
help='connect to device',
arghelp="[-nodis] [USB dev spec] | -h=host [-p=port]",
args=argparser.create{
b=false,
d=false,
p=false,
s=false,
h=false,
nodis=false,
nopat=false,
},
help_detail=[[
If no options are given, connects to the first available USB device.
USB dev spec:
-b=<bus>
-d=<dev>
-p=<pid>
-s=<serial>
model
<pid> is the USB product ID, as a decimal or hexadecimal number.
All other values are treated as a Lua pattern, unless -nopat is given.
If the serial or model are specified, a temporary connection will be made to each device
If <model> includes spaces, it must be quoted.
If multiple devices match, the first matching device will be connected.
other options:
-nodis do not close current connection
-nopat use plain substring matches instead of patterns
]],
func=function(self,args)
local match = {}
local opt_map = {
b='bus',
d='dev',
p='product_id',
s='serial_number',
[1]='model',
}
for k,v in pairs(opt_map) do
-- TODO matches expect nil
if type(args[k]) == 'string' then
match[v] = args[k]
end
-- printf('%s=%s\n',v,tostring(args[k]))
end
match.plain = args.nopat
if not args.nodis and con:is_connected() then
con:disconnect()
end
-- ptp/ip ignore other options
-- TODO should warn
local lcon
if args.h then
if not args.p then
args.p = nil
end
lcon = chdku.connection({host=args.h,port=args.p})
else
if match.product_id and not tonumber(match.product_id) then
return false,"expected number for product id"
end
local devices = chdk.list_usb_devices()
for i, devinfo in ipairs(devices) do
lcon = nil
if chdku.match_device(devinfo,match) then
lcon = chdku.connection(devinfo)
-- if we are looking for model or serial, need to connect to the dev to check
if match.model or match.serial_number then
local tempcon = false
cli.dbgmsg('model check %s %s\n',tostring(match.model),tostring(match.serial_number))
if not lcon:is_connected() then
lcon:connect()
tempcon = true
else
lcon:update_connection_info()
end
if not lcon:match_ptp_info(match) then
if tempcon then
lcon:disconnect()
end
lcon = nil
end
end
if lcon then
break
end
end
end
end
local status, err
if lcon then
con = lcon
if not con:is_connected() then
con:connect()
end
if con:is_connected() then
cli.infomsg('connected: %s, max packet size %d\n',con.ptpdev.model,con.ptpdev.max_packet_size)
-- TODO should have a min API version check
if con.apiver.MAJOR < 0 then
util.warnf('CHDK extension not detected\n')
end
status = true
end
else
status = false
err = "no matching devices found"
end
cli:connection_status_change()
return status,err
end,
},
{
names={'reconnect','r'},
help='reconnect to current device',
-- NOTE camera may connect to a different device,
-- will detect and fail if serial, model or pid don't match
func=function(self,args)
con:reconnect()
cli:connection_status_change()
return true
end,
},
{
names={'disconnect','dis'},
help='disconnect from device',
func=function(self,args)
con:disconnect()
cli:connection_status_change()
return true
end,
},
{
names={'ls'},
help='list files/directories on camera',
args=argparser.create{l=false},
arghelp="[-l] [path]",
func=function(self,args)
local listops
local path=args[1]
path = fsutil.make_camera_path(path)
if args.l then
listopts = { stat='*' }
else
listopts = { stat='/' }
end
listopts.dirsonly=false
local list = con:listdir(path,listopts)
local r = ''
if args.l then
-- alphabetic sort TODO sorting/grouping options
chdku.sortdir_stat(list)
for i,st in ipairs(list) do
local name = st.name
local size = st.size
if st.is_dir then
name = name..'/'
size = '<dir>'
else
end
r = r .. string.format("%s %10s %s\n",os.date('%c',chdku.ts_cam2pc(st.mtime)),tostring(size),name)
end
else
table.sort(list)
for i,name in ipairs(list) do
r = r .. name .. '\n'
end
end
return true,r
end,
},
{
names={'reboot'},
help='reboot the camera',
arghelp="[options] [file]",
args=argparser.create({
wait=3500,
norecon=false,
}),
help_detail=[[
file: Optional file to boot.
Must be an unencoded binary or for DryOS only, an encoded .FI2
Format is assumed based on extension
If not set, firmware boots normally, loading diskboot.bin if configured
options:
-norecon don't try to reconnect
-wait=<N> wait N ms before attempting to reconnect, default 3500
]],
func=function(self,args)
local bootfile=args[1]
if bootfile then
bootfile = fsutil.make_camera_path(bootfile)
bootfile = string.format("'%s'",bootfile)
else
bootfile = ''
end
-- sleep and disconnect to avoid later connection problems on some cameras
-- clobber because we don't care about memory leaks
con:exec('sleep(1000);reboot('..bootfile..')',{clobber=true})
if args.norecon then
return true
end
con:reconnect({wait=args.wait})
return true
end,
},
{
names={'lvdump','dumpframes'},
help='dump camera display frames to file',
arghelp="[options] [file]",
args=argparser.create({
count=5,
wait=100,
novp=false,
nobm=false,
nopal=false,
quiet=false,
pbm=false,
}),
help_detail=[[
file:
optional output file name, defaults to chdk_<pid>_<date>_<time>.lvdump
options:
-count=<N> number of frames to dump
-wait=<N> wait N ms between frames
-novp don't get viewfinder data
-nobm don't get ui overlay data
-nopal don't get palette for ui overlay
-quiet don't print progress
]],
func=function(self,args)
local dumpfile=args[1]
local what = 0
if not args.novp then
what = 1
end
if not args.nobm then
what = what + 4
if not args.nopal then
what = what + 8
end
end
if what == 0 then
return false,'nothing selected'
end
if args.wait then
args.wait = tonumber(args.wait)
end
if args.count then
args.count = tonumber(args.count)
end
local status,err
if not con:live_is_api_compatible() then
return false,'incompatible api'
end
status, err = con:live_dump_start(dumpfile)
if not status then
return false,err
end
for i=1,args.count do
if not args.quiet then
printf('grabbing frame %d\n',i)
end
status, err = con:live_get_frame(what)
if not status then
break
end
status, err = con:live_dump_frame()
if not status then
break
end
if args.wait and i < args.count then
sys.sleep(args.wait)
end
end
con:live_dump_end()
if status then
err = string.format('%d bytes recorded to %s\n',tonumber(con.live.dump_size),tostring(con.live.dump_fn))
end
return status,err
end,
},
{
names={'lvdumpimg'},
help='dump camera display frames to netpbm images',
arghelp="[options]",
args=argparser.create({
-- infile=false,
count=1,
wait=false,
fps=10,
vp=false,
bm=false,
pipevp=false,
pipebm=false,
nopal=false,
quiet=false,
nosubst=false,
}),
-- TODO
-- -infile=<file> lvdump file to use as source instead of camera
help_detail=[[
options:
-count=<N> number of frames to dump, default 1
-wait=<N> wait N ms between frames
-fps=<N> specify wait as a frame rate, default 10
-vp[=dest] get viewfinder in ppm format
-bm[=dest] get ui overlay in pam format
-pipevp[=oneproc]
-pipebm[=oneproc]
treat vp or bm 'dest' as a command to pipe to. With =oneproc a single process
receives all frames. Otherwise, a new process is spawned for each frame
-nopal don't get palette for ui overlay
-quiet don't print progress
-nosubst don't do pattern substitution on file names
vp and bm 'dest' may include substitution patterns
${date,datefmt} current time formatted with os.date()
${frame,strfmt} current frame number formatted with string.format
${time,strfmt} current time in seconds, as float, formatted with string.format
default vp_${time,%014.3f}.ppm bm_${time,%014.3f}.pam for viewfinder and ui respectively
if piping with oneproc, time will be the start of the first frame and frame will be 1
]],
func=function(self,args)
local what = 0
if args.vp then
what = 1
end
if args.bm then
what = what + 4
if not args.nopal then
what = what + 8
end
end
if what == 0 then
return false,'nothing selected'
end
if args.wait then
args.wait = tonumber(args.wait)
end
if args.fps then
if args.wait then
return false,'specify wait or fps, not both'
end
args.wait = 1000/tonumber(args.fps)
end
if args.count then
args.count = tonumber(args.count)
end
if not con:is_connected() then
return false,'not connected'
end
local status,err
if not con:live_is_api_compatible() then
return false,'incompatible api'
end
-- state for substitutions
local subst=varsubst.new({
frame=varsubst.format_state_val('frame','%06d'),
time=varsubst.format_state_val('time','%d'),
date=varsubst.format_state_date('date','%Y%m%d_%H%M%S'),
})
local vp_opts = cli.init_lvdumpimg_file_opts('vp',args,subst)
local bm_opts = cli.init_lvdumpimg_file_opts('bm',args,subst)
local t0=ustime.new()
local t_frame_start=ustime.new()
-- TODO frame source should be split out to allow dumping from existing lvdump file
for i=1,args.count do
t_frame_start:get()
-- TODO should use wrapped frame, maybe con:live_get_frame
frame = con:get_live_data(frame,what)
subst.state.frame = i
-- set time state once per frame to avoid varying between viewport and bitmap
subst.state.date = os.time()
subst.state.time = ustime.new():float()
if args.vp then
vp_opts.write(frame)
end
if args.bm then
bm_opts.write(frame)
end
if args.wait and i < args.count and t_frame_start:diffms() < args.wait then
sys.sleep(args.wait - t_frame_start:diffms())
end
end
-- if using oneproc pipe, need to close
if vp_opts.filehandle then
vp_opts.filehandle:close()
end
if bm_opts.filehandle then
bm_opts.filehandle:close()
end
if subst.state.frame and not args.quiet then
local t_total = t0:diffms()/1000
-- fudge to handle the final sleep being skipped
if args.wait and t_frame_start:diffms() < args.wait then
t_total = t_total + (args.wait - t_frame_start:diffms())/1000
end
cli.dbgmsg('frames:%d time:%f fps:%f\n',subst.state.frame,t_total,subst.state.frame/t_total)
end
return true
end,
},
{
names={'shoot'},
help='shoot a picture with specified exposure',
arghelp="[options]",
args=argparser.create({
u='s',
tv=false,
sv=false,
svm=false,
av=false,
isomode=false,
nd=false,
sd=false,
raw=false,
dng=false,
pretend=false,
nowait=false,
dl=false,
rm=false,
}),
-- TODO allow setting destinations and filetypes for -dl
help_detail=[[
options:
-u=<s|a|96>
s standard units (default)
a APEX
96 APEX*96
-tv=<v> shutter speed. In standard units both decimal and X/Y accepted
-sv=<v> ISO value, Canon "real" ISO
-svm=<v> ISO value, Canon "Market" ISO (requires CHDK 1.3)
-av=<v> Aperture value. In standard units, f number
-isomode=<v> ISO mode, must be ISO value in Canon UI, shooting mode must have manual ISO
-nd=<in|out> set ND filter state
-sd=<v>[units] subject distance, units one of m, mm, in, ft default m
-raw[=1|0] Force raw on or off, defaults to current camera setting
-dng[=1|0] Force DNG on or off, implies raw if on, default current camera setting
-pretend print actions instead of running them
-nowait don't wait for shot to complete
-dl download shot file(s)
-rm remove file after shooting
Any exposure parameters not set use camera defaults
]],
func=function(self,args)
local opts,err = cli:get_shoot_common_opts(args)
if not opts then
return false,err
end
-- allow -dng
if args.dng == true then
args.dng = 1
end
if args.dng then
opts.dng = tonumber(args.dng)
if opts.dng == 1 then
-- force raw on if dng. TODO complain if raw/dng mismatch?
args.raw = 1
end
end
-- allow -raw to turn raw on
if args.raw == true then
args.raw=1
end
if args.raw then
opts.raw=tonumber(args.raw)
end
if args.rm or args.dl then
if args.nowait then
return false, "can't download or remove with nowait"
end
opts.info=true
end
local cmd=string.format('rlib_shoot(%s)',util.serialize(opts))
if args.pretend then
return true,cmd
end
if args.nowait then
con:exec(cmd,{libs={'rlib_shoot'}})
return
end
local rstatus,rerr = con:execwait('return '..cmd,{libs={'serialize_msgs','rlib_shoot'}})
if not rstatus then
return false, rerr
end
if not (args.dl or args.rm) then
return true
end
local info = rstatus
local jpg_path = string.format('%s/IMG_%04d.JPG',info.dir,info.exp)
local raw_path
if info.raw then
-- TODO
-- get_config_value only returns indexes
-- chdk versions might change these
local pfx_list = {[0]="IMG", "CRW", "SND"}
local ext_list = {[0]="JPG", "CRW", "CR2", "THM", "WAV"}
local raw_dir
local raw_ext
local raw_pfx
if info.raw_in_dir then
raw_dir = info.dir
else
raw_dir = 'A/DCIM/100CANON'
end
if info.dng and info.use_dng_ext then
raw_ext = 'DNG'
else
raw_ext = ext_list[info.raw_ext]
if not raw_ext then
raw_ext = 'RAW'
end
end
raw_pfx = pfx_list[info.raw_pfx]
if not raw_pfx then
raw_pfx = 'RAW_'
end
raw_path = string.format('%s/%s_%04d.%s',raw_dir,raw_pfx,info.exp,raw_ext)
end
-- TODO some delay may be required between shot and dl start
if args.dl then
cli:print_status(cli:execute('download '..jpg_path))
if raw_path then
cli:print_status(cli:execute('download '..raw_path))
end
end
if args.rm then
cli:print_status(cli:execute('rm -maxdepth=0 '..jpg_path))
if raw_path then
cli:print_status(cli:execute('rm -maxdepth=0 '..raw_path))
end
end
return true
end,
},
-- TODO this should be combined with the shoot command,
-- or at least make the syntax / options consistent
{
names={'remoteshoot','rs'},
help='shoot and download without saving to SD (requires CHDK 1.2)',
arghelp="[local] [options]",
args=argparser.create{
u='s',
tv=false,
sv=false,
svm=false,
av=false,
isomode=false,
nd=false,
sd=false,
jpg=false,
raw=false,
dng=false,
dnghdr=false,
s=false,
c=false,
cont=false,
quick=false,
shots=false,
int=false,
badpix=false,
},
help_detail=[[
[local] local destination directory or filename (w/o extension!)
options:
-u=<s|a|96>
s standard units (default)
a APEX
96 APEX*96
-tv=<v> shutter speed. In standard units both decimal and X/Y accepted
-sv=<v> ISO value, Canon "real" ISO
-svm=<v> ISO value, Canon "Market" ISO (requires CHDK 1.3)
-av=<v> Aperture value. In standard units, f number
-isomode=<v> ISO mode, must be ISO value in Canon UI, shooting mode must have manual ISO
-nd=<in|out> set ND filter state
-sd=<v>[units] subject distance, units one of m, mm, in, ft default m
-jpg jpeg, default if no other options (not supported on all cams)
-raw framebuffer dump raw
-dng DNG format raw
-dnghdr save DNG header to a separate file, ignored with -dng
-s=<start> first line of for subimage raw
-c=<count> number of lines for subimage
-cont[=n] shoot in continuous mode, optionally specifying number of shots
-quick[=n] shoot by holding halfshoot and repeatedly clicking full
-shots=<n> shoot n shots
-int=<n.m> interval for multiple shots, in seconds
-badpix[=n] interpolate over pixels with value <= n, default 0, (dng only)
]],
func=function(self,args)
local dst = args[1]
local dst_dir
if dst then
if string.match(dst,'[\\/]+$') then
-- explicit / treat it as a directory
-- and check if it is
dst_dir = string.sub(dst,1,-2)
if lfs.attributes(dst_dir,'mode') ~= 'directory' then
cli.dbgmsg('mkdir %s\n',dst_dir)
fsutil.mkdir_m(dst_dir)
end
dst = nil
elseif lfs.attributes(dst,'mode') == 'directory' then
dst_dir = dst
dst = nil
end
end
local opts,err = cli:get_shoot_common_opts(args)
if not opts then
return false,err
end
util.extend_table(opts,{
fformat=0,
lstart=0,
lcount=0,
})
-- fformat required for init
if args.jpg then
opts.fformat = opts.fformat + 1
end
if args.dng then
opts.fformat = opts.fformat + 6
else
if args.raw then
opts.fformat = opts.fformat + 2
end
if args.dnghdr then
opts.fformat = opts.fformat + 4
end
end
-- default to jpeg TODO won't be supported on cams without raw hook
if opts.fformat == 0 then
opts.fformat = 1
args.jpg = true
end
if args.badpix and not args.dng then
util.warnf('badpix without dng ignored\n')
end
if args.s or args.c then
if args.dng or args.raw then
if args.s then
opts.lstart = tonumber(args.s)
end
if args.c then
opts.lcount = tonumber(args.c)
end
else
util.warnf('subimage without raw ignored\n')
end
end
if args.cont then
if type(args.cont) == 'string' then
opts.shots = tonumber(args.cont)
end
opts.cont = true
end
if args.quick then
if type(args.quick) == 'string' then
opts.shots = tonumber(args.quick)
end
opts.quick = true
end
if opts.shots and args.shots then
util.warnf("shot count specified with -quick or -cont, ignoring -shots")
else
if args.shots then
opts.shots = tonumber(args.shots)
elseif not opts.shots then
opts.shots = 1
end
end
-- convert to integer ms
if args.int then
opts.int = util.round(tonumber(args.int)*1000)
end
local opts_s = serialize(opts)
cli.dbgmsg('rs_init\n')
local rstatus,rerr = con:execwait('return rs_init('..opts_s..')',{libs={'rs_shoot_init'}})
if not rstatus then
return false,rerr
end
cli.dbgmsg('rs_shoot\n')
-- TODO script errors will not get picked up here
con:exec('rs_shoot('..opts_s..')',{libs={'rs_shoot'}})
local rcopts={}
if args.jpg then
rcopts.jpg=chdku.rc_handler_file(dst_dir,dst)
end
if args.dng then
if args.badpix == true then
args.badpix = 0
end
local dng_info = {
lstart=opts.lstart,
lcount=opts.lcount,
badpix=args.badpix,
}
rcopts.dng_hdr = chdku.rc_handler_store(function(chunk) dng_info.hdr=chunk.data end)
rcopts.raw = chdku.rc_handler_raw_dng_file(dst_dir,dst,'dng',dng_info)
else
if args.raw then
rcopts.raw=chdku.rc_handler_file(dst_dir,dst)
end
if args.dnghdr then
rcopts.dng_hdr=chdku.rc_handler_file(dst_dir,dst)
end
end
local status,err
local shot = 1
repeat
cli.dbgmsg('get data %d\n',shot)
status,err = con:capture_get_data_pcall(rcopts)
if not status then
warnf('capture_get_data error %s\n',tostring(err))
cli.dbgmsg('sending stop message\n')
con:write_msg_pcall('stop')
break
end
shot = shot + 1
until shot > opts.shots
local t0=ustime.new()
-- wait for shot script to end or timeout
local wpstatus,wstatus=con:wait_status_pcall{
run=false,
timeout=30000,
}
if not wpstatus then
warnf('error waiting for shot script %s\n',tostring(werr))
else
if wstatus.timeout then
warnf('timed out waiting for shot script\n')
end
-- TODO should allow passing a message handler to capture_get_data
-- stop immediately on script error
if wstatus.msg then
con:read_all_msgs({
['return']=function(msg,opts)
warnf("unexpected script return %s\n",tostring(msg.value))
end,
user=function(msg,opts)
warnf("unexpected script msg %s\n",tostring(msg.value))
end,
error=function(msg,opts)
warnf("script error %s\n",tostring(msg.value))
end,
})
end
end
cli.dbgmsg("script wait time %.4f\n",ustime.diff(t0)/1000000)
local ustatus, uerr = con:execwait_pcall('init_usb_capture(0)') -- try to uninit
-- if uninit failed, combine with previous status
if not ustatus then
uerr = 'uninit '..tostring(uerr)
status = false
if err then
err = err .. ' ' .. uerr
else
err = uerr
end
end
if not status then
return false,err
end
return true
end,
},
{
names={'rsint'},
help='shoot and download with interactive control',
arghelp="[local] [options]",
args=cli.argparser.create{
u='s',
tv=false,
sv=false,
svm=false,
av=false,
isomode=false,
nd=false,
sd=false,
jpg=false,
raw=false,
dng=false,
dnghdr=false,
s=false,
c=false,
badpix=false,
cmdwait=60,
cont=false,
},
help_detail=[[
[local] local destination directory or filename (w/o extension!)
options:
-u=<s|a|96>
s standard units (default)
a APEX
96 APEX*96
-tv=<v> shutter speed. In standard units both decimal and X/Y accepted
-sv=<v> ISO value, Canon "real" ISO
-svm=<v> ISO value, Canon "Market" ISO (requires CHDK 1.3)
-av=<v> Aperture value. In standard units, f number
-isomode=<v> ISO mode, must be ISO value in Canon UI, shooting mode must have manual ISO
-nd=<in|out> set ND filter state
-sd=<v>[units] subject distance, units one of m, mm, in, ft default m
-jpg jpeg, default if no other options (not supported on all cams)
-raw framebuffer dump raw
-dng DNG format raw
-dnghdr save DNG header to a seperate file, ignored with -dng
-s=<start> first line of for subimage raw
-c=<count> number of lines for subimage
-badpix[=n] interpolate over pixels with value <= n, default 0, (dng only)
-cmdwait=n wait n seconds for command, default 60
-cont use continuous mode
The following commands are available at the rsint> prompt
s shoot
l shoot and then quit rsint
q quit (not available in continuous mode, use l)
exec <lua code> execute code on the camera
pcall <lua code> execute code on the camera in pcall
path[=path] change download destination, equivalent to [local] in the initial command
In -cont mode, the following restrictions apply:
The camera must be set to continuous mode in the Canon UI
CHDK 1.3 shoot hooks must be available
The l command must be used to exit
]],
func=rsint.cli_cmd_func,
},
{
names={'rec'},
help='switch camera to shooting mode',
func=function(self,args)
local rstatus,rerr = con:execwait([[
if not get_mode() then
switch_mode_usb(1)
local i=0
while not get_mode() and i < 300 do
sleep(10)
i=i+1
end
if not get_mode() then
return false, 'switch failed'
end
return true
end
return false,'already in rec'
]])
cli:mode_change()
return rstatus,rerr
end,
},
{
names={'play'},
help='switch camera to playback mode',
func=function(self,args)
local rstatus,rerr = con:execwait([[
if get_mode() then
switch_mode_usb(0)
local i=0
while get_mode() and i < 300 do
sleep(10)
i=i+1
end
if get_mode() then
return false, 'switch failed'
end
return true
end
return false,'already in play'
]])
cli:mode_change()
return rstatus,rerr
end,
},
}
prefs._add('cli_time','boolean','show cli execution times')
prefs._add('cli_xferstats','boolean','show cli data transfer stats')
prefs._add('cli_verbose','number','control verbosity of cli',1)
prefs._add('cli_source_max','number','max nested source calls',10)
return cli
|
tudelft/chdkptp
|
lua/cli.lua
|
Lua
|
gpl-2.0
| 64,444 |
<?php
/**
* File containing the Price 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\FieldType\Price;
use eZ\Publish\SPI\Persistence\Content\Field;
use eZ\Publish\SPI\FieldType\Indexable;
use eZ\Publish\SPI\Search;
/**
* Indexable definition for string field type
*/
class SearchField implements Indexable
{
/**
* Get index data for field for search backend
*
* @param Field $field
*
* @return \eZ\Publish\SPI\Search\Field[]
*/
public function getIndexData( Field $field )
{
return array(
new Search\Field(
'value',
// @todo: Data is yet empty, this seems wrong, so we use the
// sort field for now
$field->value->sortKey['sort_key_int'] / 1000,
new Search\FieldType\PriceField()
),
);
}
/**
* Get index field types for search backend
*
* @return \eZ\Publish\SPI\Search\FieldType[]
*/
public function getIndexDefinition()
{
return array(
'value' => new Search\FieldType\PriceField(),
);
}
}
|
elabayoub/ezpublish-kernel
|
eZ/Publish/Core/FieldType/Price/SearchField.php
|
PHP
|
gpl-2.0
| 1,319 |
/**
* Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved.
* This software is published under the GPL GNU General Public License.
* 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.
*
* This software was written for the
* Department of Family Medicine
* McMaster University
* Hamilton
* Ontario, Canada
*/
package org.oscarehr.billing.CA.BC.dao;
import java.util.List;
import javax.persistence.Query;
import org.oscarehr.billing.CA.BC.model.Hl7Message;
import org.oscarehr.common.dao.AbstractDao;
import org.oscarehr.common.model.PatientLabRouting;
import org.springframework.stereotype.Repository;
@Repository
@SuppressWarnings("unchecked")
public class Hl7MessageDao extends AbstractDao<Hl7Message>{
public Hl7MessageDao() {
super(Hl7Message.class);
}
public List<Object[]> findByDemographicAndLabType(Integer demographicNo, String labType) {
String sql =
"FROM Hl7Message m, " + PatientLabRouting.class.getSimpleName() + " patientLabRouting " +
"WHERE patientLabRouting.labNo = m.id "+
"AND patientLabRouting.labType = :labType " +
"AND patientLabRouting.demographicNo = :demographicNo " +
"GROUP BY m.id";
Query query = entityManager.createQuery(sql);
query.setParameter("demographicNo", demographicNo);
query.setParameter("labType", labType);
return query.getResultList();
}
}
|
williamgrosset/OSCAR-ConCert
|
src/main/java/org/oscarehr/billing/CA/BC/dao/Hl7MessageDao.java
|
Java
|
gpl-2.0
| 2,115 |
//# tTableInfo.cc: Test program for class TableInfo
//# Copyright (C) 1996,2000,2001
//# Associated Universities, Inc. Washington DC, USA.
//#
//# This library is free software; you can redistribute it and/or modify it
//# under the terms of the GNU Library General Public License as published by
//# the Free Software Foundation; either version 2 of the License, or (at your
//# option) any later version.
//#
//# This library is distributed in the hope that it will be useful, but WITHOUT
//# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
//# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
//# License for more details.
//#
//# You should have received a copy of the GNU Library General Public License
//# along with this library; if not, write to the Free Software Foundation,
//# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
//#
//# Correspondence concerning AIPS++ should be addressed as follows:
//# Internet email: [email protected].
//# Postal address: AIPS++ Project Office
//# National Radio Astronomy Observatory
//# 520 Edgemont Road
//# Charlottesville, VA 22903-2475 USA
//#
//# $Id$
//# Includes
#include <casacore/tables/Tables/TableInfo.h>
#include <casacore/casa/BasicSL/String.h>
#include <casacore/casa/Exceptions/Error.h>
#include <casacore/casa/iostream.h>
#include <casacore/casa/namespace.h>
// <summary>
// Test program for the Table classes
// </summary>
// This program tests the class TableInfo.
// The results are written to stdout. The script executing this program,
// compares the results with the reference output file.
void writeInfo()
{
TableInfo info;
info.setType ("infotype");
info.setSubType ("infosubtype");
info.readmeAddLine ("first line");
info.readmeAddLine ("second line");
info.readmeAddLine ("third line\nfourth line");
info.flush ("tTableInfo_tmp.data");
}
void readInfo()
{
TableInfo info("tTableInfo_tmp.data");
cout << info.type() << endl;
cout << info.subType() << endl;
cout << info.readme() << endl;
}
int main()
{
try {
writeInfo();
readInfo();
} catch (AipsError& x) {
cout << "Caught an exception: " << x.getMesg() << endl;
return 1;
}
return 0; // exit with success status
}
|
bmerry/casacore
|
tables/Tables/test/tTableInfo.cc
|
C++
|
gpl-2.0
| 2,379 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.concurrent;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import junit.framework.TestCase;
/**
* Test class for {@link ConcurrentUtils}.
*
* @version $Id$
*/
public class ConcurrentUtilsTest extends TestCase {
/**
* Tests creating a ConcurrentException with a runtime exception as cause.
*/
public void testConcurrentExceptionCauseUnchecked() {
try {
new ConcurrentException(new RuntimeException());
fail("Could create ConcurrentException with unchecked cause!");
} catch (IllegalArgumentException iex) {
// ok
}
}
/**
* Tests creating a ConcurrentException with an error as cause.
*/
public void testConcurrentExceptionCauseError() {
try {
new ConcurrentException("An error", new Error());
fail("Could create ConcurrentException with an error cause!");
} catch (IllegalArgumentException iex) {
// ok
}
}
/**
* Tests creating a ConcurrentException with null as cause.
*/
public void testConcurrentExceptionCauseNull() {
try {
new ConcurrentException(null);
fail("Could create ConcurrentException with null cause!");
} catch (IllegalArgumentException iex) {
// ok
}
}
/**
* Tests extractCause() for a null exception.
*/
public void testExtractCauseNull() {
assertNull("Non null result", ConcurrentUtils.extractCause(null));
}
/**
* Tests extractCause() if the cause of the passed in exception is null.
*/
public void testExtractCauseNullCause() {
assertNull("Non null result", ConcurrentUtils
.extractCause(new ExecutionException("Test", null)));
}
/**
* Tests extractCause() if the cause is an error.
*/
public void testExtractCauseError() {
Error err = new AssertionError("Test");
try {
ConcurrentUtils.extractCause(new ExecutionException(err));
fail("Error not thrown!");
} catch (Error e) {
assertEquals("Wrong error", err, e);
}
}
/**
* Tests extractCause() if the cause is an unchecked exception.
*/
public void testExtractCauseUnchecked() {
RuntimeException rex = new RuntimeException("Test");
try {
ConcurrentUtils.extractCause(new ExecutionException(rex));
fail("Runtime exception not thrown!");
} catch (RuntimeException r) {
assertEquals("Wrong exception", rex, r);
}
}
/**
* Tests extractCause() if the cause is a checked exception.
*/
public void testExtractCauseChecked() {
Exception ex = new Exception("Test");
ConcurrentException cex = ConcurrentUtils
.extractCause(new ExecutionException(ex));
assertSame("Wrong cause", ex, cex.getCause());
}
/**
* Tests handleCause() if the cause is an error.
*/
public void testHandleCauseError() throws ConcurrentException {
Error err = new AssertionError("Test");
try {
ConcurrentUtils.handleCause(new ExecutionException(err));
fail("Error not thrown!");
} catch (Error e) {
assertEquals("Wrong error", err, e);
}
}
/**
* Tests handleCause() if the cause is an unchecked exception.
*/
public void testHandleCauseUnchecked() throws ConcurrentException {
RuntimeException rex = new RuntimeException("Test");
try {
ConcurrentUtils.handleCause(new ExecutionException(rex));
fail("Runtime exception not thrown!");
} catch (RuntimeException r) {
assertEquals("Wrong exception", rex, r);
}
}
/**
* Tests handleCause() if the cause is a checked exception.
*/
public void testHandleCauseChecked() {
Exception ex = new Exception("Test");
try {
ConcurrentUtils.handleCause(new ExecutionException(ex));
fail("ConcurrentException not thrown!");
} catch (ConcurrentException cex) {
assertEquals("Wrong cause", ex, cex.getCause());
}
}
/**
* Tests handleCause() for a null parameter or a null cause. In this case
* the method should do nothing. We can only test that no exception is
* thrown.
*/
public void testHandleCauseNull() throws ConcurrentException {
ConcurrentUtils.handleCause(null);
ConcurrentUtils.handleCause(new ExecutionException("Test", null));
}
//-----------------------------------------------------------------------
/**
* Tests constant future.
*/
public void testConstantFuture_Integer() throws Exception {
Integer value = new Integer(5);
Future<Integer> test = ConcurrentUtils.constantFuture(value);
assertEquals(true, test.isDone());
assertSame(value, test.get());
assertSame(value, test.get(1000, TimeUnit.SECONDS));
assertSame(value, test.get(1000, null));
assertEquals(false, test.isCancelled());
assertEquals(false, test.cancel(true));
assertEquals(false, test.cancel(false));
}
/**
* Tests constant future.
*/
public void testConstantFuture_null() throws Exception {
Integer value = null;
Future<Integer> test = ConcurrentUtils.constantFuture(value);
assertEquals(true, test.isDone());
assertSame(value, test.get());
assertSame(value, test.get(1000, TimeUnit.SECONDS));
assertSame(value, test.get(1000, null));
assertEquals(false, test.isCancelled());
assertEquals(false, test.cancel(true));
assertEquals(false, test.cancel(false));
}
}
|
justinwm/astor
|
examples/lang_39/src/test/org/apache/commons/lang3/concurrent/ConcurrentUtilsTest.java
|
Java
|
gpl-2.0
| 6,712 |
<div id='main-content-zone-outter'>
<?php if ($wrapper): ?><div<?php print $attributes; ?>><?php endif; ?>
<div<?php print $content_attributes; ?>>
<?php print $content; ?>
</div>
<?php if ($wrapper): ?></div><?php endif; ?>
</div>
|
redtrayworkshop/msdworkshop
|
tmp/omega-tools/glossy-d49cd9a6/templates/zone--slideshow.tpl.php
|
PHP
|
gpl-2.0
| 242 |
/* $Date: 2010/08/26 11:40:00 $
* $Revision: 1.1 $
*/
/*
* This software program is licensed subject to the GNU General Public License
* (GPL).Version 2,June 1991, available at http://www.fsf.org/copyleft/gpl.html
* (C) Copyright 2010 Bosch Sensortec GmbH
* All Rights Reserved
*/
/*! \file BMA222_driver.c
\brief This file contains all function implementations for the BMA222 in linux
Details.
*/
#include <linux/kernel.h>
#include <linux/i2c/bma023_dev.h>
bma023_t *p_bma023; /**< pointer to bma023 device structure */
int bma023_status = 0 ;
int bma023_init(bma023_t *bma023)
{
int comres=0;
unsigned char data;
trace_in() ;
p_bma023 = bma023; /* assign bma023 ptr */
p_bma023->dev_addr = bma023_I2C_ADDR; /* preset SM380 I2C_addr */
comres += p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, CHIP_ID__REG, &data, 1); /* read Chip Id */
p_bma023->chip_id = bma023_GET_BITSLICE(data, CHIP_ID); /* get bitslice */
comres += p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, ML_VERSION__REG, &data, 1); /* read Version reg */
p_bma023->ml_version = bma023_GET_BITSLICE(data, ML_VERSION); /* get ML Version */
p_bma023->al_version = bma023_GET_BITSLICE(data, AL_VERSION); /* get AL Version */
trace_out();
return comres;
}
int bma023_soft_reset()
{
int comres;
unsigned char data=0;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
data = bma023_SET_BITSLICE(data, SOFT_RESET, 1);
comres = p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, SOFT_RESET__REG, &data,1);
trace_out();
return comres;
}
int bma023_update_image()
{
int comres;
unsigned char data=0;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
data = bma023_SET_BITSLICE(data, UPDATE_IMAGE, 1);
comres = p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, UPDATE_IMAGE__REG, &data,1);
trace_out();
return comres;
}
int bma023_set_image (bma023regs_t *bma023Image)
{
int comres;
unsigned char data;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, EE_W__REG,&data, 1);
data = bma023_SET_BITSLICE(data, EE_W, bma023_EE_W_ON);
comres = p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, EE_W__REG, &data, 1);
comres = p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, bma023_IMAGE_BASE, (unsigned char*)bma023Image, bma023_IMAGE_LEN);
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, EE_W__REG,&data, 1);
data = bma023_SET_BITSLICE(data, EE_W, bma023_EE_W_OFF);
comres = p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, EE_W__REG, &data, 1);
trace_out();
return comres;
}
int bma023_get_image(bma023regs_t *bma023Image)
{
int comres;
unsigned char data;
trace_in() ;
if (p_bma023==0){
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, EE_W__REG,&data, 1);
data = bma023_SET_BITSLICE(data, EE_W, bma023_EE_W_ON);
comres = p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, EE_W__REG, &data, 1);
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, bma023_IMAGE_BASE, (unsigned char *)bma023Image, bma023_IMAGE_LEN);
data = bma023_SET_BITSLICE(data, EE_W, bma023_EE_W_OFF);
comres = p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, EE_W__REG, &data, 1);
trace_out();
return comres;
}
int bma023_get_offset(unsigned char xyz, unsigned short *offset)
{
int comres;
unsigned char data;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, (OFFSET_X_LSB__REG+xyz), &data, 1);
data = bma023_GET_BITSLICE(data, OFFSET_X_LSB);
*offset = data;
comres += p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, (OFFSET_X_MSB__REG+xyz), &data, 1);
*offset |= (data<<2);
trace_out();
return comres;
}
int bma023_set_offset(unsigned char xyz, unsigned short offset)
{
int comres;
unsigned char data;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, (OFFSET_X_LSB__REG+xyz), &data, 1);
data = bma023_SET_BITSLICE(data, OFFSET_X_LSB, offset);
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, (OFFSET_X_LSB__REG+xyz), &data, 1);
data = (offset&0x3ff)>>2;
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, (OFFSET_X_MSB__REG+xyz), &data, 1);
trace_out();
return comres;
}
int bma023_set_offset_eeprom(unsigned char xyz, unsigned short offset)
{
int comres;
unsigned char data;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, (OFFSET_X_LSB__REG+xyz), &data, 1);
data = bma023_SET_BITSLICE(data, OFFSET_X_LSB, offset);
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, (bma023_EEP_OFFSET+OFFSET_X_LSB__REG + xyz), &data, 1);
p_bma023->delay_msec(34);
data = (offset&0x3ff)>>2;
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, (bma023_EEP_OFFSET+ OFFSET_X_MSB__REG+xyz), &data, 1);
p_bma023->delay_msec(34);
trace_out();
return comres;
}
int bma023_set_ee_w(unsigned char eew)
{
unsigned char data;
int comres;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, EE_W__REG,&data, 1);
data = bma023_SET_BITSLICE(data, EE_W, eew);
comres = p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, EE_W__REG, &data, 1);
trace_out();
return comres;
}
int bma023_write_ee(unsigned char addr, unsigned char data)
{
int comres;
trace_in() ;
if (p_bma023==0) { /* check pointers */
trace_out();
return E_bma023_NULL_PTR;
}
if (p_bma023->delay_msec == 0)
trace_out();
return E_bma023_NULL_PTR;
comres = bma023_set_ee_w( bma023_EE_W_ON );
addr|=0x20; /* add eeprom address offset to image address if not applied */
comres += bma023_write_reg(addr, &data, 1 );
p_bma023->delay_msec( bma023_EE_W_DELAY );
comres += bma023_set_ee_w( bma023_EE_W_OFF);
trace_out();
return comres;
}
int bma023_selftest(unsigned char st)
{
int comres;
unsigned char data;
trace_in() ;
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, SELF_TEST__REG, &data, 1);
data = bma023_SET_BITSLICE(data, SELF_TEST, st);
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, SELF_TEST__REG, &data, 1);
trace_out();
return comres;
}
int bma023_set_range(char range)
{
int comres = 0;
unsigned char data;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
if (range<3)
{
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, RANGE__REG, &data, 1 );
data = bma023_SET_BITSLICE(data, RANGE, range);
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, RANGE__REG, &data, 1);
}
trace_out();
return comres;
}
int bma023_get_range(unsigned char *range)
{
int comres = 0;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, RANGE__REG, range, 1 );
*range = bma023_GET_BITSLICE(*range, RANGE);
trace_out();
return comres;
}
/*
* bma023_dev_operating()
*
* Perform Chip power Up/Down
* mode - bma023_MODE_SLEEP = 0
* bma023_MODE_NORMAL = 2
*/
int bma023_dev_operating(unsigned char mode)
{
int comres=0 ;
unsigned char data1, data2;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
debug( "mode= %c, bma023_status= %d", mode, bma023_status ) ;
if (mode<4 || mode!=1)
{
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, WAKE_UP__REG, &data1, 1 );
data1 = bma023_SET_BITSLICE(data1, WAKE_UP, mode);
comres += p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, SLEEP__REG, &data2, 1 );
data2 = bma023_SET_BITSLICE(data2, SLEEP, (mode>>1));
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, WAKE_UP__REG, &data1, 1);
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, SLEEP__REG, &data2, 1);
p_bma023->mode = mode;
}
trace_out();
return comres;
}
/*
* bma023_dev_set_staus()
*
* bma023_status = [CAL|COMPASS|ACC]
ex, 000 CAL: NO, COMPASS: standby, ACC: standby
001 CAL: NO, COMPASS: standby, ACC: normal
010 CAL: NO, COMPASS: normal, ACC: standby
011 CAL: NO, COMPASS: normal, ACC: normal
1XX CAL: YES, COMPASS: don't care,ACC: don't care
*
*/
int bma023_dev_set_status( int module, int param, int cal )
{
trace_in() ;
if( cal == TRUE )
{
bma023_status = bma023_status | ( 1 << 2 ) ;
}
else if( cal == FALSE )
{
bma023_status = bma023_status & (~( 1 << 2 ) ) ;
}
if( param == STANDBY )
{
bma023_status= bma023_status & (~(1 << module)) ;
}
else if( param == NORMAL )
{
bma023_status= bma023_status | ( 1 << module ) ;
}
else
{
printk( "bma023_dev_get_status() Fault or Calibration!!!! module= %d, param=%d, cal= %d\n", module, param, cal ) ;
}
trace_out() ;
return bma023_status ;
}
int bma023_dev_get_status( void )
{
trace_in() ;
trace_out() ;
return bma023_status ;
}
int bma023_set_operation_mode( int module, int param, int cal )
{
int status= 0 ;
trace_in() ;
status= bma023_dev_set_status( module, param, cal ) ;
printk( "bma023_status= %d\n", bma023_status ) ;
switch( status )
{
case STANDBY:
bma023_dev_operating( bma023_MODE_SLEEP ) ;
#if 0
bma023_timer.saved_timer_state= TIMER_OFF ;
bma023_timer_disable() ;
#endif
break ;
case ONLYACCEL:
case ONLYCOMPASS:
case ACCELCOMPASS:
bma023_dev_operating( bma023_MODE_NORMAL ) ;
#if 0
bma023_timer.saved_timer_state= TIMER_ON ;
bma023_timer_enable( bma023_timer.polling_time ) ;
#endif
break ;
default:
if( status > ACCELCOMPASS )
{
bma023_dev_operating( bma023_MODE_NORMAL ) ;
#if 0
bma023_timer.saved_timer_state= TIMER_ON ;
bma023_timer_enable( bma023_timer.polling_time ) ;
#endif
printk("%s: bma023_dev_set_operation_mode is CALIBRATION\n", __FUNCTION__ );
}
else {
bma023_dev_operating( bma023_MODE_SLEEP ) ;
#if 0
bma023_timer.saved_timer_state= TIMER_OFF ;
bma023_timer_disable() ;
#endif
printk("%s: bma023_dev_set_operation_mode Fault argument!!! Disable of all in force\n", __FUNCTION__ );
}
break ;
}
#if 0
switch( status )
{
case STANDBY:
bma023_report_func= NULL ;
printk("%s: bma023_dev_set_operation_mode STANDBY\n", __FUNCTION__ );
break ;
case ONLYACCEL:
bma023_report_func= bma023_report_sensorhal ;
printk("%s: bma023_dev_set_operation_mode ONLYACCEL\n", __FUNCTION__ );
break ;
case ONLYCOMPASS:
bma023_report_func= bma023_report_akmd2 ;
printk("%s: bma023_dev_set_operation_mode ONLYCOMPASS\n", __FUNCTION__ );
break ;
case ACCELCOMPASS:
bma023_report_func= bma023_report_sensorhal_akmd2 ;
printk("%s: bma023_dev_set_operation_mode ACCELCOMPASS\n", __FUNCTION__ );
break ;
default:
if( status > ACCELCOMPASS )
{
bma023_report_func= bma023_report_calibration ;
printk("%s: bma023_dev_set_operation_mode Calibration\n", __FUNCTION__ );
}
else {
bma023_report_func= NULL ;
printk("%s: bma023_dev_set_operation_mode Fault argument!!! Disable of all in force\n", __FUNCTION__ );
}
break ;
}
#endif
trace_out() ;
return status ;
}
unsigned char bma023_get_mode(void)
{
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
trace_out();
return p_bma023->mode;
}
int bma023_set_bandwidth(char bw)
{
int comres = 0;
unsigned char data;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
if (bw<8)
{
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, RANGE__REG, &data, 1 );
data = bma023_SET_BITSLICE(data, BANDWIDTH, bw);
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, RANGE__REG, &data, 1 );
}
trace_out();
return comres;
}
int bma023_get_bandwidth(unsigned char *bw)
{
int comres = 1;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, BANDWIDTH__REG, bw, 1 );
*bw = bma023_GET_BITSLICE(*bw, BANDWIDTH);
trace_out();
return comres;
}
int bma023_set_wake_up_pause(unsigned char wup)
{
int comres=0;
unsigned char data;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, WAKE_UP_PAUSE__REG, &data, 1 );
data = bma023_SET_BITSLICE(data, WAKE_UP_PAUSE, wup);
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, WAKE_UP_PAUSE__REG, &data, 1 );
trace_out();
return comres;
}
int bma023_get_wake_up_pause(unsigned char *wup)
{
int comres = 1;
unsigned char data;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, WAKE_UP_PAUSE__REG, &data, 1 );
*wup = bma023_GET_BITSLICE(data, WAKE_UP_PAUSE);
trace_out();
return comres;
}
int bma023_set_low_g_threshold(unsigned char th)
{
int comres;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, LG_THRES__REG, &th, 1);
trace_out();
return comres;
}
int bma023_get_low_g_threshold(unsigned char *th)
{
int comres=1;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, LG_THRES__REG, th, 1);
trace_out();
return comres;
}
int bma023_set_low_g_countdown(unsigned char cnt)
{
int comres=0;
unsigned char data;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, COUNTER_LG__REG, &data, 1 );
data = bma023_SET_BITSLICE(data, COUNTER_LG, cnt);
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, COUNTER_LG__REG, &data, 1 );
trace_out();
return comres;
}
int bma023_get_low_g_countdown(unsigned char *cnt)
{
int comres = 1;
unsigned char data;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, COUNTER_LG__REG, &data, 1 );
*cnt = bma023_GET_BITSLICE(data, COUNTER_LG);
trace_out();
return comres;
}
int bma023_set_high_g_countdown(unsigned char cnt)
{
int comres=1;
unsigned char data;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, COUNTER_HG__REG, &data, 1 );
data = bma023_SET_BITSLICE(data, COUNTER_HG, cnt);
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, COUNTER_HG__REG, &data, 1 );
trace_out();
return comres;
}
int bma023_get_high_g_countdown(unsigned char *cnt)
{
int comres = 0;
unsigned char data;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, COUNTER_HG__REG, &data, 1 );
*cnt = bma023_GET_BITSLICE(data, COUNTER_HG);
trace_out();
return comres;
}
int bma023_set_low_g_duration(unsigned char dur)
{
int comres=0;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, LG_DUR__REG, &dur, 1);
trace_out();
return comres;
}
int bma023_get_low_g_duration(unsigned char *dur)
{
int comres=0;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, LG_DUR__REG, dur, 1);
trace_out();
return comres;
}
int bma023_set_high_g_threshold(unsigned char th)
{
int comres=0;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, HG_THRES__REG, &th, 1);
trace_out();
return comres;
}
int bma023_get_high_g_threshold(unsigned char *th)
{
int comres=0;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, HG_THRES__REG, th, 1);
trace_out();
return comres;
}
int bma023_set_high_g_duration(unsigned char dur)
{
int comres=0;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, HG_DUR__REG, &dur, 1);
trace_out();
return comres;
}
int bma023_get_high_g_duration(unsigned char *dur) {
int comres=0;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, HG_DUR__REG, dur, 1);
trace_out();
return comres;
}
int bma023_set_any_motion_threshold(unsigned char th)
{
int comres=0;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, ANY_MOTION_THRES__REG, &th, 1);
trace_out();
return comres;
}
int bma023_get_any_motion_threshold(unsigned char *th)
{
int comres=0;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, ANY_MOTION_THRES__REG, th, 1);
trace_out();
return comres;
}
int bma023_set_any_motion_count(unsigned char amc)
{
int comres=0;
unsigned char data;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, ANY_MOTION_DUR__REG, &data, 1 );
data = bma023_SET_BITSLICE(data, ANY_MOTION_DUR, amc);
comres = p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, ANY_MOTION_DUR__REG, &data, 1 );
trace_out();
return comres;
}
int bma023_get_any_motion_count(unsigned char *amc)
{
int comres = 0;
unsigned char data;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, ANY_MOTION_DUR__REG, &data, 1 );
*amc = bma023_GET_BITSLICE(data, ANY_MOTION_DUR);
trace_out();
return comres;
}
int bma023_set_interrupt_mask(unsigned char mask)
{
int comres=0;
unsigned char data[4];
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
data[0] = mask & bma023_CONF1_INT_MSK;
data[2] = ((mask<<1) & bma023_CONF2_INT_MSK);
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, bma023_CONF1_REG, &data[1], 1);
comres += p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, bma023_CONF2_REG, &data[3], 1);
data[1] &= (~bma023_CONF1_INT_MSK);
data[1] |= data[0];
data[3] &=(~(bma023_CONF2_INT_MSK));
data[3] |= data[2];
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, bma023_CONF1_REG, &data[1], 1);
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, bma023_CONF2_REG, &data[3], 1);
trace_out();
return comres;
}
int bma023_get_interrupt_mask(unsigned char *mask)
{
int comres=0;
unsigned char data;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, bma023_CONF1_REG, &data,1);
*mask = data & bma023_CONF1_INT_MSK;
p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, bma023_CONF2_REG, &data,1);
*mask = *mask | ((data & bma023_CONF2_INT_MSK)>>1);
trace_out();
return comres;
}
int bma023_reset_interrupt(void)
{
int comres=0;
unsigned char data=(1<<RESET_INT__POS);
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, RESET_INT__REG, &data, 1);
trace_out();
return comres;
}
int bma023_read_accel_x(short *a_x)
{
int comres;
unsigned char data[2];
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, ACC_X_LSB__REG, data, 2);
*a_x = bma023_GET_BITSLICE(data[0],ACC_X_LSB) | bma023_GET_BITSLICE(data[1],ACC_X_MSB)<<ACC_X_LSB__LEN;
*a_x = *a_x << (sizeof(short)*8-(ACC_X_LSB__LEN+ACC_X_MSB__LEN));
*a_x = *a_x >> (sizeof(short)*8-(ACC_X_LSB__LEN+ACC_X_MSB__LEN));
trace_out();
return comres;
}
int bma023_read_accel_y(short *a_y)
{
int comres;
unsigned char data[2];
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, ACC_Y_LSB__REG, data, 2);
*a_y = bma023_GET_BITSLICE(data[0],ACC_Y_LSB) | bma023_GET_BITSLICE(data[1],ACC_Y_MSB)<<ACC_Y_LSB__LEN;
*a_y = *a_y << (sizeof(short)*8-(ACC_Y_LSB__LEN+ACC_Y_MSB__LEN));
*a_y = *a_y >> (sizeof(short)*8-(ACC_Y_LSB__LEN+ACC_Y_MSB__LEN));
trace_out();
return comres;
}
/** Z-axis acceleration data readout
\param *a_z pointer for 16 bit 2's complement data output (LSB aligned)
*/
int bma023_read_accel_z(short *a_z)
{
int comres;
unsigned char data[2];
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, ACC_Z_LSB__REG, data, 2);
*a_z = bma023_GET_BITSLICE(data[0],ACC_Z_LSB) | bma023_GET_BITSLICE(data[1],ACC_Z_MSB)<<ACC_Z_LSB__LEN;
*a_z = *a_z << (sizeof(short)*8-(ACC_Z_LSB__LEN+ACC_Z_MSB__LEN));
*a_z = *a_z >> (sizeof(short)*8-(ACC_Z_LSB__LEN+ACC_Z_MSB__LEN));
trace_out();
return comres;
}
int bma023_read_temperature(unsigned char * temp)
{
int comres;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, TEMPERATURE__REG, temp, 1);
trace_out();
return comres;
}
int bma023_read_accel_xyz(bma023acc_t * acc)
{
int comres;
unsigned char data[6];
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, ACC_X_LSB__REG, &data[0],6);
acc->x = bma023_GET_BITSLICE(data[0],ACC_X_LSB) | (bma023_GET_BITSLICE(data[1],ACC_X_MSB)<<ACC_X_LSB__LEN);
acc->x = acc->x << (sizeof(short)*8-(ACC_X_LSB__LEN+ACC_X_MSB__LEN));
acc->x = acc->x >> (sizeof(short)*8-(ACC_X_LSB__LEN+ACC_X_MSB__LEN));
acc->y = bma023_GET_BITSLICE(data[2],ACC_Y_LSB) | (bma023_GET_BITSLICE(data[3],ACC_Y_MSB)<<ACC_Y_LSB__LEN);
acc->y = acc->y << (sizeof(short)*8-(ACC_Y_LSB__LEN + ACC_Y_MSB__LEN));
acc->y = acc->y >> (sizeof(short)*8-(ACC_Y_LSB__LEN + ACC_Y_MSB__LEN));
/*
acc->z = bma023_GET_BITSLICE(data[4],ACC_Z_LSB);
acc->z |= (bma023_GET_BITSLICE(data[5],ACC_Z_MSB)<<ACC_Z_LSB__LEN);
acc->z = acc->z << (sizeof(short)*8-(ACC_Z_LSB__LEN+ACC_Z_MSB__LEN));
acc->z = acc->z >> (sizeof(short)*8-(ACC_Z_LSB__LEN+ACC_Z_MSB__LEN));
*/
acc->z = bma023_GET_BITSLICE(data[4],ACC_Z_LSB) | (bma023_GET_BITSLICE(data[5],ACC_Z_MSB)<<ACC_Z_LSB__LEN);
acc->z = acc->z << (sizeof(short)*8-(ACC_Z_LSB__LEN + ACC_Z_MSB__LEN));
acc->z = acc->z >> (sizeof(short)*8-(ACC_Z_LSB__LEN + ACC_Z_MSB__LEN));
debug( "%d\t, %d\t, %d\n", acc->x, acc->y, acc->z ) ;
trace_out();
return comres;
}
int bma023_get_interrupt_status(unsigned char * ist)
{
int comres=0;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, bma023_STATUS_REG, ist, 1);
trace_out();
return comres;
}
int bma023_set_low_g_int(unsigned char onoff) {
int comres;
unsigned char data;
trace_in() ;
if(p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, ENABLE_LG__REG, &data, 1);
data = bma023_SET_BITSLICE(data, ENABLE_LG, onoff);
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, ENABLE_LG__REG, &data, 1);
trace_out();
return comres;
}
int bma023_set_high_g_int(unsigned char onoff)
{
int comres;
unsigned char data;
trace_in() ;
if(p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, ENABLE_HG__REG, &data, 1);
data = bma023_SET_BITSLICE(data, ENABLE_HG, onoff);
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, ENABLE_HG__REG, &data, 1);
trace_out();
return comres;
}
int bma023_set_any_motion_int(unsigned char onoff) {
int comres;
unsigned char data;
trace_in() ;
if(p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, EN_ANY_MOTION__REG, &data, 1);
data = bma023_SET_BITSLICE(data, EN_ANY_MOTION, onoff);
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, EN_ANY_MOTION__REG, &data, 1);
trace_out();
return comres;
}
int bma023_set_alert_int(unsigned char onoff)
{
int comres;
unsigned char data;
trace_in() ;
if(p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, ALERT__REG, &data, 1);
data = bma023_SET_BITSLICE(data, ALERT, onoff);
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, ALERT__REG, &data, 1);
trace_out();
return comres;
}
int bma023_set_advanced_int(unsigned char onoff)
{
int comres;
unsigned char data;
trace_in() ;
if(p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, ENABLE_ADV_INT__REG, &data, 1);
data = bma023_SET_BITSLICE(data, EN_ANY_MOTION, onoff);
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, ENABLE_ADV_INT__REG, &data, 1);
trace_out();
return comres;
}
int bma023_latch_int(unsigned char latched)
{
int comres;
unsigned char data;
trace_in() ;
if(p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, LATCH_INT__REG, &data, 1);
data = bma023_SET_BITSLICE(data, LATCH_INT, latched);
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, LATCH_INT__REG, &data, 1);
trace_out();
return comres;
}
int bma023_set_new_data_int(unsigned char onoff)
{
int comres;
unsigned char data;
trace_in() ;
if(p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, NEW_DATA_INT__REG, &data, 1);
data = bma023_SET_BITSLICE(data, NEW_DATA_INT, onoff);
comres += p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, NEW_DATA_INT__REG, &data, 1);
trace_out();
return comres;
}
int bma023_pause(int msec)
{
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
else
p_bma023->delay_msec(msec);
trace_out();
return msec;
}
int bma023_read_reg(unsigned char addr, unsigned char *data, unsigned char len)
{
int comres;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_READ_FUNC(p_bma023->dev_addr, addr, data, len);
trace_out();
return comres;
}
int bma023_write_reg(unsigned char addr, unsigned char *data, unsigned char len)
{
int comres;
trace_in() ;
if (p_bma023==0) {
trace_out();
return E_bma023_NULL_PTR;
}
comres = p_bma023->bma023_BUS_WRITE_FUNC(p_bma023->dev_addr, addr, data, len);
trace_out();
return comres;
}
|
psyke83/codeaurora-kernel_samsung_europa
|
drivers/i2c/chips/bma023_dev.c
|
C
|
gpl-2.0
| 31,463 |
WordPress SEO by Yoast
======================
[](https://travis-ci.org/jdevalk/wordpress-seo)
Welcome to the WordPress SEO Github repository
----------------------------------------------
While the documenation for the [WordPress SEO plugin](http://yoast.com/wordpress/seo/) can be found on yoast.com, here
you can browse the source of the project, find and discuss open issues and even
[contribute yourself](https://github.com/jdevalk/wordpress-seo/blob/master/CONTRIBUTING.md).
Installation
------------
Here's a [guide on how to install WordPress SEO in your WordPress site](http://yoast.com/wordpress/seo/installation/).
If you want to run the Git version though, you have two options:
* You can clone the GitHub repository: https://github.com/jdevalk/wordpress-seo.git
* Download it directly as a ZIP file: https://github.com/jdevalk/wordpress-seo/archive/master.zip
This will download the latest development version of WordPress SEO by Yoast. While this version is usually stable,
it is not recommended for use in a production environment.
Bugs
----
If you find an issue, [let us know here](https://github.com/jdevalk/wordpress-seo/issues/new)!
Support
-------
This is a developer's portal for WordPress SEO by Yoast and should not be used for support. Please visit the
[support forums](http://wordpress.org/support/plugin/wordpress-seo).
Contributions
-------------
Anyone is welcome to contribute to WordPress SEO. Please
[read the guidelines](https://github.com/jdevalk/wordpress-seo/blob/master/CONTRIBUTING.md) for contributing to this
repository.
There are various ways you can contribute:
* [Raise an issue](https://github.com/jdevalk/wordpress-seo/issues) on GitHub.
* Send us a Pull Request with your bug fixes and/or new features.
* [Translate WordPress SEO by Yoast into different languages](http://translate.yoast.com/projects/wordpress-seo/).
* Provide feedback and [suggestions on enhancements](https://github.com/jdevalk/wordpress-seo/issues?direction=desc&labels=Enhancement&page=1&sort=created&state=open).
|
consiler/dlg_development
|
new/wp-content/plugins/wordpress-seo/README.md
|
Markdown
|
gpl-2.0
| 2,165 |
/*
* Copyright (c) 1999 Greg Haerr <[email protected]>
*
* Nano-X Core Protocol Client Request Handling Routines
*/
#include <stdio.h>
#include <unistd.h>
#include <malloc.h>
#include <assert.h>
#include <errno.h>
#include <string.h>
#include "serv.h"
#include "nxproto.h"
#define SZREQBUF 2048 /* initial request buffer size*/
/* queued request buffer*/
typedef struct {
BYTE8 * bufptr; /* next unused buffer location*/
BYTE8 * bufmax; /* max buffer location*/
BYTE8 * buffer; /* request buffer*/
} REQBUF;
static REQBUF reqbuf; /* request buffer*/
extern int nxSocket;
extern char * nxSharedMem;
/* Allocate a request buffer of passed size and fill in header fields*/
void *
nxAllocReq(int type, long size, long extra)
{
nxReq * req;
long aligned_len;
/* variable size requests must be hand-padded*/
if(extra)
assert((size & (long)(ALIGNSZ-1)) == 0);
/* calculate aligned length of request buffer*/
aligned_len = (size + extra + (long)(ALIGNSZ-1)) & ~(long)(ALIGNSZ-1);
/* verify we're not greater than max request size*/
assert(aligned_len <= MAXREQUESTSZ);
/* flush buffer if required, and allocate larger one if required*/
if(reqbuf.bufptr + aligned_len >= reqbuf.bufmax)
nxFlushReq(aligned_len,1);
/* fill in request header*/
req = (nxReq *)reqbuf.bufptr;
req->reqType = (BYTE8)type;
req->hilength = (BYTE8)((size + extra) >> 16);
req->length = (UINT16)(size + extra);
reqbuf.bufptr += aligned_len;
return req;
}
static void nxAllocReqbuffer(long newsize)
{
if(newsize < (long)SZREQBUF)
newsize = SZREQBUF;
reqbuf.buffer = malloc(newsize);
if(!reqbuf.buffer) {
EPRINTF("nxFlushReq: Can't allocate initial request buffer\n");
exit(1);
}
reqbuf.bufptr = reqbuf.buffer;
reqbuf.bufmax = reqbuf.buffer + newsize;
}
void
nxAssignReqbuffer(char *buffer, long size)
{
if ( reqbuf.buffer != 0 )
free(reqbuf.buffer);
reqbuf.buffer = buffer;
reqbuf.bufptr = reqbuf.buffer;
reqbuf.bufmax = reqbuf.buffer + size;
}
/* Write a block of data on the socket to the nano-X server */
void
nxWriteSocket(char *buf, int todo)
{
int written;
do {
written = write(nxSocket, buf, todo);
if ( written < 0 ) {
if ( errno == EAGAIN || errno == EINTR )
continue;
EPRINTF("nxFlushReq: write failed: %m\n");
exit(1);
}
buf += written;
todo -= written;
} while ( todo > 0 );
}
/* Flush request buffer if required, possibly reallocate buffer size*/
void
nxFlushReq(long newsize, int reply_needed)
{
/* handle one-time initialization case*/
if(reqbuf.buffer == NULL) {
nxAllocReqbuffer(newsize);
return;
}
/* flush buffer if required*/
if(reqbuf.bufptr > reqbuf.buffer) {
char * buf = reqbuf.buffer;
int todo = reqbuf.bufptr - reqbuf.buffer;
#if HAVE_SHAREDMEM_SUPPORT
if ( nxSharedMem != 0 ) {
/* There is a shared memory segment used for the
* request buffer. Make up a flush command and
* send it over the socket, to tell the server to
* process the shared memory segment.
* The 'reply_needed' argument should be non-zero
* when a confirmation is needed that all commands
* are flushed, so new ones can be filled into the
* request buffer. NOTE: This is *only* needed
* when explicitely flushing the request buffer, or
* when flushing it to make space for new commands.
* DO NOT REQUEST A REPLY when flushing the request
* buffer because the last command in the buffer
* will send a response: This response would be
* queued up first and had to be drained before the
* response to the flush command itsel....
* So the GrReadBlock used to read replys to commands
* must not specify a nonzero 'reply_needed'.
* Not requesting a reply in this case is
* safe, since the command executed will wait for
* the reply *it* is waiting for, and thus make
* sure the request buffer is flushed before
* continuing.
*
* We have to make the protocol request by hand,
* as it has to be sent over the socket to wake
* up the Nano-X server.
*/
char c;
nxShmCmdsFlushReq req;
req.reqType = GrNumShmCmdsFlush;
req.hilength = 0;
req.length = sizeof(req);
req.size = todo;
req.reply = reply_needed;
nxWriteSocket((char *)&req,sizeof(req));
if ( reply_needed )
while ( read(nxSocket, &c, 1) != 1 )
;
reqbuf.bufptr = reqbuf.buffer;
if ( reqbuf.buffer + newsize > reqbuf.bufmax ) {
/* Shared memory too small, critical */
EPRINTF("nxFlushReq: shm region too small\n");
exit(1);
}
return;
}
#endif /* HAVE_SHAREDMEM_SUPPORT*/
/* Standard Socket transfer */
nxWriteSocket(buf,todo);
reqbuf.bufptr = reqbuf.buffer;
}
/* allocate larger buffer for current request, if needed*/
if(reqbuf.bufptr + newsize >= reqbuf.bufmax) {
reqbuf.buffer = realloc(reqbuf.buffer, newsize);
if(!reqbuf.buffer) {
EPRINTF("nxFlushReq: Can't reallocate request buffer\n");
exit(1);
}
reqbuf.bufptr = reqbuf.buffer;
reqbuf.bufmax = reqbuf.buffer + newsize;
}
}
/* calc # bytes required for passed string according to encoding*/
int
nxCalcStringBytes(void *str, int count, int flags)
{
int nbytes;
/* calc byte length of data*/
if(flags & MWTF_UC16)
nbytes = count * 2;
else if(flags & MWTF_UC32)
nbytes = count * 4;
else
nbytes = count;
return nbytes;
}
|
sensysnetworks/uClinux
|
user/microwin/src/nanox/nxproto.c
|
C
|
gpl-2.0
| 5,315 |
/**
* $Id$
*
* Handles hotkeys for pause/continue, save states, quit, etc
*
* Copyright (c) 2009 wahrhaft
*
* 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.
*/
#include <assert.h>
#include <glib.h>
#include <sys/stat.h>
#include <stdint.h>
#include <stdlib.h>
#include "lxdream.h"
#include "dreamcast.h"
#include "display.h"
#include "hotkeys.h"
#include "gui.h"
#include "config.h"
static void hotkey_key_callback( void *data, uint32_t value, uint32_t pressure, gboolean isKeyDown );
static gboolean hotkey_config_changed( void *data, lxdream_config_group_t group, unsigned key,
const gchar *oldval, const gchar *newval );
#define TAG_RESUME 0
#define TAG_STOP 1
#define TAG_RESET 2
#define TAG_EXIT 3
#define TAG_SAVE 4
#define TAG_LOAD 5
#define TAG_SELECT(i) (6+(i))
struct lxdream_config_group hotkeys_group = {
"hotkeys", input_keygroup_changed, hotkey_key_callback, NULL, {
{"resume", N_("Resume emulation"), CONFIG_TYPE_KEY, NULL, TAG_RESUME },
{"stop", N_("Stop emulation"), CONFIG_TYPE_KEY, NULL, TAG_STOP },
{"reset", N_("Reset emulator"), CONFIG_TYPE_KEY, NULL, TAG_RESET },
{"exit", N_("Exit emulator"), CONFIG_TYPE_KEY, NULL, TAG_EXIT },
{"save", N_("Save current quick save"), CONFIG_TYPE_KEY, NULL, TAG_SAVE },
{"load", N_("Load current quick save"), CONFIG_TYPE_KEY, NULL, TAG_LOAD },
{"state0", N_("Select quick save state 0"), CONFIG_TYPE_KEY, NULL, TAG_SELECT(0) },
{"state1", N_("Select quick save state 1"), CONFIG_TYPE_KEY, NULL, TAG_SELECT(1) },
{"state2", N_("Select quick save state 2"), CONFIG_TYPE_KEY, NULL, TAG_SELECT(2) },
{"state3", N_("Select quick save state 3"), CONFIG_TYPE_KEY, NULL, TAG_SELECT(3) },
{"state4", N_("Select quick save state 4"), CONFIG_TYPE_KEY, NULL, TAG_SELECT(4) },
{"state5", N_("Select quick save state 5"), CONFIG_TYPE_KEY, NULL, TAG_SELECT(5) },
{"state6", N_("Select quick save state 6"), CONFIG_TYPE_KEY, NULL, TAG_SELECT(6) },
{"state7", N_("Select quick save state 7"), CONFIG_TYPE_KEY, NULL, TAG_SELECT(7) },
{"state8", N_("Select quick save state 8"), CONFIG_TYPE_KEY, NULL, TAG_SELECT(8) },
{"state9", N_("Select quick save state 9"), CONFIG_TYPE_KEY, NULL, TAG_SELECT(9) },
{NULL, CONFIG_TYPE_NONE}} };
void hotkeys_init()
{
hotkeys_register_keys();
}
void hotkeys_register_keys()
{
input_register_keygroup( &hotkeys_group );
}
void hotkeys_unregister_keys()
{
input_unregister_keygroup( &hotkeys_group );
}
lxdream_config_group_t hotkeys_get_config()
{
return &hotkeys_group;
}
static void hotkey_key_callback( void *data, uint32_t value, uint32_t pressure, gboolean isKeyDown )
{
if( isKeyDown ) {
switch(value) {
case TAG_RESUME:
if( !dreamcast_is_running() )
gui_do_later(dreamcast_run);
break;
case TAG_STOP:
if( dreamcast_is_running() )
gui_do_later(dreamcast_stop);
break;
case TAG_RESET:
dreamcast_reset();
break;
case TAG_EXIT:
dreamcast_shutdown();
exit(0);
break;
case TAG_SAVE:
dreamcast_quick_save();
break;
case TAG_LOAD:
dreamcast_quick_load();
break;
default:
dreamcast_set_quick_state(value- TAG_SELECT(0) );
break;
}
}
}
|
lutris/lxdream
|
src/hotkeys.c
|
C
|
gpl-2.0
| 3,962 |
/* This file is part of the KDE project
Copyright (C) 2005 Dag Andersen <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "kptwbsdefinition.h"
#include <klocale.h>
#include <kdebug.h>
#include <QList>
#include <QString>
#include <QStringList>
#include <QPair>
namespace KPlato
{
WBSDefinition::WBSDefinition() {
m_levelsEnabled = false;
m_defaultDef.code = "Number";
m_defaultDef.separator = ".";
m_codeLists.append(qMakePair(QString("Number"), i18n("Number")));
m_codeLists.append(qMakePair(QString("Roman, upper case"), i18n("Roman, upper case")));
m_codeLists.append(qMakePair(QString("Roman, lower case"), i18n("Roman, lower case")));
m_codeLists.append(qMakePair(QString("Letter, upper case"), i18n("Letter, upper case")));
m_codeLists.append(qMakePair(QString("Letter, lower case"), i18n("Letter, lower case")));
}
WBSDefinition::WBSDefinition( const WBSDefinition &def ) {
(void)this->operator=( def );
}
WBSDefinition::~WBSDefinition() {
}
WBSDefinition &WBSDefinition::operator=( const WBSDefinition &def ) {
m_projectCode = def.m_projectCode;
m_projectSeparator = def.m_projectSeparator;
m_defaultDef.code = def.m_defaultDef.code;
m_defaultDef.separator = def.m_defaultDef.separator;
m_levelsEnabled = def.m_levelsEnabled;
m_levelsDef = def.m_levelsDef;
m_codeLists = def.m_codeLists;
return *this;
}
void WBSDefinition::clear() {
m_defaultDef.clear();
m_levelsDef.clear();
}
QString WBSDefinition::wbs(uint index, int level) const {
if (isLevelsDefEnabled()) {
CodeDef def = levelsDef(level);
if (!def.isEmpty()) {
return code(def, index) + def.separator;
}
}
return code(m_defaultDef, index) + m_defaultDef.separator;
}
QString WBSDefinition::code(uint index, int level) const {
if (isLevelsDefEnabled()) {
CodeDef def = levelsDef(level);
if (!def.isEmpty()) {
return code(def, index);
}
}
return code(m_defaultDef, index);
}
QString WBSDefinition::separator(int level) const {
if (isLevelsDefEnabled()) {
CodeDef def = levelsDef(level);
if (!def.isEmpty()) {
return def.separator;
}
}
return m_defaultDef.separator;
}
void WBSDefinition::setLevelsDef(QMap<int, CodeDef> def) {
m_levelsDef.clear();
m_levelsDef = def;
}
WBSDefinition::CodeDef WBSDefinition::levelsDef(int level) const {
return m_levelsDef.contains(level) ? m_levelsDef[level] : CodeDef();
}
void WBSDefinition::setLevelsDef(int level, CodeDef def) {
m_levelsDef.insert(level, def);
}
void WBSDefinition::setLevelsDef(int level, const QString& c, const QString& s) {
m_levelsDef.insert(level, CodeDef(c, s));
}
bool WBSDefinition::level0Enabled() const {
return m_levelsEnabled && !levelsDef(0).isEmpty();
}
const QChar Letters[] = { '?','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' };
QString WBSDefinition::code(const CodeDef &def, uint index) const {
if (def.code == "Number") {
return QString("%1").arg(index);
}
if (def.code == "Roman, lower case") {
return QString("%1").arg(toRoman(index));
}
if (def.code == "Roman, upper case") {
return QString("%1").arg(toRoman(index, true));
}
if (def.code == "Letter, lower case") {
if (index > 26) {
index = 0;
}
return QString("%1").arg(Letters[index]);
}
if (def.code == "Letter, upper case") {
if (index > 26) {
index = 0;
}
return QString("%1").arg(Letters[index].toUpper());
}
return QString();
}
// Nicked from koparagcounter.cc
const QByteArray RNUnits[] = {"", "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix"};
const QByteArray RNTens[] = {"", "x", "xx", "xxx", "xl", "l", "lx", "lxx", "lxxx", "xc"};
const QByteArray RNHundreds[] = {"", "c", "cc", "ccc", "cd", "d", "dc", "dcc", "dccc", "cm"};
const QByteArray RNThousands[] = {"", "m", "mm", "mmm"};
QString WBSDefinition::toRoman( int n, bool upper ) const
{
if ( n >= 0 ) {
QString s = QString::fromLatin1( RNThousands[ ( n / 1000 ) ] +
RNHundreds[ ( n / 100 ) % 10 ] +
RNTens[ ( n / 10 ) % 10 ] +
RNUnits[ ( n ) % 10 ] );
return upper ? s.toUpper() : s;
} else { // should never happen, but better not crash if it does
kWarning()<< " n=" << n;
return QString::number( n );
}
}
QStringList WBSDefinition::codeList() const {
QStringList cl;
QList<QPair<QString, QString> >::ConstIterator it;
for (it = m_codeLists.constBegin(); it != m_codeLists.constEnd(); ++it) {
cl.append((*it).second);
}
return cl;
}
int WBSDefinition::defaultCodeIndex() const {
int index = -1;
for(int i = 0; i < m_codeLists.count(); ++i) {
if (m_defaultDef.code == m_codeLists.at(i).first) {
index = i;
break;
}
}
return index;
}
bool WBSDefinition::setDefaultCode(uint index) {
if ((int)index >= m_codeLists.size()) {
return false;
}
m_defaultDef.code = m_codeLists[index].first;
return true;
}
void WBSDefinition::setDefaultSeparator(const QString& s) {
m_defaultDef.separator = s;
}
bool WBSDefinition::loadXML(KoXmlElement &element, XMLLoaderObject & ) {
m_projectCode = element.attribute( "project-code" );
m_projectSeparator = element.attribute( "project-separator" );
m_levelsEnabled = (bool)element.attribute( "levels-enabled", "0" ).toInt();
KoXmlNode n = element.firstChild();
for ( ; ! n.isNull(); n = n.nextSibling() ) {
if ( ! n.isElement() ) {
continue;
}
KoXmlElement e = n.toElement();
if (e.tagName() == "default") {
m_defaultDef.code = e.attribute( "code", "Number" );
m_defaultDef.separator = e.attribute( "separator", "." );
} else if (e.tagName() == "levels") {
KoXmlNode n = e.firstChild();
for ( ; ! n.isNull(); n = n.nextSibling() ) {
if ( ! n.isElement() ) {
continue;
}
KoXmlElement el = n.toElement();
CodeDef d;
d.code = el.attribute( "code" );
d.separator = el.attribute( "separator" );
int lvl = el.attribute( "level", "-1" ).toInt();
if ( lvl >= 0 ) {
setLevelsDef( lvl, d );
} else kError()<<"Invalid levels definition";
}
}
}
return true;
}
void WBSDefinition::saveXML(QDomElement &element) const {
QDomElement me = element.ownerDocument().createElement("wbs-definition");
element.appendChild(me);
me.setAttribute( "project-code", m_projectCode );
me.setAttribute( "project-separator", m_projectSeparator );
me.setAttribute( "levels-enabled", m_levelsEnabled );
if ( ! m_levelsDef.isEmpty() ) {
QDomElement ld = element.ownerDocument().createElement("levels");
me.appendChild(ld);
QMap<int, CodeDef>::ConstIterator it;
for (it = m_levelsDef.constBegin(); it != m_levelsDef.constEnd(); ++it) {
QDomElement l = element.ownerDocument().createElement("level");
ld.appendChild(l);
l.setAttribute( "level", it.key() );
l.setAttribute( "code", it.value().code );
l.setAttribute( "separator", it.value().separator );
}
}
QDomElement cd = element.ownerDocument().createElement("default");
me.appendChild(cd);
cd.setAttribute("code", m_defaultDef.code);
cd.setAttribute("separator", m_defaultDef.separator);
}
} //namespace KPlato
|
wyuka/calligra
|
plan/libs/kernel/kptwbsdefinition.cpp
|
C++
|
gpl-2.0
| 8,638 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* 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 [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Rss
* @copyright Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Review form block
*
* @category Mage
* @package Mage_Rss
* @author Magento Core Team <[email protected]>
*/
class Mage_Rss_Block_Catalog_Salesrule extends Mage_Rss_Block_Abstract
{
protected function _construct()
{
/*
* setting cache to save the rss for 10 minutes
*/
$this->setCacheKey('rss_catalog_salesrule_'.$this->getStoreId().'_'.$this->_getCustomerGroupId());
$this->setCacheLifetime(600);
}
/**
* Generate RSS XML with sales rules data
*
* @return string
*/
protected function _toHtml()
{
$storeId = $this->_getStoreId();
$websiteId = Mage::app()->getStore($storeId)->getWebsiteId();
$customerGroup = $this->_getCustomerGroupId();
$now = date('Y-m-d');
$url = Mage::getUrl('');
$newUrl = Mage::getUrl('rss/catalog/salesrule');
$lang = Mage::getStoreConfig('general/locale/code');
$title = Mage::helper('rss')->__('%s - Discounts and Coupons',Mage::app()->getStore($storeId)->getName());
/** @var $rssObject Mage_Rss_Model_Rss */
$rssObject = Mage::getModel('rss/rss');
/** @var $collection Mage_SalesRule_Model_Resource_Rule_Collection */
$collection = Mage::getModel('salesrule/rule')->getResourceCollection();
$data = array(
'title' => $title,
'description' => $title,
'link' => $newUrl,
'charset' => 'UTF-8',
'language' => $lang
);
$rssObject->_addHeader($data);
$collection->addWebsiteGroupDateFilter($websiteId, $customerGroup, $now)
->addFieldToFilter('is_rss', 1)
->setOrder('from_date','desc');
$collection->load();
foreach ($collection as $sr) {
$description = '<table><tr>'.
'<td style="text-decoration:none;">'.$sr->getDescription().
'<br/>Discount Start Date: '.$this->formatDate($sr->getFromDate(), 'medium').
( $sr->getToDate() ? ('<br/>Discount End Date: '.$this->formatDate($sr->getToDate(), 'medium')):'').
($sr->getCouponCode() ? '<br/> Coupon Code: '. $this->escapeHtml($sr->getCouponCode()).'' : '').
'</td>'.
'</tr></table>';
$data = array(
'title' => $sr->getName(),
'description' => $description,
'link' => $url
);
$rssObject->_addEntry($data);
}
return $rssObject->createRssXml();
}
}
|
miguelangelramirez/magento.dev
|
app/code/core/Mage/Rss/Block/Catalog/Salesrule.php
|
PHP
|
gpl-2.0
| 3,600 |
/* GStreamer
* Copyright (C) <2005,2006> Wim Taymans <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/*
* Unless otherwise indicated, Source Code is licensed under MIT license.
* See further explanation attached in License Statement (distributed in the file
* LICENSE).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* SECTION:gstrtspurl
* @short_description: handling RTSP urls
*
* <refsect2>
* <para>
* Provides helper functions to handle RTSP urls.
* </para>
* </refsect2>
*
* Last reviewed on 2007-07-25 (0.10.14)
*/
#include <stdlib.h>
#include <string.h>
#include "gstrtspurl.h"
static void
register_rtsp_url_type (GType * id)
{
*id = g_boxed_type_register_static ("GstRTSPUrl",
(GBoxedCopyFunc) gst_rtsp_url_copy, (GBoxedFreeFunc) gst_rtsp_url_free);
}
GType
gst_rtsp_url_get_type (void)
{
static GType id;
static GOnce once = G_ONCE_INIT;
g_once (&once, (GThreadFunc) register_rtsp_url_type, &id);
return id;
}
#define RTSP_PROTO "rtsp://"
#define RTSP_PROTO_LEN 7
#define RTSPU_PROTO "rtspu://"
#define RTSPU_PROTO_LEN 8
#define RTSPT_PROTO "rtspt://"
#define RTSPT_PROTO_LEN 8
/* format is rtsp[u]://[user:passwd@]host[:port]/abspath[?query] */
/**
* gst_rtsp_url_parse:
* @urlstr: the url string to parse
* @url: location to hold the result.
*
* Parse the RTSP @urlstr into a newly allocated #GstRTSPUrl. Free after usage
* with gst_rtsp_url_free().
*
* Returns: a #GstRTSPResult.
*/
GstRTSPResult
gst_rtsp_url_parse (const gchar * urlstr, GstRTSPUrl ** url)
{
GstRTSPUrl *res;
gchar *p, *delim, *at, *col;
g_return_val_if_fail (urlstr != NULL, GST_RTSP_EINVAL);
g_return_val_if_fail (url != NULL, GST_RTSP_EINVAL);
res = g_new0 (GstRTSPUrl, 1);
p = (gchar *) urlstr;
if (g_str_has_prefix (p, RTSP_PROTO)) {
res->transports =
GST_RTSP_LOWER_TRANS_TCP | GST_RTSP_LOWER_TRANS_UDP |
GST_RTSP_LOWER_TRANS_UDP_MCAST;
p += RTSP_PROTO_LEN;
} else if (g_str_has_prefix (p, RTSPU_PROTO)) {
res->transports = GST_RTSP_LOWER_TRANS_UDP | GST_RTSP_LOWER_TRANS_UDP_MCAST;
p += RTSPU_PROTO_LEN;
} else if (g_str_has_prefix (p, RTSPT_PROTO)) {
res->transports = GST_RTSP_LOWER_TRANS_TCP;
p += RTSPT_PROTO_LEN;
} else
goto invalid;
delim = strpbrk (p, "/?");
at = strchr (p, '@');
if (at && delim && at > delim)
at = NULL;
if (at) {
col = strchr (p, ':');
/* must have a ':' and it must be before the '@' */
if (col == NULL || col > at)
goto invalid;
res->user = g_strndup (p, col - p);
col++;
res->passwd = g_strndup (col, at - col);
/* move to host */
p = at + 1;
}
col = strchr (p, ':');
/* we have a ':' and a delimiter but the ':' is after the delimiter, it's
* not really part of the hostname */
if (col && delim && col >= delim)
col = NULL;
if (col) {
res->host = g_strndup (p, col - p);
p = col + 1;
res->port = strtoul (p, (char **) &p, 10);
if (delim)
p = delim;
} else {
/* no port specified, set to 0. _get_port() will return the default port. */
res->port = 0;
if (!delim) {
res->host = g_strdup (p);
p = NULL;
} else {
res->host = g_strndup (p, delim - p);
p = delim;
}
}
if (p && *p == '/') {
delim = strchr (p, '?');
if (!delim) {
res->abspath = g_strdup (p);
p = NULL;
} else {
res->abspath = g_strndup (p, delim - p);
p = delim;
}
} else {
res->abspath = g_strdup ("/");
}
if (p && *p == '?')
res->query = g_strdup (p + 1);
*url = res;
return GST_RTSP_OK;
/* ERRORS */
invalid:
{
gst_rtsp_url_free (res);
return GST_RTSP_EINVAL;
}
}
/**
* gst_rtsp_url_copy:
* @url: a #GstRTSPUrl
*
* Make a copy of @url.
*
* Returns: a copy of @url. Free with gst_rtsp_url_free () after usage.
*
* Since: 0.10.22
*/
GstRTSPUrl *
gst_rtsp_url_copy (GstRTSPUrl * url)
{
GstRTSPUrl *res;
g_return_val_if_fail (url != NULL, NULL);
res = g_new0 (GstRTSPUrl, 1);
res->transports = url->transports;
res->family = url->family;
res->user = g_strdup (url->user);
res->passwd = g_strdup (url->passwd);
res->host = g_strdup (url->host);
res->port = url->port;
res->abspath = g_strdup (url->abspath);
res->query = g_strdup (url->query);
return res;
}
/**
* gst_rtsp_url_free:
* @url: a #GstRTSPUrl
*
* Free the memory used by @url.
*/
void
gst_rtsp_url_free (GstRTSPUrl * url)
{
if (url == NULL)
return;
g_free (url->user);
g_free (url->passwd);
g_free (url->host);
g_free (url->abspath);
g_free (url->query);
g_free (url);
}
/**
* gst_rtsp_url_set_port:
* @url: a #GstRTSPUrl
* @port: the port
*
* Set the port number in @url to @port.
*
* Returns: #GST_RTSP_OK.
*/
GstRTSPResult
gst_rtsp_url_set_port (GstRTSPUrl * url, guint16 port)
{
g_return_val_if_fail (url != NULL, GST_RTSP_EINVAL);
url->port = port;
return GST_RTSP_OK;
}
/**
* gst_rtsp_url_get_port:
* @url: a #GstRTSPUrl
* @port: location to hold the port
*
* Get the port number of @url.
*
* Returns: #GST_RTSP_OK.
*/
GstRTSPResult
gst_rtsp_url_get_port (GstRTSPUrl * url, guint16 * port)
{
g_return_val_if_fail (url != NULL, GST_RTSP_EINVAL);
g_return_val_if_fail (port != NULL, GST_RTSP_EINVAL);
/* if a port was specified, use that else use the default port. */
if (url->port != 0)
*port = url->port;
else
*port = GST_RTSP_DEFAULT_PORT;
return GST_RTSP_OK;
}
/**
* gst_rtsp_url_get_request_uri:
* @url: a #GstRTSPUrl
*
* Get a newly allocated string describing the request URI for @url.
*
* Returns: a string with the request URI. g_free() after usage.
*/
gchar *
gst_rtsp_url_get_request_uri (GstRTSPUrl * url)
{
gchar *uri;
g_return_val_if_fail (url != NULL, NULL);
if (url->port != 0) {
uri = g_strdup_printf ("rtsp://%s:%u%s%s%s", url->host, url->port,
url->abspath, url->query ? "?" : "", url->query ? url->query : "");
} else {
uri = g_strdup_printf ("rtsp://%s%s%s%s", url->host, url->abspath,
url->query ? "?" : "", url->query ? url->query : "");
}
return uri;
}
|
prajnashi/gst-plugins-base
|
gst-libs/gst/rtsp/gstrtspurl.c
|
C
|
gpl-2.0
| 7,891 |
<?php
/**
* Pager for log entries
*/
class ServerAdminLogEntryPager extends ReverseChronologicalPager {
/**
* Channel to filter entries to
*
* @var null|int
*/
protected $channel = null;
/**
* Last date for an entry
*
* @var string
*/
protected $lastDate = '';
/**
* Abstract formatting function. This should return an HTML string
* representing the result row $row. Rows will be concatenated and
* returned by getBody()
*
* @param $row Object: database row
* @return String
*/
function formatRow( $row ) {
$time = $this->getLanguage()->time( wfTimestamp( TS_MW, $row->sale_timestamp ) );
$message = htmlspecialchars( $row->sale_comment );
// Link to the user if they're not anon
if ( $row->sale_user == 0 ) {
$user = $row->sale_user_text;
} else {
$userPage = Title::makeTitle( NS_USER, $row->user_name );
$user = Linker::link( $userPage, htmlspecialchars( $userPage->getText() ) );
}
// Link to the channel name if the column is there
if ( isset( $row->salc_name ) ) {
$chanTitle = SpecialPage::getTitleFor( 'AdminLog', $row->salc_code );
$channel = Linker::link( $chanTitle, htmlspecialchars( $row->salc_name ) );
$channel = ' ' . $this->msg( 'parentheses' )->rawParams( $channel )->escaped();
} else {
$channel = '';
}
$html = "<li>{$time}{$channel} {$user}: ${message}</li>";
$date = $this->getLanguage()->date( wfTimestamp( TS_MW, $row->sale_timestamp ) );
if ( $date != $this->lastDate ) {
$html = "<h2>$date</h2>\n<ul>\n$html";
// Close the last list if there is one
if ( $this->lastDate != '' ) {
$html = "</ul>\n$html";
}
$this->lastDate = $date;
}
return $html;
}
protected function getStartBody() {
return $this->getNavigationBar();
}
protected function getEndBody() {
return '</ul>' . $this->getNavigationBar();
}
/**
* This function should be overridden to provide all parameters
* needed for the main paged query. It returns an associative
* array with the following elements:
* tables => Table(s) for passing to Database::select()
* fields => Field(s) for passing to Database::select(), may be *
* conds => WHERE conditions
* options => option array
* join_conds => JOIN conditions
*
* @return Array
*/
function getQueryInfo() {
$info = array(
'tables' => array( 'sal_entry', 'sal_channel', 'user' ),
'fields' => array(
'sale_id', 'sale_user', 'sale_user_text',
'sale_timestamp', 'sale_comment', 'user_name',
),
'join_conds' => array(
'sal_channel' => array( 'LEFT JOIN', 'sale_channel = salc_id' ),
'user' => array( 'LEFT JOIN', 'sale_user != 0 AND sale_user = user_id' ),
),
'options' => array(),
'conds' => array(),
);
if ( $this->channel === null ) {
// No channel!
$info['fields'][] = 'salc_name';
$info['fields'][] = 'salc_code';
} else {
// Has a channel, filter by it
$info['conds'][] = 'sale_channel = ' . intval( $this->channel );
}
return $info;
}
/**
* Precache the user links
*/
protected function doBatchLookups() {
parent::doBatchLookups();
$this->mResult->rewind();
$batch = new LinkBatch();
foreach ( $this->mResult as $row ) {
if ( $row->sale_user != 0 ) {
$batch->addObj( Title::makeTitleSafe( NS_USER, $row->user_name ) );
}
}
$batch->execute();
$this->mResult->rewind();
}
/**
* This function should be overridden to return the name of the index fi-
* eld. If the pager supports multiple orders, it may return an array of
* 'querykey' => 'indexfield' pairs, so that a request with &count=querykey
* will use indexfield to sort. In this case, the first returned key is
* the default.
*
* Needless to say, it's really not a good idea to use a non-unique index
* for this! That won't page right.
*
* @return string|Array
*/
function getIndexField() {
return 'sale_id';
}
/**
* Sets the channel to filter
*
* @param int $channel
*/
public function setChannel( $channel ) {
$this->channel = $channel;
}
}
|
SuriyaaKudoIsc/wikia-app-test
|
extensions/ServerAdminLog/ServerAdminLogEntryPager.php
|
PHP
|
gpl-2.0
| 4,054 |
require 'nuggets/array/flush_mixin'
class Array
include Nuggets::Array::FlushMixin
end
|
AndriyTsok/atsok.net
|
vendor/bundle/ruby/2.4.0/gems/nuggets-1.0.0/lib/nuggets/array/flush.rb
|
Ruby
|
gpl-2.0
| 90 |
/******************************************************************************
*
* Copyright(c) 2009-2010 Realtek Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License 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, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <[email protected]>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <[email protected]>
*
*****************************************************************************/
#include "wifi.h"
#include "core.h"
#include "cam.h"
#include "base.h"
#include "ps.h"
#include "btcoexist/rtl_btc.h"
/*mutex for start & stop is must here. */
static int rtl_op_start(struct ieee80211_hw *hw)
{
int err = 0;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
if (!is_hal_stop(rtlhal))
return 0;
if (!test_bit(RTL_STATUS_INTERFACE_START, &rtlpriv->status))
return 0;
mutex_lock(&rtlpriv->locks.conf_mutex);
err = rtlpriv->intf_ops->adapter_start(hw);
if (err)
goto out;
rtl_watch_dog_timer_callback((unsigned long)hw);
out:
mutex_unlock(&rtlpriv->locks.conf_mutex);
return err;
}
static void rtl_op_stop(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
if (is_hal_stop(rtlhal))
return;
/* here is must, because adhoc do stop and start,
* but stop with RFOFF may cause something wrong,
* like adhoc TP */
if (unlikely(ppsc->rfpwr_state == ERFOFF))
rtl_ips_nic_on(hw);
mutex_lock(&rtlpriv->locks.conf_mutex);
mac->link_state = MAC80211_NOLINK;
memset(mac->bssid, 0, 6);
mac->vendor = PEER_UNKNOWN;
/*reset sec info */
rtl_cam_reset_sec_info(hw);
rtl_deinit_deferred_work(hw);
rtlpriv->intf_ops->adapter_stop(hw);
mutex_unlock(&rtlpriv->locks.conf_mutex);
}
static void rtl_op_tx(struct ieee80211_hw *hw,
struct ieee80211_tx_control *control,
struct sk_buff *skb)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
struct rtl_tcb_desc tcb_desc;
memset(&tcb_desc, 0, sizeof(struct rtl_tcb_desc));
if (unlikely(is_hal_stop(rtlhal) || ppsc->rfpwr_state != ERFON))
goto err_free;
if (!test_bit(RTL_STATUS_INTERFACE_START, &rtlpriv->status))
goto err_free;
if (!rtlpriv->intf_ops->waitq_insert(hw, control->sta, skb))
rtlpriv->intf_ops->adapter_tx(hw, control->sta, skb, &tcb_desc);
return;
err_free:
dev_kfree_skb_any(skb);
return;
}
static int rtl_op_add_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
int err = 0;
if (mac->vif) {
RT_TRACE(COMP_ERR, DBG_WARNING,
("vif has been set!! mac->vif = 0x%p\n", mac->vif));
return -EOPNOTSUPP;
}
vif->driver_flags |= IEEE80211_VIF_BEACON_FILTER;
rtl_ips_nic_on(hw);
mutex_lock(&rtlpriv->locks.conf_mutex);
switch (ieee80211_vif_type_p2p(vif)) {
case NL80211_IFTYPE_P2P_CLIENT:
mac->p2p = P2P_ROLE_CLIENT;
/*fall through*/
case NL80211_IFTYPE_STATION:
if (mac->beacon_enabled == 1) {
RT_TRACE(COMP_MAC80211, DBG_LOUD,
("NL80211_IFTYPE_STATION \n"));
mac->beacon_enabled = 0;
rtlpriv->cfg->ops->update_interrupt_mask(hw, 0,
rtlpriv->cfg->maps[RTL_IBSS_INT_MASKS]);
}
break;
case NL80211_IFTYPE_ADHOC:
RT_TRACE(COMP_MAC80211, DBG_LOUD,
("NL80211_IFTYPE_ADHOC \n"));
mac->link_state = MAC80211_LINKED;
rtlpriv->cfg->ops->set_bcn_reg(hw);
if (rtlpriv->rtlhal.current_bandtype == BAND_ON_2_4G)
mac->basic_rates = 0xfff;
else
mac->basic_rates = 0xff0;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_BASIC_RATE,
(u8 *) (&mac->basic_rates));
break;
case NL80211_IFTYPE_P2P_GO:
mac->p2p = P2P_ROLE_GO;
/*fall through*/
case NL80211_IFTYPE_AP:
RT_TRACE(COMP_MAC80211, DBG_LOUD,
("NL80211_IFTYPE_AP \n"));
mac->link_state = MAC80211_LINKED;
rtlpriv->cfg->ops->set_bcn_reg(hw);
if (rtlpriv->rtlhal.current_bandtype == BAND_ON_2_4G)
mac->basic_rates = 0xfff;
else
mac->basic_rates = 0xff0;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_BASIC_RATE,
(u8 *) (&mac->basic_rates));
break;
case NL80211_IFTYPE_MESH_POINT:
RT_TRACE(COMP_MAC80211, DBG_LOUD,
("NL80211_IFTYPE_MESH_POINT \n"));
mac->link_state = MAC80211_LINKED;
rtlpriv->cfg->ops->set_bcn_reg(hw);
if (rtlpriv->rtlhal.current_bandtype == BAND_ON_2_4G)
mac->basic_rates = 0xfff;
else
mac->basic_rates = 0xff0;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_BASIC_RATE,
(u8 *) (&mac->basic_rates));
break;
default:
RT_TRACE(COMP_ERR, DBG_EMERG,
("operation mode %d is not support!\n", vif->type));
err = -EOPNOTSUPP;
goto out;
}
#ifdef VIF_TODO
if (!rtl_set_vif_info(hw, vif))
goto out;
#endif
if (mac->p2p) {
RT_TRACE(COMP_MAC80211, DBG_LOUD,
("p2p role %x \n",vif->type));
mac->basic_rates = 0xff0;/*disable cck rate for p2p*/
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_BASIC_RATE,
(u8 *) (&mac->basic_rates));
}
mac->vif = vif;
mac->opmode = vif->type;
rtlpriv->cfg->ops->set_network_type(hw, vif->type);
memcpy(mac->mac_addr, vif->addr, ETH_ALEN);
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_ETHER_ADDR, mac->mac_addr);
out:
mutex_unlock(&rtlpriv->locks.conf_mutex);
return err;
}
static void rtl_op_remove_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
mutex_lock(&rtlpriv->locks.conf_mutex);
/* Free beacon resources */
if ((vif->type == NL80211_IFTYPE_AP) ||
(vif->type == NL80211_IFTYPE_ADHOC) ||
(vif->type == NL80211_IFTYPE_MESH_POINT)) {
if (mac->beacon_enabled == 1) {
mac->beacon_enabled = 0;
rtlpriv->cfg->ops->update_interrupt_mask(hw, 0,
rtlpriv->cfg->maps[RTL_IBSS_INT_MASKS]);
}
}
/*
*Note: We assume NL80211_IFTYPE_UNSPECIFIED as
*NO LINK for our hardware.
*/
mac->p2p = 0;
mac->vif = NULL;
mac->link_state = MAC80211_NOLINK;
memset(mac->bssid, 0, 6);
mac->vendor = PEER_UNKNOWN;
mac->opmode = NL80211_IFTYPE_UNSPECIFIED;
rtlpriv->cfg->ops->set_network_type(hw, mac->opmode);
mutex_unlock(&rtlpriv->locks.conf_mutex);
}
static int rtl_op_change_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
enum nl80211_iftype new_type, bool p2p)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
int ret;
rtl_op_remove_interface(hw, vif);
vif->type = new_type;
vif->p2p = p2p;
ret = rtl_op_add_interface(hw, vif);
RT_TRACE(COMP_MAC80211, DBG_LOUD,
(" p2p %x\n",p2p));
return ret;
}
static int rtl_op_config(struct ieee80211_hw *hw, u32 changed)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
struct ieee80211_conf *conf = &hw->conf;
if (mac->skip_scan)
return 1;
mutex_lock(&rtlpriv->locks.conf_mutex);
if (changed & IEEE80211_CONF_CHANGE_LISTEN_INTERVAL) { /* BIT(2) */
RT_TRACE(COMP_MAC80211, DBG_LOUD,
("IEEE80211_CONF_CHANGE_LISTEN_INTERVAL\n"));
}
/*For IPS */
if (changed & IEEE80211_CONF_CHANGE_IDLE) {
if (hw->conf.flags & IEEE80211_CONF_IDLE)
rtl_ips_nic_off(hw);
else
rtl_ips_nic_on(hw);
} else {
/*
*although rfoff may not cause by ips, but we will
*check the reason in set_rf_power_state function
*/
if (unlikely(ppsc->rfpwr_state == ERFOFF))
rtl_ips_nic_on(hw);
}
/*For LPS */
if (changed & IEEE80211_CONF_CHANGE_PS) {
cancel_delayed_work(&rtlpriv->works.ps_work);
cancel_delayed_work(&rtlpriv->works.ps_rfon_wq);
if (conf->flags & IEEE80211_CONF_PS) {
rtlpriv->psc.sw_ps_enabled = true;
/* sleep here is must, or we may recv the beacon and
* cause mac80211 into wrong ps state, this will cause
* power save nullfunc send fail, and further cause
* pkt loss, So sleep must quickly but not immediately
* because that will cause nullfunc send by mac80211
* fail, and cause pkt loss, we have tested that 5mA
* is worked very well */
if (!rtlpriv->psc.multi_buffered)
queue_delayed_work(rtlpriv->works.rtl_wq,
&rtlpriv->works.ps_work,
MSECS(5));
} else {
rtl_swlps_rf_awake(hw);
rtlpriv->psc.sw_ps_enabled = false;
}
}
if (changed & IEEE80211_CONF_CHANGE_RETRY_LIMITS) {
RT_TRACE(COMP_MAC80211, DBG_LOUD,
("IEEE80211_CONF_CHANGE_RETRY_LIMITS %x\n",
hw->conf.long_frame_max_tx_count));
mac->retry_long = hw->conf.long_frame_max_tx_count;
mac->retry_short = hw->conf.long_frame_max_tx_count;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_RETRY_LIMIT,
(u8 *) (&hw->conf.long_frame_max_tx_count));
}
if (changed & IEEE80211_CONF_CHANGE_CHANNEL) {
struct ieee80211_channel *channel = hw->conf.chandef.chan;
enum nl80211_channel_type channel_type =
cfg80211_get_chandef_type(&(hw->conf.chandef));
u8 wide_chan = (u8) channel->hw_value;
if (mac->act_scanning)
mac->n_channels++;
if (rtlpriv->dm.supp_phymode_switch &&
mac->link_state < MAC80211_LINKED &&
!mac->act_scanning) {
if (rtlpriv->cfg->ops->check_switch_to_dmdp)
rtlpriv->cfg->ops->check_switch_to_dmdp(hw);
}
/*
*because we should back channel to
*current_network.chan in in scanning,
*So if set_chan == current_network.chan
*we should set it.
*because mac80211 tell us wrong bw40
*info for cisco1253 bw20, so we modify
*it here based on UPPER & LOWER
*/
switch (channel_type) {
case NL80211_CHAN_HT20:
case NL80211_CHAN_NO_HT:
/* SC */
mac->cur_40_prime_sc =
PRIME_CHNL_OFFSET_DONT_CARE;
rtlphy->current_chan_bw = HT_CHANNEL_WIDTH_20;
mac->bw_40 = false;
break;
case NL80211_CHAN_HT40MINUS:
/* SC */
mac->cur_40_prime_sc = PRIME_CHNL_OFFSET_UPPER;
rtlphy->current_chan_bw =
HT_CHANNEL_WIDTH_20_40;
mac->bw_40 = true;
/*wide channel */
wide_chan -= 2;
break;
case NL80211_CHAN_HT40PLUS:
/* SC */
mac->cur_40_prime_sc = PRIME_CHNL_OFFSET_LOWER;
rtlphy->current_chan_bw =
HT_CHANNEL_WIDTH_20_40;
mac->bw_40 = true;
/*wide channel */
wide_chan += 2;
break;
default:
mac->bw_40 = false;
RT_TRACE(COMP_ERR, DBG_EMERG,
("switch case not processed \n"));
break;
}
if (wide_chan <= 0)
wide_chan = 1;
/* in scanning, when before we offchannel we may send a ps=1
* null to AP, and then we may send a ps = 0 null to AP quickly,
* but first null have cause AP's put lots of packet to hw tx
* buffer, these packet must be tx before off channel so we must
* delay more time to let AP flush these packets before
* offchannel, or dis-association or delete BA will happen by AP
*/
if (rtlpriv->mac80211.offchan_deley) {
rtlpriv->mac80211.offchan_deley = false;
mdelay(50);
}
rtlphy->current_channel = wide_chan;
rtlpriv->cfg->ops->switch_channel(hw);
rtlpriv->cfg->ops->set_channel_access(hw);
rtlpriv->cfg->ops->set_bw_mode(hw,
channel_type);
}
mutex_unlock(&rtlpriv->locks.conf_mutex);
return 0;
}
static void rtl_op_configure_filter(struct ieee80211_hw *hw,
unsigned int changed_flags,
unsigned int *new_flags, u64 multicast)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
*new_flags &= RTL_SUPPORTED_FILTERS;
if (0 == changed_flags)
return;
/*TODO: we disable broadcase now, so enable here */
if (changed_flags & FIF_ALLMULTI) {
if (*new_flags & FIF_ALLMULTI) {
mac->rx_conf |= rtlpriv->cfg->maps[MAC_RCR_AM] |
rtlpriv->cfg->maps[MAC_RCR_AB];
RT_TRACE(COMP_MAC80211, DBG_LOUD,
("Enable receive multicast frame.\n"));
} else {
mac->rx_conf &= ~(rtlpriv->cfg->maps[MAC_RCR_AM] |
rtlpriv->cfg->maps[MAC_RCR_AB]);
RT_TRACE(COMP_MAC80211, DBG_LOUD,
("Disable receive multicast frame.\n"));
}
}
if (changed_flags & FIF_FCSFAIL) {
if (*new_flags & FIF_FCSFAIL) {
mac->rx_conf |= rtlpriv->cfg->maps[MAC_RCR_ACRC32];
RT_TRACE(COMP_MAC80211, DBG_LOUD,
("Enable receive FCS error frame.\n"));
} else {
mac->rx_conf &= ~rtlpriv->cfg->maps[MAC_RCR_ACRC32];
RT_TRACE(COMP_MAC80211, DBG_LOUD,
("Disable receive FCS error frame.\n"));
}
}
/* if ssid not set to hw don't check bssid
* here just used for linked scanning, & linked
* and nolink check bssid is set in set network_type */
if ((changed_flags & FIF_BCN_PRBRESP_PROMISC) &&
(mac->link_state >= MAC80211_LINKED)) {
if (mac->opmode != NL80211_IFTYPE_AP &&
mac->opmode != NL80211_IFTYPE_MESH_POINT) {
if (*new_flags & FIF_BCN_PRBRESP_PROMISC) {
rtlpriv->cfg->ops->set_chk_bssid(hw, false);
} else {
rtlpriv->cfg->ops->set_chk_bssid(hw, true);
}
}
}
if (changed_flags & FIF_CONTROL) {
if (*new_flags & FIF_CONTROL) {
mac->rx_conf |= rtlpriv->cfg->maps[MAC_RCR_ACF];
RT_TRACE(COMP_MAC80211, DBG_LOUD,
("Enable receive control frame.\n"));
} else {
mac->rx_conf &= ~rtlpriv->cfg->maps[MAC_RCR_ACF];
RT_TRACE(COMP_MAC80211, DBG_LOUD,
("Disable receive control frame.\n"));
}
}
if (changed_flags & FIF_OTHER_BSS) {
if (*new_flags & FIF_OTHER_BSS) {
mac->rx_conf |= rtlpriv->cfg->maps[MAC_RCR_AAP];
RT_TRACE(COMP_MAC80211, DBG_LOUD,
("Enable receive other BSS's frame.\n"));
} else {
mac->rx_conf &= ~rtlpriv->cfg->maps[MAC_RCR_AAP];
RT_TRACE(COMP_MAC80211, DBG_LOUD,
("Disable receive other BSS's frame.\n"));
}
}
}
static int rtl_op_sta_add(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal= rtl_hal(rtl_priv(hw));
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_sta_info *sta_entry;
if (sta) {
sta_entry = (struct rtl_sta_info *) sta->drv_priv;
spin_lock_bh(&rtlpriv->locks.entry_list_lock);
list_add_tail(&sta_entry->list, &rtlpriv->entry_list);
spin_unlock_bh(&rtlpriv->locks.entry_list_lock);
if (rtlhal->current_bandtype == BAND_ON_2_4G) {
sta_entry->wireless_mode = WIRELESS_MODE_G;
if (sta->supp_rates[0] <= 0xf)
sta_entry->wireless_mode = WIRELESS_MODE_B;
if (sta->ht_cap.ht_supported == true)
sta_entry->wireless_mode = WIRELESS_MODE_N_24G;
if (vif->type == NL80211_IFTYPE_ADHOC)
sta_entry->wireless_mode = WIRELESS_MODE_G;
} else if (rtlhal->current_bandtype == BAND_ON_5G) {
sta_entry->wireless_mode = WIRELESS_MODE_A;
if (sta->ht_cap.ht_supported == true)
sta_entry->wireless_mode = WIRELESS_MODE_N_24G;
if (vif->type == NL80211_IFTYPE_ADHOC)
sta_entry->wireless_mode = WIRELESS_MODE_A;
}
/*disable cck rate for p2p*/
if (mac->p2p)
sta->supp_rates[0] &= 0xfffffff0;
memcpy(sta_entry->mac_addr, sta->addr, ETH_ALEN);
RT_TRACE(COMP_MAC80211, DBG_DMESG,
("Add sta addr is %pM\n",sta->addr));
rtlpriv->cfg->ops->update_rate_tbl(hw, sta, 0);
}
return 0;
}
static int rtl_op_sta_remove(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_sta_info *sta_entry;
if (sta) {
RT_TRACE(COMP_MAC80211, DBG_DMESG,
("Remove sta addr is %pM\n",sta->addr));
sta_entry = (struct rtl_sta_info *) sta->drv_priv;
sta_entry->wireless_mode = 0;
sta_entry->ratr_index = 0;
spin_lock_bh(&rtlpriv->locks.entry_list_lock);
list_del(&sta_entry->list);
spin_unlock_bh(&rtlpriv->locks.entry_list_lock);
}
return 0;
}
static int _rtl_get_hal_qnum(u16 queue)
{
int qnum;
switch (queue) {
case 0:
qnum = AC3_VO;
break;
case 1:
qnum = AC2_VI;
break;
case 2:
qnum = AC0_BE;
break;
case 3:
qnum = AC1_BK;
break;
default:
qnum = AC0_BE;
break;
}
return qnum;
}
/*
*for mac80211 VO=0, VI=1, BE=2, BK=3
*for rtl819x BE=0, BK=1, VI=2, VO=3
*/
static int rtl_op_conf_tx(struct ieee80211_hw *hw,
struct ieee80211_vif *vif, u16 queue,
const struct ieee80211_tx_queue_params *param)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
int aci;
if (queue >= AC_MAX) {
RT_TRACE(COMP_ERR, DBG_WARNING,
("queue number %d is incorrect!\n", queue));
return -EINVAL;
}
aci = _rtl_get_hal_qnum(queue);
mac->ac[aci].aifs = param->aifs;
mac->ac[aci].cw_min = param->cw_min;
mac->ac[aci].cw_max = param->cw_max;
mac->ac[aci].tx_op = param->txop;
memcpy(&mac->edca_param[aci], param, sizeof(*param));
rtlpriv->cfg->ops->set_qos(hw, aci);
return 0;
}
static void rtl_op_bss_info_changed(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *bss_conf,
u32 changed)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtlpriv);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
mutex_lock(&rtlpriv->locks.conf_mutex);
if ((vif->type == NL80211_IFTYPE_ADHOC) ||
(vif->type == NL80211_IFTYPE_AP) ||
(vif->type == NL80211_IFTYPE_MESH_POINT)) {
if ((changed & BSS_CHANGED_BEACON) ||
(changed & BSS_CHANGED_BEACON_ENABLED &&
bss_conf->enable_beacon)) {
if (mac->beacon_enabled == 0) {
RT_TRACE(COMP_MAC80211, DBG_DMESG,
("BSS_CHANGED_BEACON_ENABLED \n"));
/*start hw beacon interrupt. */
/*rtlpriv->cfg->ops->set_bcn_reg(hw); */
mac->beacon_enabled = 1;
rtlpriv->cfg->ops->update_interrupt_mask(hw,
rtlpriv->cfg->maps
[RTL_IBSS_INT_MASKS], 0);
if (rtlpriv->cfg->ops->linked_set_reg)
rtlpriv->cfg->ops->linked_set_reg(hw);
}
}
if ((changed & BSS_CHANGED_BEACON_ENABLED &&
!bss_conf->enable_beacon)){
if (mac->beacon_enabled == 1) {
RT_TRACE(COMP_MAC80211, DBG_DMESG,
("ADHOC DISABLE BEACON\n"));
mac->beacon_enabled = 0;
rtlpriv->cfg->ops->update_interrupt_mask(hw, 0,
rtlpriv->cfg->maps
[RTL_IBSS_INT_MASKS]);
}
}
if (changed & BSS_CHANGED_BEACON_INT) {
RT_TRACE(COMP_BEACON, DBG_TRACE,
("BSS_CHANGED_BEACON_INT\n"));
mac->beacon_interval = bss_conf->beacon_int;
rtlpriv->cfg->ops->set_bcn_intv(hw);
}
}
/*TODO: reference to enum ieee80211_bss_change */
if (changed & BSS_CHANGED_ASSOC) {
if (bss_conf->assoc) {
struct ieee80211_sta *sta = NULL;
/* we should reset all sec info & cam
* before set cam after linked, we should not
* reset in disassoc, that will cause tkip->wep
* fail because some flag will be wrong */
/* reset sec info */
rtl_cam_reset_sec_info(hw);
/* reset cam to fix wep fail issue
* when change from wpa to wep */
rtl_cam_reset_all_entry(hw);
mac->link_state = MAC80211_LINKED;
mac->cnt_after_linked = 0;
mac->assoc_id = bss_conf->aid;
memcpy(mac->bssid, bss_conf->bssid, 6);
if (rtlpriv->cfg->ops->linked_set_reg)
rtlpriv->cfg->ops->linked_set_reg(hw);
rcu_read_lock();
sta = ieee80211_find_sta(vif, (u8*)bss_conf->bssid);
if (vif->type == NL80211_IFTYPE_STATION && sta)
rtlpriv->cfg->ops->update_rate_tbl(hw, sta, 0);
RT_TRACE(COMP_EASY_CONCURRENT, DBG_LOUD,
("send PS STATIC frame \n"));
if (rtlpriv->dm.supp_phymode_switch) {
if (sta->ht_cap.ht_supported)
rtl_send_smps_action(hw, sta,
IEEE80211_SMPS_STATIC);
}
rcu_read_unlock();
RT_TRACE(COMP_MAC80211, DBG_DMESG,
("BSS_CHANGED_ASSOC\n"));
} else {
if (mac->link_state == MAC80211_LINKED)
rtl_lps_leave(hw);
if (ppsc->p2p_ps_info.p2p_ps_mode> P2P_PS_NONE)
rtl_p2p_ps_cmd(hw, P2P_PS_DISABLE);
mac->link_state = MAC80211_NOLINK;
memset(mac->bssid, 0, 6);
mac->vendor = PEER_UNKNOWN;
if (rtlpriv->dm.supp_phymode_switch) {
if (rtlpriv->cfg->ops->check_switch_to_dmdp)
rtlpriv->cfg->ops->check_switch_to_dmdp(hw);
}
RT_TRACE(COMP_MAC80211, DBG_DMESG,
("BSS_CHANGED_UN_ASSOC\n"));
}
}
if (changed & BSS_CHANGED_ERP_CTS_PROT) {
RT_TRACE(COMP_MAC80211, DBG_TRACE,
("BSS_CHANGED_ERP_CTS_PROT\n"));
mac->use_cts_protect = bss_conf->use_cts_prot;
}
if (changed & BSS_CHANGED_ERP_PREAMBLE) {
RT_TRACE(COMP_MAC80211, DBG_LOUD,
("BSS_CHANGED_ERP_PREAMBLE use short preamble:%x \n",
bss_conf->use_short_preamble));
mac->short_preamble = bss_conf->use_short_preamble;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_ACK_PREAMBLE,
(u8 *) (&mac->short_preamble));
}
if (changed & BSS_CHANGED_ERP_SLOT) {
RT_TRACE(COMP_MAC80211, DBG_TRACE,
("BSS_CHANGED_ERP_SLOT\n"));
if (bss_conf->use_short_slot)
mac->slot_time = RTL_SLOT_TIME_9;
else
mac->slot_time = RTL_SLOT_TIME_20;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_SLOT_TIME,
(u8 *) (&mac->slot_time));
}
if (changed & BSS_CHANGED_HT) {
struct ieee80211_sta *sta = NULL;
RT_TRACE(COMP_MAC80211, DBG_TRACE,
("BSS_CHANGED_HT\n"));
rcu_read_lock();
sta = ieee80211_find_sta(vif, (u8*)bss_conf->bssid);
if (sta) {
if (sta->ht_cap.ampdu_density >
mac->current_ampdu_density)
mac->current_ampdu_density =
sta->ht_cap.ampdu_density;
if (sta->ht_cap.ampdu_factor <
mac->current_ampdu_factor)
mac->current_ampdu_factor =
sta->ht_cap.ampdu_factor;
}
rcu_read_unlock();
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_SHORTGI_DENSITY,
(u8 *) (&mac->max_mss_density));
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_AMPDU_FACTOR,
&mac->current_ampdu_factor);
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_AMPDU_MIN_SPACE,
&mac->current_ampdu_density);
}
if (changed & BSS_CHANGED_BSSID) {
u32 basic_rates;
struct ieee80211_sta *sta = NULL;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_BSSID,
(u8 *) bss_conf->bssid);
RT_TRACE(COMP_MAC80211, DBG_DMESG,
("bssid: %pM\n", bss_conf->bssid));
mac->vendor = PEER_UNKNOWN;
memcpy(mac->bssid, bss_conf->bssid, 6);
rtlpriv->cfg->ops->set_network_type(hw, vif->type);
rcu_read_lock();
sta = ieee80211_find_sta(vif, (u8*)bss_conf->bssid);
if (!sta) {
rcu_read_unlock();
goto out;
}
if (rtlhal->current_bandtype == BAND_ON_5G) {
mac->mode = WIRELESS_MODE_A;
} else {
if (sta->supp_rates[0] <= 0xf)
mac->mode = WIRELESS_MODE_B;
else
mac->mode = WIRELESS_MODE_G;
}
if (sta->ht_cap.ht_supported) {
if (rtlhal->current_bandtype == BAND_ON_2_4G)
mac->mode = WIRELESS_MODE_N_24G;
else
mac->mode = WIRELESS_MODE_N_5G;
}
/* just station need it, because ibss & ap mode will
* set in sta_add, and will be NULL here */
if (vif->type == NL80211_IFTYPE_STATION) {
struct rtl_sta_info *sta_entry;
sta_entry = (struct rtl_sta_info *) sta->drv_priv;
sta_entry->wireless_mode = mac->mode;
}
if (sta->ht_cap.ht_supported) {
mac->ht_enable = true;
/*
* for cisco 1252 bw20 it's wrong
* if (ht_cap & IEEE80211_HT_CAP_SUP_WIDTH_20_40) {
* mac->bw_40 = true;
* }
* */
}
if (changed & BSS_CHANGED_BASIC_RATES) {
/* for 5G must << RATE_6M_INDEX=4,
* because 5G have no cck rate*/
if (rtlhal->current_bandtype == BAND_ON_5G)
basic_rates = sta->supp_rates[1] << 4;
else
basic_rates = sta->supp_rates[0];
mac->basic_rates = basic_rates;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_BASIC_RATE,
(u8 *) (&basic_rates));
}
rcu_read_unlock();
}
/*
* For FW LPS and Keep Alive:
* To tell firmware we have connected
* to an AP. For 92SE/CE power save v2.
*/
if (changed & BSS_CHANGED_ASSOC) {
if (bss_conf->assoc) {
u8 keep_alive = 10;
u8 mstatus = RT_MEDIA_CONNECT;
rtlpriv->cfg->ops->set_hw_reg(hw,
HW_VAR_KEEP_ALIVE,
(u8 *) (&keep_alive));
rtlpriv->cfg->ops->set_hw_reg(hw,
HW_VAR_H2C_FW_JOINBSSRPT,
(u8 *) (&mstatus));
ppsc->report_linked = true;
} else {
u8 mstatus = RT_MEDIA_DISCONNECT;
rtlpriv->cfg->ops->set_hw_reg(hw,
HW_VAR_H2C_FW_JOINBSSRPT,
(u8 *) (&mstatus));
ppsc->report_linked = false;
}
if (rtlpriv->cfg->ops->get_btc_status()){
rtlpriv->btcoexist.btc_ops->btc_mediastatus_notify(
rtlpriv, ppsc->report_linked);
}
}
out:
mutex_unlock(&rtlpriv->locks.conf_mutex);
}
static u64 rtl_op_get_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u64 tsf;
rtlpriv->cfg->ops->get_hw_reg(hw, HW_VAR_CORRECT_TSF, (u8 *) (&tsf));
return tsf;
}
static void rtl_op_set_tsf(struct ieee80211_hw *hw,
struct ieee80211_vif *vif, u64 tsf)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
u8 bibss = (mac->opmode == NL80211_IFTYPE_ADHOC) ? 1 : 0;
mac->tsf = tsf;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_CORRECT_TSF, (u8 *) (&bibss));
}
static void rtl_op_reset_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u8 tmp = 0;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_DUAL_TSF_RST, (u8 *) (&tmp));
}
static void rtl_op_sta_notify(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
enum sta_notify_cmd cmd,
struct ieee80211_sta *sta)
{
switch (cmd) {
case STA_NOTIFY_SLEEP:
break;
case STA_NOTIFY_AWAKE:
break;
default:
break;
}
}
static int rtl_op_ampdu_action(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
enum ieee80211_ampdu_mlme_action action,
struct ieee80211_sta *sta, u16 tid, u16 * ssn
,u8 buf_size
)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
switch (action) {
case IEEE80211_AMPDU_TX_START:
RT_TRACE(COMP_MAC80211, DBG_TRACE,
("IEEE80211_AMPDU_TX_START: TID:%d\n", tid));
return rtl_tx_agg_start(hw, vif, sta, tid, ssn);
break;
case IEEE80211_AMPDU_TX_STOP_CONT:
case IEEE80211_AMPDU_TX_STOP_FLUSH:
case IEEE80211_AMPDU_TX_STOP_FLUSH_CONT:
RT_TRACE(COMP_MAC80211, DBG_TRACE,
("IEEE80211_AMPDU_TX_STOP: TID:%d\n", tid));
return rtl_tx_agg_stop(hw, vif, sta, tid);
break;
case IEEE80211_AMPDU_TX_OPERATIONAL:
RT_TRACE(COMP_MAC80211, DBG_TRACE,
("IEEE80211_AMPDU_TX_OPERATIONAL:TID:%d\n", tid));
rtl_tx_agg_oper(hw, sta, tid);
break;
case IEEE80211_AMPDU_RX_START:
RT_TRACE(COMP_MAC80211, DBG_TRACE,
("IEEE80211_AMPDU_RX_START:TID:%d\n", tid));
return rtl_rx_agg_start(hw, sta, tid);
break;
case IEEE80211_AMPDU_RX_STOP:
RT_TRACE(COMP_MAC80211, DBG_TRACE,
("IEEE80211_AMPDU_RX_STOP:TID:%d\n", tid));
return rtl_rx_agg_stop(hw, sta, tid);
break;
default:
RT_TRACE(COMP_ERR, DBG_EMERG,
("IEEE80211_AMPDU_ERR!!!!:\n"));
return -EOPNOTSUPP;
}
return 0;
}
static void rtl_op_sw_scan_start(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
RT_TRACE(COMP_MAC80211, DBG_LOUD, ("\n"));
mac->act_scanning = true;
/*rtlpriv->btcops->btc_scan_notify(rtlpriv, 0); */
if (rtlpriv->link_info.b_higher_busytraffic) {
mac->skip_scan = true;
return;
}
if (rtlpriv->dm.supp_phymode_switch) {
if (rtlpriv->cfg->ops->check_switch_to_dmdp)
rtlpriv->cfg->ops->check_switch_to_dmdp(hw);
}
if (mac->link_state == MAC80211_LINKED) {
rtl_lps_leave(hw);
mac->link_state = MAC80211_LINKED_SCANNING;
} else {
rtl_ips_nic_on(hw);
}
/* Dul mac */
rtlpriv->rtlhal.b_load_imrandiqk_setting_for2g = false;
rtlpriv->cfg->ops->led_control(hw, LED_CTL_SITE_SURVEY);
rtlpriv->cfg->ops->scan_operation_backup(hw, SCAN_OPT_BACKUP_BAND0);
}
static void rtl_op_sw_scan_complete(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
RT_TRACE(COMP_MAC80211, DBG_LOUD, ("\n"));
mac->act_scanning = false;
mac->skip_scan = false;
if (rtlpriv->link_info.b_higher_busytraffic) {
return;
}
/* p2p will use 1/6/11 to scan */
if (mac->n_channels == 3)
mac->p2p_in_use = true;
else
mac->p2p_in_use = false;
mac->n_channels = 0;
/* Dul mac */
rtlpriv->rtlhal.b_load_imrandiqk_setting_for2g = false;
if (mac->link_state == MAC80211_LINKED_SCANNING) {
mac->link_state = MAC80211_LINKED;
if (mac->opmode == NL80211_IFTYPE_STATION) {
/* fix fwlps issue */
rtlpriv->cfg->ops->set_network_type(hw, mac->opmode);
}
}
rtlpriv->cfg->ops->scan_operation_backup(hw, SCAN_OPT_RESTORE);
/* rtlpriv->btcops->btc_scan_notify(rtlpriv, 1); */
}
static int rtl_op_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
struct ieee80211_vif *vif, struct ieee80211_sta *sta,
struct ieee80211_key_conf *key)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u8 key_type = NO_ENCRYPTION;
u8 key_idx;
bool group_key = false;
bool wep_only = false;
int err = 0;
u8 mac_addr[ETH_ALEN];
u8 bcast_addr[ETH_ALEN] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
u8 zero_addr[ETH_ALEN] = { 0 };
if (rtlpriv->cfg->mod_params->sw_crypto || rtlpriv->sec.use_sw_sec) {
RT_TRACE(COMP_ERR, DBG_WARNING,
("not open hw encryption\n"));
return -ENOSPC; /*User disabled HW-crypto */
}
/* To support IBSS, use sw-crypto for GTK */
if(((vif->type == NL80211_IFTYPE_ADHOC) ||
(vif->type == NL80211_IFTYPE_MESH_POINT)) &&
!(key->flags & IEEE80211_KEY_FLAG_PAIRWISE))
return -ENOSPC;
RT_TRACE(COMP_SEC, DBG_DMESG,
("%s hardware based encryption for keyidx: %d, mac: %pM\n",
cmd == SET_KEY ? "Using" : "Disabling", key->keyidx,
sta ? sta->addr : bcast_addr));
rtlpriv->sec.being_setkey = true;
rtl_ips_nic_on(hw);
mutex_lock(&rtlpriv->locks.conf_mutex);
/* <1> get encryption alg */
switch (key->cipher) {
case WLAN_CIPHER_SUITE_WEP40:
key_type = WEP40_ENCRYPTION;
RT_TRACE(COMP_SEC, DBG_DMESG, ("alg:WEP40\n"));
break;
case WLAN_CIPHER_SUITE_WEP104:
RT_TRACE(COMP_SEC, DBG_DMESG, ("alg:WEP104\n"));
key_type = WEP104_ENCRYPTION;
break;
case WLAN_CIPHER_SUITE_TKIP:
key_type = TKIP_ENCRYPTION;
RT_TRACE(COMP_SEC, DBG_DMESG, ("alg:TKIP\n"));
break;
case WLAN_CIPHER_SUITE_CCMP:
key_type = AESCCMP_ENCRYPTION;
RT_TRACE(COMP_SEC, DBG_DMESG, ("alg:CCMP\n"));
break;
case WLAN_CIPHER_SUITE_AES_CMAC:
/* HW don't support CMAC encryption,
* use software CMAC encryption */
key_type = AESCMAC_ENCRYPTION;
RT_TRACE(COMP_SEC, DBG_DMESG, ("alg:CMAC\n"));
RT_TRACE(COMP_SEC, DBG_DMESG,
("HW don't support CMAC encryption, "
"use software CMAC encryption\n"));
err = -EOPNOTSUPP;
goto out_unlock;
default:
RT_TRACE(COMP_ERR, DBG_EMERG,
("alg_err:%x!!!!:\n", key->cipher));
goto out_unlock;
}
if(key_type == WEP40_ENCRYPTION ||
key_type == WEP104_ENCRYPTION ||
vif->type == NL80211_IFTYPE_ADHOC)
rtlpriv->sec.use_defaultkey = true;
/* <2> get key_idx */
key_idx = (u8) (key->keyidx);
if (key_idx > 3)
goto out_unlock;
/* <3> if pairwise key enable_hw_sec */
group_key = !(key->flags & IEEE80211_KEY_FLAG_PAIRWISE);
/* wep always be group key, but there are two conditions:
* 1) wep only: is just for wep enc, in this condition
* rtlpriv->sec.pairwise_enc_algorithm == NO_ENCRYPTION
* will be true & enable_hw_sec will be set when wep
* ke setting.
* 2) wep(group) + AES(pairwise): some AP like cisco
* may use it, in this condition enable_hw_sec will not
* be set when wep key setting */
/* we must reset sec_info after lingked before set key,
* or some flag will be wrong*/
if (vif->type == NL80211_IFTYPE_AP ||
vif->type == NL80211_IFTYPE_MESH_POINT) {
if (!group_key || key_type == WEP40_ENCRYPTION ||
key_type == WEP104_ENCRYPTION) {
if (group_key) {
wep_only = true;
}
rtlpriv->cfg->ops->enable_hw_sec(hw);
}
} else {
if ((!group_key) || (vif->type == NL80211_IFTYPE_ADHOC) ||
rtlpriv->sec.pairwise_enc_algorithm == NO_ENCRYPTION) {
if (rtlpriv->sec.pairwise_enc_algorithm ==
NO_ENCRYPTION &&
(key_type == WEP40_ENCRYPTION ||
key_type == WEP104_ENCRYPTION))
wep_only = true;
rtlpriv->sec.pairwise_enc_algorithm = key_type;
RT_TRACE(COMP_SEC, DBG_DMESG,
("set enable_hw_sec, key_type:%x(OPEN:0 WEP40:"
"1 TKIP:2 AES:4 WEP104:5)\n", key_type));
rtlpriv->cfg->ops->enable_hw_sec(hw);
}
}
/* <4> set key based on cmd */
switch (cmd) {
case SET_KEY:
if (wep_only) {
RT_TRACE(COMP_SEC, DBG_DMESG,
("set WEP(group/pairwise) key\n"));
/* Pairwise key with an assigned MAC address. */
rtlpriv->sec.pairwise_enc_algorithm = key_type;
rtlpriv->sec.group_enc_algorithm = key_type;
/*set local buf about wep key. */
memcpy(rtlpriv->sec.key_buf[key_idx],
key->key, key->keylen);
rtlpriv->sec.key_len[key_idx] = key->keylen;
memcpy(mac_addr, zero_addr, ETH_ALEN);
} else if (group_key) { /* group key */
RT_TRACE(COMP_SEC, DBG_DMESG,
("set group key\n"));
/* group key */
rtlpriv->sec.group_enc_algorithm = key_type;
/*set local buf about group key. */
memcpy(rtlpriv->sec.key_buf[key_idx],
key->key, key->keylen);
rtlpriv->sec.key_len[key_idx] = key->keylen;
memcpy(mac_addr, bcast_addr, ETH_ALEN);
} else { /* pairwise key */
RT_TRACE(COMP_SEC, DBG_DMESG,
("set pairwise key\n"));
if (!sta) {
RT_ASSERT(false, ("pairwise key withnot"
"mac_addr\n"));
err = -EOPNOTSUPP;
goto out_unlock;
}
/* Pairwise key with an assigned MAC address. */
rtlpriv->sec.pairwise_enc_algorithm = key_type;
/*set local buf about pairwise key. */
memcpy(rtlpriv->sec.key_buf[PAIRWISE_KEYIDX],
key->key, key->keylen);
rtlpriv->sec.key_len[PAIRWISE_KEYIDX] = key->keylen;
rtlpriv->sec.pairwise_key =
rtlpriv->sec.key_buf[PAIRWISE_KEYIDX];
memcpy(mac_addr, sta->addr, ETH_ALEN);
}
rtlpriv->cfg->ops->set_key(hw, key_idx, mac_addr,
group_key, key_type, wep_only,
false);
/* <5> tell mac80211 do something: */
/*must use sw generate IV, or can not work !!!!. */
key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
key->hw_key_idx = key_idx;
if (key_type == TKIP_ENCRYPTION)
key->flags |= IEEE80211_KEY_FLAG_GENERATE_MMIC;
/*use software CCMP encryption for management frames (MFP) */
if (key_type == AESCCMP_ENCRYPTION)
key->flags |= IEEE80211_KEY_FLAG_SW_MGMT;
break;
case DISABLE_KEY:
RT_TRACE(COMP_SEC, DBG_DMESG,
("disable key delete one entry\n"));
/*set local buf about wep key. */
if (vif->type == NL80211_IFTYPE_AP ||
vif->type == NL80211_IFTYPE_MESH_POINT) {
if (sta)
rtl_cam_del_entry(hw, sta->addr);
}
memset(rtlpriv->sec.key_buf[key_idx], 0, key->keylen);
rtlpriv->sec.key_len[key_idx] = 0;
memcpy(mac_addr, zero_addr, ETH_ALEN);
/*
*mac80211 will delete entrys one by one,
*so don't use rtl_cam_reset_all_entry
*or clear all entry here.
*/
rtl_cam_delete_one_entry(hw, mac_addr, key_idx);
break;
default:
RT_TRACE(COMP_ERR, DBG_EMERG,
("cmd_err:%x!!!!:\n", cmd));
}
out_unlock:
mutex_unlock(&rtlpriv->locks.conf_mutex);
rtlpriv->sec.being_setkey = false;
return err;
}
static void rtl_op_rfkill_poll(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
bool radio_state;
bool blocked;
u8 valid = 0;
if (!test_bit(RTL_STATUS_INTERFACE_START, &rtlpriv->status))
return;
mutex_lock(&rtlpriv->locks.conf_mutex);
/*if Radio On return true here */
radio_state = rtlpriv->cfg->ops->radio_onoff_checking(hw, &valid);
if (valid) {
if (unlikely(radio_state != rtlpriv->rfkill.rfkill_state)) {
rtlpriv->rfkill.rfkill_state = radio_state;
RT_TRACE(COMP_RF, DBG_DMESG,
(KERN_INFO "wireless radio switch turned %s\n",
radio_state ? "on" : "off"));
blocked = (rtlpriv->rfkill.rfkill_state == 1) ? 0 : 1;
wiphy_rfkill_set_hw_state(hw->wiphy, blocked);
}
}
mutex_unlock(&rtlpriv->locks.conf_mutex);
}
/* this function is called by mac80211 to flush tx buffer
* before switch channel or power save, or tx buffer packet
* maybe send after offchannel or rf sleep, this may cause
* dis-association by AP */
static void rtl_op_flush(struct ieee80211_hw *hw, u32 queues, bool drop)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
if (rtlpriv->intf_ops->flush)
rtlpriv->intf_ops->flush(hw, queues, drop);
}
const struct ieee80211_ops rtl_ops = {
.start = rtl_op_start,
.stop = rtl_op_stop,
.tx = rtl_op_tx,
.add_interface = rtl_op_add_interface,
.remove_interface = rtl_op_remove_interface,
.change_interface = rtl_op_change_interface,
.config = rtl_op_config,
.configure_filter = rtl_op_configure_filter,
.set_key = rtl_op_set_key,
.conf_tx = rtl_op_conf_tx,
.bss_info_changed = rtl_op_bss_info_changed,
.get_tsf = rtl_op_get_tsf,
.set_tsf = rtl_op_set_tsf,
.reset_tsf = rtl_op_reset_tsf,
.sta_notify = rtl_op_sta_notify,
.ampdu_action = rtl_op_ampdu_action,
.sw_scan_start = rtl_op_sw_scan_start,
.sw_scan_complete = rtl_op_sw_scan_complete,
.rfkill_poll = rtl_op_rfkill_poll,
.sta_add = rtl_op_sta_add,
.sta_remove = rtl_op_sta_remove,
.flush = rtl_op_flush,
};
|
mambomark/linux-systemsim
|
drivers/staging/rtl8821ae/core.c
|
C
|
gpl-2.0
| 37,568 |
/*
* Copyright (c) 2009-2010 jMonkeyEngine
* 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 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.asset;
import java.io.InputStream;
/**
* The result of locating an asset through an AssetKey. Provides
* a means to read the asset data through an InputStream.
*
* @author Kirill Vainer
*/
public abstract class AssetInfo {
protected AssetManager manager;
protected AssetKey key;
public AssetInfo(AssetManager manager, AssetKey key) {
this.manager = manager;
this.key = key;
}
public AssetKey getKey() {
return key;
}
public AssetManager getManager() {
return manager;
}
@Override
public String toString(){
return getClass().getName() + "[" + "key=" + key + "]";
}
/**
* Implementations of this method should return an {@link InputStream}
* allowing access to the data represented by the {@link AssetKey}.
* <p>
* Each invocation of this method should return a new stream to the
* asset data, starting at the beginning of the file.
*
* @return The asset data.
*/
public abstract InputStream openStream();
}
|
rex-xxx/mt6572_x201
|
external/jmonkeyengine/engine/src/core/com/jme3/asset/AssetInfo.java
|
Java
|
gpl-2.0
| 2,649 |
/*
* Database image access classes.
* Copyright (C) 2003-2008 Petr Kubanek <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* 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
* Used for Image-DB interaction.
*
* Build on Image, persistently update image information in
* database.
*
* @author Petr Kubanek <[email protected]>
*/
#ifndef __RTS2_IMAGEDB__
#define __RTS2_IMAGEDB__
#include "image.h"
#include "rts2target.h"
#include "rts2db/taruser.h"
// process_bitfield content
#define ASTROMETRY_PROC 0x01
// when & -> image should be in archive, otherwise it's in trash|que
// depending on ASTROMETRY_PROC
#define ASTROMETRY_OK 0x02
#define DARK_OK 0x04
#define FLAT_OK 0x08
// some error durring image operations occured, information in DB is unrealiable
#define IMG_ERR 0x8000
namespace rts2image
{
/**
* Abstract class, representing image in DB.
*
* ImageSkyDb inherits from this class. This class is used to store any
* non-sky images (mostly darks, flats and other callibration images).
*
* @author Petr Kubanek <[email protected]>
*/
class ImageDb:public Image
{
public:
ImageDb ();
ImageDb (Image * in_image);
ImageDb (Rts2Target * currTarget, rts2core::DevClientCamera * camera, const struct timeval *expStart, const char *expand_path = NULL, bool overwrite = false);
ImageDb (int in_obs_id, int in_img_id);
ImageDb (long in_img_date, int in_img_usec, float in_img_exposure);
int getOKCount ();
virtual int saveImage ();
virtual int renameImage (const char *new_filename);
friend std::ostream & operator << (std::ostream & _os, ImageDb & img_db);
protected:
virtual void initDbImage ();
void reportSqlError (const char *msg);
virtual int updateDB () { return -1; }
void getValueInd (const char *name, double &value, int &ind, char *comment = NULL);
void getValueInd (const char *name, float &value, int &ind, char *comment = NULL);
int getDBFilter ();
};
class ImageSkyDb:public ImageDb
{
public:
ImageSkyDb (Rts2Target * currTarget, rts2core::DevClientCamera * camera, const struct timeval *expStartd);
//! Construct image from already existed ImageDb instance
ImageSkyDb (Image * in_image);
//! Construct image directly from DB (eg. retrieve all missing parameters)
ImageSkyDb (int in_obs_id, int in_img_id);
//! Construcy image from one database row..
ImageSkyDb (int in_tar_id, int in_obs_id, int in_img_id,
char in_obs_subtype, long in_img_date, int in_img_usec,
float in_img_exposure, float in_img_temperature,
const char *in_img_filter, float in_img_alt,
float in_img_az, const char *in_camera_name,
const char *in_mount_name, bool in_delete_flag,
int in_process_bitfield, double in_img_err_ra,
double in_img_err_dec, double in_img_err, const char *_img_path);
virtual ~ ImageSkyDb (void);
virtual int toArchive ();
virtual int toTrash ();
virtual int saveImage ();
virtual int deleteFormDB ();
virtual int deleteImage ();
virtual bool haveOKAstrometry () { return (processBitfiedl & ASTROMETRY_OK); }
virtual bool isProcessed () { return (processBitfiedl & ASTROMETRY_PROC); }
virtual std::string getFileNameString ();
virtual img_type_t getImageType () { return IMGTYPE_OBJECT; }
protected:
virtual void initDbImage ();
virtual int updateDB ();
private:
int updateAstrometry ();
int processBitfiedl;
inline int isCalibrationImage ();
void updateCalibrationDb ();
};
template < class img > img * setValueImageType (img * in_image)
{
const char *imgTypeText = "unknow";
img *ret_i = NULL;
// guess image type..
if (in_image->getShutter () == SHUT_CLOSED)
{
ret_i = in_image;
if (in_image->getExposureLength () == 0)
imgTypeText = "zero";
else
imgTypeText = "dark";
}
else if (in_image->getShutter () == SHUT_UNKNOW)
{
// that should not happen
return in_image;
}
else if (in_image->getTargetType () == TYPE_FLAT)
{
ret_i = in_image;
imgTypeText = "flat";
}
else
{
ret_i = new ImageSkyDb (in_image);
delete in_image;
imgTypeText = "object";
}
ret_i->setValue ("IMAGETYP", imgTypeText, "IRAF based image type");
return ret_i;
}
template < class img > img * getValueImageType (img * in_image)
{
char value[20];
try
{
in_image->getValue ("IMAGETYP", value, 20);
}
catch (rts2image::KeyNotFound &er)
{
return in_image;
}
// switch based on IMAGETYPE
if (!strcasecmp (value, "dark"))
{
return in_image;
}
else if (!strcasecmp (value, "flat"))
{
return in_image;
}
else if (!strcasecmp (value, "object"))
{
ImageSkyDb *skyI = new ImageSkyDb (in_image);
delete in_image;
return skyI;
}
// "zero" and "comp" are not used
return in_image;
}
}
#endif /* ! __RTS2_IMAGEDB__ */
|
zguangyu/rts2
|
include/rts2fits/imagedb.h
|
C
|
gpl-2.0
| 5,392 |
<?php
/**
* FIFO queue that is memory based (not persistent)
*
* WARNING: API IN FLUX. DO NOT USE DIRECTLY.
*
* @access private
*
* @package Elgg.Core
* @subpackage Queue
* @since 1.9.0
*/
class Elgg_Queue_MemoryQueue implements Elgg_Queue_Queue {
/* @var array */
protected $queue = array();
/**
* Create a queue
*/
public function __construct() {
$this->queue = array();
}
/**
* {@inheritdoc}
*/
public function enqueue($item) {
return (bool)array_push($this->queue, $item);
}
/**
* {@inheritdoc}
*/
public function dequeue() {
return array_shift($this->queue);
}
/**
* {@inheritdoc}
*/
public function clear() {
$this->queue = array();
}
/**
* {@inheritdoc}
*/
public function size() {
return count($this->queue);
}
}
|
brettp/Elgg
|
engine/classes/Elgg/Queue/MemoryQueue.php
|
PHP
|
gpl-2.0
| 795 |
#ifndef HISTORY_H
#define HISTORY_H
class HistoryPoint
// ===========================================================================
// Class used to provide x,y,z history information.
// ===========================================================================
{
public:
HistoryPoint (const int_t id, const Element* e, const real_t r,
const real_t s, const real_t x, const real_t y, const real_t z):
_id (id), _E (e), _r (r), _s (s), _x (x), _y (y), _z (z) { }
int_t ID () const { return _id; }
void extract (vector<AuxField*>&, real_t*) const;
static const Element* locate (const real_t, const real_t,
vector<Element*>&, real_t&, real_t&);
private:
const int_t _id; // Numeric identifier.
const Element* _E ; // Pointer to element.
const real_t _r ; // Canonical-space r-location.
const real_t _s ; // Canonical-space s-location.
const real_t _x ; // x location.
const real_t _y ; // y location.
const real_t _z ; // Location in homogeneous direction.
};
#endif
|
hellabyte/semtex
|
src/history.h
|
C
|
gpl-2.0
| 1,066 |
/* -*- mode: C -*- */
/*
IGraph library.
Copyright (C) 2003-2012 Gabor Csardi <[email protected]>
334 Harvard street, Cambridge, MA 02139 USA
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
*/
#include "igraph_components.h"
#include "igraph_memory.h"
#include "igraph_interface.h"
#include "igraph_adjlist.h"
#include "igraph_interrupt_internal.h"
#include "igraph_progress.h"
#include "igraph_structural.h"
#include "igraph_dqueue.h"
#include "igraph_stack.h"
#include "igraph_vector.h"
#include "config.h"
#include <string.h>
#include <limits.h>
int igraph_clusters_weak(const igraph_t *graph, igraph_vector_t *membership,
igraph_vector_t *csize, igraph_integer_t *no);
int igraph_clusters_strong(const igraph_t *graph, igraph_vector_t *membership,
igraph_vector_t *csize, igraph_integer_t *no);
/**
* \ingroup structural
* \function igraph_clusters
* \brief Calculates the (weakly or strongly) connected components in a graph.
*
* \param graph The graph object to analyze.
* \param membership First half of the result will be stored here. For
* every vertex the id of its component is given. The vector
* has to be preinitialized and will be resized. Alternatively
* this argument can be \c NULL, in which case it is ignored.
* \param csize The second half of the result. For every component it
* gives its size, the order is defined by the component ids.
* The vector has to be preinitialized and will be resized.
* Alternatively this argument can be \c NULL, in which
* case it is ignored.
* \param no Pointer to an integer, if not \c NULL then the number of
* clusters will be stored here.
* \param mode For directed graph this specifies whether to calculate
* weakly or strongly connected components. Possible values:
* \c IGRAPH_WEAK,
* \c IGRAPH_STRONG. This argument is
* ignored for undirected graphs.
* \return Error code:
* \c IGRAPH_EINVAL: invalid mode argument.
*
* Time complexity: O(|V|+|E|),
* |V| and
* |E| are the number of vertices and
* edges in the graph.
*/
int igraph_clusters(const igraph_t *graph, igraph_vector_t *membership,
igraph_vector_t *csize, igraph_integer_t *no,
igraph_connectedness_t mode) {
if (mode==IGRAPH_WEAK || !igraph_is_directed(graph)) {
return igraph_clusters_weak(graph, membership, csize, no);
} else if (mode==IGRAPH_STRONG) {
return igraph_clusters_strong(graph, membership, csize, no);
} else {
IGRAPH_ERROR("Cannot calculate clusters", IGRAPH_EINVAL);
}
return 1;
}
int igraph_clusters_weak(const igraph_t *graph, igraph_vector_t *membership,
igraph_vector_t *csize, igraph_integer_t *no) {
long int no_of_nodes=igraph_vcount(graph);
char *already_added;
long int first_node, act_cluster_size=0, no_of_clusters=1;
igraph_dqueue_t q=IGRAPH_DQUEUE_NULL;
long int i;
igraph_vector_t neis=IGRAPH_VECTOR_NULL;
already_added=igraph_Calloc(no_of_nodes,char);
if (already_added==0) {
IGRAPH_ERROR("Cannot calculate clusters", IGRAPH_ENOMEM);
}
IGRAPH_FINALLY(igraph_free, already_added);
IGRAPH_DQUEUE_INIT_FINALLY(&q, no_of_nodes > 100000 ? 10000 : no_of_nodes/10);
IGRAPH_VECTOR_INIT_FINALLY(&neis, 0);
/* Memory for result, csize is dynamically allocated */
if (membership) {
IGRAPH_CHECK(igraph_vector_resize(membership, no_of_nodes));
}
if (csize) {
igraph_vector_clear(csize);
}
/* The algorithm */
for (first_node=0; first_node < no_of_nodes; ++first_node) {
if (already_added[first_node]==1) continue;
IGRAPH_ALLOW_INTERRUPTION();
already_added[first_node]=1;
act_cluster_size=1;
if (membership) {
VECTOR(*membership)[first_node]=no_of_clusters-1;
}
IGRAPH_CHECK(igraph_dqueue_push(&q, first_node));
while ( !igraph_dqueue_empty(&q) ) {
long int act_node=(long int) igraph_dqueue_pop(&q);
IGRAPH_CHECK(igraph_neighbors(graph, &neis,
(igraph_integer_t) act_node, IGRAPH_ALL));
for (i=0; i<igraph_vector_size(&neis); i++) {
long int neighbor=(long int) VECTOR(neis)[i];
if (already_added[neighbor]==1) { continue; }
IGRAPH_CHECK(igraph_dqueue_push(&q, neighbor));
already_added[neighbor]=1;
act_cluster_size++;
if (membership) {
VECTOR(*membership)[neighbor]=no_of_clusters-1;
}
}
}
no_of_clusters++;
if (csize) {
IGRAPH_CHECK(igraph_vector_push_back(csize, act_cluster_size));
}
}
/* Cleaning up */
if (no) { *no = (igraph_integer_t) no_of_clusters-1; }
igraph_Free(already_added);
igraph_dqueue_destroy(&q);
igraph_vector_destroy(&neis);
IGRAPH_FINALLY_CLEAN(3);
return 0;
}
int igraph_clusters_strong(const igraph_t *graph, igraph_vector_t *membership,
igraph_vector_t *csize, igraph_integer_t *no) {
long int no_of_nodes=igraph_vcount(graph);
igraph_vector_t next_nei=IGRAPH_VECTOR_NULL;
long int i, n, num_seen;
igraph_dqueue_t q=IGRAPH_DQUEUE_NULL;
long int no_of_clusters=1;
long int act_cluster_size;
igraph_vector_t out=IGRAPH_VECTOR_NULL;
const igraph_vector_int_t* tmp;
igraph_adjlist_t adjlist;
/* The result */
IGRAPH_VECTOR_INIT_FINALLY(&next_nei, no_of_nodes);
IGRAPH_VECTOR_INIT_FINALLY(&out, 0);
IGRAPH_DQUEUE_INIT_FINALLY(&q, 100);
if (membership) {
IGRAPH_CHECK(igraph_vector_resize(membership, no_of_nodes));
}
IGRAPH_CHECK(igraph_vector_reserve(&out, no_of_nodes));
igraph_vector_null(&out);
if (csize) {
igraph_vector_clear(csize);
}
IGRAPH_CHECK(igraph_adjlist_init(graph, &adjlist, IGRAPH_OUT));
IGRAPH_FINALLY(igraph_adjlist_destroy, &adjlist);
num_seen = 0;
for (i=0; i<no_of_nodes; i++) {
IGRAPH_ALLOW_INTERRUPTION();
tmp = igraph_adjlist_get(&adjlist, i);
if (VECTOR(next_nei)[i] > igraph_vector_int_size(tmp)) {
continue;
}
IGRAPH_CHECK(igraph_dqueue_push(&q, i));
while (!igraph_dqueue_empty(&q)) {
long int act_node=(long int) igraph_dqueue_back(&q);
tmp = igraph_adjlist_get(&adjlist, act_node);
if (VECTOR(next_nei)[act_node]==0) {
/* this is the first time we've met this vertex */
VECTOR(next_nei)[act_node]++;
} else if (VECTOR(next_nei)[act_node] <= igraph_vector_int_size(tmp)) {
/* we've already met this vertex but it has more children */
long int neighbor=(long int) VECTOR(*tmp)[(long int)
VECTOR(next_nei)[act_node]-1];
if (VECTOR(next_nei)[neighbor] == 0) {
IGRAPH_CHECK(igraph_dqueue_push(&q, neighbor));
}
VECTOR(next_nei)[act_node]++;
} else {
/* we've met this vertex and it has no more children */
IGRAPH_CHECK(igraph_vector_push_back(&out, act_node));
igraph_dqueue_pop_back(&q);
num_seen++;
if (num_seen % 10000 == 0) {
/* time to report progress and allow the user to interrupt */
IGRAPH_PROGRESS("Strongly connected components: ",
num_seen * 50.0 / no_of_nodes, NULL);
IGRAPH_ALLOW_INTERRUPTION();
}
}
} /* while q */
} /* for */
IGRAPH_PROGRESS("Strongly connected components: ", 50.0, NULL);
igraph_adjlist_destroy(&adjlist);
IGRAPH_FINALLY_CLEAN(1);
IGRAPH_CHECK(igraph_adjlist_init(graph, &adjlist, IGRAPH_IN));
IGRAPH_FINALLY(igraph_adjlist_destroy, &adjlist);
/* OK, we've the 'out' values for the nodes, let's use them in
decreasing order with the help of a heap */
igraph_vector_null(&next_nei); /* mark already added vertices */
num_seen = 0;
while (!igraph_vector_empty(&out)) {
long int grandfather=(long int) igraph_vector_pop_back(&out);
if (VECTOR(next_nei)[grandfather] != 0) { continue; }
VECTOR(next_nei)[grandfather]=1;
act_cluster_size=1;
if (membership) {
VECTOR(*membership)[grandfather]=no_of_clusters-1;
}
IGRAPH_CHECK(igraph_dqueue_push(&q, grandfather));
num_seen++;
if (num_seen % 10000 == 0) {
/* time to report progress and allow the user to interrupt */
IGRAPH_PROGRESS("Strongly connected components: ",
50.0 + num_seen * 50.0 / no_of_nodes, NULL);
IGRAPH_ALLOW_INTERRUPTION();
}
while (!igraph_dqueue_empty(&q)) {
long int act_node=(long int) igraph_dqueue_pop_back(&q);
tmp = igraph_adjlist_get(&adjlist, act_node);
n = igraph_vector_int_size(tmp);
for (i=0; i<n; i++) {
long int neighbor=(long int) VECTOR(*tmp)[i];
if (VECTOR(next_nei)[neighbor] != 0) { continue; }
IGRAPH_CHECK(igraph_dqueue_push(&q, neighbor));
VECTOR(next_nei)[neighbor]=1;
act_cluster_size++;
if (membership) {
VECTOR(*membership)[neighbor]=no_of_clusters-1;
}
num_seen++;
if (num_seen % 10000 == 0) {
/* time to report progress and allow the user to interrupt */
IGRAPH_PROGRESS("Strongly connected components: ",
50.0 + num_seen * 50.0 / no_of_nodes, NULL);
IGRAPH_ALLOW_INTERRUPTION();
}
}
}
no_of_clusters++;
if (csize) {
IGRAPH_CHECK(igraph_vector_push_back(csize, act_cluster_size));
}
}
IGRAPH_PROGRESS("Strongly connected components: ", 100.0, NULL);
if (no) { *no=(igraph_integer_t) no_of_clusters-1; }
/* Clean up, return */
igraph_adjlist_destroy(&adjlist);
igraph_vector_destroy(&out);
igraph_dqueue_destroy(&q);
igraph_vector_destroy(&next_nei);
IGRAPH_FINALLY_CLEAN(4);
return 0;
}
int igraph_is_connected_weak(const igraph_t *graph, igraph_bool_t *res);
/**
* \ingroup structural
* \function igraph_is_connected
* \brief Decides whether the graph is (weakly or strongly) connected.
*
* A graph with zero vertices (i.e. the null graph) is connected by definition.
*
* \param graph The graph object to analyze.
* \param res Pointer to a logical variable, the result will be stored
* here.
* \param mode For a directed graph this specifies whether to calculate
* weak or strong connectedness. Possible values:
* \c IGRAPH_WEAK,
* \c IGRAPH_STRONG. This argument is
* ignored for undirected graphs.
* \return Error code:
* \c IGRAPH_EINVAL: invalid mode argument.
*
* Time complexity: O(|V|+|E|), the
* number of vertices
* plus the number of edges in the graph.
*/
int igraph_is_connected(const igraph_t *graph, igraph_bool_t *res,
igraph_connectedness_t mode) {
if (igraph_vcount(graph) == 0) {
*res = 1;
return IGRAPH_SUCCESS;
}
if (mode==IGRAPH_WEAK || !igraph_is_directed(graph)) {
return igraph_is_connected_weak(graph, res);
} else if (mode==IGRAPH_STRONG) {
int retval;
igraph_integer_t no;
retval = igraph_clusters_strong(graph, 0, 0, &no);
*res = (no==1);
return retval;
} else {
IGRAPH_ERROR("mode argument", IGRAPH_EINVAL);
}
return 0;
}
/**
* \ingroup structural
* \function igraph_is_connected_weak
* \brief Query whether the graph is weakly connected.
*
* A graph with zero vertices (i.e. the null graph) is weakly connected by
* definition. A directed graph is weakly connected if its undirected version
* is connected. In the case of undirected graphs, weakly connected and
* connected are equivalent.
*
* \param graph The graph object to analyze.
* \param res Pointer to a logical variable; the result will be stored here.
* \return Error code:
* \c IGRAPH_ENOMEM: unable to allocate requested memory.
*
* Time complexity: O(|V|+|E|), the number of vertices plus the number of
* edges in the graph.
*/
int igraph_is_connected_weak(const igraph_t *graph, igraph_bool_t *res) {
long int no_of_nodes=igraph_vcount(graph);
char *already_added;
igraph_vector_t neis=IGRAPH_VECTOR_NULL;
igraph_dqueue_t q=IGRAPH_DQUEUE_NULL;
long int i, j;
if (no_of_nodes == 0) {
*res = 1;
return IGRAPH_SUCCESS;
}
already_added=igraph_Calloc(no_of_nodes, char);
if (already_added==0) {
IGRAPH_ERROR("is connected (weak) failed", IGRAPH_ENOMEM);
}
IGRAPH_FINALLY(free, already_added); /* TODO: hack */
IGRAPH_DQUEUE_INIT_FINALLY(&q, 10);
IGRAPH_VECTOR_INIT_FINALLY(&neis, 0);
/* Try to find at least two clusters */
already_added[0]=1;
IGRAPH_CHECK(igraph_dqueue_push(&q, 0));
j=1;
while ( !igraph_dqueue_empty(&q)) {
long int actnode=(long int) igraph_dqueue_pop(&q);
IGRAPH_ALLOW_INTERRUPTION();
IGRAPH_CHECK(igraph_neighbors(graph, &neis, (igraph_integer_t) actnode,
IGRAPH_ALL));
for (i=0; i <igraph_vector_size(&neis); i++) {
long int neighbor=(long int) VECTOR(neis)[i];
if (already_added[neighbor] != 0) { continue; }
IGRAPH_CHECK(igraph_dqueue_push(&q, neighbor));
j++;
already_added[neighbor]++;
}
}
/* Connected? */
*res = (j == no_of_nodes);
igraph_Free(already_added);
igraph_dqueue_destroy(&q);
igraph_vector_destroy(&neis);
IGRAPH_FINALLY_CLEAN(3);
return 0;
}
/**
* \function igraph_decompose_destroy
* \brief Free the memory allocated by \ref igraph_decompose().
*
* \param complist The list of graph components, as returned by
* \ref igraph_decompose().
*
* Time complexity: O(c), c is the number of components.
*/
void igraph_decompose_destroy(igraph_vector_ptr_t *complist) {
long int i;
for (i=0; i<igraph_vector_ptr_size(complist); i++) {
if (VECTOR(*complist)[i] != 0) {
igraph_destroy(VECTOR(*complist)[i]);
igraph_free(VECTOR(*complist)[i]);
}
}
}
/**
* \function igraph_decompose
* \brief Decompose a graph into connected components.
*
* Create separate graph for each component of a graph. Note that the
* vertex ids in the new graphs will be different than in the original
* graph. (Except if there is only one component in the original graph.)
*
* \param graph The original graph.
* \param components This pointer vector will contain pointers to the
* subcomponent graphs. It should be initialized before calling this
* function and will be resized to hold the graphs. Don't forget to
* call \ref igraph_destroy() and free() on the elements of
* this pointer vector to free unneeded memory. Alternatively, you can
* simply call \ref igraph_decompose_destroy() that does this for you.
* \param mode Either \c IGRAPH_WEAK or \c IGRAPH_STRONG for weakly
* and strongly connected components respectively. Right now only
* the former is implemented.
* \param maxcompno The maximum number of components to return. The
* first \p maxcompno components will be returned (which hold at
* least \p minelements vertices, see the next parameter), the
* others will be ignored. Supply -1 here if you don't want to limit
* the number of components.
* \param minelements The minimum number of vertices a component
* should contain in order to place it in the \p components
* vector. Eg. supply 2 here to ignore isolated vertices.
* \return Error code, \c IGRAPH_ENOMEM if there is not enough memory
* to perform the operation.
*
* Added in version 0.2.</para><para>
*
* Time complexity: O(|V|+|E|), the number of vertices plus the number
* of edges.
*
* \example examples/simple/igraph_decompose.c
*/
int igraph_decompose(const igraph_t *graph, igraph_vector_ptr_t *components,
igraph_connectedness_t mode,
long int maxcompno, long int minelements) {
long int actstart;
long int no_of_nodes=igraph_vcount(graph);
long int resco=0; /* number of graphs created so far */
char *already_added;
igraph_dqueue_t q;
igraph_vector_t verts;
igraph_vector_t neis;
long int i;
igraph_t *newg;
if (!igraph_is_directed(graph)) {
mode=IGRAPH_WEAK;
}
if (mode != IGRAPH_WEAK) {
IGRAPH_ERROR("only 'IGRAPH_WEAK' is implemented", IGRAPH_EINVAL);
}
if (maxcompno<0) {
maxcompno=LONG_MAX;
}
igraph_vector_ptr_clear(components);
IGRAPH_FINALLY(igraph_decompose_destroy, components);
already_added=igraph_Calloc(no_of_nodes, char);
if (already_added==0) {
IGRAPH_ERROR("Cannot decompose graph", IGRAPH_ENOMEM);
}
IGRAPH_FINALLY(igraph_free, already_added);
IGRAPH_CHECK(igraph_dqueue_init(&q, 100));
IGRAPH_FINALLY(igraph_dqueue_destroy, &q);
IGRAPH_VECTOR_INIT_FINALLY(&verts, 0);
IGRAPH_VECTOR_INIT_FINALLY(&neis, 0);
for(actstart=0; resco<maxcompno && actstart < no_of_nodes; actstart++) {
if (already_added[actstart]) { continue; }
IGRAPH_ALLOW_INTERRUPTION();
igraph_vector_clear(&verts);
already_added[actstart]=1;
IGRAPH_CHECK(igraph_vector_push_back(&verts, actstart));
IGRAPH_CHECK(igraph_dqueue_push(&q, actstart));
while (!igraph_dqueue_empty(&q) ) {
long int actvert=(long int) igraph_dqueue_pop(&q);
IGRAPH_CHECK(igraph_neighbors(graph, &neis, (igraph_integer_t) actvert,
IGRAPH_ALL));
for (i=0; i<igraph_vector_size(&neis); i++) {
long int neighbor=(long int) VECTOR(neis)[i];
if (already_added[neighbor]==1) { continue; }
IGRAPH_CHECK(igraph_dqueue_push(&q, neighbor));
IGRAPH_CHECK(igraph_vector_push_back(&verts, neighbor));
already_added[neighbor]=1;
}
}
/* ok, we have a component */
if (igraph_vector_size(&verts)<minelements) { continue; }
newg=igraph_Calloc(1, igraph_t);
if (newg==0) {
IGRAPH_ERROR("Cannot decompose graph", IGRAPH_ENOMEM);
}
IGRAPH_CHECK(igraph_vector_ptr_push_back(components, newg));
IGRAPH_CHECK(igraph_induced_subgraph(graph, newg,
igraph_vss_vector(&verts),
IGRAPH_SUBGRAPH_AUTO));
resco++;
} /* for actstart++ */
igraph_vector_destroy(&neis);
igraph_vector_destroy(&verts);
igraph_dqueue_destroy(&q);
igraph_free(already_added);
IGRAPH_FINALLY_CLEAN(5); /* + components */
return 0;
}
/**
* \function igraph_articulation_points
* Find the articulation points in a graph.
*
* A vertex is an articulation point if its removal increases
* the number of connected components in the graph.
* \param graph The input graph.
* \param res Pointer to an initialized vector, the
* articulation points will be stored here.
* \return Error code.
*
* Time complexity: O(|V|+|E|), linear in the number of vertices and edges.
*
* \sa \ref igraph_biconnected_components(), \ref igraph_clusters()
*/
int igraph_articulation_points(const igraph_t *graph,
igraph_vector_t *res) {
igraph_integer_t no;
return igraph_biconnected_components(graph, &no, 0, 0, 0, res);
}
void igraph_i_free_vectorlist(igraph_vector_ptr_t *list);
void igraph_i_free_vectorlist(igraph_vector_ptr_t *list) {
long int i, n=igraph_vector_ptr_size(list);
for (i=0; i<n; i++) {
igraph_vector_t *v=VECTOR(*list)[i];
if (v) {
igraph_vector_destroy(v);
igraph_Free(v);
}
}
igraph_vector_ptr_destroy(list);
}
/**
* \function igraph_biconnected_components
* Calculate biconnected components
*
* A graph is biconnected if the removal of any single vertex (and
* its incident edges) does not disconnect it.
*
* </para><para>
* A biconnected component of a graph is a maximal biconnected
* subgraph of it. The biconnected components of a graph can be given
* by the partition of its edges: every edge is a member of exactly
* one biconnected component. Note that this is not true for
* vertices: the same vertex can be part of many biconnected
* components.
* \param graph The input graph.
* \param no The number of biconnected components will be stored here.
* \param tree_edges If not a NULL pointer, then the found components
* are stored here, in a list of vectors. Every vector in the list
* is a biconnected component, represented by its edges. More precisely,
* a spanning tree of the biconnected component is returned.
* Note you'll have to
* destroy each vector first by calling \ref igraph_vector_destroy()
* and then <code>free()</code> on it, plus you need to call
* \ref igraph_vector_ptr_destroy() on the list to regain all
* allocated memory.
* \param component_edges If not a NULL pointer, then the edges of the
* biconnected components are stored here, in the same form as for
* \c tree_edges.
* \param components If not a NULL pointer, then the vertices of the
* biconnected components are stored here, in the same format as
* for the previous two arguments.
* \param articulation_points If not a NULL pointer, then the
* articulation points of the graph are stored in this vector.
* A vertex is an articulation point if its removal increases the
* number of (weakly) connected components in the graph.
* \return Error code.
*
* Time complexity: O(|V|+|E|), linear in the number of vertices and
* edges, but only if you do not calculate \c components and
* \c component_edges. If you calculate \c components, then it is
* quadratic in the number of vertices. If you calculate \c
* component_edges as well, then it is cubic in the number of
* vertices.
*
* \sa \ref igraph_articulation_points(), \ref igraph_clusters().
*
* \example examples/simple/igraph_biconnected_components.c
*/
int igraph_biconnected_components(const igraph_t *graph,
igraph_integer_t *no,
igraph_vector_ptr_t *tree_edges,
igraph_vector_ptr_t *component_edges,
igraph_vector_ptr_t *components,
igraph_vector_t *articulation_points) {
long int no_of_nodes=igraph_vcount(graph);
igraph_vector_long_t nextptr;
igraph_vector_long_t num, low;
igraph_vector_bool_t found;
igraph_vector_int_t *adjedges;
igraph_stack_t path;
igraph_vector_t edgestack;
igraph_inclist_t inclist;
long int i, counter, rootdfs=0;
igraph_vector_long_t vertex_added;
long int comps=0;
igraph_vector_ptr_t *mycomponents=components, vcomponents;
IGRAPH_CHECK(igraph_vector_long_init(&nextptr, no_of_nodes));
IGRAPH_FINALLY(igraph_vector_long_destroy, &nextptr);
IGRAPH_CHECK(igraph_vector_long_init(&num, no_of_nodes));
IGRAPH_FINALLY(igraph_vector_long_destroy, &num);
IGRAPH_CHECK(igraph_vector_long_init(&low, no_of_nodes));
IGRAPH_FINALLY(igraph_vector_long_destroy, &low);
IGRAPH_CHECK(igraph_vector_bool_init(&found, no_of_nodes));
IGRAPH_FINALLY(igraph_vector_bool_destroy, &found);
IGRAPH_CHECK(igraph_stack_init(&path, 100));
IGRAPH_FINALLY(igraph_stack_destroy, &path);
IGRAPH_VECTOR_INIT_FINALLY(&edgestack, 0);
IGRAPH_CHECK(igraph_vector_reserve(&edgestack, 100));
IGRAPH_CHECK(igraph_inclist_init(graph, &inclist, IGRAPH_ALL));
IGRAPH_FINALLY(igraph_inclist_destroy, &inclist);
IGRAPH_CHECK(igraph_vector_long_init(&vertex_added, no_of_nodes));
IGRAPH_FINALLY(igraph_vector_long_destroy, &vertex_added);
if (no) {
*no=0;
}
if (tree_edges) {
igraph_vector_ptr_clear(tree_edges);
}
if (components) {
igraph_vector_ptr_clear(components);
}
if (component_edges) {
igraph_vector_ptr_clear(component_edges);
}
if (articulation_points) {
igraph_vector_clear(articulation_points);
}
if (component_edges && !components) {
mycomponents=&vcomponents;
IGRAPH_CHECK(igraph_vector_ptr_init(mycomponents, 0));
IGRAPH_FINALLY(igraph_i_free_vectorlist, mycomponents);
}
for (i=0; i<no_of_nodes; i++) {
if (VECTOR(low)[i] != 0) { continue; } /* already visited */
IGRAPH_ALLOW_INTERRUPTION();
IGRAPH_CHECK(igraph_stack_push(&path, i));
counter=1;
rootdfs=0;
VECTOR(low)[i]=VECTOR(num)[i]=counter++;
while (!igraph_stack_empty(&path)) {
long int n;
long int act=(long int) igraph_stack_top(&path);
long int actnext=VECTOR(nextptr)[act];
adjedges=igraph_inclist_get(&inclist, act);
n=igraph_vector_int_size(adjedges);
if (actnext < n) {
/* Step down (maybe) */
long int edge=(long int) VECTOR(*adjedges)[actnext];
long int nei=IGRAPH_OTHER(graph, edge, act);
if (VECTOR(low)[nei] == 0) {
if (act==i) { rootdfs++; }
IGRAPH_CHECK(igraph_vector_push_back(&edgestack, edge));
IGRAPH_CHECK(igraph_stack_push(&path, nei));
VECTOR(low)[nei] = VECTOR(num)[nei]=counter++;
} else {
/* Update low value if needed */
if (VECTOR(num)[nei] < VECTOR(low)[act]) {
VECTOR(low)[act]=VECTOR(num)[nei];
}
}
VECTOR(nextptr)[act] += 1;
} else {
/* Step up */
igraph_stack_pop(&path);
if (!igraph_stack_empty(&path)) {
long int prev=(long int) igraph_stack_top(&path);
/* Update LOW value if needed */
if (VECTOR(low)[act] < VECTOR(low)[prev]) {
VECTOR(low)[prev] = VECTOR(low)[act];
}
/* Check for articulation point */
if (VECTOR(low)[act] >= VECTOR(num)[prev]) {
if (articulation_points && !VECTOR(found)[prev]
&& prev != i /* the root */) {
IGRAPH_CHECK(igraph_vector_push_back(articulation_points, prev));
VECTOR(found)[prev] = 1;
}
if (no) { *no += 1; }
/*------------------------------------*/
/* Record the biconnected component just found */
if (tree_edges || mycomponents) {
igraph_vector_t *v = 0, *v2 = 0;
comps++;
if (tree_edges) {
v=igraph_Calloc(1, igraph_vector_t);
if (!v) { IGRAPH_ERROR("Out of memory", IGRAPH_ENOMEM); }
IGRAPH_CHECK(igraph_vector_init(v, 0));
IGRAPH_FINALLY(igraph_vector_destroy, v);
}
if (mycomponents) {
v2=igraph_Calloc(1, igraph_vector_t);
if (!v2) { IGRAPH_ERROR("Out of memory", IGRAPH_ENOMEM); }
IGRAPH_CHECK(igraph_vector_init(v2, 0));
IGRAPH_FINALLY(igraph_vector_destroy, v2);
}
while (!igraph_vector_empty(&edgestack)) {
long int e=(long int) igraph_vector_pop_back(&edgestack);
long int from=IGRAPH_FROM(graph,e);
long int to=IGRAPH_TO(graph,e);
if (tree_edges) {
IGRAPH_CHECK(igraph_vector_push_back(v, e));
}
if (mycomponents) {
if (VECTOR(vertex_added)[from] != comps) {
VECTOR(vertex_added)[from] = comps;
IGRAPH_CHECK(igraph_vector_push_back(v2, from));
}
if (VECTOR(vertex_added)[to] != comps) {
VECTOR(vertex_added)[to] = comps;
IGRAPH_CHECK(igraph_vector_push_back(v2, to));
}
}
if (from==prev || to==prev) {
break;
}
}
if (mycomponents) {
IGRAPH_CHECK(igraph_vector_ptr_push_back(mycomponents, v2));
IGRAPH_FINALLY_CLEAN(1);
}
if (tree_edges) {
IGRAPH_CHECK(igraph_vector_ptr_push_back(tree_edges, v));
IGRAPH_FINALLY_CLEAN(1);
}
if (component_edges) {
igraph_vector_t *nodes=VECTOR(*mycomponents)[comps-1];
igraph_vector_t *vv=igraph_Calloc(1, igraph_vector_t);
long int ii, no_vert=igraph_vector_size(nodes);
if (!vv) { IGRAPH_ERROR("Out of memory", IGRAPH_ENOMEM); }
IGRAPH_CHECK(igraph_vector_init(vv, 0));
IGRAPH_FINALLY(igraph_vector_destroy, vv);
for (ii=0; ii<no_vert; ii++) {
long int vert=(long int) VECTOR(*nodes)[ii];
igraph_vector_int_t *edges=igraph_inclist_get(&inclist,
vert);
long int j, nn=igraph_vector_int_size(edges);
for (j=0; j<nn; j++) {
long int e=(long int) VECTOR(*edges)[j];
long int nei=IGRAPH_OTHER(graph, e, vert);
if (VECTOR(vertex_added)[nei] == comps && nei<vert) {
IGRAPH_CHECK(igraph_vector_push_back(vv, e));
}
}
}
IGRAPH_CHECK(igraph_vector_ptr_push_back(component_edges, vv));
IGRAPH_FINALLY_CLEAN(1);
}
} /* record component if requested */
/*------------------------------------*/
}
} /* !igraph_stack_empty(&path) */
}
} /* !igraph_stack_empty(&path) */
if (articulation_points && rootdfs >= 2) {
IGRAPH_CHECK(igraph_vector_push_back(articulation_points, i));
}
} /* i < no_of_nodes */
if (mycomponents != components) {
igraph_i_free_vectorlist(mycomponents);
IGRAPH_FINALLY_CLEAN(1);
}
igraph_vector_long_destroy(&vertex_added);
igraph_inclist_destroy(&inclist);
igraph_vector_destroy(&edgestack);
igraph_stack_destroy(&path);
igraph_vector_bool_destroy(&found);
igraph_vector_long_destroy(&low);
igraph_vector_long_destroy(&num);
igraph_vector_long_destroy(&nextptr);
IGRAPH_FINALLY_CLEAN(8);
return 0;
}
|
feeds/igraph
|
src/components.c
|
C
|
gpl-2.0
| 28,646 |
#include <QPainter>
#include <QGraphicsScene>
#include <QCursor>
#include <QGraphicsSceneMouseEvent>
#include <cmath>
#ifdef _WIN32
#include "round.h"
#endif /* _WIN32 */
#include "carddatabase.h"
#include "cardinfowidget.h"
#include "abstractcarditem.h"
#include "settingscache.h"
#include "main.h"
#include "gamescene.h"
#include <QDebug>
AbstractCardItem::AbstractCardItem(const QString &_name, Player *_owner, int _id, QGraphicsItem *parent)
: ArrowTarget(_owner, parent), infoWidget(0), id(_id), name(_name), tapped(false), facedown(false), tapAngle(0), isHovered(false), realZValue(0)
{
setCursor(Qt::OpenHandCursor);
setFlag(ItemIsSelectable);
setCacheMode(DeviceCoordinateCache);
connect(db, SIGNAL(cardListChanged()), this, SLOT(cardInfoUpdated()));
connect(settingsCache, SIGNAL(displayCardNamesChanged()), this, SLOT(callUpdate()));
cardInfoUpdated();
}
AbstractCardItem::~AbstractCardItem()
{
emit deleteCardInfoPopup(name);
}
QRectF AbstractCardItem::boundingRect() const
{
return QRectF(0, 0, CARD_WIDTH, CARD_HEIGHT);
}
void AbstractCardItem::pixmapUpdated()
{
update();
emit sigPixmapUpdated();
}
void AbstractCardItem::cardInfoUpdated()
{
info = db->getCard(name);
connect(info, SIGNAL(pixmapUpdated()), this, SLOT(pixmapUpdated()));
}
void AbstractCardItem::setRealZValue(qreal _zValue)
{
realZValue = _zValue;
setZValue(_zValue);
}
QSizeF AbstractCardItem::getTranslatedSize(QPainter *painter) const
{
return QSizeF(
painter->combinedTransform().map(QLineF(0, 0, boundingRect().width(), 0)).length(),
painter->combinedTransform().map(QLineF(0, 0, 0, boundingRect().height())).length()
);
}
void AbstractCardItem::transformPainter(QPainter *painter, const QSizeF &translatedSize, int angle)
{
QRectF totalBoundingRect = painter->combinedTransform().mapRect(boundingRect());
painter->resetTransform();
QTransform pixmapTransform;
pixmapTransform.translate(totalBoundingRect.width() / 2, totalBoundingRect.height() / 2);
pixmapTransform.rotate(angle);
pixmapTransform.translate(-translatedSize.width() / 2, -translatedSize.height() / 2);
painter->setTransform(pixmapTransform);
QFont f;
int fontSize = round(translatedSize.height() / 8);
if (fontSize < 9)
fontSize = 9;
if (fontSize > 10)
fontSize = 10;
f.setPixelSize(fontSize);
painter->setFont(f);
}
void AbstractCardItem::paintPicture(QPainter *painter, const QSizeF &translatedSize, int angle)
{
qreal scaleFactor = translatedSize.width() / boundingRect().width();
CardInfo *imageSource = facedown ? db->getCard() : info;
QPixmap translatedPixmap;
// don't even spend time trying to load the picture if our size is too small
if(translatedSize.width() > 10)
imageSource->getPixmap(translatedSize.toSize(), translatedPixmap);
painter->save();
QColor bgColor = Qt::transparent;
if (translatedPixmap.isNull()) {
QString colorStr;
if (!color.isEmpty())
colorStr = color;
else if (info->getColors().size() > 1)
colorStr = "m";
else if (!info->getColors().isEmpty())
colorStr = info->getColors().first().toLower();
if (colorStr == "b")
bgColor = QColor(0, 0, 0);
else if (colorStr == "u")
bgColor = QColor(0, 140, 180);
else if (colorStr == "w")
bgColor = QColor(255, 250, 140);
else if (colorStr == "r")
bgColor = QColor(230, 0, 0);
else if (colorStr == "g")
bgColor = QColor(0, 160, 0);
else if (colorStr == "m")
bgColor = QColor(250, 190, 30);
else
bgColor = QColor(230, 230, 230);
} else {
painter->save();
transformPainter(painter, translatedSize, angle);
painter->drawPixmap(QPointF(1, 1), translatedPixmap);
painter->restore();
}
painter->setBrush(bgColor);
QPen pen(Qt::black);
pen.setJoinStyle(Qt::MiterJoin);
const int penWidth = 2;
pen.setWidth(penWidth);
painter->setPen(pen);
if (!angle)
painter->drawRect(QRectF(0, 0, CARD_WIDTH - 1, CARD_HEIGHT - penWidth));
else
painter->drawRect(QRectF(1, 1, CARD_WIDTH - 2, CARD_HEIGHT - 1.5));
if (translatedPixmap.isNull() || settingsCache->getDisplayCardNames() || facedown) {
painter->save();
transformPainter(painter, translatedSize, angle);
painter->setPen(Qt::white);
painter->setBackground(Qt::black);
painter->setBackgroundMode(Qt::OpaqueMode);
QString nameStr;
if (facedown)
nameStr = "# " + QString::number(id);
else
nameStr = name;
painter->drawText(QRectF(3 * scaleFactor, 3 * scaleFactor, translatedSize.width() - 6 * scaleFactor, translatedSize.height() - 6 * scaleFactor), Qt::AlignTop | Qt::AlignLeft | Qt::TextWrapAnywhere, nameStr);
painter->restore();
}
painter->restore();
}
void AbstractCardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
{
painter->save();
QSizeF translatedSize = getTranslatedSize(painter);
paintPicture(painter, translatedSize, tapAngle);
painter->save();
painter->setRenderHint(QPainter::Antialiasing, false);
transformPainter(painter, translatedSize, tapAngle);
if (isSelected() || isHovered) {
QPen pen;
if (isHovered)
pen.setColor(Qt::yellow);
if (isSelected())
pen.setColor(Qt::red);
const int penWidth = 1;
pen.setWidth(penWidth);
painter->setPen(pen);
painter->drawRect(QRectF(0, 0, translatedSize.width() + penWidth, translatedSize.height() - penWidth));
}
painter->restore();
painter->restore();
}
void AbstractCardItem::setName(const QString &_name)
{
if (name == _name)
return;
emit deleteCardInfoPopup(name);
disconnect(info, 0, this, 0);
name = _name;
info = db->getCard(name);
connect(info, SIGNAL(pixmapUpdated()), this, SLOT(pixmapUpdated()));
update();
}
void AbstractCardItem::setHovered(bool _hovered)
{
if (isHovered == _hovered)
return;
if (_hovered)
processHoverEvent();
isHovered = _hovered;
setZValue(_hovered ? 2000000004 : realZValue);
setScale(_hovered && settingsCache->getScaleCards() ? 1.1 : 1);
setTransformOriginPoint(_hovered ? CARD_WIDTH / 2 : 0, _hovered ? CARD_HEIGHT / 2 : 0);
update();
}
void AbstractCardItem::setColor(const QString &_color)
{
color = _color;
update();
}
void AbstractCardItem::setTapped(bool _tapped, bool canAnimate)
{
if (tapped == _tapped)
return;
tapped = _tapped;
if (settingsCache->getTapAnimation() && canAnimate)
static_cast<GameScene *>(scene())->registerAnimationItem(this);
else {
tapAngle = tapped ? 90 : 0;
setTransform(QTransform().translate((float) CARD_WIDTH / 2, (float) CARD_HEIGHT / 2).rotate(tapAngle).translate((float) -CARD_WIDTH / 2, (float) -CARD_HEIGHT / 2));
update();
}
}
void AbstractCardItem::setFaceDown(bool _facedown)
{
facedown = _facedown;
update();
emit updateCardMenu(this);
}
void AbstractCardItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if ((event->modifiers() & Qt::ControlModifier)) {
setSelected(!isSelected());
}
else if (!isSelected()) {
scene()->clearSelection();
setSelected(true);
}
if (event->button() == Qt::LeftButton)
setCursor(Qt::ClosedHandCursor);
else if (event->button() == Qt::MidButton)
emit showCardInfoPopup(event->screenPos(), name);
event->accept();
}
void AbstractCardItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::MidButton)
emit deleteCardInfoPopup(name);
// This function ensures the parent function doesn't mess around with our selection.
event->accept();
}
void AbstractCardItem::processHoverEvent()
{
emit hovered(this);
}
QVariant AbstractCardItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{
if (change == ItemSelectedHasChanged) {
update();
return value;
} else
return QGraphicsItem::itemChange(change, value);
}
|
ideocl4st/Cockatrice
|
cockatrice/src/abstractcarditem.cpp
|
C++
|
gpl-2.0
| 8,443 |
/// -*- c++ -*-
#ifndef COLVARMODULE_H
#define COLVARMODULE_H
#ifndef COLVARS_VERSION
#define COLVARS_VERSION "2015-07-21"
#endif
#ifndef COLVARS_DEBUG
#define COLVARS_DEBUG false
#endif
/// \file colvarmodule.h
/// \brief Collective variables main module
///
/// This file declares the main class for defining and manipulating
/// collective variables: there should be only one instance of this
/// class, because several variables are made static (i.e. they are
/// shared between all object instances) to be accessed from other
/// objects.
// Internal method return codes
#define COLVARS_NOT_IMPLEMENTED -2
#define COLVARS_ERROR -1
#define COLVARS_OK 0
// On error, values of the colvars module error register
#define GENERAL_ERROR 1
#define FILE_ERROR (1<<1)
#define MEMORY_ERROR (1<<2)
#define BUG_ERROR (1<<3) // Inconsistent state indicating bug
#define INPUT_ERROR (1<<4) // out of bounds or inconsistent input
#define DELETE_COLVARS (1<<5) // Instruct the caller to delete cvm
#define FATAL_ERROR (1<<6) // Should be set, or not, together with other bits
#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
#include <sstream>
#include <fstream>
#include <cmath>
#include <vector>
#include <list>
#ifdef NAMD_VERSION
// use Lustre-friendly wrapper to POSIX write()
#include "fstream_namd.h"
#endif
class colvarparse;
class colvar;
class colvarbias;
class colvarproxy;
class colvarscript;
/// \brief Collective variables module (main class)
///
/// Class to control the collective variables calculation. An object
/// (usually one) of this class is spawned from the MD program,
/// containing all i/o routines and general interface.
///
/// At initialization, the colvarmodule object creates a proxy object
/// to provide a transparent interface between the MD program and the
/// child objects
class colvarmodule {
private:
/// Impossible to initialize the main object without arguments
colvarmodule();
public:
friend class colvarproxy;
// TODO colvarscript should be unaware of colvarmodule's internals
friend class colvarscript;
/// Defining an abstract real number allows to switch precision
typedef double real;
/// Residue identifier
typedef int residue_id;
class rvector;
template <class T> class vector1d;
template <class T> class matrix2d;
class quaternion;
class rotation;
/// \brief Atom position (different type name from rvector, to make
/// possible future PBC-transparent implementations)
typedef rvector atom_pos;
/// \brief 3x3 matrix of real numbers
class rmatrix;
// allow these classes to access protected data
class atom;
class atom_group;
friend class atom;
friend class atom_group;
typedef std::vector<atom>::iterator atom_iter;
typedef std::vector<atom>::const_iterator atom_const_iter;
/// Module-wide error state
/// see constants at the top of this file
static int errorCode;
static inline void set_error_bits(int code)
{
errorCode |= code;
}
static inline int get_error()
{
return errorCode;
}
static inline void clear_error()
{
errorCode = 0;
}
/// Current step number
static long it;
/// Starting step number for this run
static long it_restart;
/// Return the current step number from the beginning of this run
static inline long step_relative()
{
return it - it_restart;
}
/// Return the current step number from the beginning of the whole
/// calculation
static inline long step_absolute()
{
return it;
}
/// If true, get it_restart from the state file; if set to false,
/// the MD program is providing it
bool it_restart_from_state_file;
/// \brief Finite difference step size (if there is no dynamics, or
/// if gradients need to be tested independently from the size of
/// dt)
static real debug_gradients_step_size;
/// Prefix for all output files for this run
static std::string output_prefix;
/// input restart file name (determined from input_prefix)
static std::string restart_in_name;
/// Array of collective variables
static std::vector<colvar *> colvars;
/* TODO: implement named CVCs
/// Array of named (reusable) collective variable components
static std::vector<cvc *> cvcs;
/// Named cvcs register themselves at initialization time
inline void register_cvc(cvc *p) {
cvcs.push_back(p);
}
*/
/// Array of collective variable biases
static std::vector<colvarbias *> biases;
/// \brief Number of ABF biases initialized (in normal conditions
/// should be 1)
static size_t n_abf_biases;
/// \brief Number of metadynamics biases initialized (in normal
/// conditions should be 1)
static size_t n_meta_biases;
/// \brief Number of restraint biases initialized (no limit on the
/// number)
static size_t n_rest_biases;
/// \brief Number of histograms initialized (no limit on the
/// number)
static size_t n_histo_biases;
/// \brief Whether debug output should be enabled (compile-time option)
static inline bool debug()
{
return COLVARS_DEBUG;
}
/// \brief Constructor \param config_name Configuration file name
/// \param restart_name (optional) Restart file name
colvarmodule(colvarproxy *proxy);
/// Destructor
~colvarmodule();
/// Actual function called by the destructor
int reset();
/// Open a config file, load its contents, and pass it to config_string()
int read_config_file(char const *config_file_name);
/// \brief Parse a config string assuming it is a complete configuration
/// (i.e. calling all parse functions)
int read_config_string(std::string const &conf);
/// \brief Parse a "clean" config string (no comments)
int parse_config(std::string &conf);
// Parse functions (setup internal data based on a string)
/// Parse the few module's global parameters
int parse_global_params(std::string const &conf);
/// Parse and initialize collective variables
int parse_colvars(std::string const &conf);
/// Parse and initialize collective variable biases
int parse_biases(std::string const &conf);
/// Parse and initialize collective variable biases of a specific type
template <class bias_type>
int parse_biases_type(std::string const &conf, char const *keyword, size_t &bias_count);
/// Test error condition and keyword parsing
/// on error, delete new bias
bool check_new_bias(std::string &conf, char const *key);
// "Setup" functions (change internal data based on related data
// from the proxy that may change during program execution)
// No additional parsing is done within these functions
/// (Re)initialize internal data (currently used by LAMMPS)
/// Also calls setup() member functions of colvars and biases
int setup();
/// (Re)initialize and (re)read the input state file calling read_restart()
int setup_input();
/// (Re)initialize the output trajectory and state file (does not write it yet)
int setup_output();
#ifdef NAMD_VERSION
typedef ofstream_namd ofstream;
#else
typedef std::ofstream ofstream;
#endif
/// Read the input restart file
std::istream & read_restart(std::istream &is);
/// Write the output restart file
std::ostream & write_restart(std::ostream &os);
/// Open a trajectory file if requested (and leave it open)
int open_traj_file(std::string const &file_name);
/// Close it
int close_traj_file();
/// Write in the trajectory file
std::ostream & write_traj(std::ostream &os);
/// Write explanatory labels in the trajectory file
std::ostream & write_traj_label(std::ostream &os);
/// Write all FINAL output files
int write_output_files();
/// Backup a file before writing it
static int backup_file(char const *filename);
/// Look up a bias by name; returns NULL if not found
static colvarbias * bias_by_name(std::string const &name);
/// Look up a colvar by name; returns NULL if not found
static colvar * colvar_by_name(std::string const &name);
/// Load new configuration for the given bias -
/// currently works for harmonic (force constant and/or centers)
int change_configuration(std::string const &bias_name, std::string const &conf);
/// Read a colvar value
std::string read_colvar(std::string const &name);
/// Calculate change in energy from using alt. config. for the given bias -
/// currently works for harmonic (force constant and/or centers)
real energy_difference(std::string const &bias_name, std::string const &conf);
/// Give the total number of bins for a given bias.
int bias_bin_num(std::string const &bias_name);
/// Calculate the bin index for a given bias.
int bias_current_bin(std::string const &bias_name);
//// Give the count at a given bin index.
int bias_bin_count(std::string const &bias_name, size_t bin_index);
//// Share among replicas.
int bias_share(std::string const &bias_name);
/// Calculate collective variables and biases
int calc();
/// Perform analysis
int analyze();
/// \brief Read a collective variable trajectory (post-processing
/// only, not called at runtime)
int read_traj(char const *traj_filename,
long traj_read_begin,
long traj_read_end);
/// Quick conversion of an object to a string
template<typename T> static std::string to_str(T const &x,
size_t const &width = 0,
size_t const &prec = 0);
/// Quick conversion of a vector of objects to a string
template<typename T> static std::string to_str(std::vector<T> const &x,
size_t const &width = 0,
size_t const &prec = 0);
/// Reduce the number of characters in a string
static inline std::string wrap_string(std::string const &s,
size_t const &nchars)
{
if (!s.size())
return std::string(nchars, ' ');
else
return ( (s.size() <= size_t(nchars)) ?
(s+std::string(nchars-s.size(), ' ')) :
(std::string(s, 0, nchars)) );
}
/// Number of characters to represent a time step
static size_t const it_width;
/// Number of digits to represent a collective variables value(s)
static size_t const cv_prec;
/// Number of characters to represent a collective variables value(s)
static size_t const cv_width;
/// Number of digits to represent the collective variables energy
static size_t const en_prec;
/// Number of characters to represent the collective variables energy
static size_t const en_width;
/// Line separator in the log output
static std::string const line_marker;
// proxy functions
/// \brief Value of the unit for atomic coordinates with respect to
/// angstroms (used by some variables for hard-coded default values)
static real unit_angstrom();
/// \brief Boltmann constant
static real boltzmann();
/// \brief Temperature of the simulation (K)
static real temperature();
/// \brief Time step of MD integrator (fs)
static real dt();
/// Request calculation of system force from MD engine
static void request_system_force();
/// Print a message to the main log
static void log(std::string const &message);
/// Print a message to the main log and exit with error code
static void fatal_error(std::string const &message);
/// Print a message to the main log and set global error code
static void error(std::string const &message, int code = GENERAL_ERROR);
/// Print a message to the main log and exit normally
static void exit(std::string const &message);
// Replica exchange commands.
static bool replica_enabled();
static int replica_index();
static int replica_num();
static void replica_comm_barrier();
static int replica_comm_recv(char* msg_data, int buf_len, int src_rep);
static int replica_comm_send(char* msg_data, int msg_len, int dest_rep);
/// \brief Get the distance between two atomic positions with pbcs handled
/// correctly
static rvector position_distance(atom_pos const &pos1,
atom_pos const &pos2);
/// \brief Get the square distance between two positions (with
/// periodic boundary conditions handled transparently)
///
/// Note: in the case of periodic boundary conditions, this provides
/// an analytical square distance (while taking the square of
/// position_distance() would produce leads to a cusp)
static real position_dist2(atom_pos const &pos1,
atom_pos const &pos2);
/// \brief Get the closest periodic image to a reference position
/// \param pos The position to look for the closest periodic image
/// \param ref_pos (optional) The reference position
static void select_closest_image(atom_pos &pos,
atom_pos const &ref_pos);
/// \brief Perform select_closest_image() on a set of atomic positions
///
/// After that, distance vectors can then be calculated directly,
/// without using position_distance()
static void select_closest_images(std::vector<atom_pos> &pos,
atom_pos const &ref_pos);
/// \brief Names of groups from a Gromacs .ndx file to be read at startup
static std::list<std::string> index_group_names;
/// \brief Groups from a Gromacs .ndx file read at startup
static std::list<std::vector<int> > index_groups;
/// \brief Read a Gromacs .ndx file
static int read_index_file(char const *filename);
/// \brief Create atoms from a file \param filename name of the file
/// (usually a PDB) \param atoms array of the atoms to be allocated
/// \param pdb_field (optiona) if "filename" is a PDB file, use this
/// field to determine which are the atoms to be set
static int load_atoms(char const *filename,
std::vector<atom> &atoms,
std::string const &pdb_field,
double const pdb_field_value = 0.0);
/// \brief Load the coordinates for a group of atoms from a file
/// (PDB or XYZ)
static int load_coords(char const *filename,
std::vector<atom_pos> &pos,
const std::vector<int> &indices,
std::string const &pdb_field,
double const pdb_field_value = 0.0);
/// \brief Load the coordinates for a group of atoms from an
/// XYZ file
static int load_coords_xyz(char const *filename,
std::vector<atom_pos> &pos,
const std::vector<int> &indices);
/// Frequency for collective variables trajectory output
static size_t cv_traj_freq;
/// \brief True if only analysis is performed and not a run
static bool b_analysis;
/// Frequency for saving output restarts
static size_t restart_out_freq;
/// Output restart file name
std::string restart_out_name;
/// Pseudo-random number with Gaussian distribution
static real rand_gaussian(void);
protected:
/// Configuration file
std::ifstream config_s;
/// Configuration file parser object
colvarparse *parse;
/// Name of the trajectory file
std::string cv_traj_name;
/// Collective variables output trajectory file
colvarmodule::ofstream cv_traj_os;
/// Appending to the existing trajectory file?
bool cv_traj_append;
/// Output restart file
colvarmodule::ofstream restart_out_os;
/// \brief Counter for the current depth in the object hierarchy (useg e.g. in output
static size_t depth;
/// Use scripted colvars forces?
static bool use_scripted_forces;
public:
/// \brief Pointer to the proxy object, used to retrieve atomic data
/// from the hosting program; it is static in order to be accessible
/// from static functions in the colvarmodule class
static colvarproxy *proxy;
/// Increase the depth (number of indentations in the output)
static void increase_depth();
/// Decrease the depth (number of indentations in the output)
static void decrease_depth();
static inline bool scripted_forces() { return use_scripted_forces; }
};
/// Shorthand for the frequently used type prefix
typedef colvarmodule cvm;
#include "colvartypes.h"
std::ostream & operator << (std::ostream &os, cvm::rvector const &v);
std::istream & operator >> (std::istream &is, cvm::rvector &v);
template<typename T> std::string cvm::to_str(T const &x,
size_t const &width,
size_t const &prec) {
std::ostringstream os;
if (width) os.width(width);
if (prec) {
os.setf(std::ios::scientific, std::ios::floatfield);
os.precision(prec);
}
os << x;
return os.str();
}
template<typename T> std::string cvm::to_str(std::vector<T> const &x,
size_t const &width,
size_t const &prec) {
if (!x.size()) return std::string("");
std::ostringstream os;
if (prec) {
os.setf(std::ios::scientific, std::ios::floatfield);
}
os << "{ ";
if (width) os.width(width);
if (prec) os.precision(prec);
os << x[0];
for (size_t i = 1; i < x.size(); i++) {
os << ", ";
if (width) os.width(width);
if (prec) os.precision(prec);
os << x[i];
}
os << " }";
return os.str();
}
#include "colvarproxy.h"
inline cvm::real cvm::unit_angstrom()
{
return proxy->unit_angstrom();
}
inline cvm::real cvm::boltzmann()
{
return proxy->boltzmann();
}
inline cvm::real cvm::temperature()
{
return proxy->temperature();
}
inline cvm::real cvm::dt()
{
return proxy->dt();
}
// Replica exchange commands
inline bool cvm::replica_enabled() {
return proxy->replica_enabled();
}
inline int cvm::replica_index() {
return proxy->replica_index();
}
inline int cvm::replica_num() {
return proxy->replica_num();
}
inline void cvm::replica_comm_barrier() {
return proxy->replica_comm_barrier();
}
inline int cvm::replica_comm_recv(char* msg_data, int buf_len, int src_rep) {
return proxy->replica_comm_recv(msg_data,buf_len,src_rep);
}
inline int cvm::replica_comm_send(char* msg_data, int msg_len, int dest_rep) {
return proxy->replica_comm_send(msg_data,msg_len,dest_rep);
}
inline void cvm::request_system_force()
{
proxy->request_system_force(true);
}
inline void cvm::select_closest_image(atom_pos &pos,
atom_pos const &ref_pos)
{
proxy->select_closest_image(pos, ref_pos);
}
inline void cvm::select_closest_images(std::vector<atom_pos> &pos,
atom_pos const &ref_pos)
{
proxy->select_closest_images(pos, ref_pos);
}
inline cvm::rvector cvm::position_distance(atom_pos const &pos1,
atom_pos const &pos2)
{
return proxy->position_distance(pos1, pos2);
}
inline cvm::real cvm::position_dist2(cvm::atom_pos const &pos1,
cvm::atom_pos const &pos2)
{
return proxy->position_dist2(pos1, pos2);
}
inline cvm::real cvm::rand_gaussian(void)
{
return proxy->rand_gaussian();
}
#endif
|
dh4nav/lammps
|
lib/colvars/colvarmodule.h
|
C
|
gpl-2.0
| 19,246 |
/* thread_info.h: x86_64 low-level thread information
*
* Copyright (C) 2002 David Howells ([email protected])
* - Incorporating suggestions made by Linus Torvalds and Dave Miller
*/
#ifndef _ASM_THREAD_INFO_H
#define _ASM_THREAD_INFO_H
#ifdef __KERNEL__
#include <asm/page.h>
#include <asm/types.h>
#include <asm/pda.h>
/*
* low level task data that entry.S needs immediate access to
* - this struct should fit entirely inside of one cache line
* - this struct shares the supervisor stack pages
*/
#ifndef __ASSEMBLY__
struct task_struct;
struct exec_domain;
#include <asm/mmsegment.h>
struct thread_info {
struct task_struct *task; /* main task structure */
struct exec_domain *exec_domain; /* execution domain */
__u32 flags; /* low level flags */
__u32 status; /* thread synchronous flags */
__u32 cpu; /* current CPU */
int preempt_count; /* 0 => preemptable, <0 => BUG */
mm_segment_t addr_limit;
struct restart_block restart_block;
};
#endif
/*
* macros/functions for gaining access to the thread information structure
* preempt_count needs to be 1 initially, until the scheduler is functional.
*/
#ifndef __ASSEMBLY__
#define INIT_THREAD_INFO(tsk) \
{ \
.task = &tsk, \
.exec_domain = &default_exec_domain, \
.flags = 0, \
.cpu = 0, \
.preempt_count = 1, \
.addr_limit = KERNEL_DS, \
.restart_block = { \
.fn = do_no_restart_syscall, \
}, \
}
#define init_thread_info (init_thread_union.thread_info)
#define init_stack (init_thread_union.stack)
static inline struct thread_info *current_thread_info(void)
{
struct thread_info *ti;
ti = (void *)(read_pda(kernelstack) + PDA_STACKOFFSET - THREAD_SIZE);
return ti;
}
/* do not use in interrupt context */
static inline struct thread_info *stack_thread_info(void)
{
struct thread_info *ti;
__asm__("andq %%rsp,%0; ":"=r" (ti) : "0" (~(THREAD_SIZE - 1)));
return ti;
}
/* thread information allocation */
#ifdef CONFIG_DEBUG_STACK_USAGE
#define alloc_thread_info(tsk) \
({ \
struct thread_info *ret; \
\
ret = ((struct thread_info *) __get_free_pages(GFP_KERNEL,THREAD_ORDER)); \
if (ret) \
memset(ret, 0, THREAD_SIZE); \
ret; \
})
#else
#define alloc_thread_info(tsk) \
((struct thread_info *) __get_free_pages(GFP_KERNEL,THREAD_ORDER))
#endif
#define free_thread_info(ti) free_pages((unsigned long) (ti), THREAD_ORDER)
#else /* !__ASSEMBLY__ */
/* how to get the thread information struct from ASM */
#define GET_THREAD_INFO(reg) \
movq %gs:pda_kernelstack,reg ; \
subq $(THREAD_SIZE-PDA_STACKOFFSET),reg
#endif
/*
* thread information flags
* - these are process state flags that various assembly files may need to access
* - pending work-to-be-done flags are in LSW
* - other flags in MSW
* Warning: layout of LSW is hardcoded in entry.S
*/
#define TIF_SYSCALL_TRACE 0 /* syscall trace active */
#define TIF_NOTIFY_RESUME 1 /* resumption notification requested */
#define TIF_SIGPENDING 2 /* signal pending */
#define TIF_NEED_RESCHED 3 /* rescheduling necessary */
#define TIF_SINGLESTEP 4 /* reenable singlestep on user return*/
#define TIF_IRET 5 /* force IRET */
#define TIF_SYSCALL_AUDIT 7 /* syscall auditing active */
#define TIF_SECCOMP 8 /* secure computing */
/* 16 free */
#define TIF_IA32 17 /* 32bit process */
#define TIF_FORK 18 /* ret_from_fork */
#define TIF_ABI_PENDING 19
#define TIF_MEMDIE 20
#define _TIF_SYSCALL_TRACE (1<<TIF_SYSCALL_TRACE)
#define _TIF_NOTIFY_RESUME (1<<TIF_NOTIFY_RESUME)
#define _TIF_SIGPENDING (1<<TIF_SIGPENDING)
#define _TIF_SINGLESTEP (1<<TIF_SINGLESTEP)
#define _TIF_NEED_RESCHED (1<<TIF_NEED_RESCHED)
#define _TIF_IRET (1<<TIF_IRET)
#define _TIF_SYSCALL_AUDIT (1<<TIF_SYSCALL_AUDIT)
#define _TIF_SECCOMP (1<<TIF_SECCOMP)
#define _TIF_IA32 (1<<TIF_IA32)
#define _TIF_FORK (1<<TIF_FORK)
#define _TIF_ABI_PENDING (1<<TIF_ABI_PENDING)
/* work to do on interrupt/exception return */
#define _TIF_WORK_MASK \
(0x0000FFFF & ~(_TIF_SYSCALL_TRACE|_TIF_SYSCALL_AUDIT|_TIF_SINGLESTEP|_TIF_SECCOMP))
/* work to do on any return to user space */
#define _TIF_ALLWORK_MASK (0x0000FFFF & ~_TIF_SECCOMP)
#define PREEMPT_ACTIVE 0x10000000
/*
* Thread-synchronous status.
*
* This is different from the flags in that nobody else
* ever touches our thread-synchronous status, so we don't
* have to worry about atomic accesses.
*/
#define TS_USEDFPU 0x0001 /* FPU was used by this task this quantum (SMP) */
#define TS_COMPAT 0x0002 /* 32bit syscall active */
#define TS_POLLING 0x0004 /* true if in idle loop and not sleeping */
#define tsk_is_polling(t) ((t)->thread_info->status & TS_POLLING)
#endif /* __KERNEL__ */
#endif /* _ASM_THREAD_INFO_H */
|
laitianli/kernel-change_linux-2.6.18
|
include/asm-x86_64/thread_info.h
|
C
|
gpl-2.0
| 4,756 |
/*
* Copyright (c) 2007-2010 Stefano Sabatini
*
* This file is part of FFmpeg.
*
* FFmpeg 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.
*
* FFmpeg 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 FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* simple media prober based on the FFmpeg libraries
*/
#include "config.h"
#include "libavutil/ffversion.h"
#include <string.h>
#include "libavformat/avformat.h"
#include "libavcodec/avcodec.h"
#include "libavutil/avassert.h"
#include "libavutil/avstring.h"
#include "libavutil/bprint.h"
#include "libavutil/display.h"
#include "libavutil/hash.h"
#include "libavutil/opt.h"
#include "libavutil/pixdesc.h"
#include "libavutil/dict.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/libm.h"
#include "libavutil/parseutils.h"
#include "libavutil/timecode.h"
#include "libavutil/timestamp.h"
#include "libavdevice/avdevice.h"
#include "libswscale/swscale.h"
#include "libswresample/swresample.h"
#include "libpostproc/postprocess.h"
#include "cmdutils.h"
const char program_name[] = "ffprobe";
const int program_birth_year = 2007;
static int do_bitexact = 0;
static int do_count_frames = 0;
static int do_count_packets = 0;
static int do_read_frames = 0;
static int do_read_packets = 0;
static int do_show_chapters = 0;
static int do_show_error = 0;
static int do_show_format = 0;
static int do_show_frames = 0;
static int do_show_packets = 0;
static int do_show_programs = 0;
static int do_show_streams = 0;
static int do_show_stream_disposition = 0;
static int do_show_data = 0;
static int do_show_program_version = 0;
static int do_show_library_versions = 0;
static int do_show_pixel_formats = 0;
static int do_show_pixel_format_flags = 0;
static int do_show_pixel_format_components = 0;
static int do_show_chapter_tags = 0;
static int do_show_format_tags = 0;
static int do_show_frame_tags = 0;
static int do_show_program_tags = 0;
static int do_show_stream_tags = 0;
static int show_value_unit = 0;
static int use_value_prefix = 0;
static int use_byte_value_binary_prefix = 0;
static int use_value_sexagesimal_format = 0;
static int show_private_data = 1;
static char *print_format;
static char *stream_specifier;
static char *show_data_hash;
typedef struct ReadInterval {
int id; ///< identifier
int64_t start, end; ///< start, end in second/AV_TIME_BASE units
int has_start, has_end;
int start_is_offset, end_is_offset;
int duration_frames;
} ReadInterval;
static ReadInterval *read_intervals;
static int read_intervals_nb = 0;
/* section structure definition */
#define SECTION_MAX_NB_CHILDREN 10
struct section {
int id; ///< unique id identifying a section
const char *name;
#define SECTION_FLAG_IS_WRAPPER 1 ///< the section only contains other sections, but has no data at its own level
#define SECTION_FLAG_IS_ARRAY 2 ///< the section contains an array of elements of the same type
#define SECTION_FLAG_HAS_VARIABLE_FIELDS 4 ///< the section may contain a variable number of fields with variable keys.
/// For these sections the element_name field is mandatory.
int flags;
int children_ids[SECTION_MAX_NB_CHILDREN+1]; ///< list of children section IDS, terminated by -1
const char *element_name; ///< name of the contained element, if provided
const char *unique_name; ///< unique section name, in case the name is ambiguous
AVDictionary *entries_to_show;
int show_all_entries;
};
typedef enum {
SECTION_ID_NONE = -1,
SECTION_ID_CHAPTER,
SECTION_ID_CHAPTER_TAGS,
SECTION_ID_CHAPTERS,
SECTION_ID_ERROR,
SECTION_ID_FORMAT,
SECTION_ID_FORMAT_TAGS,
SECTION_ID_FRAME,
SECTION_ID_FRAMES,
SECTION_ID_FRAME_TAGS,
SECTION_ID_FRAME_SIDE_DATA_LIST,
SECTION_ID_FRAME_SIDE_DATA,
SECTION_ID_LIBRARY_VERSION,
SECTION_ID_LIBRARY_VERSIONS,
SECTION_ID_PACKET,
SECTION_ID_PACKETS,
SECTION_ID_PACKETS_AND_FRAMES,
SECTION_ID_PACKET_SIDE_DATA_LIST,
SECTION_ID_PACKET_SIDE_DATA,
SECTION_ID_PIXEL_FORMAT,
SECTION_ID_PIXEL_FORMAT_FLAGS,
SECTION_ID_PIXEL_FORMAT_COMPONENT,
SECTION_ID_PIXEL_FORMAT_COMPONENTS,
SECTION_ID_PIXEL_FORMATS,
SECTION_ID_PROGRAM_STREAM_DISPOSITION,
SECTION_ID_PROGRAM_STREAM_TAGS,
SECTION_ID_PROGRAM,
SECTION_ID_PROGRAM_STREAMS,
SECTION_ID_PROGRAM_STREAM,
SECTION_ID_PROGRAM_TAGS,
SECTION_ID_PROGRAM_VERSION,
SECTION_ID_PROGRAMS,
SECTION_ID_ROOT,
SECTION_ID_STREAM,
SECTION_ID_STREAM_DISPOSITION,
SECTION_ID_STREAMS,
SECTION_ID_STREAM_TAGS,
SECTION_ID_STREAM_SIDE_DATA_LIST,
SECTION_ID_STREAM_SIDE_DATA,
SECTION_ID_SUBTITLE,
} SectionID;
static struct section sections[] = {
[SECTION_ID_CHAPTERS] = { SECTION_ID_CHAPTERS, "chapters", SECTION_FLAG_IS_ARRAY, { SECTION_ID_CHAPTER, -1 } },
[SECTION_ID_CHAPTER] = { SECTION_ID_CHAPTER, "chapter", 0, { SECTION_ID_CHAPTER_TAGS, -1 } },
[SECTION_ID_CHAPTER_TAGS] = { SECTION_ID_CHAPTER_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "chapter_tags" },
[SECTION_ID_ERROR] = { SECTION_ID_ERROR, "error", 0, { -1 } },
[SECTION_ID_FORMAT] = { SECTION_ID_FORMAT, "format", 0, { SECTION_ID_FORMAT_TAGS, -1 } },
[SECTION_ID_FORMAT_TAGS] = { SECTION_ID_FORMAT_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "format_tags" },
[SECTION_ID_FRAMES] = { SECTION_ID_FRAMES, "frames", SECTION_FLAG_IS_ARRAY, { SECTION_ID_FRAME, SECTION_ID_SUBTITLE, -1 } },
[SECTION_ID_FRAME] = { SECTION_ID_FRAME, "frame", 0, { SECTION_ID_FRAME_TAGS, SECTION_ID_FRAME_SIDE_DATA_LIST, -1 } },
[SECTION_ID_FRAME_TAGS] = { SECTION_ID_FRAME_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "frame_tags" },
[SECTION_ID_FRAME_SIDE_DATA_LIST] ={ SECTION_ID_FRAME_SIDE_DATA_LIST, "side_data_list", SECTION_FLAG_IS_ARRAY, { SECTION_ID_FRAME_SIDE_DATA, -1 } },
[SECTION_ID_FRAME_SIDE_DATA] = { SECTION_ID_FRAME_SIDE_DATA, "side_data", 0, { -1 } },
[SECTION_ID_LIBRARY_VERSIONS] = { SECTION_ID_LIBRARY_VERSIONS, "library_versions", SECTION_FLAG_IS_ARRAY, { SECTION_ID_LIBRARY_VERSION, -1 } },
[SECTION_ID_LIBRARY_VERSION] = { SECTION_ID_LIBRARY_VERSION, "library_version", 0, { -1 } },
[SECTION_ID_PACKETS] = { SECTION_ID_PACKETS, "packets", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PACKET, -1} },
[SECTION_ID_PACKETS_AND_FRAMES] = { SECTION_ID_PACKETS_AND_FRAMES, "packets_and_frames", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PACKET, -1} },
[SECTION_ID_PACKET] = { SECTION_ID_PACKET, "packet", 0, { SECTION_ID_PACKET_SIDE_DATA_LIST, -1 } },
[SECTION_ID_PACKET_SIDE_DATA_LIST] ={ SECTION_ID_PACKET_SIDE_DATA_LIST, "side_data_list", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PACKET_SIDE_DATA, -1 } },
[SECTION_ID_PACKET_SIDE_DATA] = { SECTION_ID_PACKET_SIDE_DATA, "side_data", 0, { -1 } },
[SECTION_ID_PIXEL_FORMATS] = { SECTION_ID_PIXEL_FORMATS, "pixel_formats", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PIXEL_FORMAT, -1 } },
[SECTION_ID_PIXEL_FORMAT] = { SECTION_ID_PIXEL_FORMAT, "pixel_format", 0, { SECTION_ID_PIXEL_FORMAT_FLAGS, SECTION_ID_PIXEL_FORMAT_COMPONENTS, -1 } },
[SECTION_ID_PIXEL_FORMAT_FLAGS] = { SECTION_ID_PIXEL_FORMAT_FLAGS, "flags", 0, { -1 }, .unique_name = "pixel_format_flags" },
[SECTION_ID_PIXEL_FORMAT_COMPONENTS] = { SECTION_ID_PIXEL_FORMAT_COMPONENTS, "components", SECTION_FLAG_IS_ARRAY, {SECTION_ID_PIXEL_FORMAT_COMPONENT, -1 }, .unique_name = "pixel_format_components" },
[SECTION_ID_PIXEL_FORMAT_COMPONENT] = { SECTION_ID_PIXEL_FORMAT_COMPONENT, "component", 0, { -1 } },
[SECTION_ID_PROGRAM_STREAM_DISPOSITION] = { SECTION_ID_PROGRAM_STREAM_DISPOSITION, "disposition", 0, { -1 }, .unique_name = "program_stream_disposition" },
[SECTION_ID_PROGRAM_STREAM_TAGS] = { SECTION_ID_PROGRAM_STREAM_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "program_stream_tags" },
[SECTION_ID_PROGRAM] = { SECTION_ID_PROGRAM, "program", 0, { SECTION_ID_PROGRAM_TAGS, SECTION_ID_PROGRAM_STREAMS, -1 } },
[SECTION_ID_PROGRAM_STREAMS] = { SECTION_ID_PROGRAM_STREAMS, "streams", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PROGRAM_STREAM, -1 }, .unique_name = "program_streams" },
[SECTION_ID_PROGRAM_STREAM] = { SECTION_ID_PROGRAM_STREAM, "stream", 0, { SECTION_ID_PROGRAM_STREAM_DISPOSITION, SECTION_ID_PROGRAM_STREAM_TAGS, -1 }, .unique_name = "program_stream" },
[SECTION_ID_PROGRAM_TAGS] = { SECTION_ID_PROGRAM_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "program_tags" },
[SECTION_ID_PROGRAM_VERSION] = { SECTION_ID_PROGRAM_VERSION, "program_version", 0, { -1 } },
[SECTION_ID_PROGRAMS] = { SECTION_ID_PROGRAMS, "programs", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PROGRAM, -1 } },
[SECTION_ID_ROOT] = { SECTION_ID_ROOT, "root", SECTION_FLAG_IS_WRAPPER,
{ SECTION_ID_CHAPTERS, SECTION_ID_FORMAT, SECTION_ID_FRAMES, SECTION_ID_PROGRAMS, SECTION_ID_STREAMS,
SECTION_ID_PACKETS, SECTION_ID_ERROR, SECTION_ID_PROGRAM_VERSION, SECTION_ID_LIBRARY_VERSIONS,
SECTION_ID_PIXEL_FORMATS, -1} },
[SECTION_ID_STREAMS] = { SECTION_ID_STREAMS, "streams", SECTION_FLAG_IS_ARRAY, { SECTION_ID_STREAM, -1 } },
[SECTION_ID_STREAM] = { SECTION_ID_STREAM, "stream", 0, { SECTION_ID_STREAM_DISPOSITION, SECTION_ID_STREAM_TAGS, SECTION_ID_STREAM_SIDE_DATA_LIST, -1 } },
[SECTION_ID_STREAM_DISPOSITION] = { SECTION_ID_STREAM_DISPOSITION, "disposition", 0, { -1 }, .unique_name = "stream_disposition" },
[SECTION_ID_STREAM_TAGS] = { SECTION_ID_STREAM_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "stream_tags" },
[SECTION_ID_STREAM_SIDE_DATA_LIST] ={ SECTION_ID_STREAM_SIDE_DATA_LIST, "side_data_list", SECTION_FLAG_IS_ARRAY, { SECTION_ID_STREAM_SIDE_DATA, -1 } },
[SECTION_ID_STREAM_SIDE_DATA] = { SECTION_ID_STREAM_SIDE_DATA, "side_data", 0, { -1 } },
[SECTION_ID_SUBTITLE] = { SECTION_ID_SUBTITLE, "subtitle", 0, { -1 } },
};
static const OptionDef *options;
/* FFprobe context */
static const char *input_filename;
static AVInputFormat *iformat = NULL;
static struct AVHashContext *hash;
static const char *const binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
static const char *const decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P" };
static const char unit_second_str[] = "s" ;
static const char unit_hertz_str[] = "Hz" ;
static const char unit_byte_str[] = "byte" ;
static const char unit_bit_per_second_str[] = "bit/s";
static int nb_streams;
static uint64_t *nb_streams_packets;
static uint64_t *nb_streams_frames;
static int *selected_streams;
static void ffprobe_cleanup(int ret)
{
int i;
for (i = 0; i < FF_ARRAY_ELEMS(sections); i++)
av_dict_free(&(sections[i].entries_to_show));
}
struct unit_value {
union { double d; long long int i; } val;
const char *unit;
};
static char *value_string(char *buf, int buf_size, struct unit_value uv)
{
double vald;
long long int vali;
int show_float = 0;
if (uv.unit == unit_second_str) {
vald = uv.val.d;
show_float = 1;
} else {
vald = vali = uv.val.i;
}
if (uv.unit == unit_second_str && use_value_sexagesimal_format) {
double secs;
int hours, mins;
secs = vald;
mins = (int)secs / 60;
secs = secs - mins * 60;
hours = mins / 60;
mins %= 60;
snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
} else {
const char *prefix_string = "";
if (use_value_prefix && vald > 1) {
long long int index;
if (uv.unit == unit_byte_str && use_byte_value_binary_prefix) {
index = (long long int) (log2(vald)) / 10;
index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) - 1);
vald /= exp2(index * 10);
prefix_string = binary_unit_prefixes[index];
} else {
index = (long long int) (log10(vald)) / 3;
index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) - 1);
vald /= pow(10, index * 3);
prefix_string = decimal_unit_prefixes[index];
}
vali = vald;
}
if (show_float || (use_value_prefix && vald != (long long int)vald))
snprintf(buf, buf_size, "%f", vald);
else
snprintf(buf, buf_size, "%lld", vali);
av_strlcatf(buf, buf_size, "%s%s%s", *prefix_string || show_value_unit ? " " : "",
prefix_string, show_value_unit ? uv.unit : "");
}
return buf;
}
/* WRITERS API */
typedef struct WriterContext WriterContext;
#define WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS 1
#define WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER 2
typedef enum {
WRITER_STRING_VALIDATION_FAIL,
WRITER_STRING_VALIDATION_REPLACE,
WRITER_STRING_VALIDATION_IGNORE,
WRITER_STRING_VALIDATION_NB
} StringValidation;
typedef struct Writer {
const AVClass *priv_class; ///< private class of the writer, if any
int priv_size; ///< private size for the writer context
const char *name;
int (*init) (WriterContext *wctx);
void (*uninit)(WriterContext *wctx);
void (*print_section_header)(WriterContext *wctx);
void (*print_section_footer)(WriterContext *wctx);
void (*print_integer) (WriterContext *wctx, const char *, long long int);
void (*print_rational) (WriterContext *wctx, AVRational *q, char *sep);
void (*print_string) (WriterContext *wctx, const char *, const char *);
int flags; ///< a combination or WRITER_FLAG_*
} Writer;
#define SECTION_MAX_NB_LEVELS 10
struct WriterContext {
const AVClass *class; ///< class of the writer
const Writer *writer; ///< the Writer of which this is an instance
char *name; ///< name of this writer instance
void *priv; ///< private data for use by the filter
const struct section *sections; ///< array containing all sections
int nb_sections; ///< number of sections
int level; ///< current level, starting from 0
/** number of the item printed in the given section, starting from 0 */
unsigned int nb_item[SECTION_MAX_NB_LEVELS];
/** section per each level */
const struct section *section[SECTION_MAX_NB_LEVELS];
AVBPrint section_pbuf[SECTION_MAX_NB_LEVELS]; ///< generic print buffer dedicated to each section,
/// used by various writers
unsigned int nb_section_packet; ///< number of the packet section in case we are in "packets_and_frames" section
unsigned int nb_section_frame; ///< number of the frame section in case we are in "packets_and_frames" section
unsigned int nb_section_packet_frame; ///< nb_section_packet or nb_section_frame according if is_packets_and_frames
int string_validation;
char *string_validation_replacement;
unsigned int string_validation_utf8_flags;
};
static const char *writer_get_name(void *p)
{
WriterContext *wctx = p;
return wctx->writer->name;
}
#define OFFSET(x) offsetof(WriterContext, x)
static const AVOption writer_options[] = {
{ "string_validation", "set string validation mode",
OFFSET(string_validation), AV_OPT_TYPE_INT, {.i64=WRITER_STRING_VALIDATION_REPLACE}, 0, WRITER_STRING_VALIDATION_NB-1, .unit = "sv" },
{ "sv", "set string validation mode",
OFFSET(string_validation), AV_OPT_TYPE_INT, {.i64=WRITER_STRING_VALIDATION_REPLACE}, 0, WRITER_STRING_VALIDATION_NB-1, .unit = "sv" },
{ "ignore", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = WRITER_STRING_VALIDATION_IGNORE}, .unit = "sv" },
{ "replace", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = WRITER_STRING_VALIDATION_REPLACE}, .unit = "sv" },
{ "fail", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = WRITER_STRING_VALIDATION_FAIL}, .unit = "sv" },
{ "string_validation_replacement", "set string validation replacement string", OFFSET(string_validation_replacement), AV_OPT_TYPE_STRING, {.str=""}},
{ "svr", "set string validation replacement string", OFFSET(string_validation_replacement), AV_OPT_TYPE_STRING, {.str="\xEF\xBF\xBD"}},
{ NULL }
};
static void *writer_child_next(void *obj, void *prev)
{
WriterContext *ctx = obj;
if (!prev && ctx->writer && ctx->writer->priv_class && ctx->priv)
return ctx->priv;
return NULL;
}
static const AVClass writer_class = {
.class_name = "Writer",
.item_name = writer_get_name,
.option = writer_options,
.version = LIBAVUTIL_VERSION_INT,
.child_next = writer_child_next,
};
static void writer_close(WriterContext **wctx)
{
int i;
if (!*wctx)
return;
if ((*wctx)->writer->uninit)
(*wctx)->writer->uninit(*wctx);
for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
av_bprint_finalize(&(*wctx)->section_pbuf[i], NULL);
if ((*wctx)->writer->priv_class)
av_opt_free((*wctx)->priv);
av_freep(&((*wctx)->priv));
av_opt_free(*wctx);
av_freep(wctx);
}
static void bprint_bytes(AVBPrint *bp, const uint8_t *ubuf, size_t ubuf_size)
{
int i;
av_bprintf(bp, "0X");
for (i = 0; i < ubuf_size; i++)
av_bprintf(bp, "%02X", ubuf[i]);
}
static int writer_open(WriterContext **wctx, const Writer *writer, const char *args,
const struct section *sections, int nb_sections)
{
int i, ret = 0;
if (!(*wctx = av_mallocz(sizeof(WriterContext)))) {
ret = AVERROR(ENOMEM);
goto fail;
}
if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
ret = AVERROR(ENOMEM);
goto fail;
}
(*wctx)->class = &writer_class;
(*wctx)->writer = writer;
(*wctx)->level = -1;
(*wctx)->sections = sections;
(*wctx)->nb_sections = nb_sections;
av_opt_set_defaults(*wctx);
if (writer->priv_class) {
void *priv_ctx = (*wctx)->priv;
*((const AVClass **)priv_ctx) = writer->priv_class;
av_opt_set_defaults(priv_ctx);
}
/* convert options to dictionary */
if (args) {
AVDictionary *opts = NULL;
AVDictionaryEntry *opt = NULL;
if ((ret = av_dict_parse_string(&opts, args, "=", ":", 0)) < 0) {
av_log(*wctx, AV_LOG_ERROR, "Failed to parse option string '%s' provided to writer context\n", args);
av_dict_free(&opts);
goto fail;
}
while ((opt = av_dict_get(opts, "", opt, AV_DICT_IGNORE_SUFFIX))) {
if ((ret = av_opt_set(*wctx, opt->key, opt->value, AV_OPT_SEARCH_CHILDREN)) < 0) {
av_log(*wctx, AV_LOG_ERROR, "Failed to set option '%s' with value '%s' provided to writer context\n",
opt->key, opt->value);
av_dict_free(&opts);
goto fail;
}
}
av_dict_free(&opts);
}
/* validate replace string */
{
const uint8_t *p = (*wctx)->string_validation_replacement;
const uint8_t *endp = p + strlen(p);
while (*p) {
const uint8_t *p0 = p;
int32_t code;
ret = av_utf8_decode(&code, &p, endp, (*wctx)->string_validation_utf8_flags);
if (ret < 0) {
AVBPrint bp;
av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
bprint_bytes(&bp, p0, p-p0),
av_log(wctx, AV_LOG_ERROR,
"Invalid UTF8 sequence %s found in string validation replace '%s'\n",
bp.str, (*wctx)->string_validation_replacement);
return ret;
}
}
}
for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
av_bprint_init(&(*wctx)->section_pbuf[i], 1, AV_BPRINT_SIZE_UNLIMITED);
if ((*wctx)->writer->init)
ret = (*wctx)->writer->init(*wctx);
if (ret < 0)
goto fail;
return 0;
fail:
writer_close(wctx);
return ret;
}
static inline void writer_print_section_header(WriterContext *wctx,
int section_id)
{
int parent_section_id;
wctx->level++;
av_assert0(wctx->level < SECTION_MAX_NB_LEVELS);
parent_section_id = wctx->level ?
(wctx->section[wctx->level-1])->id : SECTION_ID_NONE;
wctx->nb_item[wctx->level] = 0;
wctx->section[wctx->level] = &wctx->sections[section_id];
if (section_id == SECTION_ID_PACKETS_AND_FRAMES) {
wctx->nb_section_packet = wctx->nb_section_frame =
wctx->nb_section_packet_frame = 0;
} else if (parent_section_id == SECTION_ID_PACKETS_AND_FRAMES) {
wctx->nb_section_packet_frame = section_id == SECTION_ID_PACKET ?
wctx->nb_section_packet : wctx->nb_section_frame;
}
if (wctx->writer->print_section_header)
wctx->writer->print_section_header(wctx);
}
static inline void writer_print_section_footer(WriterContext *wctx)
{
int section_id = wctx->section[wctx->level]->id;
int parent_section_id = wctx->level ?
wctx->section[wctx->level-1]->id : SECTION_ID_NONE;
if (parent_section_id != SECTION_ID_NONE)
wctx->nb_item[wctx->level-1]++;
if (parent_section_id == SECTION_ID_PACKETS_AND_FRAMES) {
if (section_id == SECTION_ID_PACKET) wctx->nb_section_packet++;
else wctx->nb_section_frame++;
}
if (wctx->writer->print_section_footer)
wctx->writer->print_section_footer(wctx);
wctx->level--;
}
static inline void writer_print_integer(WriterContext *wctx,
const char *key, long long int val)
{
const struct section *section = wctx->section[wctx->level];
if (section->show_all_entries || av_dict_get(section->entries_to_show, key, NULL, 0)) {
wctx->writer->print_integer(wctx, key, val);
wctx->nb_item[wctx->level]++;
}
}
static inline int validate_string(WriterContext *wctx, char **dstp, const char *src)
{
const uint8_t *p, *endp;
AVBPrint dstbuf;
int invalid_chars_nb = 0, ret = 0;
av_bprint_init(&dstbuf, 0, AV_BPRINT_SIZE_UNLIMITED);
endp = src + strlen(src);
for (p = (uint8_t *)src; *p;) {
uint32_t code;
int invalid = 0;
const uint8_t *p0 = p;
if (av_utf8_decode(&code, &p, endp, wctx->string_validation_utf8_flags) < 0) {
AVBPrint bp;
av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
bprint_bytes(&bp, p0, p-p0);
av_log(wctx, AV_LOG_DEBUG,
"Invalid UTF-8 sequence %s found in string '%s'\n", bp.str, src);
invalid = 1;
}
if (invalid) {
invalid_chars_nb++;
switch (wctx->string_validation) {
case WRITER_STRING_VALIDATION_FAIL:
av_log(wctx, AV_LOG_ERROR,
"Invalid UTF-8 sequence found in string '%s'\n", src);
ret = AVERROR_INVALIDDATA;
goto end;
break;
case WRITER_STRING_VALIDATION_REPLACE:
av_bprintf(&dstbuf, "%s", wctx->string_validation_replacement);
break;
}
}
if (!invalid || wctx->string_validation == WRITER_STRING_VALIDATION_IGNORE)
av_bprint_append_data(&dstbuf, p0, p-p0);
}
if (invalid_chars_nb && wctx->string_validation == WRITER_STRING_VALIDATION_REPLACE) {
av_log(wctx, AV_LOG_WARNING,
"%d invalid UTF-8 sequence(s) found in string '%s', replaced with '%s'\n",
invalid_chars_nb, src, wctx->string_validation_replacement);
}
end:
av_bprint_finalize(&dstbuf, dstp);
return ret;
}
#define PRINT_STRING_OPT 1
#define PRINT_STRING_VALIDATE 2
static inline int writer_print_string(WriterContext *wctx,
const char *key, const char *val, int flags)
{
const struct section *section = wctx->section[wctx->level];
int ret = 0;
if ((flags & PRINT_STRING_OPT)
&& !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))
return 0;
if (section->show_all_entries || av_dict_get(section->entries_to_show, key, NULL, 0)) {
if (flags & PRINT_STRING_VALIDATE) {
char *key1 = NULL, *val1 = NULL;
ret = validate_string(wctx, &key1, key);
if (ret < 0) goto end;
ret = validate_string(wctx, &val1, val);
if (ret < 0) goto end;
wctx->writer->print_string(wctx, key1, val1);
end:
if (ret < 0) {
av_log(wctx, AV_LOG_ERROR,
"Invalid key=value string combination %s=%s in section %s\n",
key, val, section->unique_name);
}
av_free(key1);
av_free(val1);
} else {
wctx->writer->print_string(wctx, key, val);
}
wctx->nb_item[wctx->level]++;
}
return ret;
}
static inline void writer_print_rational(WriterContext *wctx,
const char *key, AVRational q, char sep)
{
AVBPrint buf;
av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
av_bprintf(&buf, "%d%c%d", q.num, sep, q.den);
writer_print_string(wctx, key, buf.str, 0);
}
static void writer_print_time(WriterContext *wctx, const char *key,
int64_t ts, const AVRational *time_base, int is_duration)
{
char buf[128];
if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
writer_print_string(wctx, key, "N/A", PRINT_STRING_OPT);
} else {
double d = ts * av_q2d(*time_base);
struct unit_value uv;
uv.val.d = d;
uv.unit = unit_second_str;
value_string(buf, sizeof(buf), uv);
writer_print_string(wctx, key, buf, 0);
}
}
static void writer_print_ts(WriterContext *wctx, const char *key, int64_t ts, int is_duration)
{
if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
writer_print_string(wctx, key, "N/A", PRINT_STRING_OPT);
} else {
writer_print_integer(wctx, key, ts);
}
}
static void writer_print_data(WriterContext *wctx, const char *name,
uint8_t *data, int size)
{
AVBPrint bp;
int offset = 0, l, i;
av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
av_bprintf(&bp, "\n");
while (size) {
av_bprintf(&bp, "%08x: ", offset);
l = FFMIN(size, 16);
for (i = 0; i < l; i++) {
av_bprintf(&bp, "%02x", data[i]);
if (i & 1)
av_bprintf(&bp, " ");
}
av_bprint_chars(&bp, ' ', 41 - 2 * i - i / 2);
for (i = 0; i < l; i++)
av_bprint_chars(&bp, data[i] - 32U < 95 ? data[i] : '.', 1);
av_bprintf(&bp, "\n");
offset += l;
data += l;
size -= l;
}
writer_print_string(wctx, name, bp.str, 0);
av_bprint_finalize(&bp, NULL);
}
static void writer_print_data_hash(WriterContext *wctx, const char *name,
uint8_t *data, int size)
{
char *p, buf[AV_HASH_MAX_SIZE * 2 + 64] = { 0 };
if (!hash)
return;
av_hash_init(hash);
av_hash_update(hash, data, size);
snprintf(buf, sizeof(buf), "%s:", av_hash_get_name(hash));
p = buf + strlen(buf);
av_hash_final_hex(hash, p, buf + sizeof(buf) - p);
writer_print_string(wctx, name, buf, 0);
}
static void writer_print_integers(WriterContext *wctx, const char *name,
uint8_t *data, int size, const char *format,
int columns, int bytes, int offset_add)
{
AVBPrint bp;
int offset = 0, l, i;
av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
av_bprintf(&bp, "\n");
while (size) {
av_bprintf(&bp, "%08x: ", offset);
l = FFMIN(size, columns);
for (i = 0; i < l; i++) {
if (bytes == 1) av_bprintf(&bp, format, *data);
else if (bytes == 2) av_bprintf(&bp, format, AV_RN16(data));
else if (bytes == 4) av_bprintf(&bp, format, AV_RN32(data));
data += bytes;
size --;
}
av_bprintf(&bp, "\n");
offset += offset_add;
}
writer_print_string(wctx, name, bp.str, 0);
av_bprint_finalize(&bp, NULL);
}
#define MAX_REGISTERED_WRITERS_NB 64
static const Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
static int writer_register(const Writer *writer)
{
static int next_registered_writer_idx = 0;
if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
return AVERROR(ENOMEM);
registered_writers[next_registered_writer_idx++] = writer;
return 0;
}
static const Writer *writer_get_by_name(const char *name)
{
int i;
for (i = 0; registered_writers[i]; i++)
if (!strcmp(registered_writers[i]->name, name))
return registered_writers[i];
return NULL;
}
/* WRITERS */
#define DEFINE_WRITER_CLASS(name) \
static const char *name##_get_name(void *ctx) \
{ \
return #name ; \
} \
static const AVClass name##_class = { \
.class_name = #name, \
.item_name = name##_get_name, \
.option = name##_options \
}
/* Default output */
typedef struct DefaultContext {
const AVClass *class;
int nokey;
int noprint_wrappers;
int nested_section[SECTION_MAX_NB_LEVELS];
} DefaultContext;
#undef OFFSET
#define OFFSET(x) offsetof(DefaultContext, x)
static const AVOption default_options[] = {
{ "noprint_wrappers", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
{ "nw", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
{ "nokey", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
{ "nk", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
{NULL},
};
DEFINE_WRITER_CLASS(default);
/* lame uppercasing routine, assumes the string is lower case ASCII */
static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
{
int i;
for (i = 0; src[i] && i < dst_size-1; i++)
dst[i] = av_toupper(src[i]);
dst[i] = 0;
return dst;
}
static void default_print_section_header(WriterContext *wctx)
{
DefaultContext *def = wctx->priv;
char buf[32];
const struct section *section = wctx->section[wctx->level];
const struct section *parent_section = wctx->level ?
wctx->section[wctx->level-1] : NULL;
av_bprint_clear(&wctx->section_pbuf[wctx->level]);
if (parent_section &&
!(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY))) {
def->nested_section[wctx->level] = 1;
av_bprintf(&wctx->section_pbuf[wctx->level], "%s%s:",
wctx->section_pbuf[wctx->level-1].str,
upcase_string(buf, sizeof(buf),
av_x_if_null(section->element_name, section->name)));
}
if (def->noprint_wrappers || def->nested_section[wctx->level])
return;
if (!(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
printf("[%s]\n", upcase_string(buf, sizeof(buf), section->name));
}
static void default_print_section_footer(WriterContext *wctx)
{
DefaultContext *def = wctx->priv;
const struct section *section = wctx->section[wctx->level];
char buf[32];
if (def->noprint_wrappers || def->nested_section[wctx->level])
return;
if (!(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
printf("[/%s]\n", upcase_string(buf, sizeof(buf), section->name));
}
static void default_print_str(WriterContext *wctx, const char *key, const char *value)
{
DefaultContext *def = wctx->priv;
if (!def->nokey)
printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
printf("%s\n", value);
}
static void default_print_int(WriterContext *wctx, const char *key, long long int value)
{
DefaultContext *def = wctx->priv;
if (!def->nokey)
printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
printf("%lld\n", value);
}
static const Writer default_writer = {
.name = "default",
.priv_size = sizeof(DefaultContext),
.print_section_header = default_print_section_header,
.print_section_footer = default_print_section_footer,
.print_integer = default_print_int,
.print_string = default_print_str,
.flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
.priv_class = &default_class,
};
/* Compact output */
/**
* Apply C-language-like string escaping.
*/
static const char *c_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
{
const char *p;
for (p = src; *p; p++) {
switch (*p) {
case '\b': av_bprintf(dst, "%s", "\\b"); break;
case '\f': av_bprintf(dst, "%s", "\\f"); break;
case '\n': av_bprintf(dst, "%s", "\\n"); break;
case '\r': av_bprintf(dst, "%s", "\\r"); break;
case '\\': av_bprintf(dst, "%s", "\\\\"); break;
default:
if (*p == sep)
av_bprint_chars(dst, '\\', 1);
av_bprint_chars(dst, *p, 1);
}
}
return dst->str;
}
/**
* Quote fields containing special characters, check RFC4180.
*/
static const char *csv_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
{
char meta_chars[] = { sep, '"', '\n', '\r', '\0' };
int needs_quoting = !!src[strcspn(src, meta_chars)];
if (needs_quoting)
av_bprint_chars(dst, '"', 1);
for (; *src; src++) {
if (*src == '"')
av_bprint_chars(dst, '"', 1);
av_bprint_chars(dst, *src, 1);
}
if (needs_quoting)
av_bprint_chars(dst, '"', 1);
return dst->str;
}
static const char *none_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
{
return src;
}
typedef struct CompactContext {
const AVClass *class;
char *item_sep_str;
char item_sep;
int nokey;
int print_section;
char *escape_mode_str;
const char * (*escape_str)(AVBPrint *dst, const char *src, const char sep, void *log_ctx);
int nested_section[SECTION_MAX_NB_LEVELS];
int has_nested_elems[SECTION_MAX_NB_LEVELS];
int terminate_line[SECTION_MAX_NB_LEVELS];
} CompactContext;
#undef OFFSET
#define OFFSET(x) offsetof(CompactContext, x)
static const AVOption compact_options[]= {
{"item_sep", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str="|"}, CHAR_MIN, CHAR_MAX },
{"s", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str="|"}, CHAR_MIN, CHAR_MAX },
{"nokey", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
{"nk", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
{"escape", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"}, CHAR_MIN, CHAR_MAX },
{"e", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"}, CHAR_MIN, CHAR_MAX },
{"print_section", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
{"p", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
{NULL},
};
DEFINE_WRITER_CLASS(compact);
static av_cold int compact_init(WriterContext *wctx)
{
CompactContext *compact = wctx->priv;
if (strlen(compact->item_sep_str) != 1) {
av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
compact->item_sep_str);
return AVERROR(EINVAL);
}
compact->item_sep = compact->item_sep_str[0];
if (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
else if (!strcmp(compact->escape_mode_str, "c" )) compact->escape_str = c_escape_str;
else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
else {
av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
return AVERROR(EINVAL);
}
return 0;
}
static void compact_print_section_header(WriterContext *wctx)
{
CompactContext *compact = wctx->priv;
const struct section *section = wctx->section[wctx->level];
const struct section *parent_section = wctx->level ?
wctx->section[wctx->level-1] : NULL;
compact->terminate_line[wctx->level] = 1;
compact->has_nested_elems[wctx->level] = 0;
av_bprint_clear(&wctx->section_pbuf[wctx->level]);
if (!(section->flags & SECTION_FLAG_IS_ARRAY) && parent_section &&
!(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY))) {
compact->nested_section[wctx->level] = 1;
compact->has_nested_elems[wctx->level-1] = 1;
av_bprintf(&wctx->section_pbuf[wctx->level], "%s%s:",
wctx->section_pbuf[wctx->level-1].str,
(char *)av_x_if_null(section->element_name, section->name));
wctx->nb_item[wctx->level] = wctx->nb_item[wctx->level-1];
} else {
if (parent_section && compact->has_nested_elems[wctx->level-1] &&
(section->flags & SECTION_FLAG_IS_ARRAY)) {
compact->terminate_line[wctx->level-1] = 0;
printf("\n");
}
if (compact->print_section &&
!(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
printf("%s%c", section->name, compact->item_sep);
}
}
static void compact_print_section_footer(WriterContext *wctx)
{
CompactContext *compact = wctx->priv;
if (!compact->nested_section[wctx->level] &&
compact->terminate_line[wctx->level] &&
!(wctx->section[wctx->level]->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
printf("\n");
}
static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
{
CompactContext *compact = wctx->priv;
AVBPrint buf;
if (wctx->nb_item[wctx->level]) printf("%c", compact->item_sep);
if (!compact->nokey)
printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
printf("%s", compact->escape_str(&buf, value, compact->item_sep, wctx));
av_bprint_finalize(&buf, NULL);
}
static void compact_print_int(WriterContext *wctx, const char *key, long long int value)
{
CompactContext *compact = wctx->priv;
if (wctx->nb_item[wctx->level]) printf("%c", compact->item_sep);
if (!compact->nokey)
printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
printf("%lld", value);
}
static const Writer compact_writer = {
.name = "compact",
.priv_size = sizeof(CompactContext),
.init = compact_init,
.print_section_header = compact_print_section_header,
.print_section_footer = compact_print_section_footer,
.print_integer = compact_print_int,
.print_string = compact_print_str,
.flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
.priv_class = &compact_class,
};
/* CSV output */
#undef OFFSET
#define OFFSET(x) offsetof(CompactContext, x)
static const AVOption csv_options[] = {
{"item_sep", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str=","}, CHAR_MIN, CHAR_MAX },
{"s", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str=","}, CHAR_MIN, CHAR_MAX },
{"nokey", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
{"nk", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
{"escape", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="csv"}, CHAR_MIN, CHAR_MAX },
{"e", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="csv"}, CHAR_MIN, CHAR_MAX },
{"print_section", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
{"p", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
{NULL},
};
DEFINE_WRITER_CLASS(csv);
static const Writer csv_writer = {
.name = "csv",
.priv_size = sizeof(CompactContext),
.init = compact_init,
.print_section_header = compact_print_section_header,
.print_section_footer = compact_print_section_footer,
.print_integer = compact_print_int,
.print_string = compact_print_str,
.flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
.priv_class = &csv_class,
};
/* Flat output */
typedef struct FlatContext {
const AVClass *class;
const char *sep_str;
char sep;
int hierarchical;
} FlatContext;
#undef OFFSET
#define OFFSET(x) offsetof(FlatContext, x)
static const AVOption flat_options[]= {
{"sep_char", "set separator", OFFSET(sep_str), AV_OPT_TYPE_STRING, {.str="."}, CHAR_MIN, CHAR_MAX },
{"s", "set separator", OFFSET(sep_str), AV_OPT_TYPE_STRING, {.str="."}, CHAR_MIN, CHAR_MAX },
{"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
{"h", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
{NULL},
};
DEFINE_WRITER_CLASS(flat);
static av_cold int flat_init(WriterContext *wctx)
{
FlatContext *flat = wctx->priv;
if (strlen(flat->sep_str) != 1) {
av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
flat->sep_str);
return AVERROR(EINVAL);
}
flat->sep = flat->sep_str[0];
return 0;
}
static const char *flat_escape_key_str(AVBPrint *dst, const char *src, const char sep)
{
const char *p;
for (p = src; *p; p++) {
if (!((*p >= '0' && *p <= '9') ||
(*p >= 'a' && *p <= 'z') ||
(*p >= 'A' && *p <= 'Z')))
av_bprint_chars(dst, '_', 1);
else
av_bprint_chars(dst, *p, 1);
}
return dst->str;
}
static const char *flat_escape_value_str(AVBPrint *dst, const char *src)
{
const char *p;
for (p = src; *p; p++) {
switch (*p) {
case '\n': av_bprintf(dst, "%s", "\\n"); break;
case '\r': av_bprintf(dst, "%s", "\\r"); break;
case '\\': av_bprintf(dst, "%s", "\\\\"); break;
case '"': av_bprintf(dst, "%s", "\\\""); break;
case '`': av_bprintf(dst, "%s", "\\`"); break;
case '$': av_bprintf(dst, "%s", "\\$"); break;
default: av_bprint_chars(dst, *p, 1); break;
}
}
return dst->str;
}
static void flat_print_section_header(WriterContext *wctx)
{
FlatContext *flat = wctx->priv;
AVBPrint *buf = &wctx->section_pbuf[wctx->level];
const struct section *section = wctx->section[wctx->level];
const struct section *parent_section = wctx->level ?
wctx->section[wctx->level-1] : NULL;
/* build section header */
av_bprint_clear(buf);
if (!parent_section)
return;
av_bprintf(buf, "%s", wctx->section_pbuf[wctx->level-1].str);
if (flat->hierarchical ||
!(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER))) {
av_bprintf(buf, "%s%s", wctx->section[wctx->level]->name, flat->sep_str);
if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {
int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?
wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];
av_bprintf(buf, "%d%s", n, flat->sep_str);
}
}
}
static void flat_print_int(WriterContext *wctx, const char *key, long long int value)
{
printf("%s%s=%lld\n", wctx->section_pbuf[wctx->level].str, key, value);
}
static void flat_print_str(WriterContext *wctx, const char *key, const char *value)
{
FlatContext *flat = wctx->priv;
AVBPrint buf;
printf("%s", wctx->section_pbuf[wctx->level].str);
av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
printf("%s=", flat_escape_key_str(&buf, key, flat->sep));
av_bprint_clear(&buf);
printf("\"%s\"\n", flat_escape_value_str(&buf, value));
av_bprint_finalize(&buf, NULL);
}
static const Writer flat_writer = {
.name = "flat",
.priv_size = sizeof(FlatContext),
.init = flat_init,
.print_section_header = flat_print_section_header,
.print_integer = flat_print_int,
.print_string = flat_print_str,
.flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
.priv_class = &flat_class,
};
/* INI format output */
typedef struct INIContext {
const AVClass *class;
int hierarchical;
} INIContext;
#undef OFFSET
#define OFFSET(x) offsetof(INIContext, x)
static const AVOption ini_options[] = {
{"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
{"h", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
{NULL},
};
DEFINE_WRITER_CLASS(ini);
static char *ini_escape_str(AVBPrint *dst, const char *src)
{
int i = 0;
char c = 0;
while (c = src[i++]) {
switch (c) {
case '\b': av_bprintf(dst, "%s", "\\b"); break;
case '\f': av_bprintf(dst, "%s", "\\f"); break;
case '\n': av_bprintf(dst, "%s", "\\n"); break;
case '\r': av_bprintf(dst, "%s", "\\r"); break;
case '\t': av_bprintf(dst, "%s", "\\t"); break;
case '\\':
case '#' :
case '=' :
case ':' : av_bprint_chars(dst, '\\', 1);
default:
if ((unsigned char)c < 32)
av_bprintf(dst, "\\x00%02x", c & 0xff);
else
av_bprint_chars(dst, c, 1);
break;
}
}
return dst->str;
}
static void ini_print_section_header(WriterContext *wctx)
{
INIContext *ini = wctx->priv;
AVBPrint *buf = &wctx->section_pbuf[wctx->level];
const struct section *section = wctx->section[wctx->level];
const struct section *parent_section = wctx->level ?
wctx->section[wctx->level-1] : NULL;
av_bprint_clear(buf);
if (!parent_section) {
printf("# ffprobe output\n\n");
return;
}
if (wctx->nb_item[wctx->level-1])
printf("\n");
av_bprintf(buf, "%s", wctx->section_pbuf[wctx->level-1].str);
if (ini->hierarchical ||
!(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER))) {
av_bprintf(buf, "%s%s", buf->str[0] ? "." : "", wctx->section[wctx->level]->name);
if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {
int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?
wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];
av_bprintf(buf, ".%d", n);
}
}
if (!(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER)))
printf("[%s]\n", buf->str);
}
static void ini_print_str(WriterContext *wctx, const char *key, const char *value)
{
AVBPrint buf;
av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
printf("%s=", ini_escape_str(&buf, key));
av_bprint_clear(&buf);
printf("%s\n", ini_escape_str(&buf, value));
av_bprint_finalize(&buf, NULL);
}
static void ini_print_int(WriterContext *wctx, const char *key, long long int value)
{
printf("%s=%lld\n", key, value);
}
static const Writer ini_writer = {
.name = "ini",
.priv_size = sizeof(INIContext),
.print_section_header = ini_print_section_header,
.print_integer = ini_print_int,
.print_string = ini_print_str,
.flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
.priv_class = &ini_class,
};
/* JSON output */
typedef struct JSONContext {
const AVClass *class;
int indent_level;
int compact;
const char *item_sep, *item_start_end;
} JSONContext;
#undef OFFSET
#define OFFSET(x) offsetof(JSONContext, x)
static const AVOption json_options[]= {
{ "compact", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
{ "c", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
{ NULL }
};
DEFINE_WRITER_CLASS(json);
static av_cold int json_init(WriterContext *wctx)
{
JSONContext *json = wctx->priv;
json->item_sep = json->compact ? ", " : ",\n";
json->item_start_end = json->compact ? " " : "\n";
return 0;
}
static const char *json_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
{
static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
static const char json_subst[] = {'"', '\\', 'b', 'f', 'n', 'r', 't', 0};
const char *p;
for (p = src; *p; p++) {
char *s = strchr(json_escape, *p);
if (s) {
av_bprint_chars(dst, '\\', 1);
av_bprint_chars(dst, json_subst[s - json_escape], 1);
} else if ((unsigned char)*p < 32) {
av_bprintf(dst, "\\u00%02x", *p & 0xff);
} else {
av_bprint_chars(dst, *p, 1);
}
}
return dst->str;
}
#define JSON_INDENT() printf("%*c", json->indent_level * 4, ' ')
static void json_print_section_header(WriterContext *wctx)
{
JSONContext *json = wctx->priv;
AVBPrint buf;
const struct section *section = wctx->section[wctx->level];
const struct section *parent_section = wctx->level ?
wctx->section[wctx->level-1] : NULL;
if (wctx->level && wctx->nb_item[wctx->level-1])
printf(",\n");
if (section->flags & SECTION_FLAG_IS_WRAPPER) {
printf("{\n");
json->indent_level++;
} else {
av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
json_escape_str(&buf, section->name, wctx);
JSON_INDENT();
json->indent_level++;
if (section->flags & SECTION_FLAG_IS_ARRAY) {
printf("\"%s\": [\n", buf.str);
} else if (parent_section && !(parent_section->flags & SECTION_FLAG_IS_ARRAY)) {
printf("\"%s\": {%s", buf.str, json->item_start_end);
} else {
printf("{%s", json->item_start_end);
/* this is required so the parser can distinguish between packets and frames */
if (parent_section && parent_section->id == SECTION_ID_PACKETS_AND_FRAMES) {
if (!json->compact)
JSON_INDENT();
printf("\"type\": \"%s\"%s", section->name, json->item_sep);
}
}
av_bprint_finalize(&buf, NULL);
}
}
static void json_print_section_footer(WriterContext *wctx)
{
JSONContext *json = wctx->priv;
const struct section *section = wctx->section[wctx->level];
if (wctx->level == 0) {
json->indent_level--;
printf("\n}\n");
} else if (section->flags & SECTION_FLAG_IS_ARRAY) {
printf("\n");
json->indent_level--;
JSON_INDENT();
printf("]");
} else {
printf("%s", json->item_start_end);
json->indent_level--;
if (!json->compact)
JSON_INDENT();
printf("}");
}
}
static inline void json_print_item_str(WriterContext *wctx,
const char *key, const char *value)
{
AVBPrint buf;
av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
printf("\"%s\":", json_escape_str(&buf, key, wctx));
av_bprint_clear(&buf);
printf(" \"%s\"", json_escape_str(&buf, value, wctx));
av_bprint_finalize(&buf, NULL);
}
static void json_print_str(WriterContext *wctx, const char *key, const char *value)
{
JSONContext *json = wctx->priv;
if (wctx->nb_item[wctx->level])
printf("%s", json->item_sep);
if (!json->compact)
JSON_INDENT();
json_print_item_str(wctx, key, value);
}
static void json_print_int(WriterContext *wctx, const char *key, long long int value)
{
JSONContext *json = wctx->priv;
AVBPrint buf;
if (wctx->nb_item[wctx->level])
printf("%s", json->item_sep);
if (!json->compact)
JSON_INDENT();
av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
printf("\"%s\": %lld", json_escape_str(&buf, key, wctx), value);
av_bprint_finalize(&buf, NULL);
}
static const Writer json_writer = {
.name = "json",
.priv_size = sizeof(JSONContext),
.init = json_init,
.print_section_header = json_print_section_header,
.print_section_footer = json_print_section_footer,
.print_integer = json_print_int,
.print_string = json_print_str,
.flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
.priv_class = &json_class,
};
/* XML output */
typedef struct XMLContext {
const AVClass *class;
int within_tag;
int indent_level;
int fully_qualified;
int xsd_strict;
} XMLContext;
#undef OFFSET
#define OFFSET(x) offsetof(XMLContext, x)
static const AVOption xml_options[] = {
{"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
{"q", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
{"xsd_strict", "ensure that the output is XSD compliant", OFFSET(xsd_strict), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
{"x", "ensure that the output is XSD compliant", OFFSET(xsd_strict), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
{NULL},
};
DEFINE_WRITER_CLASS(xml);
static av_cold int xml_init(WriterContext *wctx)
{
XMLContext *xml = wctx->priv;
if (xml->xsd_strict) {
xml->fully_qualified = 1;
#define CHECK_COMPLIANCE(opt, opt_name) \
if (opt) { \
av_log(wctx, AV_LOG_ERROR, \
"XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
"You need to disable such option with '-no%s'\n", opt_name, opt_name); \
return AVERROR(EINVAL); \
}
CHECK_COMPLIANCE(show_private_data, "private");
CHECK_COMPLIANCE(show_value_unit, "unit");
CHECK_COMPLIANCE(use_value_prefix, "prefix");
if (do_show_frames && do_show_packets) {
av_log(wctx, AV_LOG_ERROR,
"Interleaved frames and packets are not allowed in XSD. "
"Select only one between the -show_frames and the -show_packets options.\n");
return AVERROR(EINVAL);
}
}
return 0;
}
static const char *xml_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
{
const char *p;
for (p = src; *p; p++) {
switch (*p) {
case '&' : av_bprintf(dst, "%s", "&"); break;
case '<' : av_bprintf(dst, "%s", "<"); break;
case '>' : av_bprintf(dst, "%s", ">"); break;
case '"' : av_bprintf(dst, "%s", """); break;
case '\'': av_bprintf(dst, "%s", "'"); break;
default: av_bprint_chars(dst, *p, 1);
}
}
return dst->str;
}
#define XML_INDENT() printf("%*c", xml->indent_level * 4, ' ')
static void xml_print_section_header(WriterContext *wctx)
{
XMLContext *xml = wctx->priv;
const struct section *section = wctx->section[wctx->level];
const struct section *parent_section = wctx->level ?
wctx->section[wctx->level-1] : NULL;
if (wctx->level == 0) {
const char *qual = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
"xmlns:ffprobe='http://www.ffmpeg.org/schema/ffprobe' "
"xsi:schemaLocation='http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd'";
printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
printf("<%sffprobe%s>\n",
xml->fully_qualified ? "ffprobe:" : "",
xml->fully_qualified ? qual : "");
return;
}
if (xml->within_tag) {
xml->within_tag = 0;
printf(">\n");
}
if (section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS) {
xml->indent_level++;
} else {
if (parent_section && (parent_section->flags & SECTION_FLAG_IS_WRAPPER) &&
wctx->level && wctx->nb_item[wctx->level-1])
printf("\n");
xml->indent_level++;
if (section->flags & SECTION_FLAG_IS_ARRAY) {
XML_INDENT(); printf("<%s>\n", section->name);
} else {
XML_INDENT(); printf("<%s ", section->name);
xml->within_tag = 1;
}
}
}
static void xml_print_section_footer(WriterContext *wctx)
{
XMLContext *xml = wctx->priv;
const struct section *section = wctx->section[wctx->level];
if (wctx->level == 0) {
printf("</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
} else if (xml->within_tag) {
xml->within_tag = 0;
printf("/>\n");
xml->indent_level--;
} else if (section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS) {
xml->indent_level--;
} else {
XML_INDENT(); printf("</%s>\n", section->name);
xml->indent_level--;
}
}
static void xml_print_str(WriterContext *wctx, const char *key, const char *value)
{
AVBPrint buf;
XMLContext *xml = wctx->priv;
const struct section *section = wctx->section[wctx->level];
av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
if (section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS) {
XML_INDENT();
printf("<%s key=\"%s\"",
section->element_name, xml_escape_str(&buf, key, wctx));
av_bprint_clear(&buf);
printf(" value=\"%s\"/>\n", xml_escape_str(&buf, value, wctx));
} else {
if (wctx->nb_item[wctx->level])
printf(" ");
printf("%s=\"%s\"", key, xml_escape_str(&buf, value, wctx));
}
av_bprint_finalize(&buf, NULL);
}
static void xml_print_int(WriterContext *wctx, const char *key, long long int value)
{
if (wctx->nb_item[wctx->level])
printf(" ");
printf("%s=\"%lld\"", key, value);
}
static Writer xml_writer = {
.name = "xml",
.priv_size = sizeof(XMLContext),
.init = xml_init,
.print_section_header = xml_print_section_header,
.print_section_footer = xml_print_section_footer,
.print_integer = xml_print_int,
.print_string = xml_print_str,
.flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
.priv_class = &xml_class,
};
static void writer_register_all(void)
{
static int initialized;
if (initialized)
return;
initialized = 1;
writer_register(&default_writer);
writer_register(&compact_writer);
writer_register(&csv_writer);
writer_register(&flat_writer);
writer_register(&ini_writer);
writer_register(&json_writer);
writer_register(&xml_writer);
}
#define print_fmt(k, f, ...) do { \
av_bprint_clear(&pbuf); \
av_bprintf(&pbuf, f, __VA_ARGS__); \
writer_print_string(w, k, pbuf.str, 0); \
} while (0)
#define print_int(k, v) writer_print_integer(w, k, v)
#define print_q(k, v, s) writer_print_rational(w, k, v, s)
#define print_str(k, v) writer_print_string(w, k, v, 0)
#define print_str_opt(k, v) writer_print_string(w, k, v, PRINT_STRING_OPT)
#define print_str_validate(k, v) writer_print_string(w, k, v, PRINT_STRING_VALIDATE)
#define print_time(k, v, tb) writer_print_time(w, k, v, tb, 0)
#define print_ts(k, v) writer_print_ts(w, k, v, 0)
#define print_duration_time(k, v, tb) writer_print_time(w, k, v, tb, 1)
#define print_duration_ts(k, v) writer_print_ts(w, k, v, 1)
#define print_val(k, v, u) do { \
struct unit_value uv; \
uv.val.i = v; \
uv.unit = u; \
writer_print_string(w, k, value_string(val_str, sizeof(val_str), uv), 0); \
} while (0)
#define print_section_header(s) writer_print_section_header(w, s)
#define print_section_footer(s) writer_print_section_footer(w, s)
#define REALLOCZ_ARRAY_STREAM(ptr, cur_n, new_n) \
{ \
ret = av_reallocp_array(&(ptr), (new_n), sizeof(*(ptr))); \
if (ret < 0) \
goto end; \
memset( (ptr) + (cur_n), 0, ((new_n) - (cur_n)) * sizeof(*(ptr)) ); \
}
static inline int show_tags(WriterContext *w, AVDictionary *tags, int section_id)
{
AVDictionaryEntry *tag = NULL;
int ret = 0;
if (!tags)
return 0;
writer_print_section_header(w, section_id);
while ((tag = av_dict_get(tags, "", tag, AV_DICT_IGNORE_SUFFIX))) {
if ((ret = print_str_validate(tag->key, tag->value)) < 0)
break;
}
writer_print_section_footer(w);
return ret;
}
static void print_color_range(WriterContext *w, enum AVColorRange color_range, const char *fallback)
{
const char *val = av_color_range_name(color_range);
if (!val || color_range == AVCOL_RANGE_UNSPECIFIED) {
print_str_opt("color_range", fallback);
} else {
print_str("color_range", val);
}
}
static void print_color_space(WriterContext *w, enum AVColorSpace color_space)
{
const char *val = av_color_space_name(color_space);
if (!val || color_space == AVCOL_SPC_UNSPECIFIED) {
print_str_opt("color_space", "unknown");
} else {
print_str("color_space", val);
}
}
static void print_primaries(WriterContext *w, enum AVColorPrimaries color_primaries)
{
const char *val = av_color_primaries_name(color_primaries);
if (!val || color_primaries == AVCOL_PRI_UNSPECIFIED) {
print_str_opt("color_primaries", "unknown");
} else {
print_str("color_primaries", val);
}
}
static void print_color_trc(WriterContext *w, enum AVColorTransferCharacteristic color_trc)
{
const char *val = av_color_transfer_name(color_trc);
if (!val || color_trc == AVCOL_TRC_UNSPECIFIED) {
print_str_opt("color_transfer", "unknown");
} else {
print_str("color_transfer", val);
}
}
static void print_chroma_location(WriterContext *w, enum AVChromaLocation chroma_location)
{
const char *val = av_chroma_location_name(chroma_location);
if (!val || chroma_location == AVCHROMA_LOC_UNSPECIFIED) {
print_str_opt("chroma_location", "unspecified");
} else {
print_str("chroma_location", val);
}
}
static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
{
char val_str[128];
AVStream *st = fmt_ctx->streams[pkt->stream_index];
AVBPrint pbuf;
const char *s;
av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
writer_print_section_header(w, SECTION_ID_PACKET);
s = av_get_media_type_string(st->codec->codec_type);
if (s) print_str ("codec_type", s);
else print_str_opt("codec_type", "unknown");
print_int("stream_index", pkt->stream_index);
print_ts ("pts", pkt->pts);
print_time("pts_time", pkt->pts, &st->time_base);
print_ts ("dts", pkt->dts);
print_time("dts_time", pkt->dts, &st->time_base);
print_duration_ts("duration", pkt->duration);
print_duration_time("duration_time", pkt->duration, &st->time_base);
print_duration_ts("convergence_duration", pkt->convergence_duration);
print_duration_time("convergence_duration_time", pkt->convergence_duration, &st->time_base);
print_val("size", pkt->size, unit_byte_str);
if (pkt->pos != -1) print_fmt ("pos", "%"PRId64, pkt->pos);
else print_str_opt("pos", "N/A");
print_fmt("flags", "%c", pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
if (pkt->side_data_elems) {
int i;
writer_print_section_header(w, SECTION_ID_PACKET_SIDE_DATA_LIST);
for (i = 0; i < pkt->side_data_elems; i++) {
AVPacketSideData *sd = &pkt->side_data[i];
const char *name = av_packet_side_data_name(sd->type);
writer_print_section_header(w, SECTION_ID_PACKET_SIDE_DATA);
print_str("side_data_type", name ? name : "unknown");
print_int("side_data_size", sd->size);
if (sd->type == AV_PKT_DATA_DISPLAYMATRIX && sd->size >= 9*4) {
writer_print_integers(w, "displaymatrix", sd->data, 9, " %11d", 3, 4, 1);
print_int("rotation", av_display_rotation_get((int32_t *)sd->data));
}
writer_print_section_footer(w);
}
writer_print_section_footer(w);
}
if (do_show_data)
writer_print_data(w, "data", pkt->data, pkt->size);
writer_print_data_hash(w, "data_hash", pkt->data, pkt->size);
writer_print_section_footer(w);
av_bprint_finalize(&pbuf, NULL);
fflush(stdout);
}
static void show_subtitle(WriterContext *w, AVSubtitle *sub, AVStream *stream,
AVFormatContext *fmt_ctx)
{
AVBPrint pbuf;
av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
writer_print_section_header(w, SECTION_ID_SUBTITLE);
print_str ("media_type", "subtitle");
print_ts ("pts", sub->pts);
print_time("pts_time", sub->pts, &AV_TIME_BASE_Q);
print_int ("format", sub->format);
print_int ("start_display_time", sub->start_display_time);
print_int ("end_display_time", sub->end_display_time);
print_int ("num_rects", sub->num_rects);
writer_print_section_footer(w);
av_bprint_finalize(&pbuf, NULL);
fflush(stdout);
}
static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream,
AVFormatContext *fmt_ctx)
{
AVBPrint pbuf;
const char *s;
int i;
av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
writer_print_section_header(w, SECTION_ID_FRAME);
s = av_get_media_type_string(stream->codec->codec_type);
if (s) print_str ("media_type", s);
else print_str_opt("media_type", "unknown");
print_int("stream_index", stream->index);
print_int("key_frame", frame->key_frame);
print_ts ("pkt_pts", frame->pkt_pts);
print_time("pkt_pts_time", frame->pkt_pts, &stream->time_base);
print_ts ("pkt_dts", frame->pkt_dts);
print_time("pkt_dts_time", frame->pkt_dts, &stream->time_base);
print_ts ("best_effort_timestamp", av_frame_get_best_effort_timestamp(frame));
print_time("best_effort_timestamp_time", av_frame_get_best_effort_timestamp(frame), &stream->time_base);
print_duration_ts ("pkt_duration", av_frame_get_pkt_duration(frame));
print_duration_time("pkt_duration_time", av_frame_get_pkt_duration(frame), &stream->time_base);
if (av_frame_get_pkt_pos (frame) != -1) print_fmt ("pkt_pos", "%"PRId64, av_frame_get_pkt_pos(frame));
else print_str_opt("pkt_pos", "N/A");
if (av_frame_get_pkt_size(frame) != -1) print_fmt ("pkt_size", "%d", av_frame_get_pkt_size(frame));
else print_str_opt("pkt_size", "N/A");
switch (stream->codec->codec_type) {
AVRational sar;
case AVMEDIA_TYPE_VIDEO:
print_int("width", frame->width);
print_int("height", frame->height);
s = av_get_pix_fmt_name(frame->format);
if (s) print_str ("pix_fmt", s);
else print_str_opt("pix_fmt", "unknown");
sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, frame);
if (sar.num) {
print_q("sample_aspect_ratio", sar, ':');
} else {
print_str_opt("sample_aspect_ratio", "N/A");
}
print_fmt("pict_type", "%c", av_get_picture_type_char(frame->pict_type));
print_int("coded_picture_number", frame->coded_picture_number);
print_int("display_picture_number", frame->display_picture_number);
print_int("interlaced_frame", frame->interlaced_frame);
print_int("top_field_first", frame->top_field_first);
print_int("repeat_pict", frame->repeat_pict);
break;
case AVMEDIA_TYPE_AUDIO:
s = av_get_sample_fmt_name(frame->format);
if (s) print_str ("sample_fmt", s);
else print_str_opt("sample_fmt", "unknown");
print_int("nb_samples", frame->nb_samples);
print_int("channels", av_frame_get_channels(frame));
if (av_frame_get_channel_layout(frame)) {
av_bprint_clear(&pbuf);
av_bprint_channel_layout(&pbuf, av_frame_get_channels(frame),
av_frame_get_channel_layout(frame));
print_str ("channel_layout", pbuf.str);
} else
print_str_opt("channel_layout", "unknown");
break;
}
if (do_show_frame_tags)
show_tags(w, av_frame_get_metadata(frame), SECTION_ID_FRAME_TAGS);
if (frame->nb_side_data) {
writer_print_section_header(w, SECTION_ID_FRAME_SIDE_DATA_LIST);
for (i = 0; i < frame->nb_side_data; i++) {
AVFrameSideData *sd = frame->side_data[i];
const char *name;
writer_print_section_header(w, SECTION_ID_FRAME_SIDE_DATA);
name = av_frame_side_data_name(sd->type);
print_str("side_data_type", name ? name : "unknown");
print_int("side_data_size", sd->size);
if (sd->type == AV_FRAME_DATA_DISPLAYMATRIX && sd->size >= 9*4) {
abort();
writer_print_integers(w, "displaymatrix", sd->data, 9, " %11d", 3, 4, 1);
print_int("rotation", av_display_rotation_get((int32_t *)sd->data));
}
writer_print_section_footer(w);
}
writer_print_section_footer(w);
}
writer_print_section_footer(w);
av_bprint_finalize(&pbuf, NULL);
fflush(stdout);
}
static av_always_inline int process_frame(WriterContext *w,
AVFormatContext *fmt_ctx,
AVFrame *frame, AVPacket *pkt)
{
AVCodecContext *dec_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
AVSubtitle sub;
int ret = 0, got_frame = 0;
if (dec_ctx->codec) {
switch (dec_ctx->codec_type) {
case AVMEDIA_TYPE_VIDEO:
ret = avcodec_decode_video2(dec_ctx, frame, &got_frame, pkt);
break;
case AVMEDIA_TYPE_AUDIO:
ret = avcodec_decode_audio4(dec_ctx, frame, &got_frame, pkt);
break;
case AVMEDIA_TYPE_SUBTITLE:
ret = avcodec_decode_subtitle2(dec_ctx, &sub, &got_frame, pkt);
break;
}
}
if (ret < 0)
return ret;
ret = FFMIN(ret, pkt->size); /* guard against bogus return values */
pkt->data += ret;
pkt->size -= ret;
if (got_frame) {
int is_sub = (dec_ctx->codec_type == AVMEDIA_TYPE_SUBTITLE);
nb_streams_frames[pkt->stream_index]++;
if (do_show_frames)
if (is_sub)
show_subtitle(w, &sub, fmt_ctx->streams[pkt->stream_index], fmt_ctx);
else
show_frame(w, frame, fmt_ctx->streams[pkt->stream_index], fmt_ctx);
if (is_sub)
avsubtitle_free(&sub);
}
return got_frame;
}
static void log_read_interval(const ReadInterval *interval, void *log_ctx, int log_level)
{
av_log(log_ctx, log_level, "id:%d", interval->id);
if (interval->has_start) {
av_log(log_ctx, log_level, " start:%s%s", interval->start_is_offset ? "+" : "",
av_ts2timestr(interval->start, &AV_TIME_BASE_Q));
} else {
av_log(log_ctx, log_level, " start:N/A");
}
if (interval->has_end) {
av_log(log_ctx, log_level, " end:%s", interval->end_is_offset ? "+" : "");
if (interval->duration_frames)
av_log(log_ctx, log_level, "#%"PRId64, interval->end);
else
av_log(log_ctx, log_level, "%s", av_ts2timestr(interval->end, &AV_TIME_BASE_Q));
} else {
av_log(log_ctx, log_level, " end:N/A");
}
av_log(log_ctx, log_level, "\n");
}
static int read_interval_packets(WriterContext *w, AVFormatContext *fmt_ctx,
const ReadInterval *interval, int64_t *cur_ts)
{
AVPacket pkt, pkt1;
AVFrame *frame = NULL;
int ret = 0, i = 0, frame_count = 0;
int64_t start = -INT64_MAX, end = interval->end;
int has_start = 0, has_end = interval->has_end && !interval->end_is_offset;
av_init_packet(&pkt);
av_log(NULL, AV_LOG_VERBOSE, "Processing read interval ");
log_read_interval(interval, NULL, AV_LOG_VERBOSE);
if (interval->has_start) {
int64_t target;
if (interval->start_is_offset) {
if (*cur_ts == AV_NOPTS_VALUE) {
av_log(NULL, AV_LOG_ERROR,
"Could not seek to relative position since current "
"timestamp is not defined\n");
ret = AVERROR(EINVAL);
goto end;
}
target = *cur_ts + interval->start;
} else {
target = interval->start;
}
av_log(NULL, AV_LOG_VERBOSE, "Seeking to read interval start point %s\n",
av_ts2timestr(target, &AV_TIME_BASE_Q));
if ((ret = avformat_seek_file(fmt_ctx, -1, -INT64_MAX, target, INT64_MAX, 0)) < 0) {
av_log(NULL, AV_LOG_ERROR, "Could not seek to position %"PRId64": %s\n",
interval->start, av_err2str(ret));
goto end;
}
}
frame = av_frame_alloc();
if (!frame) {
ret = AVERROR(ENOMEM);
goto end;
}
while (!av_read_frame(fmt_ctx, &pkt)) {
if (fmt_ctx->nb_streams > nb_streams) {
REALLOCZ_ARRAY_STREAM(nb_streams_frames, nb_streams, fmt_ctx->nb_streams);
REALLOCZ_ARRAY_STREAM(nb_streams_packets, nb_streams, fmt_ctx->nb_streams);
REALLOCZ_ARRAY_STREAM(selected_streams, nb_streams, fmt_ctx->nb_streams);
nb_streams = fmt_ctx->nb_streams;
}
if (selected_streams[pkt.stream_index]) {
AVRational tb = fmt_ctx->streams[pkt.stream_index]->time_base;
if (pkt.pts != AV_NOPTS_VALUE)
*cur_ts = av_rescale_q(pkt.pts, tb, AV_TIME_BASE_Q);
if (!has_start && *cur_ts != AV_NOPTS_VALUE) {
start = *cur_ts;
has_start = 1;
}
if (has_start && !has_end && interval->end_is_offset) {
end = start + interval->end;
has_end = 1;
}
if (interval->end_is_offset && interval->duration_frames) {
if (frame_count >= interval->end)
break;
} else if (has_end && *cur_ts != AV_NOPTS_VALUE && *cur_ts >= end) {
break;
}
frame_count++;
if (do_read_packets) {
if (do_show_packets)
show_packet(w, fmt_ctx, &pkt, i++);
nb_streams_packets[pkt.stream_index]++;
}
if (do_read_frames) {
pkt1 = pkt;
while (pkt1.size && process_frame(w, fmt_ctx, frame, &pkt1) > 0);
}
}
av_free_packet(&pkt);
}
av_init_packet(&pkt);
pkt.data = NULL;
pkt.size = 0;
//Flush remaining frames that are cached in the decoder
for (i = 0; i < fmt_ctx->nb_streams; i++) {
pkt.stream_index = i;
if (do_read_frames)
while (process_frame(w, fmt_ctx, frame, &pkt) > 0);
}
end:
av_frame_free(&frame);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Could not read packets in interval ");
log_read_interval(interval, NULL, AV_LOG_ERROR);
}
return ret;
}
static int read_packets(WriterContext *w, AVFormatContext *fmt_ctx)
{
int i, ret = 0;
int64_t cur_ts = fmt_ctx->start_time;
if (read_intervals_nb == 0) {
ReadInterval interval = (ReadInterval) { .has_start = 0, .has_end = 0 };
ret = read_interval_packets(w, fmt_ctx, &interval, &cur_ts);
} else {
for (i = 0; i < read_intervals_nb; i++) {
ret = read_interval_packets(w, fmt_ctx, &read_intervals[i], &cur_ts);
if (ret < 0)
break;
}
}
return ret;
}
static int show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx, int in_program)
{
AVStream *stream = fmt_ctx->streams[stream_idx];
AVCodecContext *dec_ctx;
const AVCodec *dec;
char val_str[128];
const char *s;
AVRational sar, dar;
AVBPrint pbuf;
const AVCodecDescriptor *cd;
int ret = 0;
av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
writer_print_section_header(w, in_program ? SECTION_ID_PROGRAM_STREAM : SECTION_ID_STREAM);
print_int("index", stream->index);
if ((dec_ctx = stream->codec)) {
const char *profile = NULL;
dec = dec_ctx->codec;
if (dec) {
print_str("codec_name", dec->name);
if (!do_bitexact) {
if (dec->long_name) print_str ("codec_long_name", dec->long_name);
else print_str_opt("codec_long_name", "unknown");
}
} else if ((cd = avcodec_descriptor_get(stream->codec->codec_id))) {
print_str_opt("codec_name", cd->name);
if (!do_bitexact) {
print_str_opt("codec_long_name",
cd->long_name ? cd->long_name : "unknown");
}
} else {
print_str_opt("codec_name", "unknown");
if (!do_bitexact) {
print_str_opt("codec_long_name", "unknown");
}
}
if (dec && (profile = av_get_profile_name(dec, dec_ctx->profile)))
print_str("profile", profile);
else
print_str_opt("profile", "unknown");
s = av_get_media_type_string(dec_ctx->codec_type);
if (s) print_str ("codec_type", s);
else print_str_opt("codec_type", "unknown");
print_q("codec_time_base", dec_ctx->time_base, '/');
/* print AVI/FourCC tag */
av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
print_str("codec_tag_string", val_str);
print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
switch (dec_ctx->codec_type) {
case AVMEDIA_TYPE_VIDEO:
print_int("width", dec_ctx->width);
print_int("height", dec_ctx->height);
print_int("coded_width", dec_ctx->coded_width);
print_int("coded_height", dec_ctx->coded_height);
print_int("has_b_frames", dec_ctx->has_b_frames);
sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, NULL);
if (sar.den) {
print_q("sample_aspect_ratio", sar, ':');
av_reduce(&dar.num, &dar.den,
dec_ctx->width * sar.num,
dec_ctx->height * sar.den,
1024*1024);
print_q("display_aspect_ratio", dar, ':');
} else {
print_str_opt("sample_aspect_ratio", "N/A");
print_str_opt("display_aspect_ratio", "N/A");
}
s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
if (s) print_str ("pix_fmt", s);
else print_str_opt("pix_fmt", "unknown");
print_int("level", dec_ctx->level);
print_color_range(w, dec_ctx->color_range, "N/A");
print_color_space(w, dec_ctx->colorspace);
print_color_trc(w, dec_ctx->color_trc);
print_primaries(w, dec_ctx->color_primaries);
print_chroma_location(w, dec_ctx->chroma_sample_location);
if (dec_ctx->timecode_frame_start >= 0) {
char tcbuf[AV_TIMECODE_STR_SIZE];
av_timecode_make_mpeg_tc_string(tcbuf, dec_ctx->timecode_frame_start);
print_str("timecode", tcbuf);
} else {
print_str_opt("timecode", "N/A");
}
print_int("refs", dec_ctx->refs);
break;
case AVMEDIA_TYPE_AUDIO:
s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
if (s) print_str ("sample_fmt", s);
else print_str_opt("sample_fmt", "unknown");
print_val("sample_rate", dec_ctx->sample_rate, unit_hertz_str);
print_int("channels", dec_ctx->channels);
if (dec_ctx->channel_layout) {
av_bprint_clear(&pbuf);
av_bprint_channel_layout(&pbuf, dec_ctx->channels, dec_ctx->channel_layout);
print_str ("channel_layout", pbuf.str);
} else {
print_str_opt("channel_layout", "unknown");
}
print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
break;
case AVMEDIA_TYPE_SUBTITLE:
if (dec_ctx->width)
print_int("width", dec_ctx->width);
else
print_str_opt("width", "N/A");
if (dec_ctx->height)
print_int("height", dec_ctx->height);
else
print_str_opt("height", "N/A");
break;
}
} else {
print_str_opt("codec_type", "unknown");
}
if (dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
const AVOption *opt = NULL;
while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
uint8_t *str;
if (opt->flags) continue;
if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
print_str(opt->name, str);
av_free(str);
}
}
}
if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt ("id", "0x%x", stream->id);
else print_str_opt("id", "N/A");
print_q("r_frame_rate", stream->r_frame_rate, '/');
print_q("avg_frame_rate", stream->avg_frame_rate, '/');
print_q("time_base", stream->time_base, '/');
print_ts ("start_pts", stream->start_time);
print_time("start_time", stream->start_time, &stream->time_base);
print_ts ("duration_ts", stream->duration);
print_time("duration", stream->duration, &stream->time_base);
if (dec_ctx->bit_rate > 0) print_val ("bit_rate", dec_ctx->bit_rate, unit_bit_per_second_str);
else print_str_opt("bit_rate", "N/A");
if (dec_ctx->rc_max_rate > 0) print_val ("max_bit_rate", dec_ctx->rc_max_rate, unit_bit_per_second_str);
else print_str_opt("max_bit_rate", "N/A");
if (dec_ctx->bits_per_raw_sample > 0) print_fmt("bits_per_raw_sample", "%d", dec_ctx->bits_per_raw_sample);
else print_str_opt("bits_per_raw_sample", "N/A");
if (stream->nb_frames) print_fmt ("nb_frames", "%"PRId64, stream->nb_frames);
else print_str_opt("nb_frames", "N/A");
if (nb_streams_frames[stream_idx]) print_fmt ("nb_read_frames", "%"PRIu64, nb_streams_frames[stream_idx]);
else print_str_opt("nb_read_frames", "N/A");
if (nb_streams_packets[stream_idx]) print_fmt ("nb_read_packets", "%"PRIu64, nb_streams_packets[stream_idx]);
else print_str_opt("nb_read_packets", "N/A");
if (do_show_data)
writer_print_data(w, "extradata", dec_ctx->extradata,
dec_ctx->extradata_size);
writer_print_data_hash(w, "extradata_hash", dec_ctx->extradata,
dec_ctx->extradata_size);
/* Print disposition information */
#define PRINT_DISPOSITION(flagname, name) do { \
print_int(name, !!(stream->disposition & AV_DISPOSITION_##flagname)); \
} while (0)
if (do_show_stream_disposition) {
writer_print_section_header(w, in_program ? SECTION_ID_PROGRAM_STREAM_DISPOSITION : SECTION_ID_STREAM_DISPOSITION);
PRINT_DISPOSITION(DEFAULT, "default");
PRINT_DISPOSITION(DUB, "dub");
PRINT_DISPOSITION(ORIGINAL, "original");
PRINT_DISPOSITION(COMMENT, "comment");
PRINT_DISPOSITION(LYRICS, "lyrics");
PRINT_DISPOSITION(KARAOKE, "karaoke");
PRINT_DISPOSITION(FORCED, "forced");
PRINT_DISPOSITION(HEARING_IMPAIRED, "hearing_impaired");
PRINT_DISPOSITION(VISUAL_IMPAIRED, "visual_impaired");
PRINT_DISPOSITION(CLEAN_EFFECTS, "clean_effects");
PRINT_DISPOSITION(ATTACHED_PIC, "attached_pic");
writer_print_section_footer(w);
}
if (do_show_stream_tags)
ret = show_tags(w, stream->metadata, in_program ? SECTION_ID_PROGRAM_STREAM_TAGS : SECTION_ID_STREAM_TAGS);
if (stream->nb_side_data) {
int i;
writer_print_section_header(w, SECTION_ID_STREAM_SIDE_DATA_LIST);
for (i = 0; i < stream->nb_side_data; i++) {
AVPacketSideData *sd = &stream->side_data[i];
const char *name = av_packet_side_data_name(sd->type);
writer_print_section_header(w, SECTION_ID_STREAM_SIDE_DATA);
print_str("side_data_type", name ? name : "unknown");
print_int("side_data_size", sd->size);
if (sd->type == AV_PKT_DATA_DISPLAYMATRIX && sd->size >= 9*4) {
writer_print_integers(w, "displaymatrix", sd->data, 9, " %11d", 3, 4, 1);
print_int("rotation", av_display_rotation_get((int32_t *)sd->data));
}
writer_print_section_footer(w);
}
writer_print_section_footer(w);
}
writer_print_section_footer(w);
av_bprint_finalize(&pbuf, NULL);
fflush(stdout);
return ret;
}
static int show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
{
int i, ret = 0;
writer_print_section_header(w, SECTION_ID_STREAMS);
for (i = 0; i < fmt_ctx->nb_streams; i++)
if (selected_streams[i]) {
ret = show_stream(w, fmt_ctx, i, 0);
if (ret < 0)
break;
}
writer_print_section_footer(w);
return ret;
}
static int show_program(WriterContext *w, AVFormatContext *fmt_ctx, AVProgram *program)
{
int i, ret = 0;
writer_print_section_header(w, SECTION_ID_PROGRAM);
print_int("program_id", program->id);
print_int("program_num", program->program_num);
print_int("nb_streams", program->nb_stream_indexes);
print_int("pmt_pid", program->pmt_pid);
print_int("pcr_pid", program->pcr_pid);
print_ts("start_pts", program->start_time);
print_time("start_time", program->start_time, &AV_TIME_BASE_Q);
print_ts("end_pts", program->end_time);
print_time("end_time", program->end_time, &AV_TIME_BASE_Q);
if (do_show_program_tags)
ret = show_tags(w, program->metadata, SECTION_ID_PROGRAM_TAGS);
if (ret < 0)
goto end;
writer_print_section_header(w, SECTION_ID_PROGRAM_STREAMS);
for (i = 0; i < program->nb_stream_indexes; i++) {
if (selected_streams[program->stream_index[i]]) {
ret = show_stream(w, fmt_ctx, program->stream_index[i], 1);
if (ret < 0)
break;
}
}
writer_print_section_footer(w);
end:
writer_print_section_footer(w);
return ret;
}
static int show_programs(WriterContext *w, AVFormatContext *fmt_ctx)
{
int i, ret = 0;
writer_print_section_header(w, SECTION_ID_PROGRAMS);
for (i = 0; i < fmt_ctx->nb_programs; i++) {
AVProgram *program = fmt_ctx->programs[i];
if (!program)
continue;
ret = show_program(w, fmt_ctx, program);
if (ret < 0)
break;
}
writer_print_section_footer(w);
return ret;
}
static int show_chapters(WriterContext *w, AVFormatContext *fmt_ctx)
{
int i, ret = 0;
writer_print_section_header(w, SECTION_ID_CHAPTERS);
for (i = 0; i < fmt_ctx->nb_chapters; i++) {
AVChapter *chapter = fmt_ctx->chapters[i];
writer_print_section_header(w, SECTION_ID_CHAPTER);
print_int("id", chapter->id);
print_q ("time_base", chapter->time_base, '/');
print_int("start", chapter->start);
print_time("start_time", chapter->start, &chapter->time_base);
print_int("end", chapter->end);
print_time("end_time", chapter->end, &chapter->time_base);
if (do_show_chapter_tags)
ret = show_tags(w, chapter->metadata, SECTION_ID_CHAPTER_TAGS);
writer_print_section_footer(w);
}
writer_print_section_footer(w);
return ret;
}
static int show_format(WriterContext *w, AVFormatContext *fmt_ctx)
{
char val_str[128];
int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
int ret = 0;
writer_print_section_header(w, SECTION_ID_FORMAT);
print_str_validate("filename", fmt_ctx->filename);
print_int("nb_streams", fmt_ctx->nb_streams);
print_int("nb_programs", fmt_ctx->nb_programs);
print_str("format_name", fmt_ctx->iformat->name);
if (!do_bitexact) {
if (fmt_ctx->iformat->long_name) print_str ("format_long_name", fmt_ctx->iformat->long_name);
else print_str_opt("format_long_name", "unknown");
}
print_time("start_time", fmt_ctx->start_time, &AV_TIME_BASE_Q);
print_time("duration", fmt_ctx->duration, &AV_TIME_BASE_Q);
if (size >= 0) print_val ("size", size, unit_byte_str);
else print_str_opt("size", "N/A");
if (fmt_ctx->bit_rate > 0) print_val ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
else print_str_opt("bit_rate", "N/A");
print_int("probe_score", av_format_get_probe_score(fmt_ctx));
if (do_show_format_tags)
ret = show_tags(w, fmt_ctx->metadata, SECTION_ID_FORMAT_TAGS);
writer_print_section_footer(w);
fflush(stdout);
return ret;
}
static void show_error(WriterContext *w, int err)
{
char errbuf[128];
const char *errbuf_ptr = errbuf;
if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
errbuf_ptr = strerror(AVUNERROR(err));
writer_print_section_header(w, SECTION_ID_ERROR);
print_int("code", err);
print_str("string", errbuf_ptr);
writer_print_section_footer(w);
}
static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
{
int err, i, orig_nb_streams;
AVFormatContext *fmt_ctx = NULL;
AVDictionaryEntry *t;
AVDictionary **opts;
int scan_all_pmts_set = 0;
if (!av_dict_get(format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE)) {
av_dict_set(&format_opts, "scan_all_pmts", "1", AV_DICT_DONT_OVERWRITE);
scan_all_pmts_set = 1;
}
if ((err = avformat_open_input(&fmt_ctx, filename,
iformat, &format_opts)) < 0) {
print_error(filename, err);
return err;
}
*fmt_ctx_ptr = fmt_ctx;
if (scan_all_pmts_set)
av_dict_set(&format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE);
if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
return AVERROR_OPTION_NOT_FOUND;
}
/* fill the streams in the format context */
opts = setup_find_stream_info_opts(fmt_ctx, codec_opts);
orig_nb_streams = fmt_ctx->nb_streams;
err = avformat_find_stream_info(fmt_ctx, opts);
for (i = 0; i < orig_nb_streams; i++)
av_dict_free(&opts[i]);
av_freep(&opts);
if (err < 0) {
print_error(filename, err);
return err;
}
av_dump_format(fmt_ctx, 0, filename, 0);
/* bind a decoder to each input stream */
for (i = 0; i < fmt_ctx->nb_streams; i++) {
AVStream *stream = fmt_ctx->streams[i];
AVCodec *codec;
if (stream->codec->codec_id == AV_CODEC_ID_PROBE) {
av_log(NULL, AV_LOG_WARNING,
"Failed to probe codec for input stream %d\n",
stream->index);
} else if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
av_log(NULL, AV_LOG_WARNING,
"Unsupported codec with id %d for input stream %d\n",
stream->codec->codec_id, stream->index);
} else {
AVDictionary *opts = filter_codec_opts(codec_opts, stream->codec->codec_id,
fmt_ctx, stream, codec);
if (avcodec_open2(stream->codec, codec, &opts) < 0) {
av_log(NULL, AV_LOG_WARNING, "Could not open codec for input stream %d\n",
stream->index);
}
if ((t = av_dict_get(opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
av_log(NULL, AV_LOG_ERROR, "Option %s for input stream %d not found\n",
t->key, stream->index);
return AVERROR_OPTION_NOT_FOUND;
}
}
}
*fmt_ctx_ptr = fmt_ctx;
return 0;
}
static void close_input_file(AVFormatContext **ctx_ptr)
{
int i;
AVFormatContext *fmt_ctx = *ctx_ptr;
/* close decoder for each stream */
for (i = 0; i < fmt_ctx->nb_streams; i++)
if (fmt_ctx->streams[i]->codec->codec_id != AV_CODEC_ID_NONE)
avcodec_close(fmt_ctx->streams[i]->codec);
avformat_close_input(ctx_ptr);
}
static int probe_file(WriterContext *wctx, const char *filename)
{
AVFormatContext *fmt_ctx = NULL;
int ret, i;
int section_id;
do_read_frames = do_show_frames || do_count_frames;
do_read_packets = do_show_packets || do_count_packets;
ret = open_input_file(&fmt_ctx, filename);
if (ret < 0)
goto end;
#define CHECK_END if (ret < 0) goto end
nb_streams = fmt_ctx->nb_streams;
REALLOCZ_ARRAY_STREAM(nb_streams_frames,0,fmt_ctx->nb_streams);
REALLOCZ_ARRAY_STREAM(nb_streams_packets,0,fmt_ctx->nb_streams);
REALLOCZ_ARRAY_STREAM(selected_streams,0,fmt_ctx->nb_streams);
for (i = 0; i < fmt_ctx->nb_streams; i++) {
if (stream_specifier) {
ret = avformat_match_stream_specifier(fmt_ctx,
fmt_ctx->streams[i],
stream_specifier);
CHECK_END;
else
selected_streams[i] = ret;
ret = 0;
} else {
selected_streams[i] = 1;
}
}
if (do_read_frames || do_read_packets) {
if (do_show_frames && do_show_packets &&
wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
section_id = SECTION_ID_PACKETS_AND_FRAMES;
else if (do_show_packets && !do_show_frames)
section_id = SECTION_ID_PACKETS;
else // (!do_show_packets && do_show_frames)
section_id = SECTION_ID_FRAMES;
if (do_show_frames || do_show_packets)
writer_print_section_header(wctx, section_id);
ret = read_packets(wctx, fmt_ctx);
if (do_show_frames || do_show_packets)
writer_print_section_footer(wctx);
CHECK_END;
}
if (do_show_programs) {
ret = show_programs(wctx, fmt_ctx);
CHECK_END;
}
if (do_show_streams) {
ret = show_streams(wctx, fmt_ctx);
CHECK_END;
}
if (do_show_chapters) {
ret = show_chapters(wctx, fmt_ctx);
CHECK_END;
}
if (do_show_format) {
ret = show_format(wctx, fmt_ctx);
CHECK_END;
}
end:
if (fmt_ctx)
close_input_file(&fmt_ctx);
av_freep(&nb_streams_frames);
av_freep(&nb_streams_packets);
av_freep(&selected_streams);
return ret;
}
static void show_usage(void)
{
av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
av_log(NULL, AV_LOG_INFO, "\n");
}
static void ffprobe_show_program_version(WriterContext *w)
{
AVBPrint pbuf;
av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
writer_print_section_header(w, SECTION_ID_PROGRAM_VERSION);
print_str("version", FFMPEG_VERSION);
print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
program_birth_year, CONFIG_THIS_YEAR);
print_str("compiler_ident", CC_IDENT);
print_str("configuration", FFMPEG_CONFIGURATION);
writer_print_section_footer(w);
av_bprint_finalize(&pbuf, NULL);
}
#define SHOW_LIB_VERSION(libname, LIBNAME) \
do { \
if (CONFIG_##LIBNAME) { \
unsigned int version = libname##_version(); \
writer_print_section_header(w, SECTION_ID_LIBRARY_VERSION); \
print_str("name", "lib" #libname); \
print_int("major", LIB##LIBNAME##_VERSION_MAJOR); \
print_int("minor", LIB##LIBNAME##_VERSION_MINOR); \
print_int("micro", LIB##LIBNAME##_VERSION_MICRO); \
print_int("version", version); \
print_str("ident", LIB##LIBNAME##_IDENT); \
writer_print_section_footer(w); \
} \
} while (0)
static void ffprobe_show_library_versions(WriterContext *w)
{
writer_print_section_header(w, SECTION_ID_LIBRARY_VERSIONS);
SHOW_LIB_VERSION(avutil, AVUTIL);
SHOW_LIB_VERSION(avcodec, AVCODEC);
SHOW_LIB_VERSION(avformat, AVFORMAT);
SHOW_LIB_VERSION(avdevice, AVDEVICE);
SHOW_LIB_VERSION(avfilter, AVFILTER);
SHOW_LIB_VERSION(swscale, SWSCALE);
SHOW_LIB_VERSION(swresample, SWRESAMPLE);
SHOW_LIB_VERSION(postproc, POSTPROC);
writer_print_section_footer(w);
}
#define PRINT_PIX_FMT_FLAG(flagname, name) \
do { \
print_int(name, !!(pixdesc->flags & AV_PIX_FMT_FLAG_##flagname)); \
} while (0)
static void ffprobe_show_pixel_formats(WriterContext *w)
{
const AVPixFmtDescriptor *pixdesc = NULL;
int i, n;
writer_print_section_header(w, SECTION_ID_PIXEL_FORMATS);
while (pixdesc = av_pix_fmt_desc_next(pixdesc)) {
writer_print_section_header(w, SECTION_ID_PIXEL_FORMAT);
print_str("name", pixdesc->name);
print_int("nb_components", pixdesc->nb_components);
if ((pixdesc->nb_components >= 3) && !(pixdesc->flags & AV_PIX_FMT_FLAG_RGB)) {
print_int ("log2_chroma_w", pixdesc->log2_chroma_w);
print_int ("log2_chroma_h", pixdesc->log2_chroma_h);
} else {
print_str_opt("log2_chroma_w", "N/A");
print_str_opt("log2_chroma_h", "N/A");
}
n = av_get_bits_per_pixel(pixdesc);
if (n) print_int ("bits_per_pixel", n);
else print_str_opt("bits_per_pixel", "N/A");
if (do_show_pixel_format_flags) {
writer_print_section_header(w, SECTION_ID_PIXEL_FORMAT_FLAGS);
PRINT_PIX_FMT_FLAG(BE, "big_endian");
PRINT_PIX_FMT_FLAG(PAL, "palette");
PRINT_PIX_FMT_FLAG(BITSTREAM, "bitstream");
PRINT_PIX_FMT_FLAG(HWACCEL, "hwaccel");
PRINT_PIX_FMT_FLAG(PLANAR, "planar");
PRINT_PIX_FMT_FLAG(RGB, "rgb");
PRINT_PIX_FMT_FLAG(PSEUDOPAL, "pseudopal");
PRINT_PIX_FMT_FLAG(ALPHA, "alpha");
writer_print_section_footer(w);
}
if (do_show_pixel_format_components && (pixdesc->nb_components > 0)) {
writer_print_section_header(w, SECTION_ID_PIXEL_FORMAT_COMPONENTS);
for (i = 0; i < pixdesc->nb_components; i++) {
writer_print_section_header(w, SECTION_ID_PIXEL_FORMAT_COMPONENT);
print_int("index", i + 1);
print_int("bit_depth", pixdesc->comp[i].depth_minus1 + 1);
writer_print_section_footer(w);
}
writer_print_section_footer(w);
}
writer_print_section_footer(w);
}
writer_print_section_footer(w);
}
static int opt_format(void *optctx, const char *opt, const char *arg)
{
iformat = av_find_input_format(arg);
if (!iformat) {
av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
return AVERROR(EINVAL);
}
return 0;
}
static inline void mark_section_show_entries(SectionID section_id,
int show_all_entries, AVDictionary *entries)
{
struct section *section = §ions[section_id];
section->show_all_entries = show_all_entries;
if (show_all_entries) {
SectionID *id;
for (id = section->children_ids; *id != -1; id++)
mark_section_show_entries(*id, show_all_entries, entries);
} else {
av_dict_copy(§ion->entries_to_show, entries, 0);
}
}
static int match_section(const char *section_name,
int show_all_entries, AVDictionary *entries)
{
int i, ret = 0;
for (i = 0; i < FF_ARRAY_ELEMS(sections); i++) {
const struct section *section = §ions[i];
if (!strcmp(section_name, section->name) ||
(section->unique_name && !strcmp(section_name, section->unique_name))) {
av_log(NULL, AV_LOG_DEBUG,
"'%s' matches section with unique name '%s'\n", section_name,
(char *)av_x_if_null(section->unique_name, section->name));
ret++;
mark_section_show_entries(section->id, show_all_entries, entries);
}
}
return ret;
}
static int opt_show_entries(void *optctx, const char *opt, const char *arg)
{
const char *p = arg;
int ret = 0;
while (*p) {
AVDictionary *entries = NULL;
char *section_name = av_get_token(&p, "=:");
int show_all_entries = 0;
if (!section_name) {
av_log(NULL, AV_LOG_ERROR,
"Missing section name for option '%s'\n", opt);
return AVERROR(EINVAL);
}
if (*p == '=') {
p++;
while (*p && *p != ':') {
char *entry = av_get_token(&p, ",:");
if (!entry)
break;
av_log(NULL, AV_LOG_VERBOSE,
"Adding '%s' to the entries to show in section '%s'\n",
entry, section_name);
av_dict_set(&entries, entry, "", AV_DICT_DONT_STRDUP_KEY);
if (*p == ',')
p++;
}
} else {
show_all_entries = 1;
}
ret = match_section(section_name, show_all_entries, entries);
if (ret == 0) {
av_log(NULL, AV_LOG_ERROR, "No match for section '%s'\n", section_name);
ret = AVERROR(EINVAL);
}
av_dict_free(&entries);
av_free(section_name);
if (ret <= 0)
break;
if (*p)
p++;
}
return ret;
}
static int opt_show_format_entry(void *optctx, const char *opt, const char *arg)
{
char *buf = av_asprintf("format=%s", arg);
int ret;
if (!buf)
return AVERROR(ENOMEM);
av_log(NULL, AV_LOG_WARNING,
"Option '%s' is deprecated, use '-show_entries format=%s' instead\n",
opt, arg);
ret = opt_show_entries(optctx, opt, buf);
av_free(buf);
return ret;
}
static void opt_input_file(void *optctx, const char *arg)
{
if (input_filename) {
av_log(NULL, AV_LOG_ERROR,
"Argument '%s' provided as input filename, but '%s' was already specified.\n",
arg, input_filename);
exit_program(1);
}
if (!strcmp(arg, "-"))
arg = "pipe:";
input_filename = arg;
}
static int opt_input_file_i(void *optctx, const char *opt, const char *arg)
{
opt_input_file(optctx, arg);
return 0;
}
void show_help_default(const char *opt, const char *arg)
{
av_log_set_callback(log_callback_help);
show_usage();
show_help_options(options, "Main options:", 0, 0, 0);
printf("\n");
show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
}
/**
* Parse interval specification, according to the format:
* INTERVAL ::= [START|+START_OFFSET][%[END|+END_OFFSET]]
* INTERVALS ::= INTERVAL[,INTERVALS]
*/
static int parse_read_interval(const char *interval_spec,
ReadInterval *interval)
{
int ret = 0;
char *next, *p, *spec = av_strdup(interval_spec);
if (!spec)
return AVERROR(ENOMEM);
if (!*spec) {
av_log(NULL, AV_LOG_ERROR, "Invalid empty interval specification\n");
ret = AVERROR(EINVAL);
goto end;
}
p = spec;
next = strchr(spec, '%');
if (next)
*next++ = 0;
/* parse first part */
if (*p) {
interval->has_start = 1;
if (*p == '+') {
interval->start_is_offset = 1;
p++;
} else {
interval->start_is_offset = 0;
}
ret = av_parse_time(&interval->start, p, 1);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Invalid interval start specification '%s'\n", p);
goto end;
}
} else {
interval->has_start = 0;
}
/* parse second part */
p = next;
if (p && *p) {
int64_t us;
interval->has_end = 1;
if (*p == '+') {
interval->end_is_offset = 1;
p++;
} else {
interval->end_is_offset = 0;
}
if (interval->end_is_offset && *p == '#') {
long long int lli;
char *tail;
interval->duration_frames = 1;
p++;
lli = strtoll(p, &tail, 10);
if (*tail || lli < 0) {
av_log(NULL, AV_LOG_ERROR,
"Invalid or negative value '%s' for duration number of frames\n", p);
goto end;
}
interval->end = lli;
} else {
ret = av_parse_time(&us, p, 1);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Invalid interval end/duration specification '%s'\n", p);
goto end;
}
interval->end = us;
}
} else {
interval->has_end = 0;
}
end:
av_free(spec);
return ret;
}
static int parse_read_intervals(const char *intervals_spec)
{
int ret, n, i;
char *p, *spec = av_strdup(intervals_spec);
if (!spec)
return AVERROR(ENOMEM);
/* preparse specification, get number of intervals */
for (n = 0, p = spec; *p; p++)
if (*p == ',')
n++;
n++;
read_intervals = av_malloc_array(n, sizeof(*read_intervals));
if (!read_intervals) {
ret = AVERROR(ENOMEM);
goto end;
}
read_intervals_nb = n;
/* parse intervals */
p = spec;
for (i = 0; p; i++) {
char *next;
av_assert0(i < read_intervals_nb);
next = strchr(p, ',');
if (next)
*next++ = 0;
read_intervals[i].id = i;
ret = parse_read_interval(p, &read_intervals[i]);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Error parsing read interval #%d '%s'\n",
i, p);
goto end;
}
av_log(NULL, AV_LOG_VERBOSE, "Parsed log interval ");
log_read_interval(&read_intervals[i], NULL, AV_LOG_VERBOSE);
p = next;
}
av_assert0(i == read_intervals_nb);
end:
av_free(spec);
return ret;
}
static int opt_read_intervals(void *optctx, const char *opt, const char *arg)
{
return parse_read_intervals(arg);
}
static int opt_pretty(void *optctx, const char *opt, const char *arg)
{
show_value_unit = 1;
use_value_prefix = 1;
use_byte_value_binary_prefix = 1;
use_value_sexagesimal_format = 1;
return 0;
}
static void print_section(SectionID id, int level)
{
const SectionID *pid;
const struct section *section = §ions[id];
printf("%c%c%c",
section->flags & SECTION_FLAG_IS_WRAPPER ? 'W' : '.',
section->flags & SECTION_FLAG_IS_ARRAY ? 'A' : '.',
section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS ? 'V' : '.');
printf("%*c %s", level * 4, ' ', section->name);
if (section->unique_name)
printf("/%s", section->unique_name);
printf("\n");
for (pid = section->children_ids; *pid != -1; pid++)
print_section(*pid, level+1);
}
static int opt_sections(void *optctx, const char *opt, const char *arg)
{
printf("Sections:\n"
"W.. = Section is a wrapper (contains other sections, no local entries)\n"
".A. = Section contains an array of elements of the same type\n"
"..V = Section may contain a variable number of fields with variable keys\n"
"FLAGS NAME/UNIQUE_NAME\n"
"---\n");
print_section(SECTION_ID_ROOT, 0);
return 0;
}
static int opt_show_versions(const char *opt, const char *arg)
{
mark_section_show_entries(SECTION_ID_PROGRAM_VERSION, 1, NULL);
mark_section_show_entries(SECTION_ID_LIBRARY_VERSION, 1, NULL);
return 0;
}
#define DEFINE_OPT_SHOW_SECTION(section, target_section_id) \
static int opt_show_##section(const char *opt, const char *arg) \
{ \
mark_section_show_entries(SECTION_ID_##target_section_id, 1, NULL); \
return 0; \
}
DEFINE_OPT_SHOW_SECTION(chapters, CHAPTERS);
DEFINE_OPT_SHOW_SECTION(error, ERROR);
DEFINE_OPT_SHOW_SECTION(format, FORMAT);
DEFINE_OPT_SHOW_SECTION(frames, FRAMES);
DEFINE_OPT_SHOW_SECTION(library_versions, LIBRARY_VERSIONS);
DEFINE_OPT_SHOW_SECTION(packets, PACKETS);
DEFINE_OPT_SHOW_SECTION(pixel_formats, PIXEL_FORMATS);
DEFINE_OPT_SHOW_SECTION(program_version, PROGRAM_VERSION);
DEFINE_OPT_SHOW_SECTION(streams, STREAMS);
DEFINE_OPT_SHOW_SECTION(programs, PROGRAMS);
static const OptionDef real_options[] = {
#include "cmdutils_common_opts.h"
{ "f", HAS_ARG, {.func_arg = opt_format}, "force format", "format" },
{ "unit", OPT_BOOL, {&show_value_unit}, "show unit of the displayed values" },
{ "prefix", OPT_BOOL, {&use_value_prefix}, "use SI prefixes for the displayed values" },
{ "byte_binary_prefix", OPT_BOOL, {&use_byte_value_binary_prefix},
"use binary prefixes for byte units" },
{ "sexagesimal", OPT_BOOL, {&use_value_sexagesimal_format},
"use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
{ "pretty", 0, {.func_arg = opt_pretty},
"prettify the format of displayed values, make it more human readable" },
{ "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
"set the output printing format (available formats are: default, compact, csv, flat, ini, json, xml)", "format" },
{ "of", OPT_STRING | HAS_ARG, {(void*)&print_format}, "alias for -print_format", "format" },
{ "select_streams", OPT_STRING | HAS_ARG, {(void*)&stream_specifier}, "select the specified streams", "stream_specifier" },
{ "sections", OPT_EXIT, {.func_arg = opt_sections}, "print sections structure and section information, and exit" },
{ "show_data", OPT_BOOL, {(void*)&do_show_data}, "show packets data" },
{ "show_data_hash", OPT_STRING | HAS_ARG, {(void*)&show_data_hash}, "show packets data hash" },
{ "show_error", 0, {(void*)&opt_show_error}, "show probing error" },
{ "show_format", 0, {(void*)&opt_show_format}, "show format/container info" },
{ "show_frames", 0, {(void*)&opt_show_frames}, "show frames info" },
{ "show_format_entry", HAS_ARG, {.func_arg = opt_show_format_entry},
"show a particular entry from the format/container info", "entry" },
{ "show_entries", HAS_ARG, {.func_arg = opt_show_entries},
"show a set of specified entries", "entry_list" },
{ "show_packets", 0, {(void*)&opt_show_packets}, "show packets info" },
{ "show_programs", 0, {(void*)&opt_show_programs}, "show programs info" },
{ "show_streams", 0, {(void*)&opt_show_streams}, "show streams info" },
{ "show_chapters", 0, {(void*)&opt_show_chapters}, "show chapters info" },
{ "count_frames", OPT_BOOL, {(void*)&do_count_frames}, "count the number of frames per stream" },
{ "count_packets", OPT_BOOL, {(void*)&do_count_packets}, "count the number of packets per stream" },
{ "show_program_version", 0, {(void*)&opt_show_program_version}, "show ffprobe version" },
{ "show_library_versions", 0, {(void*)&opt_show_library_versions}, "show library versions" },
{ "show_versions", 0, {(void*)&opt_show_versions}, "show program and library versions" },
{ "show_pixel_formats", 0, {(void*)&opt_show_pixel_formats}, "show pixel format descriptions" },
{ "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
{ "private", OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
{ "bitexact", OPT_BOOL, {&do_bitexact}, "force bitexact output" },
{ "read_intervals", HAS_ARG, {.func_arg = opt_read_intervals}, "set read intervals", "read_intervals" },
{ "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {.func_arg = opt_default}, "generic catch all option", "" },
{ "i", HAS_ARG, {.func_arg = opt_input_file_i}, "read specified file", "input_file"},
{ NULL, },
};
static inline int check_section_show_entries(int section_id)
{
int *id;
struct section *section = §ions[section_id];
if (sections[section_id].show_all_entries || sections[section_id].entries_to_show)
return 1;
for (id = section->children_ids; *id != -1; id++)
if (check_section_show_entries(*id))
return 1;
return 0;
}
#define SET_DO_SHOW(id, varname) do { \
if (check_section_show_entries(SECTION_ID_##id)) \
do_show_##varname = 1; \
} while (0)
int main(int argc, char **argv)
{
const Writer *w;
WriterContext *wctx;
char *buf;
char *w_name = NULL, *w_args = NULL;
int ret, i;
init_dynload();
av_log_set_flags(AV_LOG_SKIP_REPEATED);
register_exit(ffprobe_cleanup);
options = real_options;
parse_loglevel(argc, argv, options);
av_register_all();
avformat_network_init();
init_opts();
#if CONFIG_AVDEVICE
avdevice_register_all();
#endif
show_banner(argc, argv, options);
parse_options(NULL, argc, argv, options, opt_input_file);
/* mark things to show, based on -show_entries */
SET_DO_SHOW(CHAPTERS, chapters);
SET_DO_SHOW(ERROR, error);
SET_DO_SHOW(FORMAT, format);
SET_DO_SHOW(FRAMES, frames);
SET_DO_SHOW(LIBRARY_VERSIONS, library_versions);
SET_DO_SHOW(PACKETS, packets);
SET_DO_SHOW(PIXEL_FORMATS, pixel_formats);
SET_DO_SHOW(PIXEL_FORMAT_FLAGS, pixel_format_flags);
SET_DO_SHOW(PIXEL_FORMAT_COMPONENTS, pixel_format_components);
SET_DO_SHOW(PROGRAM_VERSION, program_version);
SET_DO_SHOW(PROGRAMS, programs);
SET_DO_SHOW(STREAMS, streams);
SET_DO_SHOW(STREAM_DISPOSITION, stream_disposition);
SET_DO_SHOW(PROGRAM_STREAM_DISPOSITION, stream_disposition);
SET_DO_SHOW(CHAPTER_TAGS, chapter_tags);
SET_DO_SHOW(FORMAT_TAGS, format_tags);
SET_DO_SHOW(FRAME_TAGS, frame_tags);
SET_DO_SHOW(PROGRAM_TAGS, program_tags);
SET_DO_SHOW(STREAM_TAGS, stream_tags);
if (do_bitexact && (do_show_program_version || do_show_library_versions)) {
av_log(NULL, AV_LOG_ERROR,
"-bitexact and -show_program_version or -show_library_versions "
"options are incompatible\n");
ret = AVERROR(EINVAL);
goto end;
}
writer_register_all();
if (!print_format)
print_format = av_strdup("default");
if (!print_format) {
ret = AVERROR(ENOMEM);
goto end;
}
w_name = av_strtok(print_format, "=", &buf);
w_args = buf;
if (show_data_hash) {
if ((ret = av_hash_alloc(&hash, show_data_hash)) < 0) {
if (ret == AVERROR(EINVAL)) {
const char *n;
av_log(NULL, AV_LOG_ERROR,
"Unknown hash algorithm '%s'\nKnown algorithms:",
show_data_hash);
for (i = 0; (n = av_hash_names(i)); i++)
av_log(NULL, AV_LOG_ERROR, " %s", n);
av_log(NULL, AV_LOG_ERROR, "\n");
}
goto end;
}
}
w = writer_get_by_name(w_name);
if (!w) {
av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
ret = AVERROR(EINVAL);
goto end;
}
if ((ret = writer_open(&wctx, w, w_args,
sections, FF_ARRAY_ELEMS(sections))) >= 0) {
if (w == &xml_writer)
wctx->string_validation_utf8_flags |= AV_UTF8_FLAG_EXCLUDE_XML_INVALID_CONTROL_CODES;
writer_print_section_header(wctx, SECTION_ID_ROOT);
if (do_show_program_version)
ffprobe_show_program_version(wctx);
if (do_show_library_versions)
ffprobe_show_library_versions(wctx);
if (do_show_pixel_formats)
ffprobe_show_pixel_formats(wctx);
if (!input_filename &&
((do_show_format || do_show_programs || do_show_streams || do_show_chapters || do_show_packets || do_show_error) ||
(!do_show_program_version && !do_show_library_versions && !do_show_pixel_formats))) {
show_usage();
av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
ret = AVERROR(EINVAL);
} else if (input_filename) {
ret = probe_file(wctx, input_filename);
if (ret < 0 && do_show_error)
show_error(wctx, ret);
}
writer_print_section_footer(wctx);
writer_close(&wctx);
}
end:
av_freep(&print_format);
av_freep(&read_intervals);
av_hash_freep(&hash);
uninit_opts();
for (i = 0; i < FF_ARRAY_ELEMS(sections); i++)
av_dict_free(&(sections[i].entries_to_show));
avformat_network_deinit();
return ret < 0;
}
|
RasPlex/OpenPHT
|
lib/ffmpeg/ffprobe.c
|
C
|
gpl-2.0
| 121,934 |
#ifndef _LINUX_SUSPEND_H
#define _LINUX_SUSPEND_H
#if defined(CONFIG_X86) || defined(CONFIG_FRV) || defined(CONFIG_PPC32) || defined(CONFIG_PPC64)
#include <asm/suspend.h>
#endif
#include <linux/swap.h>
#include <linux/notifier.h>
#include <linux/init.h>
#include <linux/pm.h>
#include <linux/mm.h>
#include <asm/errno.h>
#if defined(CONFIG_PM_SLEEP) && defined(CONFIG_VT) && defined(CONFIG_VT_CONSOLE)
extern void pm_set_vt_switch(int);
extern int pm_prepare_console(void);
extern void pm_restore_console(void);
#else
static inline void pm_set_vt_switch(int do_switch)
{
}
static inline int pm_prepare_console(void)
{
return 0;
}
static inline void pm_restore_console(void)
{
}
#endif
typedef int __bitwise suspend_state_t;
#define PM_SUSPEND_ON ((__force suspend_state_t) 0)
#define PM_SUSPEND_STANDBY ((__force suspend_state_t) 1)
#define PM_SUSPEND_MEM ((__force suspend_state_t) 3)
#define PM_SUSPEND_MAX ((__force suspend_state_t) 4)
/**
* struct platform_suspend_ops - Callbacks for managing platform dependent
* system sleep states.
*
* @valid: Callback to determine if given system sleep state is supported by
* the platform.
* Valid (ie. supported) states are advertised in /sys/power/state. Note
* that it still may be impossible to enter given system sleep state if the
* conditions aren't right.
* There is the %suspend_valid_only_mem function available that can be
* assigned to this if the platform only supports mem sleep.
*
* @begin: Initialise a transition to given system sleep state.
* @begin() is executed right prior to suspending devices. The information
* conveyed to the platform code by @begin() should be disregarded by it as
* soon as @end() is executed. If @begin() fails (ie. returns nonzero),
* @prepare(), @enter() and @finish() will not be called by the PM core.
* This callback is optional. However, if it is implemented, the argument
* passed to @enter() is redundant and should be ignored.
*
* @prepare: Prepare the platform for entering the system sleep state indicated
* by @begin().
* @prepare() is called right after devices have been suspended (ie. the
* appropriate .suspend() method has been executed for each device) and
* before the nonboot CPUs are disabled (it is executed with IRQs enabled).
* This callback is optional. It returns 0 on success or a negative
* error code otherwise, in which case the system cannot enter the desired
* sleep state (@enter() and @finish() will not be called in that case).
*
* @enter: Enter the system sleep state indicated by @begin() or represented by
* the argument if @begin() is not implemented.
* This callback is mandatory. It returns 0 on success or a negative
* error code otherwise, in which case the system cannot enter the desired
* sleep state.
*
* @finish: Called when the system has just left a sleep state, right after
* the nonboot CPUs have been enabled and before devices are resumed (it is
* executed with IRQs enabled).
* This callback is optional, but should be implemented by the platforms
* that implement @prepare(). If implemented, it is always called after
* @enter() (even if @enter() fails).
*
* @end: Called by the PM core right after resuming devices, to indicate to
* the platform that the system has returned to the working state or
* the transition to the sleep state has been aborted.
* This callback is optional, but should be implemented by the platforms
* that implement @begin(), but platforms implementing @begin() should
* also provide a @end() which cleans up transitions aborted before
* @enter().
*
* @recover: Recover the platform from a suspend failure.
* Called by the PM core if the suspending of devices fails.
* This callback is optional and should only be implemented by platforms
* which require special recovery actions in that situation.
*/
struct platform_suspend_ops {
int (*valid)(suspend_state_t state);
int (*begin)(suspend_state_t state);
int (*prepare)(void);
int (*enter)(suspend_state_t state);
void (*finish)(void);
void (*end)(void);
void (*recover)(void);
};
#ifdef CONFIG_SUSPEND
/**
* suspend_set_ops - set platform dependent suspend operations
* @ops: The new suspend operations to set.
*/
extern void suspend_set_ops(struct platform_suspend_ops *ops);
extern int suspend_valid_only_mem(suspend_state_t state);
/**
* arch_suspend_disable_irqs - disable IRQs for suspend
*
* Disables IRQs (in the default case). This is a weak symbol in the common
* code and thus allows architectures to override it if more needs to be
* done. Not called for suspend to disk.
*/
extern void arch_suspend_disable_irqs(void);
/**
* arch_suspend_enable_irqs - enable IRQs after suspend
*
* Enables IRQs (in the default case). This is a weak symbol in the common
* code and thus allows architectures to override it if more needs to be
* done. Not called for suspend to disk.
*/
extern void arch_suspend_enable_irqs(void);
extern int pm_suspend(suspend_state_t state);
extern void late_resume(struct work_struct *work);
#else /* !CONFIG_SUSPEND */
#define suspend_valid_only_mem NULL
static inline void suspend_set_ops(struct platform_suspend_ops *ops) {}
static inline int pm_suspend(suspend_state_t state) { return -ENOSYS; }
#endif /* !CONFIG_SUSPEND */
/* struct pbe is used for creating lists of pages that should be restored
* atomically during the resume from disk, because the page frames they have
* occupied before the suspend are in use.
*/
struct pbe {
void *address; /* address of the copy */
void *orig_address; /* original address of a page */
struct pbe *next;
};
/* mm/page_alloc.c */
extern void mark_free_pages(struct zone *zone);
/**
* struct platform_hibernation_ops - hibernation platform support
*
* The methods in this structure allow a platform to carry out special
* operations required by it during a hibernation transition.
*
* All the methods below, except for @recover(), must be implemented.
*
* @begin: Tell the platform driver that we're starting hibernation.
* Called right after shrinking memory and before freezing devices.
*
* @end: Called by the PM core right after resuming devices, to indicate to
* the platform that the system has returned to the working state.
*
* @pre_snapshot: Prepare the platform for creating the hibernation image.
* Called right after devices have been frozen and before the nonboot
* CPUs are disabled (runs with IRQs on).
*
* @finish: Restore the previous state of the platform after the hibernation
* image has been created *or* put the platform into the normal operation
* mode after the hibernation (the same method is executed in both cases).
* Called right after the nonboot CPUs have been enabled and before
* thawing devices (runs with IRQs on).
*
* @prepare: Prepare the platform for entering the low power state.
* Called right after the hibernation image has been saved and before
* devices are prepared for entering the low power state.
*
* @enter: Put the system into the low power state after the hibernation image
* has been saved to disk.
* Called after the nonboot CPUs have been disabled and all of the low
* level devices have been shut down (runs with IRQs off).
*
* @leave: Perform the first stage of the cleanup after the system sleep state
* indicated by @set_target() has been left.
* Called right after the control has been passed from the boot kernel to
* the image kernel, before the nonboot CPUs are enabled and before devices
* are resumed. Executed with interrupts disabled.
*
* @pre_restore: Prepare system for the restoration from a hibernation image.
* Called right after devices have been frozen and before the nonboot
* CPUs are disabled (runs with IRQs on).
*
* @restore_cleanup: Clean up after a failing image restoration.
* Called right after the nonboot CPUs have been enabled and before
* thawing devices (runs with IRQs on).
*
* @recover: Recover the platform from a failure to suspend devices.
* Called by the PM core if the suspending of devices during hibernation
* fails. This callback is optional and should only be implemented by
* platforms which require special recovery actions in that situation.
*/
struct platform_hibernation_ops {
int (*begin)(void);
void (*end)(void);
int (*pre_snapshot)(void);
void (*finish)(void);
int (*prepare)(void);
int (*enter)(void);
void (*leave)(void);
int (*pre_restore)(void);
void (*restore_cleanup)(void);
void (*recover)(void);
};
#ifdef CONFIG_HIBERNATION
/* kernel/power/snapshot.c */
extern void __register_nosave_region(unsigned long b, unsigned long e, int km);
static inline void __init register_nosave_region(unsigned long b, unsigned long e)
{
__register_nosave_region(b, e, 0);
}
static inline void __init register_nosave_region_late(unsigned long b, unsigned long e)
{
__register_nosave_region(b, e, 1);
}
extern int swsusp_page_is_forbidden(struct page *);
extern void swsusp_set_page_free(struct page *);
extern void swsusp_unset_page_free(struct page *);
extern unsigned long get_safe_page(gfp_t gfp_mask);
extern void hibernation_set_ops(struct platform_hibernation_ops *ops);
extern int hibernate(void);
extern int hibernate_nvs_register(unsigned long start, unsigned long size);
extern int hibernate_nvs_alloc(void);
extern void hibernate_nvs_free(void);
extern void hibernate_nvs_save(void);
extern void hibernate_nvs_restore(void);
extern bool system_entering_hibernation(void);
#else /* CONFIG_HIBERNATION */
static inline int swsusp_page_is_forbidden(struct page *p) { return 0; }
static inline void swsusp_set_page_free(struct page *p) {}
static inline void swsusp_unset_page_free(struct page *p) {}
static inline void hibernation_set_ops(struct platform_hibernation_ops *ops) {}
static inline int hibernate(void) { return -ENOSYS; }
static inline int hibernate_nvs_register(unsigned long a, unsigned long b)
{
return 0;
}
static inline int hibernate_nvs_alloc(void) { return 0; }
static inline void hibernate_nvs_free(void) {}
static inline void hibernate_nvs_save(void) {}
static inline void hibernate_nvs_restore(void) {}
static inline bool system_entering_hibernation(void) { return false; }
#endif /* CONFIG_HIBERNATION */
#ifdef CONFIG_PM_SLEEP
void save_processor_state(void);
void restore_processor_state(void);
/* kernel/power/main.c */
extern int register_pm_notifier(struct notifier_block *nb);
extern int unregister_pm_notifier(struct notifier_block *nb);
#define pm_notifier(fn, pri) { \
static struct notifier_block fn##_nb = \
{ .notifier_call = fn, .priority = pri }; \
register_pm_notifier(&fn##_nb); \
}
#else /* !CONFIG_PM_SLEEP */
static inline int register_pm_notifier(struct notifier_block *nb)
{
return 0;
}
static inline int unregister_pm_notifier(struct notifier_block *nb)
{
return 0;
}
#define pm_notifier(fn, pri) do { (void)(fn); } while (0)
#endif /* !CONFIG_PM_SLEEP */
#ifndef CONFIG_HIBERNATION
static inline void register_nosave_region(unsigned long b, unsigned long e)
{
}
static inline void register_nosave_region_late(unsigned long b, unsigned long e)
{
}
#endif
extern struct mutex pm_mutex;
#endif /* _LINUX_SUSPEND_H */
|
RomzesRover/liquid-chocolate-beta4
|
include/linux/suspend.h
|
C
|
gpl-2.0
| 11,462 |
/* 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/kernel.h>
#include <linux/interrupt.h>
#include <linux/reboot.h>
#include <linux/workqueue.h>
#include <linux/io.h>
#include <linux/jiffies.h>
#include <linux/stringify.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/debugfs.h>
#include <mach/irqs.h>
#include <mach/scm.h>
#include <mach/peripheral-loader.h>
#include <mach/subsystem_restart.h>
#include <mach/subsystem_notif.h>
#include <mach/socinfo.h>
#include <mach/msm_smsm.h>
#include "smd_private.h"
#include "modem_notifier.h"
#include "ramdump.h"
static int crash_shutdown;
#define MAX_SSR_REASON_LEN 81U
#define Q6_FW_WDOG_ENABLE 0x08882024
#define Q6_SW_WDOG_ENABLE 0x08982024
static void log_modem_sfr(void)
{
u32 size;
char *smem_reason, reason[MAX_SSR_REASON_LEN];
smem_reason = smem_get_entry(SMEM_SSR_REASON_MSS0, &size);
if (!smem_reason || !size) {
pr_err("modem subsystem failure reason: (unknown, smem_get_entry failed).\n");
return;
}
if (!smem_reason[0]) {
pr_err("modem subsystem failure reason: (unknown, init string found).\n");
return;
}
size = min(size, MAX_SSR_REASON_LEN-1);
memcpy(reason, smem_reason, size);
reason[size] = '\0';
pr_err("modem subsystem failure reason: %s.\n", reason);
smem_reason[0] = '\0';
wmb();
}
static void restart_modem(void)
{
log_modem_sfr();
subsystem_restart("modem");
}
static void modem_wdog_check(struct work_struct *work)
{
void __iomem *q6_sw_wdog_addr;
u32 regval;
q6_sw_wdog_addr = ioremap_nocache(Q6_SW_WDOG_ENABLE, 4);
if (!q6_sw_wdog_addr)
panic("Unable to check modem watchdog status.\n");
regval = readl_relaxed(q6_sw_wdog_addr);
if (!regval) {
pr_err("modem-8960: Modem watchdog wasn't activated!. Restarting the modem now.\n");
restart_modem();
}
iounmap(q6_sw_wdog_addr);
}
static DECLARE_DELAYED_WORK(modem_wdog_check_work, modem_wdog_check);
static void smsm_state_cb(void *data, uint32_t old_state, uint32_t new_state)
{
/* Ignore if we're the one that set SMSM_RESET */
if (crash_shutdown)
return;
if (new_state & SMSM_RESET) {
pr_err("Probable fatal error on the modem.\n");
restart_modem();
}
}
static int modem_shutdown(const struct subsys_data *subsys)
{
void __iomem *q6_fw_wdog_addr;
void __iomem *q6_sw_wdog_addr;
/*
* Cancel any pending wdog_check work items, since we're shutting
* down anyway.
*/
cancel_delayed_work(&modem_wdog_check_work);
/*
* Disable the modem watchdog since it keeps running even after the
* modem is shutdown.
*/
q6_fw_wdog_addr = ioremap_nocache(Q6_FW_WDOG_ENABLE, 4);
if (!q6_fw_wdog_addr)
return -ENOMEM;
q6_sw_wdog_addr = ioremap_nocache(Q6_SW_WDOG_ENABLE, 4);
if (!q6_sw_wdog_addr) {
iounmap(q6_fw_wdog_addr);
return -ENOMEM;
}
writel_relaxed(0x0, q6_fw_wdog_addr);
writel_relaxed(0x0, q6_sw_wdog_addr);
mb();
iounmap(q6_sw_wdog_addr);
iounmap(q6_fw_wdog_addr);
pil_force_shutdown("modem");
pil_force_shutdown("modem_fw");
disable_irq_nosync(Q6FW_WDOG_EXPIRED_IRQ);
disable_irq_nosync(Q6SW_WDOG_EXPIRED_IRQ);
return 0;
}
#define MODEM_WDOG_CHECK_TIMEOUT_MS 10000
static int modem_powerup(const struct subsys_data *subsys)
{
pil_force_boot("modem_fw");
pil_force_boot("modem");
enable_irq(Q6FW_WDOG_EXPIRED_IRQ);
enable_irq(Q6SW_WDOG_EXPIRED_IRQ);
schedule_delayed_work(&modem_wdog_check_work,
msecs_to_jiffies(MODEM_WDOG_CHECK_TIMEOUT_MS));
return 0;
}
void modem_crash_shutdown(const struct subsys_data *subsys)
{
crash_shutdown = 1;
smsm_reset_modem(SMSM_RESET);
}
/* FIXME: Get address, size from PIL */
static struct ramdump_segment modemsw_segments[] = {
{0x89000000, 0x8D400000 - 0x89000000},
};
static struct ramdump_segment modemfw_segments[] = {
{0x8D400000, 0x8DA00000 - 0x8D400000},
};
static struct ramdump_segment smem_segments[] = {
{0x80000000, 0x00200000},
};
static void *modemfw_ramdump_dev;
static void *modemsw_ramdump_dev;
static void *smem_ramdump_dev;
static int modem_ramdump(int enable,
const struct subsys_data *crashed_subsys)
{
int ret = 0;
if (enable) {
ret = do_ramdump(modemsw_ramdump_dev, modemsw_segments,
ARRAY_SIZE(modemsw_segments));
if (ret < 0) {
pr_err("Unable to dump modem sw memory (rc = %d).\n",
ret);
goto out;
}
ret = do_ramdump(modemfw_ramdump_dev, modemfw_segments,
ARRAY_SIZE(modemfw_segments));
if (ret < 0) {
pr_err("Unable to dump modem fw memory (rc = %d).\n",
ret);
goto out;
}
ret = do_ramdump(smem_ramdump_dev, smem_segments,
ARRAY_SIZE(smem_segments));
if (ret < 0) {
pr_err("Unable to dump smem memory (rc = %d).\n", ret);
goto out;
}
}
out:
return ret;
}
static irqreturn_t modem_wdog_bite_irq(int irq, void *dev_id)
{
switch (irq) {
case Q6SW_WDOG_EXPIRED_IRQ:
pr_err("Watchdog bite received from modem software!\n");
restart_modem();
break;
case Q6FW_WDOG_EXPIRED_IRQ:
pr_err("Watchdog bite received from modem firmware!\n");
restart_modem();
break;
break;
default:
pr_err("%s: Unknown IRQ!\n", __func__);
}
return IRQ_HANDLED;
}
static struct subsys_data modem_8960 = {
.name = "modem",
.shutdown = modem_shutdown,
.powerup = modem_powerup,
.ramdump = modem_ramdump,
.crash_shutdown = modem_crash_shutdown
};
static int modem_subsystem_restart_init(void)
{
return ssr_register_subsystem(&modem_8960);
}
static int modem_debug_set(void *data, u64 val)
{
if (val == 1)
subsystem_restart("modem");
return 0;
}
static int modem_debug_get(void *data, u64 *val)
{
*val = 0;
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(modem_debug_fops, modem_debug_get, modem_debug_set,
"%llu\n");
static int modem_debugfs_init(void)
{
struct dentry *dent;
dent = debugfs_create_dir("modem_debug", 0);
if (IS_ERR(dent))
return PTR_ERR(dent);
debugfs_create_file("reset_modem", 0644, dent, NULL,
&modem_debug_fops);
return 0;
}
static int __init modem_8960_init(void)
{
int ret;
if (cpu_is_apq8064())
return -ENODEV;
ret = smsm_state_cb_register(SMSM_MODEM_STATE, SMSM_RESET,
smsm_state_cb, 0);
if (ret < 0)
pr_err("%s: Unable to register SMSM callback! (%d)\n",
__func__, ret);
ret = request_irq(Q6FW_WDOG_EXPIRED_IRQ, modem_wdog_bite_irq,
IRQF_TRIGGER_RISING, "modem_wdog_fw", NULL);
if (ret < 0) {
pr_err("%s: Unable to request q6fw watchdog IRQ. (%d)\n",
__func__, ret);
goto out;
}
ret = request_irq(Q6SW_WDOG_EXPIRED_IRQ, modem_wdog_bite_irq,
IRQF_TRIGGER_RISING, "modem_wdog_sw", NULL);
if (ret < 0) {
pr_err("%s: Unable to request q6sw watchdog IRQ. (%d)\n",
__func__, ret);
disable_irq_nosync(Q6FW_WDOG_EXPIRED_IRQ);
goto out;
}
ret = modem_subsystem_restart_init();
if (ret < 0) {
pr_err("%s: Unable to reg with subsystem restart. (%d)\n",
__func__, ret);
goto out;
}
modemfw_ramdump_dev = create_ramdump_device("modem_fw");
if (!modemfw_ramdump_dev) {
pr_err("%s: Unable to create modem fw ramdump device. (%d)\n",
__func__, -ENOMEM);
ret = -ENOMEM;
goto out;
}
modemsw_ramdump_dev = create_ramdump_device("modem_sw");
if (!modemsw_ramdump_dev) {
pr_err("%s: Unable to create modem sw ramdump device. (%d)\n",
__func__, -ENOMEM);
ret = -ENOMEM;
goto out;
}
smem_ramdump_dev = create_ramdump_device("smem-modem");
if (!smem_ramdump_dev) {
pr_err("%s: Unable to create smem ramdump device. (%d)\n",
__func__, -ENOMEM);
ret = -ENOMEM;
goto out;
}
ret = modem_debugfs_init();
pr_info("%s: modem fatal driver init'ed.\n", __func__);
out:
return ret;
}
module_init(modem_8960_init);
|
MiCode/mi2_kernel
|
arch/arm/mach-msm/modem-8960.c
|
C
|
gpl-2.0
| 8,034 |
<!DOCTYPE html>
<script src="../../resources/js-test-pre.js"></script>
<style>
.test { display: height: 10px; background: #ddf; font: 20px/1 Ahem; }
#nocalc { width: 310px; }
#calc { width: calc(15em + 10px); width: -moz-calc(15em + 10px); width: calc(15em + 10px); }
</style>
<div id="nocalc" class="test"></div>
<div id="calc" class="test"></div>
<script>
descriptionQuiet("Tests that zooming a calc expression containing 'em' units works correctly");
zoomLevels = [0.67, 0.75, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 1];
calc = document.getElementById("calc");
nocalc = document.getElementById("nocalc");
for (var z = 0; z < zoomLevels.length; z++) {
var zoom = zoomLevels[z];
document.body.style.zoom = zoom;
shouldBe(calc.offsetWidth + "", nocalc.offsetWidth + "", true);
}
</script>
<script src="../../resources/js-test-post.js"></script>
|
achellies/src
|
LayoutTests/css3/calc/zoom-with-em.html
|
HTML
|
gpl-2.0
| 872 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.