code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
import Ember from 'ember';
export default Ember.Controller.extend({
canCreateTask: Ember.computed('model.isAdmin', function() {
return this.get('model.isAdmin');
}),
});
| singularities/circular-works | frontend/app/controllers/organizations/show.js | JavaScript | agpl-3.0 | 180 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('activities', '0004_manytomany_not_null'),
]
operations = [
migrations.AddField(
model_name='activity',
name='is_approved',
field=models.NullBooleanField(verbose_name='\u0627\u0644\u062d\u0627\u0644\u0629', choices=[(True, '\u0645\u0639\u062a\u0645\u062f'), (False, '\u0645\u0631\u0641\u0648\u0636'), (None, '\u0645\u0639\u0644\u0642')]),
),
]
| enjaz/enjaz | activities/migrations/0005_activity_is_approved.py | Python | agpl-3.0 | 587 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed 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.
*/
#include <Max3421e.h>
#include <Usb.h>
#include <AndroidAccessory.h>
#define USB_ACCESSORY_VENDOR_ID 0x18D1
#define USB_ACCESSORY_PRODUCT_ID 0x2D00
#define USB_ACCESSORY_ADB_PRODUCT_ID 0x2D01
#define ACCESSORY_STRING_MANUFACTURER 0
#define ACCESSORY_STRING_MODEL 1
#define ACCESSORY_STRING_DESCRIPTION 2
#define ACCESSORY_STRING_VERSION 3
#define ACCESSORY_STRING_URI 4
#define ACCESSORY_STRING_SERIAL 5
#define ACCESSORY_GET_PROTOCOL 51
#define ACCESSORY_SEND_STRING 52
#define ACCESSORY_START 53
AndroidAccessory::AndroidAccessory(const char *manufacturer,
const char *model,
const char *description,
const char *version,
const char *uri,
const char *serial) : manufacturer(manufacturer),
model(model),
description(description),
version(version),
uri(uri),
serial(serial),
connected(false)
{
}
void AndroidAccessory::powerOn(void)
{
max.powerOn();
delay(200);
}
int AndroidAccessory::getProtocol(byte addr)
{
uint16_t protocol = -1;
usb.ctrlReq(addr, 0,
USB_SETUP_DEVICE_TO_HOST |
USB_SETUP_TYPE_VENDOR |
USB_SETUP_RECIPIENT_DEVICE,
ACCESSORY_GET_PROTOCOL, 0, 0, 0, 2, (char *)&protocol);
return protocol;
}
void AndroidAccessory::sendString(byte addr, int index, const char *str)
{
usb.ctrlReq(addr, 0,
USB_SETUP_HOST_TO_DEVICE |
USB_SETUP_TYPE_VENDOR |
USB_SETUP_RECIPIENT_DEVICE,
ACCESSORY_SEND_STRING, 0, 0, index,
strlen(str) + 1, (char *)str);
}
bool AndroidAccessory::switchDevice(byte addr)
{
int protocol = getProtocol(addr);
if (protocol == 1) {
Serial.print(F("device supports protcol 1\n"));
} else {
Serial.print(F("could not read device protocol version\n"));
return false;
}
sendString(addr, ACCESSORY_STRING_MANUFACTURER, manufacturer);
sendString(addr, ACCESSORY_STRING_MODEL, model);
sendString(addr, ACCESSORY_STRING_DESCRIPTION, description);
sendString(addr, ACCESSORY_STRING_VERSION, version);
sendString(addr, ACCESSORY_STRING_URI, uri);
sendString(addr, ACCESSORY_STRING_SERIAL, serial);
usb.ctrlReq(addr, 0,
USB_SETUP_HOST_TO_DEVICE |
USB_SETUP_TYPE_VENDOR |
USB_SETUP_RECIPIENT_DEVICE,
ACCESSORY_START, 0, 0, 0, 0, NULL);
while (usb.getUsbTaskState() != USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE) {
max.Task();
usb.Task();
}
return true;
}
// Finds the first bulk IN and bulk OUT endpoints
bool AndroidAccessory::findEndpoints(byte addr, EP_RECORD *inEp, EP_RECORD *outEp)
{
int len;
byte err;
uint8_t *p;
err = usb.getConfDescr(addr, 0, 4, 0, (char *)descBuff);
if (err) {
Serial.print(F("Can't get config descriptor length\n"));
return false;
}
len = descBuff[2] | ((int)descBuff[3] << 8);
if (len > sizeof(descBuff)) {
Serial.print(F("config descriptor too large\n"));
/* might want to truncate here */
return false;
}
err = usb.getConfDescr(addr, 0, len, 0, (char *)descBuff);
if (err) {
Serial.print(F("Can't get config descriptor\n"));
return false;
}
p = descBuff;
inEp->epAddr = 0;
outEp->epAddr = 0;
while (p < (descBuff + len)){
uint8_t descLen = p[0];
uint8_t descType = p[1];
USB_ENDPOINT_DESCRIPTOR *epDesc;
EP_RECORD *ep;
switch (descType) {
case USB_DESCRIPTOR_CONFIGURATION:
Serial.print(F("config desc\n"));
break;
case USB_DESCRIPTOR_INTERFACE:
Serial.print(F("interface desc\n"));
break;
case USB_DESCRIPTOR_ENDPOINT:
epDesc = (USB_ENDPOINT_DESCRIPTOR *)p;
if (!inEp->epAddr && (epDesc->bEndpointAddress & 0x80))
ep = inEp;
else if (!outEp->epAddr)
ep = outEp;
else
ep = NULL;
if (ep) {
ep->epAddr = epDesc->bEndpointAddress & 0x7f;
ep->Attr = epDesc->bmAttributes;
ep->MaxPktSize = epDesc->wMaxPacketSize;
ep->sndToggle = bmSNDTOG0;
ep->rcvToggle = bmRCVTOG0;
}
break;
default:
Serial.print(F("unkown desc type "));
Serial.println( descType, HEX);
break;
}
p += descLen;
}
if (!(inEp->epAddr && outEp->epAddr))
Serial.println(F("can't find accessory endpoints"));
return inEp->epAddr && outEp->epAddr;
}
bool AndroidAccessory::configureAndroid(void)
{
byte err;
EP_RECORD inEp, outEp;
if (!findEndpoints(1, &inEp, &outEp))
return false;
memset(&epRecord, 0x0, sizeof(epRecord));
epRecord[inEp.epAddr] = inEp;
if (outEp.epAddr != inEp.epAddr)
epRecord[outEp.epAddr] = outEp;
in = inEp.epAddr;
out = outEp.epAddr;
Serial.println(inEp.epAddr, HEX);
Serial.println(outEp.epAddr, HEX);
epRecord[0] = *(usb.getDevTableEntry(0,0));
usb.setDevTableEntry(1, epRecord);
err = usb.setConf( 1, 0, 1 );
if (err) {
Serial.print(F("Can't set config to 1\n"));
return false;
}
usb.setUsbTaskState( USB_STATE_RUNNING );
return true;
}
bool AndroidAccessory::isConnected(void)
{
USB_DEVICE_DESCRIPTOR *devDesc = (USB_DEVICE_DESCRIPTOR *) descBuff;
byte err;
max.Task();
usb.Task();
if (!connected &&
usb.getUsbTaskState() >= USB_STATE_CONFIGURING &&
usb.getUsbTaskState() != USB_STATE_RUNNING) {
Serial.print(F("\nDevice addressed... "));
Serial.print(F("Requesting device descriptor.\n"));
err = usb.getDevDescr(1, 0, 0x12, (char *) devDesc);
if (err) {
Serial.print(F("\nDevice descriptor cannot be retrieved. Trying again\n"));
return false;
}
if (isAccessoryDevice(devDesc)) {
Serial.print(F("found android acessory device\n"));
connected = configureAndroid();
} else {
Serial.print(F("found possible device. swithcing to serial mode\n"));
switchDevice(1);
}
} else if (usb.getUsbTaskState() == USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE) {
if (connected)
Serial.println(F("disconnect\n"));
connected = false;
}
return connected;
}
bool AndroidAccessory::dataBufferIsEmpty() {
return (numBytesInDataBuff == nextByteInDataBuffOffset);
}
void AndroidAccessory::refillDataBuffer() {
int bytesRead = 0;
numBytesInDataBuff = nextByteInDataBuffOffset = 0;
// TODO: Add is connected check?
bytesRead = read(dataBuff, sizeof(dataBuff));
if (bytesRead >= 1) {
numBytesInDataBuff = bytesRead;
}
}
int AndroidAccessory::read() {
if (dataBufferIsEmpty()) {
refillDataBuffer();
}
return dataBufferIsEmpty() ? -1 : dataBuff[nextByteInDataBuffOffset++];
}
int AndroidAccessory::peek() {
if (dataBufferIsEmpty()) {
refillDataBuffer();
}
return dataBufferIsEmpty() ? -1 : dataBuff[nextByteInDataBuffOffset];
}
int AndroidAccessory::available() {
// Strictly speaking this doesn't meet the "This is only for bytes
// that have already arrived" definition from
// <http://arduino.cc/en/Reference/StreamAvailable> but since the
// data isn't handled by an ISR it's the only way to avoid hanging
// waiting for `available()` to return true.
if (dataBufferIsEmpty()) {
refillDataBuffer();
}
return numBytesInDataBuff - nextByteInDataBuffOffset;
}
int AndroidAccessory::read(void *buff, int len, unsigned int nakLimit)
{
return usb.newInTransfer(1, in, len, (char *)buff, nakLimit);
}
size_t AndroidAccessory::write(uint8_t *buff, size_t len)
{
usb.outTransfer(1, out, len, (char *)buff);
return len;
}
size_t AndroidAccessory::write(uint8_t c) {
return write(&c, 1);
}
void AndroidAccessory::flush() {
/*
"Waits for the transmission of outgoing [...] data to complete."
from <http://arduino.cc/en/Serial/Flush>
We're treating this as a no-op at the moment.
*/
}
| xin3liang/platform_external_arduino-ide | hardware/arduino/sam/system/AndroidAccessory/AndroidAccessory.cpp | C++ | lgpl-2.1 | 9,423 |
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtXmlPatterns module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qitem_p.h"
#include "qboolean_p.h"
#include "qbuiltintypes_p.h"
#include "qcommonsequencetypes_p.h"
#include "qemptysequence_p.h"
#include "qoptimizationpasses_p.h"
#include "qvaluecomparison_p.h"
QT_BEGIN_NAMESPACE
using namespace QPatternist;
ValueComparison::ValueComparison(const Expression::Ptr &op1,
const AtomicComparator::Operator op,
const Expression::Ptr &op2) : PairContainer(op1, op2),
m_operator(op)
{
}
Item ValueComparison::evaluateSingleton(const DynamicContext::Ptr &context) const
{
const Item it1(m_operand1->evaluateSingleton(context));
if(!it1)
return Item();
const Item it2(m_operand2->evaluateSingleton(context));
if(!it2)
return Item();
return Boolean::fromValue(flexibleCompare(it1, it2, context));
}
Expression::Ptr ValueComparison::typeCheck(const StaticContext::Ptr &context,
const SequenceType::Ptr &reqType)
{
const Expression::Ptr me(PairContainer::typeCheck(context, reqType));
const ItemType::Ptr t1(m_operand1->staticType()->itemType());
const ItemType::Ptr t2(m_operand2->staticType()->itemType());
Q_ASSERT(t1);
Q_ASSERT(t2);
if(*CommonSequenceTypes::Empty == *t1 ||
*CommonSequenceTypes::Empty == *t2)
{
return EmptySequence::create(this, context);
}
else
{
prepareComparison(fetchComparator(t1, t2, context));
return me;
}
}
Expression::Ptr ValueComparison::compress(const StaticContext::Ptr &context)
{
const Expression::Ptr me(PairContainer::compress(context));
if(me != this)
return me;
if(isCaseInsensitiveCompare(m_operand1, m_operand2))
useCaseInsensitiveComparator();
return me;
}
bool ValueComparison::isCaseInsensitiveCompare(Expression::Ptr &op1, Expression::Ptr &op2)
{
Q_ASSERT(op1);
Q_ASSERT(op2);
const ID iD = op1->id();
if((iD == IDLowerCaseFN || iD == IDUpperCaseFN) && iD == op2->id())
{
/* Both are either fn:lower-case() or fn:upper-case(). */
/* Replace the calls to the functions with its operands. */
op1 = op1->operands().first();
op2 = op2->operands().first();
return true;
}
else
return false;
}
OptimizationPass::List ValueComparison::optimizationPasses() const
{
return OptimizationPasses::comparisonPasses;
}
SequenceType::List ValueComparison::expectedOperandTypes() const
{
SequenceType::List result;
result.append(CommonSequenceTypes::ZeroOrOneAtomicType);
result.append(CommonSequenceTypes::ZeroOrOneAtomicType);
return result;
}
SequenceType::Ptr ValueComparison::staticType() const
{
if(m_operand1->staticType()->cardinality().allowsEmpty() ||
m_operand2->staticType()->cardinality().allowsEmpty())
return CommonSequenceTypes::ZeroOrOneBoolean;
else
return CommonSequenceTypes::ExactlyOneBoolean;
}
ExpressionVisitorResult::Ptr ValueComparison::accept(const ExpressionVisitor::Ptr &visitor) const
{
return visitor->visit(this);
}
Expression::ID ValueComparison::id() const
{
return IDValueComparison;
}
QT_END_NAMESPACE
| igor-sfdc/qt-wk | src/xmlpatterns/expr/qvaluecomparison.cpp | C++ | lgpl-2.1 | 4,779 |
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qlandmarknamefilter.h"
#include "qlandmarknamefilter_p.h"
QTM_BEGIN_NAMESPACE
/*!
\class QLandmarkNameFilter
\brief The QLandmarkNameFilter class is used to search for landmarks by name.
\inmodule QtLocation
\since 1.1
\ingroup landmarks-filter
Please note that different platforms support different capabilities with the attribute filter.
\list
\o The S60 3.1, 3.2 and 5.0 platforms do not support the MatchContains flag while the Symbian
platform does.
\o Note also that MatchContains is supported using the sparql and sqlite \l {Landmark Managers and Plugins} {managers}.
\endlist
*/
Q_IMPLEMENT_LANDMARKFILTER_PRIVATE(QLandmarkNameFilter)
/*!
Creates a filter that selects landmarks by \a name.
\since 1.1
*/
QLandmarkNameFilter::QLandmarkNameFilter(const QString &name)
: QLandmarkFilter(new QLandmarkNameFilterPrivate(name)) {}
/*!
\fn QLandmarkNameFilter::QLandmarkNameFilter(const QLandmarkFilter &other)
Constructs a copy of \a other if possible, otherwise constructs a new name filter.
*/
/*!
Destroys the filter.
*/
QLandmarkNameFilter::~QLandmarkNameFilter()
{
// pointer deleted in superclass destructor
}
/*!
Returns the name that the filter will use to determine matches.
\since 1.1
*/
QString QLandmarkNameFilter::name() const
{
Q_D(const QLandmarkNameFilter);
return d->name;
}
/*!
Sets the \a name that the filter will use to determine matches.
\since 1.1
*/
void QLandmarkNameFilter::setName(const QString &name)
{
Q_D(QLandmarkNameFilter);
d->name = name;
}
/*!
Returns the matching criteria of the filter.
\since 1.1
*/
QLandmarkFilter::MatchFlags QLandmarkNameFilter::matchFlags() const
{
Q_D(const QLandmarkNameFilter);
return d->flags;
}
/*!
Sets the matching criteria to those defined in \a flags.
\since 1.1
*/
void QLandmarkNameFilter::setMatchFlags(QLandmarkFilter::MatchFlags flags)
{
Q_D(QLandmarkNameFilter);
d->flags = flags;
}
/*******************************************************************************
*******************************************************************************/
QLandmarkNameFilterPrivate::QLandmarkNameFilterPrivate(const QString &name)
: name(name),
flags(0)
{
type = QLandmarkFilter::NameFilter;
}
QLandmarkNameFilterPrivate::QLandmarkNameFilterPrivate(const QLandmarkNameFilterPrivate &other)
: QLandmarkFilterPrivate(other),
name(other.name),
flags(other.flags) {}
QLandmarkNameFilterPrivate::~QLandmarkNameFilterPrivate() {}
QTM_END_NAMESPACE
| kaltsi/qt-mobility | src/location/landmarks/qlandmarknamefilter.cpp | C++ | lgpl-2.1 | 4,339 |
package org.skyve.domain;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This is an annotation used for indicating that the associated metadata document that generated the domain class
* has at least one sub-document in its hierarchy that uses an inheritance strategy of joined or single.
* This is useful to know when executing metadata document queries as the query evaluator needs to include
* the THIS projection to allow for polymorphic methods.
*
* @author mike
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE) //on class level
public @interface PolymorphicPersistentBean {
// nothing to see here
} | skyvers/wildcat | skyve-core/src/main/java/org/skyve/domain/PolymorphicPersistentBean.java | Java | lgpl-2.1 | 752 |
/*
* ParallelJ, framework for parallel computing
*
* Copyright (C) 2010, 2011, 2012 Atos Worldline or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* This package contains implementations of {@link org.parallelj.internal.kernel.KJoin}.
*/
package org.parallelj.internal.kernel.join; | awltech/org.parallelj | parallelj-core-parent/parallelj-core-api/src/main/java/org/parallelj/internal/kernel/join/package-info.java | Java | lgpl-2.1 | 1,144 |
package net.minecraft.inventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.IChatComponent;
import net.minecraft.world.ILockableContainer;
import net.minecraft.world.LockCode;
public class InventoryLargeChest implements ILockableContainer
{
/** Name of the chest. */
private String name;
/** Inventory object corresponding to double chest upper part */
private ILockableContainer upperChest;
/** Inventory object corresponding to double chest lower part */
private ILockableContainer lowerChest;
private static final String __OBFID = "CL_00001507";
public InventoryLargeChest(String p_i45905_1_, ILockableContainer p_i45905_2_, ILockableContainer p_i45905_3_)
{
this.name = p_i45905_1_;
if (p_i45905_2_ == null)
{
p_i45905_2_ = p_i45905_3_;
}
if (p_i45905_3_ == null)
{
p_i45905_3_ = p_i45905_2_;
}
this.upperChest = p_i45905_2_;
this.lowerChest = p_i45905_3_;
if (p_i45905_2_.isLocked())
{
p_i45905_3_.setLockCode(p_i45905_2_.getLockCode());
}
else if (p_i45905_3_.isLocked())
{
p_i45905_2_.setLockCode(p_i45905_3_.getLockCode());
}
}
/**
* Returns the number of slots in the inventory.
*/
public int getSizeInventory()
{
return this.upperChest.getSizeInventory() + this.lowerChest.getSizeInventory();
}
/**
* Return whether the given inventory is part of this large chest.
*/
public boolean isPartOfLargeChest(IInventory inventoryIn)
{
return this.upperChest == inventoryIn || this.lowerChest == inventoryIn;
}
/**
* Gets the name of this command sender (usually username, but possibly "Rcon")
*/
public String getName()
{
return this.upperChest.hasCustomName() ? this.upperChest.getName() : (this.lowerChest.hasCustomName() ? this.lowerChest.getName() : this.name);
}
/**
* Returns true if this thing is named
*/
public boolean hasCustomName()
{
return this.upperChest.hasCustomName() || this.lowerChest.hasCustomName();
}
public IChatComponent getDisplayName()
{
return (IChatComponent)(this.hasCustomName() ? new ChatComponentText(this.getName()) : new ChatComponentTranslation(this.getName(), new Object[0]));
}
/**
* Returns the stack in slot i
*/
public ItemStack getStackInSlot(int index)
{
return index >= this.upperChest.getSizeInventory() ? this.lowerChest.getStackInSlot(index - this.upperChest.getSizeInventory()) : this.upperChest.getStackInSlot(index);
}
/**
* Removes from an inventory slot (first arg) up to a specified number (second arg) of items and returns them in a
* new stack.
*/
public ItemStack decrStackSize(int index, int count)
{
return index >= this.upperChest.getSizeInventory() ? this.lowerChest.decrStackSize(index - this.upperChest.getSizeInventory(), count) : this.upperChest.decrStackSize(index, count);
}
/**
* When some containers are closed they call this on each slot, then drop whatever it returns as an EntityItem -
* like when you close a workbench GUI.
*/
public ItemStack getStackInSlotOnClosing(int index)
{
return index >= this.upperChest.getSizeInventory() ? this.lowerChest.getStackInSlotOnClosing(index - this.upperChest.getSizeInventory()) : this.upperChest.getStackInSlotOnClosing(index);
}
/**
* Sets the given item stack to the specified slot in the inventory (can be crafting or armor sections).
*/
public void setInventorySlotContents(int index, ItemStack stack)
{
if (index >= this.upperChest.getSizeInventory())
{
this.lowerChest.setInventorySlotContents(index - this.upperChest.getSizeInventory(), stack);
}
else
{
this.upperChest.setInventorySlotContents(index, stack);
}
}
/**
* Returns the maximum stack size for a inventory slot. Seems to always be 64, possibly will be extended. *Isn't
* this more of a set than a get?*
*/
public int getInventoryStackLimit()
{
return this.upperChest.getInventoryStackLimit();
}
/**
* For tile entities, ensures the chunk containing the tile entity is saved to disk later - the game won't think it
* hasn't changed and skip it.
*/
public void markDirty()
{
this.upperChest.markDirty();
this.lowerChest.markDirty();
}
/**
* Do not make give this method the name canInteractWith because it clashes with Container
*/
public boolean isUseableByPlayer(EntityPlayer player)
{
return this.upperChest.isUseableByPlayer(player) && this.lowerChest.isUseableByPlayer(player);
}
public void openInventory(EntityPlayer player)
{
this.upperChest.openInventory(player);
this.lowerChest.openInventory(player);
}
public void closeInventory(EntityPlayer player)
{
this.upperChest.closeInventory(player);
this.lowerChest.closeInventory(player);
}
/**
* Returns true if automation is allowed to insert the given stack (ignoring stack size) into the given slot.
*/
public boolean isItemValidForSlot(int index, ItemStack stack)
{
return true;
}
public int getField(int id)
{
return 0;
}
public void setField(int id, int value) {}
public int getFieldCount()
{
return 0;
}
public boolean isLocked()
{
return this.upperChest.isLocked() || this.lowerChest.isLocked();
}
public void setLockCode(LockCode code)
{
this.upperChest.setLockCode(code);
this.lowerChest.setLockCode(code);
}
public LockCode getLockCode()
{
return this.upperChest.getLockCode();
}
public String getGuiID()
{
return this.upperChest.getGuiID();
}
public Container createContainer(InventoryPlayer playerInventory, EntityPlayer playerIn)
{
return new ContainerChest(playerInventory, this, playerIn);
}
public void clear()
{
this.upperChest.clear();
this.lowerChest.clear();
}
} | trixmot/mod1 | build/tmp/recompileMc/sources/net/minecraft/inventory/InventoryLargeChest.java | Java | lgpl-2.1 | 6,532 |
<?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id: phpunit.php 57962 2016-03-17 20:02:39Z jonnybradley $
/**
* A simple wrapper around /usr/bin/phpunit to enable debugging
* tests with Xdebug from within Aptana or Eclipse.
*
* Linux only (it should be simple to add support to other OSs).
*/
// Linux
require_once('/usr/bin/phpunit');
// Windows
// comment out the Linux require line (above) and uncomment the 2 lines below
//$pear_bin_path = getenv('PHP_PEAR_BIN_DIR').DIRECTORY_SEPARATOR;
//require_once($pear_bin_path."phpunit");
| lorddavy/TikiWiki-Improvement-Project | lib/test/phpunit.php | PHP | lgpl-2.1 | 752 |
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <mapnik/geom_util.hpp>
#include <mapnik/query.hpp>
#include "osm_datasource.hpp"
#include "osm_featureset.hpp"
#include "dataset_deliverer.h"
#include "osmtagtypes.h"
#include "osmparser.h"
#include <set>
DATASOURCE_PLUGIN(osm_datasource)
using mapnik::String;
using mapnik::Double;
using mapnik::Integer;
using mapnik::datasource_exception;
using mapnik::filter_in_box;
using mapnik::filter_at_point;
using mapnik::attribute_descriptor;
osm_datasource::osm_datasource(const parameters ¶ms, bool bind)
: datasource (params),
type_(datasource::Vector),
desc_(*params_.get<std::string>("type"), *params_.get<std::string>("encoding","utf-8"))
{
if (bind)
{
this->bind();
}
}
void osm_datasource::bind() const
{
if (is_bound_) return;
osm_data_ = NULL;
std::string osm_filename= *params_.get<std::string>("file","");
std::string parser = *params_.get<std::string>("parser","libxml2");
std::string url = *params_.get<std::string>("url","");
std::string bbox = *params_.get<std::string>("bbox","");
bool do_process=false;
// load the data
// if we supplied a filename, load from file
if (url!="" && bbox!="")
{
// otherwise if we supplied a url and a bounding box, load from the url
#ifdef MAPNIK_DEBUG
cerr<<"loading_from_url: url="<<url << " bbox="<<bbox<<endl;
#endif
if((osm_data_=dataset_deliverer::load_from_url
(url,bbox,parser))==NULL)
{
throw datasource_exception("Error loading from URL");
}
do_process=true;
}
else if(osm_filename!="")
{
if ((osm_data_=
dataset_deliverer::load_from_file(osm_filename,parser))==NULL)
{
throw datasource_exception("Error loading from file");
}
do_process=true;
}
if(do_process==true)
{
osm_tag_types tagtypes;
tagtypes.add_type("maxspeed",mapnik::Integer);
tagtypes.add_type("z_order",mapnik::Integer);
osm_data_->rewind();
// Need code to get the attributes of all the data
std::set<std::string> keys= osm_data_->get_keys();
// Add the attributes to the datasource descriptor - assume they are
// all of type String
for(std::set<std::string>::iterator i=keys.begin(); i!=keys.end(); i++)
desc_.add_descriptor(attribute_descriptor(*i,tagtypes.get_type(*i)));
// Get the bounds of the data and set extent_ accordingly
bounds b = osm_data_->get_bounds();
extent_ = box2d<double>(b.w,b.s,b.e,b.n);
}
is_bound_ = true;
}
osm_datasource::~osm_datasource()
{
// Do not do as is now static variable and cleaned up at exit
//delete osm_data_;
}
std::string osm_datasource::name()
{
return "osm";
}
int osm_datasource::type() const
{
return type_;
}
layer_descriptor osm_datasource::get_descriptor() const
{
return desc_;
}
featureset_ptr osm_datasource::features(const query& q) const
{
if (!is_bound_) bind();
filter_in_box filter(q.get_bbox());
// so we need to filter osm features by bbox here...
return featureset_ptr
(new osm_featureset<filter_in_box>(filter,
osm_data_,
q.property_names(),
desc_.get_encoding()));
}
featureset_ptr osm_datasource::features_at_point(coord2d const& pt) const
{
if (!is_bound_) bind();
filter_at_point filter(pt);
// collect all attribute names
std::vector<attribute_descriptor> const& desc_vector =
desc_.get_descriptors();
std::vector<attribute_descriptor>::const_iterator itr = desc_vector.begin();
std::vector<attribute_descriptor>::const_iterator end = desc_vector.end();
std::set<std::string> names;
while (itr != end)
{
names.insert(itr->get_name());
++itr;
}
return featureset_ptr
(new osm_featureset<filter_at_point>(filter,
osm_data_,
names,
desc_.get_encoding()));
}
box2d<double> osm_datasource::envelope() const
{
if (!is_bound_) bind();
return extent_;
}
| carlos-lopez-garces/mapnik-trunk | plugins/input/osm/osm_datasource.cpp | C++ | lgpl-2.1 | 5,406 |
<?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id: MasterSlaveDispatch.php 57968 2016-03-17 20:06:57Z jonnybradley $
class TikiDb_MasterSlaveDispatch extends TikiDb
{
private $master;
private $slave;
private $lastUsed;
function __construct( TikiDb $master, TikiDb $slave )
{
$this->master = $master;
$this->slave = $slave;
$this->lastUsed = $slave;
}
function getReal()
{
return $this->slave;
}
function startTimer() // {{{
{
$this->getApplicable()->startTimer();
} // }}}
function stopTimer($starttime) // {{{
{
$this->getApplicable()->stopTimer($starttime);
} // }}}
function qstr( $str ) // {{{
{
return $this->getApplicable()->qstr($str);
} // }}}
function query( $query = null, $values = null, $numrows = -1, $offset = -1, $reporterrors = true ) // {{{
{
return $this->getApplicable($query)->query($query, $values, $numrows, $offset, $reporterrors);
} // }}}
function queryError( $query, &$error, $values = null, $numrows = -1, $offset = -1 ) // {{{
{
return $this->getApplicable($query)->queryError($query, $error, $values, $numrows, $offset);
} // }}}
function getOne( $query, $values = null, $reporterrors = true, $offset = 0 ) // {{{
{
return $this->getApplicable($query)->getOne($query, $values, $reporterrors, $offset);
} // }}}
function setErrorHandler( TikiDb_ErrorHandler $handler ) // {{{
{
$this->getApplicable()->setErrorHandler($handler);
} // }}}
function setTablePrefix( $prefix ) // {{{
{
$this->getApplicable()->setTablePrefix($prefix);
} // }}}
function setUsersTablePrefix( $prefix ) // {{{
{
$this->getApplicable()->setUsersTablePrefix($prefix);
} // }}}
function getServerType() // {{{
{
return $this->getApplicable()->getServerType();
} // }}}
function setServerType( $type ) // {{{
{
$this->getApplicable()->setServerType($type);
} // }}}
function getErrorMessage() // {{{
{
return $this->lastUsed->getErrorMessage();
} // }}}
protected function setErrorMessage( $message ) // {{{
{
$this->getApplicable()->setErrorMessage($message);
} // }}}
protected function handleQueryError( $query, $values, $result ) // {{{
{
$this->getApplicable()->handleQueryError($query, $values, $result);
} // }}}
protected function convertQueryTablePrefixes( &$query ) // {{{
{
$this->getApplicable($query)->convertQueryTablePrefixes($query);
} // }}}
function convertSortMode( $sort_mode ) // {{{
{
return $this->getApplicable()->convertSortMode($sort_mode);
} // }}}
function getQuery() // {{{
{
return $this->getApplicable()->getQuery();
} // }}}
function setQuery( $sql ) // {{{
{
return $this->getApplicable()->setQuery($sql);
} // }}}
function ifNull( $field, $ifNull ) // {{{
{
return $this->getApplicable()->ifNull($field, $ifNull);
} // }}}
function in( $field, $values, &$bindvars ) // {{{
{
return $this->getApplicable()->in($field, $values, $bindvars);
} // }}}
function concat() // {{{
{
$arr = func_get_args();
return call_user_func_array(array( $this->getApplicable(), 'concat' ), $arr);
} // }}}
private function getApplicable( $query = '' )
{
if ( empty($query) ) {
return $this->lastUsed = $this->slave;
}
// If it's a write
// regex is for things starting with select in any case with potential
// whitespace in front of it
if (!preg_match('/^\s*select/i', $query)) {
return $this->lastUsed = $this->master;
}
return $this->lastUsed = $this->slave;
}
}
| lorddavy/TikiWiki-Improvement-Project | lib/core/TikiDb/MasterSlaveDispatch.php | PHP | lgpl-2.1 | 3,672 |
var searchData=
[
['narrowing_5ferror',['narrowing_error',['../structgsl_1_1narrowing__error.html',1,'gsl']]],
['not_5fnull',['not_null',['../classgsl_1_1not__null.html',1,'gsl']]],
['null_5fspin_5fpolicy',['null_spin_policy',['../structquickcpplib_1_1__xxx_1_1configurable__spinlock_1_1null__spin__policy.html',1,'quickcpplib::_xxx::configurable_spinlock']]]
];
| FSMaxB/molch | outcome/include/outcome/quickcpplib/doc/html/search/classes_9.js | JavaScript | lgpl-2.1 | 369 |
package StevenDimDoors.mod_pocketDim.blocks;
import java.util.Random;
import net.minecraft.block.BlockDoor;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.IconFlipped;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import StevenDimDoors.mod_pocketDim.mod_pocketDim;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class BlockDoorGold extends BlockDoor
{
public BlockDoorGold(Material par2Material)
{
super( par2Material);
}
@SideOnly(Side.CLIENT)
protected String getTextureName()
{
return mod_pocketDim.modid + ":" + this.getUnlocalizedName();
}
@Override
public Item getItemDropped(int par1, Random par2Random, int par3)
{
return (par1 & 8) != 0 ? null : mod_pocketDim.itemGoldenDoor;
}
@Override
@SideOnly(Side.CLIENT)
public Item getItem(World world, int x, int y, int z) {
return mod_pocketDim.itemGoldenDoor;
}
}
| CannibalVox/DimDoors | src/main/java/StevenDimDoors/mod_pocketDim/blocks/BlockDoorGold.java | Java | lgpl-2.1 | 1,123 |
package org.skyve.impl.domain.messages;
import org.skyve.domain.messages.DomainException;
public class SecurityException extends DomainException {
/**
* For Serialization
*/
private static final long serialVersionUID = 2941808458696267548L;
public SecurityException(String resource, String userName) {
super(userName + " does not have access to " + resource);
}
}
| skyvers/wildcat | skyve-ext/src/main/java/org/skyve/impl/domain/messages/SecurityException.java | Java | lgpl-2.1 | 377 |
<?php
// (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id: flagnames.php 39469 2012-01-12 21:13:48Z changi67 $
// -*- coding:utf-8 -*-
/*
* The listing associates country names used as filenames for flags in Tikiwiki for language translation
*/
// This script is only for language translations - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}
// Here come the dynamically generated strings for img/flags/*.gif
// This file ensures that the following strings will be included in the language translation files.
tra('Afghanistan');
tra('Aland Islands');
tra('Aland_Islands');
tra('Albania');
tra('Algeria');
tra('American Samoa');
tra('American_Samoa');
tra('Andorra');
tra('Angola');
tra('Anguilla');
tra('Antigua');
tra('Argentina');
tra('Armenia');
tra('Aruba');
tra('Australia');
tra('Austria');
tra('Azerbaijan');
tra('Bahamas');
tra('Bahrain');
tra('Bangladesh');
tra('Barbados');
tra('Belarus');
tra('Belgium');
tra('Belize');
tra('Benin');
tra('Bermuda');
tra('Bhutan');
tra('Bolivia');
tra('Bosnia and Herzegovina');
tra('Bosnia_and_Herzegovina');
tra('Botswana');
tra('Bouvet Island');
tra('Bouvet_Island');
tra('Brazil');
tra('British Indian Ocean Territory');
tra('British Virgin Islands');
tra('British_Indian_Ocean_Territory');
tra('British_Virgin_Islands');
tra('Brunei');
tra('Bulgaria');
tra('Burkina Faso');
tra('Burkina_Faso');
tra('Burundi');
tra('Cambodia');
tra('Cameroon');
tra('Canada');
tra('Cape Verde');
tra('Cape_Verde');
tra('Catalan Countries');
tra('Catalan_Countries');
tra('Cayman Islands');
tra('Cayman_Islands');
tra('Central African Republic');
tra('Central_African_Republic');
tra('Chad');
tra('Chile');
tra('China');
tra('Christmas Island');
tra('Christmas_Island');
tra('Cocos Islands');
tra('Cocos_Islands');
tra('Colombia');
tra('Comoros');
tra('Congo Democratic');
tra('Congo');
tra('Congo_Democratic');
tra('Cook Islands');
tra('Cook_Islands');
tra('Costa Rica');
tra('Costa_Rica');
tra('Croatia');
tra('Cuba');
tra('Cyprus');
tra('Czech Republic');
tra('Czech_Republic');
tra('Denmark');
tra('Djibouti');
tra('Dominica');
tra('Dominican Republic');
tra('Dominican_Republic');
tra('Ecuador');
tra('Egypt');
tra('El Salvador');
tra('El_Salvador');
tra('Equatorial Guinea');
tra('Equatorial_Guinea');
tra('Eritrea');
tra('Estonia');
tra('Ethiopia');
tra('Europe');
tra('Falkland Islands');
tra('Falkland_Islands');
tra('Faroe Islands');
tra('Faroe_Islands');
tra('Federated States of Micronesia');
tra('Federated_States_of_Micronesia');
tra('Fiji');
tra('Finland');
tra('France');
tra('French Guiana');
tra('French Polynesia');
tra('French Southern Territories');
tra('French_Guiana');
tra('French_Polynesia');
tra('French_Southern_Territories');
tra('Gabon');
tra('Gambia');
tra('Georgia');
tra('Germany');
tra('Ghana');
tra('Gibraltar');
tra('Greece');
tra('Greenland');
tra('Grenada');
tra('Guadeloupe');
tra('Guam');
tra('Guatemala');
tra('Guernsey');
tra('Guinea Bissau');
tra('Guinea');
tra('Guinea_Bissau');
tra('Guyana');
tra('Haiti');
tra('Heard Island and McDonald Islands');
tra('Heard_Island_and_McDonald_Islands');
tra('Honduras');
tra('Hong Kong');
tra('Hong_Kong');
tra('Hungary');
tra('Iceland');
tra('India');
tra('Indonesia');
tra('Iran');
tra('Iraq');
tra('Ireland');
tra('Isle of Man');
tra('Israel');
tra('Italy');
tra('Ivory Coast');
tra('Ivory_Coast');
tra('Jamaica');
tra('Japan');
tra('Jersey');
tra('Jordan');
tra('Kazakstan');
tra('Kenya');
tra('Kiribati');
tra('Kuwait');
tra('Kyrgyzstan');
tra('Laos');
tra('Latvia');
tra('Lebanon');
tra('Lesotho');
tra('Liberia');
tra('Libya');
tra('Liechtenstein');
tra('Lithuania');
tra('Luxemburg');
tra('Macao');
tra('Macedonia');
tra('Madagascar');
tra('Malawi');
tra('Malaysia');
tra('Maldives');
tra('Mali');
tra('Malta');
tra('Marshall Islands');
tra('Marshall_Islands');
tra('Martinique');
tra('Mauritania');
tra('Mauritius');
tra('Mayotte');
tra('Mexico');
tra('Moldova');
tra('Monaco');
tra('Mongolia');
tra('Montenegro');
tra('Montserrat');
tra('Morocco');
tra('Mozambique');
tra('Myanmar');
tra('Namibia');
tra('Nauru');
tra('Nepal');
tra('Netherlands Antilles');
tra('Netherlands');
tra('Netherlands_Antilles');
tra('New Caledonia');
tra('New Zealand');
tra('New_Caledonia');
tra('New_Zealand');
tra('Nicaragua');
tra('Niger');
tra('Nigeria');
tra('Niue');
tra('None');
tra('Norfolk Island');
tra('Norfolk_Island');
tra('North Korea');
tra('North_Korea');
tra('Northern Mariana Islands');
tra('Northern_Mariana_Islands');
tra('Norway');
tra('Oman');
tra('Other');
tra('Pakistan');
tra('Palau');
tra('Palestine');
tra('Panama');
tra('Papua New Guinea');
tra('Papua_New_Guinea');
tra('Paraguay');
tra('Peru');
tra('Philippines');
tra('Pitcairn');
tra('Poland');
tra('Portugal');
tra('Puerto Rico');
tra('Puerto_Rico');
tra('Quatar');
tra('Republic of Macedonia');
tra('Republic_of_Macedonia');
tra('Reunion');
tra('Romania');
tra('Russia');
tra('Russian Federation');
tra('Russian_Federation');
tra('Rwanda');
tra('Saint Helena');
tra('Saint Kitts and Nevis');
tra('Saint Lucia');
tra('Saint Pierre and Miquelon');
tra('Saint_Helena');
tra('Saint_Kitts_and_Nevis');
tra('Saint_Lucia');
tra('Saint_Pierre_and_Miquelon');
tra('Samoa');
tra('San Marino');
tra('San_Marino');
tra('Sao Tome and Principe');
tra('Sao_Tome_and_Principe');
tra('Saudi Arabia');
tra('Saudi_Arabia');
tra('Senegal');
tra('Serbia');
tra('Seychelles');
tra('Sierra Leone');
tra('Sierra_Leone');
tra('Singapore');
tra('Slovakia');
tra('Slovenia');
tra('Solomon Islands');
tra('Solomon_Islands');
tra('Somalia');
tra('South Africa');
tra('South Georgia and South Sandwich Islands');
tra('South Korea');
tra('South_Africa');
tra('South_Georgia_and_South_Sandwich_Islands');
tra('South_Korea');
tra('Spain');
tra('Sri Lanka');
tra('Sri_Lanka');
tra('St Vincent Grenadines');
tra('St_Vincent_Grenadines');
tra('Sudan');
tra('Surinam');
tra('Svalbard and Jan Mayen');
tra('Svalbard_and_Jan_Mayen');
tra('Swaziland');
tra('Sweden');
tra('Switzerland');
tra('Syria');
tra('Taiwan');
tra('Tajikistan');
tra('Tanzania');
tra('Thailand');
tra('Timor-Leste');
tra('Togo');
tra('Tokelau');
tra('Tonga');
tra('Trinidad Tobago');
tra('Trinidad_Tobago');
tra('Tunisia');
tra('Turkey');
tra('Turkmenistan');
tra('Turks and Caicos Islands');
tra('Turks_and_Caicos_Islands');
tra('Tuvalu');
tra('US Virgin Islands');
tra('US_Virgin_Islands');
tra('Uganda');
tra('Ukraine');
tra('United Arab Emirates');
tra('United Kingdom');
tra('United Nations Organization');
tra('United States Minor Outlying Islands');
tra('United States');
tra('United_Arab_Emirates');
tra('United_Kingdom');
tra('United_Kingdom_-_England_and_Wales');
tra('United_Kingdom_-_Northern_Ireland');
tra('United_Kingdom_-_Scotland');
tra('United_Nations_Organization');
tra('United_States');
tra('United_States_Minor_Outlying_Islands');
tra('Uruguay');
tra('Uzbekistan');
tra('Vanuatu');
tra('Vatican');
tra('Venezuela');
tra('Viet Nam');
tra('Viet_Nam');
tra('Wales');
tra('Wallis and Futuna');
tra('Wallis_and_Futuna');
tra('Western Sahara');
tra('Western_Sahara');
tra('World');
tra('Yemen');
tra('Yugoslavia');
tra('Zambia');
tra('Zimbabwe');
tra('the former Yugoslav Republic of Macedonia');
tra('the_former_Yugoslav_Republic_of_Macedonia');
| railfuture/tiki-website | img/flags/flagnames.php | PHP | lgpl-2.1 | 7,500 |
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2018 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.design;
import static com.puppycrawl.tools.checkstyle.checks.design.OneTopLevelClassCheck.MSG_KEY;
import static org.junit.Assert.assertArrayEquals;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.google.common.collect.ImmutableMap;
import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
public class OneTopLevelClassCheckTest extends AbstractModuleTestSupport {
@Override
protected String getPackageLocation() {
return "com/puppycrawl/tools/checkstyle/checks/design/onetoplevelclass";
}
@Test
public void testGetRequiredTokens() {
final OneTopLevelClassCheck checkObj = new OneTopLevelClassCheck();
assertArrayEquals("Required tokens array is not empty",
CommonUtils.EMPTY_INT_ARRAY, checkObj.getRequiredTokens());
}
@Test
public void testClearState() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(OneTopLevelClassCheck.class);
final String firstInputFilePath = getPath("InputOneTopLevelClassDeclarationOrder.java");
final String secondInputFilePath = getPath("InputOneTopLevelClassInterface2.java");
final File[] inputs = {
new File(firstInputFilePath),
new File(secondInputFilePath),
};
final List<String> expectedFirstInput = Collections.singletonList(
"10: " + getCheckMessage(MSG_KEY, "InputDeclarationOrderEnum"));
final List<String> expectedSecondInput = Arrays.asList(
"3: " + getCheckMessage(MSG_KEY, "InputOneTopLevelClassInterface2inner1"),
"11: " + getCheckMessage(MSG_KEY, "InputOneTopLevelClassInterface2inner2"));
verify(createChecker(checkConfig), inputs,
ImmutableMap.of(firstInputFilePath, expectedFirstInput,
secondInputFilePath, expectedSecondInput));
}
@Test
public void testAcceptableTokens() {
final OneTopLevelClassCheck check = new OneTopLevelClassCheck();
check.getAcceptableTokens();
// ZERO tokens as Check do Traverse of Tree himself, he does not need to subscribed to
// Tokens
Assert.assertEquals("Acceptable tokens array size larger than 0",
0, check.getAcceptableTokens().length);
}
@Test
public void testFileWithOneTopLevelClass() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(OneTopLevelClassCheck.class);
final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
verify(checkConfig, getPath("InputOneTopLevelClass.java"), expected);
}
@Test
public void testFileWithOneTopLevelInterface() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(OneTopLevelClassCheck.class);
final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
verify(checkConfig, getPath("InputOneTopLevelClassInterface.java"), expected);
}
@Test
public void testFileWithOneTopLevelEnum() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(OneTopLevelClassCheck.class);
final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
verify(checkConfig, getPath("InputOneTopLevelClassEnum.java"), expected);
}
@Test
public void testFileWithNoPublicTopLevelClass() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(OneTopLevelClassCheck.class);
final String[] expected = {
"8: " + getCheckMessage(MSG_KEY, "InputOneTopLevelClassNoPublic2"),
};
verify(checkConfig, getPath("InputOneTopLevelClassNoPublic.java"), expected);
}
@Test
public void testFileWithThreeTopLevelInterface() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(OneTopLevelClassCheck.class);
final String[] expected = {
"3: " + getCheckMessage(MSG_KEY, "InputOneTopLevelClassInterface2inner1"),
"11: " + getCheckMessage(MSG_KEY, "InputOneTopLevelClassInterface2inner2"),
};
verify(checkConfig, getPath("InputOneTopLevelClassInterface2.java"), expected);
}
@Test
public void testFileWithThreeTopLevelEnum() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(OneTopLevelClassCheck.class);
final String[] expected = {
"3: " + getCheckMessage(MSG_KEY, "InputOneTopLevelClassEnum2inner1"),
"11: " + getCheckMessage(MSG_KEY, "InputOneTopLevelClassEnum2inner2"),
};
verify(checkConfig, getPath("InputOneTopLevelClassEnum2.java"), expected);
}
@Test
public void testFileWithFewTopLevelClasses() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(OneTopLevelClassCheck.class);
final String[] expected = {
"25: " + getCheckMessage(MSG_KEY, "NoSuperClone"),
"29: " + getCheckMessage(MSG_KEY, "InnerClone"),
"33: " + getCheckMessage(MSG_KEY, "CloneWithTypeArguments"),
"37: " + getCheckMessage(MSG_KEY, "CloneWithTypeArgumentsAndNoSuper"),
"41: " + getCheckMessage(MSG_KEY, "MyClassWithGenericSuperMethod"),
"45: " + getCheckMessage(MSG_KEY, "AnotherClass"),
"48: " + getCheckMessage(MSG_KEY, "NativeTest"),
};
verify(checkConfig, getPath("InputOneTopLevelClassClone.java"), expected);
}
@Test
public void testFileWithSecondEnumTopLevelClass() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(OneTopLevelClassCheck.class);
final String[] expected = {
"10: " + getCheckMessage(MSG_KEY, "InputDeclarationOrderEnum"),
};
verify(checkConfig, getPath("InputOneTopLevelClassDeclarationOrder.java"), expected);
}
@Test
public void testPackageInfoWithNoTypesDeclared() throws Exception {
final DefaultConfiguration checkConfig = createModuleConfig(OneTopLevelClassCheck.class);
final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
verify(checkConfig, getNonCompilablePath("package-info.java"), expected);
}
}
| jonmbake/checkstyle | src/test/java/com/puppycrawl/tools/checkstyle/checks/design/OneTopLevelClassCheckTest.java | Java | lgpl-2.1 | 7,614 |
// This file was generated by qlalr - DO NOT EDIT!
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Linguist of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
class QScriptGrammar
{
public:
enum {
EOF_SYMBOL = 0,
T_AND = 1,
T_AND_AND = 2,
T_AND_EQ = 3,
T_AUTOMATIC_SEMICOLON = 62,
T_BREAK = 4,
T_CASE = 5,
T_CATCH = 6,
T_COLON = 7,
T_COMMA = 8,
T_CONST = 81,
T_CONTINUE = 9,
T_DEBUGGER = 82,
T_DEFAULT = 10,
T_DELETE = 11,
T_DIVIDE_ = 12,
T_DIVIDE_EQ = 13,
T_DO = 14,
T_DOT = 15,
T_ELSE = 16,
T_EQ = 17,
T_EQ_EQ = 18,
T_EQ_EQ_EQ = 19,
T_FALSE = 80,
T_FINALLY = 20,
T_FOR = 21,
T_FUNCTION = 22,
T_GE = 23,
T_GT = 24,
T_GT_GT = 25,
T_GT_GT_EQ = 26,
T_GT_GT_GT = 27,
T_GT_GT_GT_EQ = 28,
T_IDENTIFIER = 29,
T_IF = 30,
T_IN = 31,
T_INSTANCEOF = 32,
T_LBRACE = 33,
T_LBRACKET = 34,
T_LE = 35,
T_LPAREN = 36,
T_LT = 37,
T_LT_LT = 38,
T_LT_LT_EQ = 39,
T_MINUS = 40,
T_MINUS_EQ = 41,
T_MINUS_MINUS = 42,
T_NEW = 43,
T_NOT = 44,
T_NOT_EQ = 45,
T_NOT_EQ_EQ = 46,
T_NULL = 78,
T_NUMERIC_LITERAL = 47,
T_OR = 48,
T_OR_EQ = 49,
T_OR_OR = 50,
T_PLUS = 51,
T_PLUS_EQ = 52,
T_PLUS_PLUS = 53,
T_QUESTION = 54,
T_RBRACE = 55,
T_RBRACKET = 56,
T_REMAINDER = 57,
T_REMAINDER_EQ = 58,
T_RESERVED_WORD = 83,
T_RETURN = 59,
T_RPAREN = 60,
T_SEMICOLON = 61,
T_STAR = 63,
T_STAR_EQ = 64,
T_STRING_LITERAL = 65,
T_SWITCH = 66,
T_THIS = 67,
T_THROW = 68,
T_TILDE = 69,
T_TRUE = 79,
T_TRY = 70,
T_TYPEOF = 71,
T_VAR = 72,
T_VOID = 73,
T_WHILE = 74,
T_WITH = 75,
T_XOR = 76,
T_XOR_EQ = 77,
ACCEPT_STATE = 236,
RULE_COUNT = 267,
STATE_COUNT = 465,
TERMINAL_COUNT = 84,
NON_TERMINAL_COUNT = 88,
GOTO_INDEX_OFFSET = 465,
GOTO_INFO_OFFSET = 1374,
GOTO_CHECK_OFFSET = 1374
};
static const char *const spell [];
static const int lhs [];
static const int rhs [];
static const int goto_default [];
static const int action_default [];
static const int action_index [];
static const int action_info [];
static const int action_check [];
static inline int nt_action (int state, int nt)
{
const int *const goto_index = &action_index [GOTO_INDEX_OFFSET];
const int *const goto_check = &action_check [GOTO_CHECK_OFFSET];
const int yyn = goto_index [state] + nt;
if (yyn < 0 || goto_check [yyn] != nt)
return goto_default [nt];
const int *const goto_info = &action_info [GOTO_INFO_OFFSET];
return goto_info [yyn];
}
static inline int t_action (int state, int token)
{
const int yyn = action_index [state] + token;
if (yyn < 0 || action_check [yyn] != token)
return - action_default [state];
return action_info [yyn];
}
};
const char *const QScriptGrammar::spell [] = {
"end of file", "&", "&&", "&=", "break", "case", "catch", ":", ";", "continue",
"default", "delete", "/", "/=", "do", ".", "else", "=", "==", "===",
"finally", "for", "function", ">=", ">", ">>", ">>=", ">>>", ">>>=", "identifier",
"if", "in", "instanceof", "{", "[", "<=", "(", "<", "<<", "<<=",
"-", "-=", "--", "new", "!", "!=", "!==", "numeric literal", "|", "|=",
"||", "+", "+=", "++", "?", "}", "]", "%", "%=", "return",
")", ";", 0, "*", "*=", "string literal", "switch", "this", "throw", "~",
"try", "typeof", "var", "void", "while", "with", "^", "^=", "null", "true",
"false", "const", "debugger", "reserved word"};
const int QScriptGrammar::lhs [] = {
85, 85, 85, 85, 85, 85, 85, 85, 85, 85,
85, 85, 85, 85, 87, 87, 91, 91, 86, 86,
92, 92, 93, 93, 93, 93, 94, 94, 94, 94,
94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
94, 94, 94, 94, 94, 94, 94, 95, 95, 96,
96, 96, 96, 96, 99, 99, 100, 100, 100, 100,
98, 98, 101, 101, 102, 102, 103, 103, 103, 104,
104, 104, 104, 104, 104, 104, 104, 104, 104, 105,
105, 105, 105, 106, 106, 106, 107, 107, 107, 107,
108, 108, 108, 108, 108, 108, 108, 109, 109, 109,
109, 109, 109, 110, 110, 110, 110, 110, 111, 111,
111, 111, 111, 112, 112, 113, 113, 114, 114, 115,
115, 116, 116, 117, 117, 118, 118, 119, 119, 120,
120, 121, 121, 122, 122, 123, 123, 90, 90, 124,
124, 125, 125, 125, 125, 125, 125, 125, 125, 125,
125, 125, 125, 89, 89, 126, 126, 127, 127, 128,
128, 129, 129, 129, 129, 129, 129, 129, 129, 129,
129, 129, 129, 129, 129, 129, 130, 146, 146, 145,
145, 131, 131, 147, 147, 148, 148, 150, 150, 149,
151, 154, 152, 152, 155, 153, 153, 132, 133, 133,
134, 134, 135, 135, 135, 135, 135, 135, 135, 136,
136, 136, 136, 137, 137, 137, 137, 138, 138, 139,
141, 156, 156, 159, 159, 157, 157, 160, 158, 140,
142, 142, 143, 143, 143, 161, 162, 144, 163, 97,
167, 167, 164, 164, 165, 165, 168, 84, 169, 169,
170, 170, 166, 166, 88, 88, 171};
const int QScriptGrammar:: rhs[] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 3,
3, 5, 3, 3, 2, 4, 1, 2, 0, 1,
3, 5, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 4, 3, 3, 1, 2, 2, 2, 4, 3,
2, 3, 1, 3, 1, 1, 1, 2, 2, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 1,
3, 3, 3, 1, 3, 3, 1, 3, 3, 3,
1, 3, 3, 3, 3, 3, 3, 1, 3, 3,
3, 3, 3, 1, 3, 3, 3, 3, 1, 3,
3, 3, 3, 1, 3, 1, 3, 1, 3, 1,
3, 1, 3, 1, 3, 1, 3, 1, 3, 1,
3, 1, 3, 1, 5, 1, 5, 1, 3, 1,
3, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 3, 0, 1, 1, 3, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 3, 1, 2, 0,
1, 3, 3, 1, 1, 1, 3, 1, 3, 2,
2, 2, 0, 1, 2, 0, 1, 1, 2, 2,
7, 5, 7, 7, 5, 9, 10, 7, 8, 2,
2, 3, 3, 2, 2, 3, 3, 3, 3, 5,
5, 3, 5, 1, 2, 0, 1, 4, 3, 3,
3, 3, 3, 3, 4, 5, 2, 1, 8, 8,
1, 3, 0, 1, 0, 1, 1, 1, 1, 2,
1, 1, 0, 1, 0, 1, 2};
const int QScriptGrammar::action_default [] = {
0, 97, 164, 128, 136, 132, 172, 179, 76, 148,
178, 186, 174, 124, 0, 175, 262, 61, 176, 177,
182, 77, 140, 144, 65, 94, 75, 80, 60, 0,
114, 180, 101, 259, 258, 261, 183, 0, 194, 0,
248, 0, 8, 9, 0, 5, 0, 263, 2, 0,
265, 19, 0, 0, 0, 0, 0, 3, 6, 0,
0, 166, 208, 7, 0, 1, 0, 0, 4, 0,
0, 195, 0, 0, 0, 184, 185, 90, 0, 173,
181, 0, 0, 77, 96, 263, 2, 265, 79, 78,
0, 0, 0, 92, 93, 91, 0, 264, 253, 254,
0, 251, 0, 252, 0, 255, 256, 0, 257, 250,
260, 0, 266, 0, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 23,
41, 42, 43, 44, 45, 25, 46, 47, 24, 48,
49, 50, 51, 52, 53, 54, 55, 56, 57, 0,
21, 0, 0, 0, 22, 13, 95, 0, 125, 0,
0, 0, 0, 115, 0, 0, 0, 0, 0, 0,
105, 0, 0, 0, 99, 100, 98, 103, 107, 106,
104, 102, 117, 116, 118, 0, 133, 0, 129, 68,
0, 0, 0, 70, 59, 58, 0, 0, 69, 165,
0, 73, 71, 0, 72, 74, 209, 210, 0, 161,
154, 152, 159, 160, 158, 157, 163, 156, 155, 153,
162, 149, 0, 137, 0, 0, 141, 0, 0, 145,
67, 0, 0, 63, 0, 62, 267, 224, 0, 225,
226, 227, 220, 0, 221, 222, 223, 81, 0, 0,
0, 0, 0, 213, 214, 170, 168, 130, 138, 134,
150, 126, 171, 0, 77, 142, 146, 119, 108, 0,
0, 127, 0, 0, 0, 0, 120, 0, 0, 0,
0, 0, 112, 110, 113, 111, 109, 122, 121, 123,
0, 135, 0, 131, 0, 169, 77, 0, 151, 166,
167, 0, 166, 0, 0, 216, 0, 0, 0, 218,
0, 139, 0, 0, 143, 0, 0, 147, 206, 0,
198, 207, 201, 0, 205, 0, 166, 199, 0, 166,
0, 0, 217, 0, 0, 0, 219, 264, 253, 0,
0, 255, 0, 249, 0, 240, 0, 0, 0, 212,
0, 211, 188, 191, 0, 27, 30, 31, 248, 34,
35, 5, 39, 40, 2, 41, 44, 3, 6, 166,
7, 48, 1, 50, 4, 52, 53, 54, 55, 56,
57, 189, 187, 65, 66, 64, 0, 228, 229, 0,
0, 0, 231, 236, 234, 237, 0, 0, 235, 236,
0, 232, 0, 233, 190, 239, 0, 190, 238, 0,
241, 242, 0, 190, 243, 244, 0, 0, 245, 0,
0, 0, 246, 247, 83, 82, 0, 0, 0, 215,
0, 0, 0, 230, 0, 20, 0, 17, 19, 11,
0, 16, 12, 18, 15, 10, 0, 14, 87, 85,
89, 86, 84, 88, 203, 196, 0, 204, 200, 0,
202, 192, 0, 193, 197};
const int QScriptGrammar::goto_default [] = {
29, 28, 436, 434, 113, 14, 2, 435, 112, 111,
114, 193, 24, 17, 189, 26, 8, 200, 21, 27,
77, 25, 1, 32, 30, 267, 13, 261, 3, 257,
5, 259, 4, 258, 22, 265, 23, 266, 9, 260,
256, 297, 386, 262, 263, 35, 6, 79, 12, 15,
18, 19, 10, 7, 31, 80, 20, 36, 75, 76,
11, 354, 353, 78, 456, 455, 319, 320, 458, 322,
457, 321, 392, 396, 399, 395, 394, 414, 415, 16,
100, 107, 96, 99, 106, 108, 33, 0};
const int QScriptGrammar::action_index [] = {
1210, 59, -84, 71, 41, -1, -84, -84, 148, -84,
-84, -84, -84, 201, 130, -84, -84, -84, -84, -84,
-84, 343, 67, 62, 122, 109, -84, -84, -84, 85,
273, -84, 184, -84, 1210, -84, -84, 119, -84, 112,
-84, 521, -84, -84, 1130, -84, 45, 54, 58, 38,
1290, 50, 521, 521, 521, 376, 521, -84, -84, 521,
521, 521, -84, -84, 25, -84, 521, 521, -84, 43,
521, -84, 521, 18, 15, -84, -84, -84, 24, -84,
-84, 521, 521, 64, 153, 27, -84, 1050, -84, -84,
521, 521, 521, -84, -84, -84, 28, -84, 37, 55,
19, -84, 33, -84, 34, 1210, -84, 16, 1210, -84,
-84, 39, 52, -3, -84, -84, -84, -84, -84, -84,
-84, -84, -84, -84, -84, -84, -84, -84, -84, -84,
-84, -84, -84, -84, -84, -84, -84, -84, -84, -84,
-84, -84, -84, -84, -84, -84, -84, -84, -84, 521,
-84, 1050, 125, 521, -84, -84, 155, 521, 189, 521,
521, 521, 521, 248, 521, 521, 521, 521, 521, 521,
243, 521, 521, 521, 75, 82, 94, 177, 184, 184,
184, 184, 263, 283, 298, 521, 44, 521, 77, -84,
970, 521, 817, -84, -84, -84, 95, 521, -84, -84,
93, -84, -84, 521, -84, -84, -84, -84, 521, -84,
-84, -84, -84, -84, -84, -84, -84, -84, -84, -84,
-84, -84, 521, 41, 521, 521, 68, 66, 521, -84,
-84, 970, 521, -84, 103, -84, -84, -84, 63, -84,
-84, -84, -84, 69, -84, -84, -84, -84, -27, 12,
521, 92, 100, -84, -84, 890, -84, 31, -13, -45,
-84, 210, 32, -28, 387, 20, 73, 304, 117, -5,
521, 212, 521, 521, 521, 521, 213, 521, 521, 521,
521, 521, 151, 150, 176, 158, 168, 304, 304, 228,
521, -72, 521, 4, 521, -84, 306, 521, -84, 521,
8, -50, 521, -48, 1130, -84, 521, 80, 1130, -84,
521, -33, 521, 521, 5, 48, 521, -84, 17, 88,
11, -84, -84, 521, -84, -29, 521, -84, -41, 521,
-39, 1130, -84, 521, 87, 1130, -84, -8, -2, -35,
10, 1210, -16, -84, 1130, -84, 521, 86, 1130, -14,
1130, -84, -84, 1130, -36, 107, -21, 165, 3, 521,
1130, 6, 14, 61, 7, -19, 448, -4, -6, 671,
29, 13, 23, 521, 30, -10, 521, 9, 521, -30,
-18, -84, -84, 164, -84, -84, 46, -84, -84, 521,
111, -24, -84, 36, -84, 40, 99, 521, -84, 21,
22, -84, -11, -84, 1130, -84, 106, 1130, -84, 178,
-84, -84, 98, 1130, 57, -84, 56, 60, -84, 51,
26, 35, -84, -84, -84, -84, 521, 97, 1130, -84,
521, 90, 1130, -84, 79, 76, 744, -84, 49, -84,
594, -84, -84, -84, -84, -84, 83, -84, -84, -84,
-84, -84, -84, -84, 42, -84, 162, -84, -84, 521,
-84, -84, 53, -84, -84,
-61, -88, -88, -88, -88, -88, -88, -88, -88, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -88, -88,
-88, -4, -88, -88, 22, -88, -88, -88, -88, -88,
-88, -88, -88, -88, -51, -88, -88, -88, -88, -88,
-88, 105, -88, -88, -12, -88, -88, -88, -88, -88,
-7, -88, 35, 132, 62, 154, 79, -88, -88, 100,
75, 36, -88, -88, -88, -88, 37, 70, -88, -1,
86, -88, 92, -88, -88, -88, -88, -88, -88, -88,
-88, 90, 95, -88, -88, -88, -88, -88, -88, -88,
87, 82, 74, -88, -88, -88, -88, -88, -88, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -47, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -88, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -88, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -88, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -88, 28,
-88, 20, -88, 19, -88, -88, -88, 39, -88, 42,
43, 106, 61, -88, 63, 55, 52, 53, 91, 125,
-88, 120, 123, 118, -88, -88, -88, -88, -88, -88,
-88, -88, -88, -88, -88, 116, -88, 59, -88, -88,
16, 18, 15, -88, -88, -88, -88, 21, -88, -88,
-88, -88, -88, 24, -88, -88, -88, -88, 38, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -88, -88,
-88, -88, 97, -88, 115, 25, -88, -88, 26, -88,
-88, 111, 14, -88, -88, -88, -88, -88, -88, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -88, -88,
23, -88, -88, -88, -88, 108, -88, -88, -88, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -88, -88,
160, -88, 171, 163, 145, 179, -88, 135, 45, 41,
66, 80, -88, -88, -88, -88, -88, -88, -88, -88,
172, -88, 156, -88, 142, -88, -88, 144, -88, 122,
-88, -88, 114, -88, -23, -88, 48, -88, 29, -88,
224, -88, 157, 175, -88, -88, 182, -88, -88, -88,
-88, -88, -88, 183, -88, -21, 134, -88, -88, 49,
-88, 3, -88, 44, -88, 2, -88, -88, -37, -88,
-88, -31, -88, -88, 10, -88, 47, -88, 17, -88,
27, -88, -88, 13, -88, -88, -88, -88, -88, 117,
6, -88, -88, -88, -88, -88, 154, -88, -88, 1,
-88, -88, -88, 7, -88, -35, 137, -88, 141, -88,
-88, -88, -88, -6, -88, -88, -88, -88, -88, 78,
-88, -88, -88, -88, -88, -69, -88, 11, -88, -59,
-88, -88, -88, -88, 83, -88, -88, 56, -88, -88,
-88, -88, -88, -40, -58, -88, -88, -29, -88, -88,
-88, -45, -88, -88, -88, -88, -3, -88, -42, -88,
-5, -88, -32, -88, -88, -88, 9, -88, 8, -88,
-2, -88, -88, -88, -88, -88, -88, -88, -88, -88,
-88, -88, -88, -88, -88, -88, -88, -88, -88, 12,
-88, -88, -56, -88, -88};
const int QScriptGrammar::action_info [] = {
318, -25, 350, -45, 292, 270, 426, 310, -194, 393,
-32, 302, 304, -37, 344, 290, 197, 346, 430, 382,
329, 331, 310, 413, 318, 340, 397, 101, 338, 404,
-49, 292, 270, 299, 323, 290, -24, -51, -195, 343,
294, 397, 333, 341, 403, 397, 149, 249, 250, 389,
255, 430, 155, 454, 426, 316, 97, 437, 437, 459,
151, 389, 103, 102, 98, 344, 101, 105, 413, 222,
222, 109, 157, 228, 346, 187, 413, 417, 157, 104,
420, 255, 454, 337, 443, 236, 421, 438, 197, 185,
97, 197, 419, 413, 197, 197, 325, -263, 197, 81,
197, 203, 0, 197, 416, 197, 88, 388, 387, 400,
82, 197, 224, 407, 197, 81, 225, 89, 417, 197,
187, 90, 81, 312, 241, 240, 82, 313, 0, 0,
246, 245, 153, 82, 81, 439, 238, 231, 197, 0,
308, 243, 171, 447, 172, 82, 348, 335, 238, 326,
432, 198, 252, 204, 401, 173, 232, 428, 192, 235,
0, 254, 253, 190, 0, 90, 91, 90, 239, 237,
462, 391, 92, 244, 242, 171, 171, 172, 172, 231,
239, 237, 191, 171, 192, 172, 197, 0, 173, 173,
0, 207, 206, 171, 243, 172, 173, 0, 232, 0,
192, 171, 171, 172, 172, 0, 173, 159, 160, 171,
91, 172, 91, 0, 173, 173, 92, 0, 92, 159,
160, 0, 173, 463, 461, 0, 244, 242, 272, 273,
272, 273, 0, 0, 161, 162, 277, 278, 0, 411,
410, 0, 0, 0, 0, 279, 161, 162, 280, 0,
281, 277, 278, 0, 0, 274, 275, 274, 275, 0,
279, 0, 0, 280, 0, 281, 0, 0, 171, 0,
172, 164, 165, 0, 0, 0, 0, 0, 0, 166,
167, 173, 0, 168, 0, 169, 164, 165, 0, 0,
0, 0, 0, 0, 166, 167, 164, 165, 168, 0,
169, 0, 0, 0, 166, 167, 164, 165, 168, 209,
169, 0, 0, 0, 166, 167, 0, 0, 168, 210,
169, 164, 165, 211, 0, 0, 0, 277, 278, 166,
167, 0, 212, 168, 213, 169, 279, 0, 0, 280,
0, 281, 0, 0, 0, 214, 209, 215, 88, 0,
0, 0, 0, 0, 0, 216, 210, 0, 217, 89,
211, 0, 0, 0, 218, 0, 0, 0, 0, 212,
219, 213, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 214, 220, 215, 88, 0, 0, 42, 43,
209, 0, 216, 0, 0, 217, 89, 0, 85, 0,
210, 218, 0, 0, 211, 86, 0, 219, 0, 87,
51, 0, 52, 212, 0, 213, 0, 0, 306, 55,
220, 0, 0, 58, 0, 0, 214, 0, 215, 88,
0, 0, 0, 0, 0, 0, 216, 0, 0, 217,
89, 63, 0, 65, 0, 218, 0, 0, 0, 0,
0, 219, 0, 0, 57, 68, 45, 0, 0, 0,
42, 43, 0, 0, 220, 0, 0, 0, 0, 0,
85, 0, 0, 0, 0, 0, 0, 86, 0, 0,
0, 87, 51, 0, 52, 0, 0, 0, 0, 0,
0, 55, 0, 0, 0, 58, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 63, 0, 65, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 57, 68, 45, 0,
0, 0, 41, 42, 43, 0, 0, 0, 0, 0,
0, 0, 0, 85, 0, 0, 0, 0, 0, 0,
86, 0, 0, 0, 87, 51, 0, 52, 0, 0,
0, 53, 0, 54, 55, 56, 0, 0, 58, 0,
0, 0, 59, 0, 60, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 63, 0, 65, 0,
67, 0, 70, 0, 72, 0, 0, 0, 0, 57,
68, 45, 0, 0, 0, 41, 42, 43, 0, 0,
0, 0, 0, 0, 0, 0, 85, 0, 0, 0,
0, 0, 0, 86, 0, 0, 0, 87, 51, 0,
52, 0, 0, 0, 53, 0, 54, 55, 56, 0,
0, 58, 0, 0, 0, 59, 0, 60, 0, 0,
442, 0, 0, 0, 0, 0, 0, 0, 0, 63,
0, 65, 0, 67, 0, 70, 0, 72, 0, 0,
0, 0, 57, 68, 45, 0, 0, 0, -47, 0,
0, 0, 41, 42, 43, 0, 0, 0, 0, 0,
0, 0, 0, 85, 0, 0, 0, 0, 0, 0,
86, 0, 0, 0, 87, 51, 0, 52, 0, 0,
0, 53, 0, 54, 55, 56, 0, 0, 58, 0,
0, 0, 59, 0, 60, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 63, 0, 65, 0,
67, 0, 70, 0, 72, 0, 0, 0, 0, 57,
68, 45, 0, 0, 0, 41, 42, 43, 0, 0,
0, 0, 0, 0, 0, 0, 85, 0, 0, 0,
0, 0, 0, 86, 0, 0, 0, 87, 51, 0,
52, 0, 0, 0, 53, 0, 54, 55, 56, 0,
0, 58, 0, 0, 0, 59, 0, 60, 0, 0,
445, 0, 0, 0, 0, 0, 0, 0, 0, 63,
0, 65, 0, 67, 0, 70, 0, 72, 0, 0,
0, 0, 57, 68, 45, 0, 0, 0, 41, 42,
43, 0, 0, 0, 0, 0, 0, 0, 0, 85,
0, 0, 0, 0, 0, 0, 86, 0, 0, 0,
87, 51, 0, 52, 0, 0, 0, 53, 0, 54,
55, 56, 0, 0, 58, 0, 0, 0, 59, 0,
60, 0, 0, 0, 0, 0, 0, 202, 0, 0,
0, 0, 63, 0, 65, 0, 67, 0, 70, 0,
72, 0, 0, 0, 0, 57, 68, 45, 0, 0,
0, 41, 42, 43, 0, 0, 0, 0, 0, 0,
0, 0, 85, 0, 0, 0, 0, 0, 0, 86,
0, 0, 0, 87, 51, 0, 52, 0, 0, 0,
53, 0, 54, 55, 56, 0, 0, 58, 0, 0,
0, 59, 0, 60, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 63, 0, 65, 0, 67,
0, 70, 269, 72, 0, 0, 0, 0, 57, 68,
45, 0, 0, 0, 115, 116, 117, 0, 0, 119,
121, 122, 0, 0, 123, 0, 124, 0, 0, 0,
126, 127, 128, 0, 0, 0, 0, 0, 0, 195,
130, 131, 132, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 133, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 137,
0, 0, 0, 0, 0, 0, 139, 140, 141, 0,
143, 144, 145, 146, 147, 148, 0, 0, 134, 142,
125, 118, 120, 136, 115, 116, 117, 0, 0, 119,
121, 122, 0, 0, 123, 0, 124, 0, 0, 0,
126, 127, 128, 0, 0, 0, 0, 0, 0, 129,
130, 131, 132, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 133, 0, 0, 0, 135, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 137,
0, 0, 0, 0, 0, 138, 139, 140, 141, 0,
143, 144, 145, 146, 147, 148, 0, 0, 134, 142,
125, 118, 120, 136, 37, 0, 0, 0, 0, 39,
0, 41, 42, 43, 44, 0, 0, 0, 0, 0,
0, 46, 85, 0, 0, 0, 0, 0, 0, 48,
49, 0, 0, 50, 51, 0, 52, 0, 0, 0,
53, 0, 54, 55, 56, 0, 0, 58, 0, 0,
0, 59, 0, 60, 0, 0, 0, 0, 0, 61,
0, 62, 0, 0, 0, 63, 64, 65, 66, 67,
69, 70, 71, 72, 73, 74, 0, 0, 57, 68,
45, 38, 40, 0, 37, 0, 0, 0, 0, 39,
0, 41, 42, 43, 44, 0, 0, 0, 0, 0,
0, 46, 47, 0, 0, 0, 0, 0, 0, 48,
49, 0, 0, 50, 51, 0, 52, 0, 0, 0,
53, 0, 54, 55, 56, 0, 0, 58, 0, 0,
0, 59, 0, 60, 0, 0, 0, 0, 0, 61,
0, 62, 0, 0, 0, 63, 64, 65, 66, 67,
69, 70, 71, 72, 73, 74, 0, 0, 57, 68,
45, 38, 40, 0, 355, 116, 117, 0, 0, 357,
121, 359, 42, 43, 360, 0, 124, 0, 0, 0,
126, 362, 363, 0, 0, 0, 0, 0, 0, 364,
365, 131, 132, 50, 51, 0, 52, 0, 0, 0,
53, 0, 54, 366, 56, 0, 0, 368, 0, 0,
0, 59, 0, 60, 0, -190, 0, 0, 0, 369,
0, 62, 0, 0, 0, 370, 371, 372, 373, 67,
375, 376, 377, 378, 379, 380, 0, 0, 367, 374,
361, 356, 358, 136,
431, 422, 427, 429, 441, 352, 300, 398, 385, 464,
440, 412, 409, 433, 402, 444, 406, 423, 460, 234,
418, 201, 305, 196, 34, 154, 194, 199, 251, 152,
205, 227, 229, 248, 150, 110, 230, 208, 352, 110,
446, 300, 409, 339, 221, 412, 327, 336, 332, 334,
342, 248, 347, 307, 300, 345, 0, 83, 381, 83,
83, 83, 349, 83, 284, 158, 163, 182, 283, 0,
83, 83, 351, 83, 309, 178, 179, 83, 177, 83,
83, 83, 449, 390, 83, 184, 170, 188, 83, 285,
453, 330, 83, 83, 95, 452, 0, 83, 83, 450,
83, 352, 94, 286, 83, 83, 424, 93, 83, 83,
83, 84, 425, 83, 180, 83, 156, 408, 83, 300,
451, 194, 233, 83, 83, 247, 264, 300, 352, 223,
183, 268, 0, 83, 83, 83, 83, 247, 83, 300,
176, 83, 174, 83, 405, 175, 186, 0, 181, 226,
83, 0, 448, 83, 0, 83, 303, 424, 282, 83,
296, 425, 296, 83, 301, 268, 383, 268, 268, 384,
288, 0, 0, 0, 83, 83, 328, 0, 83, 268,
268, 83, 295, 268, 298, 293, 268, 271, 287, 83,
83, 0, 314, 296, 268, 268, 276, 83, 268, 0,
296, 296, 268, 291, 289, 268, 268, 0, 0, 0,
0, 0, 0, 0, 0, 315, 0, 0, 0, 0,
0, 0, 317, 324, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 83, 0, 0, 0, 0, 268, 0, 0,
0, 0, 0, 0, 0, 0, 0, 311, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0};
const int QScriptGrammar::action_check [] = {
29, 7, 16, 7, 76, 1, 36, 2, 29, 33,
7, 61, 60, 7, 7, 48, 8, 36, 36, 55,
61, 60, 2, 33, 29, 60, 5, 29, 36, 7,
7, 76, 1, 61, 17, 48, 7, 7, 29, 55,
8, 5, 31, 33, 55, 5, 7, 74, 36, 36,
36, 36, 55, 29, 36, 7, 29, 8, 8, 17,
8, 36, 29, 8, 36, 7, 29, 33, 33, 2,
2, 55, 1, 7, 36, 76, 33, 20, 1, 60,
29, 36, 29, 29, 8, 0, 60, 8, 8, 48,
29, 8, 36, 33, 8, 8, 8, 36, 8, 40,
8, 8, -1, 8, 6, 8, 42, 61, 62, 10,
51, 8, 50, 7, 8, 40, 54, 53, 20, 8,
76, 12, 40, 50, 61, 62, 51, 54, -1, -1,
61, 62, 7, 51, 40, 56, 29, 15, 8, -1,
60, 29, 25, 60, 27, 51, 60, 60, 29, 61,
60, 56, 60, 60, 55, 38, 34, 60, 36, 56,
-1, 61, 62, 15, -1, 12, 57, 12, 61, 62,
8, 60, 63, 61, 62, 25, 25, 27, 27, 15,
61, 62, 34, 25, 36, 27, 8, -1, 38, 38,
-1, 61, 62, 25, 29, 27, 38, -1, 34, -1,
36, 25, 25, 27, 27, -1, 38, 18, 19, 25,
57, 27, 57, -1, 38, 38, 63, -1, 63, 18,
19, -1, 38, 61, 62, -1, 61, 62, 18, 19,
18, 19, -1, -1, 45, 46, 23, 24, -1, 61,
62, -1, -1, -1, -1, 32, 45, 46, 35, -1,
37, 23, 24, -1, -1, 45, 46, 45, 46, -1,
32, -1, -1, 35, -1, 37, -1, -1, 25, -1,
27, 23, 24, -1, -1, -1, -1, -1, -1, 31,
32, 38, -1, 35, -1, 37, 23, 24, -1, -1,
-1, -1, -1, -1, 31, 32, 23, 24, 35, -1,
37, -1, -1, -1, 31, 32, 23, 24, 35, 3,
37, -1, -1, -1, 31, 32, -1, -1, 35, 13,
37, 23, 24, 17, -1, -1, -1, 23, 24, 31,
32, -1, 26, 35, 28, 37, 32, -1, -1, 35,
-1, 37, -1, -1, -1, 39, 3, 41, 42, -1,
-1, -1, -1, -1, -1, 49, 13, -1, 52, 53,
17, -1, -1, -1, 58, -1, -1, -1, -1, 26,
64, 28, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, 39, 77, 41, 42, -1, -1, 12, 13,
3, -1, 49, -1, -1, 52, 53, -1, 22, -1,
13, 58, -1, -1, 17, 29, -1, 64, -1, 33,
34, -1, 36, 26, -1, 28, -1, -1, 31, 43,
77, -1, -1, 47, -1, -1, 39, -1, 41, 42,
-1, -1, -1, -1, -1, -1, 49, -1, -1, 52,
53, 65, -1, 67, -1, 58, -1, -1, -1, -1,
-1, 64, -1, -1, 78, 79, 80, -1, -1, -1,
12, 13, -1, -1, 77, -1, -1, -1, -1, -1,
22, -1, -1, -1, -1, -1, -1, 29, -1, -1,
-1, 33, 34, -1, 36, -1, -1, -1, -1, -1,
-1, 43, -1, -1, -1, 47, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 65, -1, 67, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 78, 79, 80, -1,
-1, -1, 11, 12, 13, -1, -1, -1, -1, -1,
-1, -1, -1, 22, -1, -1, -1, -1, -1, -1,
29, -1, -1, -1, 33, 34, -1, 36, -1, -1,
-1, 40, -1, 42, 43, 44, -1, -1, 47, -1,
-1, -1, 51, -1, 53, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 65, -1, 67, -1,
69, -1, 71, -1, 73, -1, -1, -1, -1, 78,
79, 80, -1, -1, -1, 11, 12, 13, -1, -1,
-1, -1, -1, -1, -1, -1, 22, -1, -1, -1,
-1, -1, -1, 29, -1, -1, -1, 33, 34, -1,
36, -1, -1, -1, 40, -1, 42, 43, 44, -1,
-1, 47, -1, -1, -1, 51, -1, 53, -1, -1,
56, -1, -1, -1, -1, -1, -1, -1, -1, 65,
-1, 67, -1, 69, -1, 71, -1, 73, -1, -1,
-1, -1, 78, 79, 80, -1, -1, -1, 7, -1,
-1, -1, 11, 12, 13, -1, -1, -1, -1, -1,
-1, -1, -1, 22, -1, -1, -1, -1, -1, -1,
29, -1, -1, -1, 33, 34, -1, 36, -1, -1,
-1, 40, -1, 42, 43, 44, -1, -1, 47, -1,
-1, -1, 51, -1, 53, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 65, -1, 67, -1,
69, -1, 71, -1, 73, -1, -1, -1, -1, 78,
79, 80, -1, -1, -1, 11, 12, 13, -1, -1,
-1, -1, -1, -1, -1, -1, 22, -1, -1, -1,
-1, -1, -1, 29, -1, -1, -1, 33, 34, -1,
36, -1, -1, -1, 40, -1, 42, 43, 44, -1,
-1, 47, -1, -1, -1, 51, -1, 53, -1, -1,
56, -1, -1, -1, -1, -1, -1, -1, -1, 65,
-1, 67, -1, 69, -1, 71, -1, 73, -1, -1,
-1, -1, 78, 79, 80, -1, -1, -1, 11, 12,
13, -1, -1, -1, -1, -1, -1, -1, -1, 22,
-1, -1, -1, -1, -1, -1, 29, -1, -1, -1,
33, 34, -1, 36, -1, -1, -1, 40, -1, 42,
43, 44, -1, -1, 47, -1, -1, -1, 51, -1,
53, -1, -1, -1, -1, -1, -1, 60, -1, -1,
-1, -1, 65, -1, 67, -1, 69, -1, 71, -1,
73, -1, -1, -1, -1, 78, 79, 80, -1, -1,
-1, 11, 12, 13, -1, -1, -1, -1, -1, -1,
-1, -1, 22, -1, -1, -1, -1, -1, -1, 29,
-1, -1, -1, 33, 34, -1, 36, -1, -1, -1,
40, -1, 42, 43, 44, -1, -1, 47, -1, -1,
-1, 51, -1, 53, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 65, -1, 67, -1, 69,
-1, 71, 72, 73, -1, -1, -1, -1, 78, 79,
80, -1, -1, -1, 4, 5, 6, -1, -1, 9,
10, 11, -1, -1, 14, -1, 16, -1, -1, -1,
20, 21, 22, -1, -1, -1, -1, -1, -1, 29,
30, 31, 32, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 43, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 59,
-1, -1, -1, -1, -1, -1, 66, 67, 68, -1,
70, 71, 72, 73, 74, 75, -1, -1, 78, 79,
80, 81, 82, 83, 4, 5, 6, -1, -1, 9,
10, 11, -1, -1, 14, -1, 16, -1, -1, -1,
20, 21, 22, -1, -1, -1, -1, -1, -1, 29,
30, 31, 32, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 43, -1, -1, -1, 47, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, 59,
-1, -1, -1, -1, -1, 65, 66, 67, 68, -1,
70, 71, 72, 73, 74, 75, -1, -1, 78, 79,
80, 81, 82, 83, 4, -1, -1, -1, -1, 9,
-1, 11, 12, 13, 14, -1, -1, -1, -1, -1,
-1, 21, 22, -1, -1, -1, -1, -1, -1, 29,
30, -1, -1, 33, 34, -1, 36, -1, -1, -1,
40, -1, 42, 43, 44, -1, -1, 47, -1, -1,
-1, 51, -1, 53, -1, -1, -1, -1, -1, 59,
-1, 61, -1, -1, -1, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, -1, -1, 78, 79,
80, 81, 82, -1, 4, -1, -1, -1, -1, 9,
-1, 11, 12, 13, 14, -1, -1, -1, -1, -1,
-1, 21, 22, -1, -1, -1, -1, -1, -1, 29,
30, -1, -1, 33, 34, -1, 36, -1, -1, -1,
40, -1, 42, 43, 44, -1, -1, 47, -1, -1,
-1, 51, -1, 53, -1, -1, -1, -1, -1, 59,
-1, 61, -1, -1, -1, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, -1, -1, 78, 79,
80, 81, 82, -1, 4, 5, 6, -1, -1, 9,
10, 11, 12, 13, 14, -1, 16, -1, -1, -1,
20, 21, 22, -1, -1, -1, -1, -1, -1, 29,
30, 31, 32, 33, 34, -1, 36, -1, -1, -1,
40, -1, 42, 43, 44, -1, -1, 47, -1, -1,
-1, 51, -1, 53, -1, 55, -1, -1, -1, 59,
-1, 61, -1, -1, -1, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, -1, -1, 78, 79,
80, 81, 82, 83,
5, 46, 5, 45, 6, 45, 5, 76, 14, 65,
2, 46, 5, 45, 73, 6, 5, 46, 6, 5,
78, 6, 45, 5, 85, 6, 10, 6, 5, 9,
6, 6, 6, 45, 6, 86, 14, 41, 45, 86,
5, 5, 5, 80, 6, 46, 67, 45, 45, 5,
81, 45, 5, 5, 5, 45, -1, 18, 45, 18,
18, 18, 45, 18, 23, 26, 24, 24, 23, -1,
18, 18, 45, 18, 45, 23, 23, 18, 23, 18,
18, 18, 20, 5, 18, 24, 23, 28, 18, 23,
20, 42, 18, 18, 20, 20, -1, 18, 18, 20,
18, 45, 20, 23, 18, 18, 20, 20, 18, 18,
18, 21, 20, 18, 23, 18, 21, 61, 18, 5,
20, 10, 11, 18, 18, 20, 18, 5, 45, 32,
24, 23, -1, 18, 18, 18, 18, 20, 18, 5,
22, 18, 22, 18, 61, 22, 30, -1, 23, 34,
18, -1, 20, 18, -1, 18, 42, 20, 23, 18,
18, 20, 18, 18, 42, 23, 12, 23, 23, 15,
25, -1, -1, -1, 18, 18, 42, -1, 18, 23,
23, 18, 40, 23, 40, 29, 23, 27, 25, 18,
18, -1, 35, 18, 23, 23, 25, 18, 23, -1,
18, 18, 23, 31, 25, 23, 23, -1, -1, -1,
-1, -1, -1, -1, -1, 40, -1, -1, -1, -1,
-1, -1, 40, 40, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, 18, -1, -1, -1, -1, 23, -1, -1,
-1, -1, -1, -1, -1, -1, -1, 33, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1};
#define Q_SCRIPT_REGEXPLITERAL_RULE1 7
#define Q_SCRIPT_REGEXPLITERAL_RULE2 8
#include "translator.h"
#include <QtCore/qdebug.h>
#include <QtCore/qnumeric.h>
#include <QtCore/qstring.h>
#include <QtCore/qtextcodec.h>
#include <QtCore/qvariant.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
QT_BEGIN_NAMESPACE
static void recordMessage(
Translator *tor, const QString &context, const QString &text, const QString &comment,
const QString &extracomment, bool plural, const QString &fileName, int lineNo)
{
TranslatorMessage msg(
context, text, comment, QString(),
fileName, lineNo, QStringList(),
TranslatorMessage::Unfinished, plural);
msg.setExtraComment(extracomment.simplified());
tor->replace(msg);
}
namespace QScript
{
class Lexer
{
public:
Lexer();
~Lexer();
void setCode(const QString &c, int lineno);
int lex();
int currentLineNo() const { return yylineno; }
int currentColumnNo() const { return yycolumn; }
int startLineNo() const { return startlineno; }
int startColumnNo() const { return startcolumn; }
int endLineNo() const { return currentLineNo(); }
int endColumnNo() const
{ int col = currentColumnNo(); return (col > 0) ? col - 1 : col; }
bool prevTerminator() const { return terminator; }
enum State { Start,
Identifier,
InIdentifier,
InSingleLineComment,
InMultiLineComment,
InNum,
InNum0,
InHex,
InOctal,
InDecimal,
InExponentIndicator,
InExponent,
Hex,
Octal,
Number,
String,
Eof,
InString,
InEscapeSequence,
InHexEscape,
InUnicodeEscape,
Other,
Bad };
enum Error {
NoError,
IllegalCharacter,
UnclosedStringLiteral,
IllegalEscapeSequence,
IllegalUnicodeEscapeSequence,
UnclosedComment,
IllegalExponentIndicator,
IllegalIdentifier
};
enum ParenthesesState {
IgnoreParentheses,
CountParentheses,
BalancedParentheses
};
enum RegExpBodyPrefix {
NoPrefix,
EqualPrefix
};
bool scanRegExp(RegExpBodyPrefix prefix = NoPrefix);
QString pattern;
int flags;
State lexerState() const
{ return state; }
QString errorMessage() const
{ return errmsg; }
void setErrorMessage(const QString &err)
{ errmsg = err; }
void setErrorMessage(const char *err)
{ setErrorMessage(QString::fromLatin1(err)); }
Error error() const
{ return err; }
void clearError()
{ err = NoError; }
private:
int yylineno;
bool done;
char *buffer8;
QChar *buffer16;
uint size8, size16;
uint pos8, pos16;
bool terminator;
bool restrKeyword;
// encountered delimiter like "'" and "}" on last run
bool delimited;
int stackToken;
State state;
void setDone(State s);
uint pos;
void shift(uint p);
int lookupKeyword(const char *);
bool isWhiteSpace() const;
bool isLineTerminator() const;
bool isHexDigit(ushort c) const;
bool isOctalDigit(ushort c) const;
int matchPunctuator(ushort c1, ushort c2,
ushort c3, ushort c4);
ushort singleEscape(ushort c) const;
ushort convertOctal(ushort c1, ushort c2,
ushort c3) const;
public:
static unsigned char convertHex(ushort c1);
static unsigned char convertHex(ushort c1, ushort c2);
static QChar convertUnicode(ushort c1, ushort c2,
ushort c3, ushort c4);
static bool isIdentLetter(ushort c);
static bool isDecimalDigit(ushort c);
inline int ival() const { return qsyylval.toInt(); }
inline double dval() const { return qsyylval.toDouble(); }
inline QString ustr() const { return qsyylval.toString(); }
inline QVariant val() const { return qsyylval; }
const QChar *characterBuffer() const { return buffer16; }
int characterCount() const { return pos16; }
private:
void record8(ushort c);
void record16(QChar c);
void recordStartPos();
int findReservedWord(const QChar *buffer, int size) const;
void syncProhibitAutomaticSemicolon();
const QChar *code;
uint length;
int yycolumn;
int startlineno;
int startcolumn;
int bol; // begin of line
QVariant qsyylval;
// current and following unicode characters
ushort current, next1, next2, next3;
struct keyword {
const char *name;
int token;
};
QString errmsg;
Error err;
bool wantRx;
bool check_reserved;
ParenthesesState parenthesesState;
int parenthesesCount;
bool prohibitAutomaticSemicolon;
};
} // namespace QScript
extern double qstrtod(const char *s00, char const **se, bool *ok);
#define shiftWindowsLineBreak() if(current == '\r' && next1 == '\n') shift(1);
namespace QScript {
static int toDigit(char c)
{
if ((c >= '0') && (c <= '9'))
return c - '0';
else if ((c >= 'a') && (c <= 'z'))
return 10 + c - 'a';
else if ((c >= 'A') && (c <= 'Z'))
return 10 + c - 'A';
return -1;
}
double integerFromString(const char *buf, int size, int radix)
{
if (size == 0)
return qSNaN();
double sign = 1.0;
int i = 0;
if (buf[0] == '+') {
++i;
} else if (buf[0] == '-') {
sign = -1.0;
++i;
}
if (((size-i) >= 2) && (buf[i] == '0')) {
if (((buf[i+1] == 'x') || (buf[i+1] == 'X'))
&& (radix < 34)) {
if ((radix != 0) && (radix != 16))
return 0;
radix = 16;
i += 2;
} else {
if (radix == 0) {
radix = 8;
++i;
}
}
} else if (radix == 0) {
radix = 10;
}
int j = i;
for ( ; i < size; ++i) {
int d = toDigit(buf[i]);
if ((d == -1) || (d >= radix))
break;
}
double result;
if (j == i) {
if (!qstrcmp(buf, "Infinity"))
result = qInf();
else
result = qSNaN();
} else {
result = 0;
double multiplier = 1;
for (--i ; i >= j; --i, multiplier *= radix)
result += toDigit(buf[i]) * multiplier;
}
result *= sign;
return result;
}
} // namespace QScript
QScript::Lexer::Lexer()
:
yylineno(0),
size8(128), size16(128), restrKeyword(false),
stackToken(-1), pos(0),
code(0), length(0),
bol(true),
current(0), next1(0), next2(0), next3(0),
err(NoError),
check_reserved(true),
parenthesesState(IgnoreParentheses),
prohibitAutomaticSemicolon(false)
{
// allocate space for read buffers
buffer8 = new char[size8];
buffer16 = new QChar[size16];
flags = 0;
}
QScript::Lexer::~Lexer()
{
delete [] buffer8;
delete [] buffer16;
}
void QScript::Lexer::setCode(const QString &c, int lineno)
{
errmsg = QString();
yylineno = lineno;
yycolumn = 1;
restrKeyword = false;
delimited = false;
stackToken = -1;
pos = 0;
code = c.unicode();
length = c.length();
bol = true;
// read first characters
current = (length > 0) ? code[0].unicode() : 0;
next1 = (length > 1) ? code[1].unicode() : 0;
next2 = (length > 2) ? code[2].unicode() : 0;
next3 = (length > 3) ? code[3].unicode() : 0;
}
void QScript::Lexer::shift(uint p)
{
while (p--) {
++pos;
++yycolumn;
current = next1;
next1 = next2;
next2 = next3;
next3 = (pos + 3 < length) ? code[pos+3].unicode() : 0;
}
}
void QScript::Lexer::setDone(State s)
{
state = s;
done = true;
}
int QScript::Lexer::findReservedWord(const QChar *c, int size) const
{
switch (size) {
case 2: {
if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('o'))
return QScriptGrammar::T_DO;
else if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('f'))
return QScriptGrammar::T_IF;
else if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n'))
return QScriptGrammar::T_IN;
} break;
case 3: {
if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('o') && c[2] == QLatin1Char('r'))
return QScriptGrammar::T_FOR;
else if (c[0] == QLatin1Char('n') && c[1] == QLatin1Char('e') && c[2] == QLatin1Char('w'))
return QScriptGrammar::T_NEW;
else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('r') && c[2] == QLatin1Char('y'))
return QScriptGrammar::T_TRY;
else if (c[0] == QLatin1Char('v') && c[1] == QLatin1Char('a') && c[2] == QLatin1Char('r'))
return QScriptGrammar::T_VAR;
else if (check_reserved) {
if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n') && c[2] == QLatin1Char('t'))
return QScriptGrammar::T_RESERVED_WORD;
}
} break;
case 4: {
if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('a')
&& c[2] == QLatin1Char('s') && c[3] == QLatin1Char('e'))
return QScriptGrammar::T_CASE;
else if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('l')
&& c[2] == QLatin1Char('s') && c[3] == QLatin1Char('e'))
return QScriptGrammar::T_ELSE;
else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('h')
&& c[2] == QLatin1Char('i') && c[3] == QLatin1Char('s'))
return QScriptGrammar::T_THIS;
else if (c[0] == QLatin1Char('v') && c[1] == QLatin1Char('o')
&& c[2] == QLatin1Char('i') && c[3] == QLatin1Char('d'))
return QScriptGrammar::T_VOID;
else if (c[0] == QLatin1Char('w') && c[1] == QLatin1Char('i')
&& c[2] == QLatin1Char('t') && c[3] == QLatin1Char('h'))
return QScriptGrammar::T_WITH;
else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('r')
&& c[2] == QLatin1Char('u') && c[3] == QLatin1Char('e'))
return QScriptGrammar::T_TRUE;
else if (c[0] == QLatin1Char('n') && c[1] == QLatin1Char('u')
&& c[2] == QLatin1Char('l') && c[3] == QLatin1Char('l'))
return QScriptGrammar::T_NULL;
else if (check_reserved) {
if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('n')
&& c[2] == QLatin1Char('u') && c[3] == QLatin1Char('m'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('b') && c[1] == QLatin1Char('y')
&& c[2] == QLatin1Char('t') && c[3] == QLatin1Char('e'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('l') && c[1] == QLatin1Char('o')
&& c[2] == QLatin1Char('n') && c[3] == QLatin1Char('g'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('h')
&& c[2] == QLatin1Char('a') && c[3] == QLatin1Char('r'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('g') && c[1] == QLatin1Char('o')
&& c[2] == QLatin1Char('t') && c[3] == QLatin1Char('o'))
return QScriptGrammar::T_RESERVED_WORD;
}
} break;
case 5: {
if (c[0] == QLatin1Char('b') && c[1] == QLatin1Char('r')
&& c[2] == QLatin1Char('e') && c[3] == QLatin1Char('a')
&& c[4] == QLatin1Char('k'))
return QScriptGrammar::T_BREAK;
else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('a')
&& c[2] == QLatin1Char('t') && c[3] == QLatin1Char('c')
&& c[4] == QLatin1Char('h'))
return QScriptGrammar::T_CATCH;
else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('h')
&& c[2] == QLatin1Char('r') && c[3] == QLatin1Char('o')
&& c[4] == QLatin1Char('w'))
return QScriptGrammar::T_THROW;
else if (c[0] == QLatin1Char('w') && c[1] == QLatin1Char('h')
&& c[2] == QLatin1Char('i') && c[3] == QLatin1Char('l')
&& c[4] == QLatin1Char('e'))
return QScriptGrammar::T_WHILE;
else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('o')
&& c[2] == QLatin1Char('n') && c[3] == QLatin1Char('s')
&& c[4] == QLatin1Char('t'))
return QScriptGrammar::T_CONST;
else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('a')
&& c[2] == QLatin1Char('l') && c[3] == QLatin1Char('s')
&& c[4] == QLatin1Char('e'))
return QScriptGrammar::T_FALSE;
else if (check_reserved) {
if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('h')
&& c[2] == QLatin1Char('o') && c[3] == QLatin1Char('r')
&& c[4] == QLatin1Char('t'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('u')
&& c[2] == QLatin1Char('p') && c[3] == QLatin1Char('e')
&& c[4] == QLatin1Char('r'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('i')
&& c[2] == QLatin1Char('n') && c[3] == QLatin1Char('a')
&& c[4] == QLatin1Char('l'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('l')
&& c[2] == QLatin1Char('a') && c[3] == QLatin1Char('s')
&& c[4] == QLatin1Char('s'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('l')
&& c[2] == QLatin1Char('o') && c[3] == QLatin1Char('a')
&& c[4] == QLatin1Char('t'))
return QScriptGrammar::T_RESERVED_WORD;
}
} break;
case 6: {
if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('e')
&& c[2] == QLatin1Char('l') && c[3] == QLatin1Char('e')
&& c[4] == QLatin1Char('t') && c[5] == QLatin1Char('e'))
return QScriptGrammar::T_DELETE;
else if (c[0] == QLatin1Char('r') && c[1] == QLatin1Char('e')
&& c[2] == QLatin1Char('t') && c[3] == QLatin1Char('u')
&& c[4] == QLatin1Char('r') && c[5] == QLatin1Char('n'))
return QScriptGrammar::T_RETURN;
else if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('w')
&& c[2] == QLatin1Char('i') && c[3] == QLatin1Char('t')
&& c[4] == QLatin1Char('c') && c[5] == QLatin1Char('h'))
return QScriptGrammar::T_SWITCH;
else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('y')
&& c[2] == QLatin1Char('p') && c[3] == QLatin1Char('e')
&& c[4] == QLatin1Char('o') && c[5] == QLatin1Char('f'))
return QScriptGrammar::T_TYPEOF;
else if (check_reserved) {
if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('x')
&& c[2] == QLatin1Char('p') && c[3] == QLatin1Char('o')
&& c[4] == QLatin1Char('r') && c[5] == QLatin1Char('t'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('t')
&& c[2] == QLatin1Char('a') && c[3] == QLatin1Char('t')
&& c[4] == QLatin1Char('i') && c[5] == QLatin1Char('c'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('o')
&& c[2] == QLatin1Char('u') && c[3] == QLatin1Char('b')
&& c[4] == QLatin1Char('l') && c[5] == QLatin1Char('e'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('m')
&& c[2] == QLatin1Char('p') && c[3] == QLatin1Char('o')
&& c[4] == QLatin1Char('r') && c[5] == QLatin1Char('t'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('u')
&& c[2] == QLatin1Char('b') && c[3] == QLatin1Char('l')
&& c[4] == QLatin1Char('i') && c[5] == QLatin1Char('c'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('n') && c[1] == QLatin1Char('a')
&& c[2] == QLatin1Char('t') && c[3] == QLatin1Char('i')
&& c[4] == QLatin1Char('v') && c[5] == QLatin1Char('e'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('h')
&& c[2] == QLatin1Char('r') && c[3] == QLatin1Char('o')
&& c[4] == QLatin1Char('w') && c[5] == QLatin1Char('s'))
return QScriptGrammar::T_RESERVED_WORD;
}
} break;
case 7: {
if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('e')
&& c[2] == QLatin1Char('f') && c[3] == QLatin1Char('a')
&& c[4] == QLatin1Char('u') && c[5] == QLatin1Char('l')
&& c[6] == QLatin1Char('t'))
return QScriptGrammar::T_DEFAULT;
else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('i')
&& c[2] == QLatin1Char('n') && c[3] == QLatin1Char('a')
&& c[4] == QLatin1Char('l') && c[5] == QLatin1Char('l')
&& c[6] == QLatin1Char('y'))
return QScriptGrammar::T_FINALLY;
else if (check_reserved) {
if (c[0] == QLatin1Char('b') && c[1] == QLatin1Char('o')
&& c[2] == QLatin1Char('o') && c[3] == QLatin1Char('l')
&& c[4] == QLatin1Char('e') && c[5] == QLatin1Char('a')
&& c[6] == QLatin1Char('n'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('x')
&& c[2] == QLatin1Char('t') && c[3] == QLatin1Char('e')
&& c[4] == QLatin1Char('n') && c[5] == QLatin1Char('d')
&& c[6] == QLatin1Char('s'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('a')
&& c[2] == QLatin1Char('c') && c[3] == QLatin1Char('k')
&& c[4] == QLatin1Char('a') && c[5] == QLatin1Char('g')
&& c[6] == QLatin1Char('e'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('r')
&& c[2] == QLatin1Char('i') && c[3] == QLatin1Char('v')
&& c[4] == QLatin1Char('a') && c[5] == QLatin1Char('t')
&& c[6] == QLatin1Char('e'))
return QScriptGrammar::T_RESERVED_WORD;
}
} break;
case 8: {
if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('o')
&& c[2] == QLatin1Char('n') && c[3] == QLatin1Char('t')
&& c[4] == QLatin1Char('i') && c[5] == QLatin1Char('n')
&& c[6] == QLatin1Char('u') && c[7] == QLatin1Char('e'))
return QScriptGrammar::T_CONTINUE;
else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('u')
&& c[2] == QLatin1Char('n') && c[3] == QLatin1Char('c')
&& c[4] == QLatin1Char('t') && c[5] == QLatin1Char('i')
&& c[6] == QLatin1Char('o') && c[7] == QLatin1Char('n'))
return QScriptGrammar::T_FUNCTION;
else if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('e')
&& c[2] == QLatin1Char('b') && c[3] == QLatin1Char('u')
&& c[4] == QLatin1Char('g') && c[5] == QLatin1Char('g')
&& c[6] == QLatin1Char('e') && c[7] == QLatin1Char('r'))
return QScriptGrammar::T_DEBUGGER;
else if (check_reserved) {
if (c[0] == QLatin1Char('a') && c[1] == QLatin1Char('b')
&& c[2] == QLatin1Char('s') && c[3] == QLatin1Char('t')
&& c[4] == QLatin1Char('r') && c[5] == QLatin1Char('a')
&& c[6] == QLatin1Char('c') && c[7] == QLatin1Char('t'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('v') && c[1] == QLatin1Char('o')
&& c[2] == QLatin1Char('l') && c[3] == QLatin1Char('a')
&& c[4] == QLatin1Char('t') && c[5] == QLatin1Char('i')
&& c[6] == QLatin1Char('l') && c[7] == QLatin1Char('e'))
return QScriptGrammar::T_RESERVED_WORD;
}
} break;
case 9: {
if (check_reserved) {
if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n')
&& c[2] == QLatin1Char('t') && c[3] == QLatin1Char('e')
&& c[4] == QLatin1Char('r') && c[5] == QLatin1Char('f')
&& c[6] == QLatin1Char('a') && c[7] == QLatin1Char('c')
&& c[8] == QLatin1Char('e'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('r')
&& c[2] == QLatin1Char('a') && c[3] == QLatin1Char('n')
&& c[4] == QLatin1Char('s') && c[5] == QLatin1Char('i')
&& c[6] == QLatin1Char('e') && c[7] == QLatin1Char('n')
&& c[8] == QLatin1Char('t'))
return QScriptGrammar::T_RESERVED_WORD;
else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('r')
&& c[2] == QLatin1Char('o') && c[3] == QLatin1Char('t')
&& c[4] == QLatin1Char('e') && c[5] == QLatin1Char('c')
&& c[6] == QLatin1Char('t') && c[7] == QLatin1Char('e')
&& c[8] == QLatin1Char('d'))
return QScriptGrammar::T_RESERVED_WORD;
}
} break;
case 10: {
if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n')
&& c[2] == QLatin1Char('s') && c[3] == QLatin1Char('t')
&& c[4] == QLatin1Char('a') && c[5] == QLatin1Char('n')
&& c[6] == QLatin1Char('c') && c[7] == QLatin1Char('e')
&& c[8] == QLatin1Char('o') && c[9] == QLatin1Char('f'))
return QScriptGrammar::T_INSTANCEOF;
else if (check_reserved) {
if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('m')
&& c[2] == QLatin1Char('p') && c[3] == QLatin1Char('l')
&& c[4] == QLatin1Char('e') && c[5] == QLatin1Char('m')
&& c[6] == QLatin1Char('e') && c[7] == QLatin1Char('n')
&& c[8] == QLatin1Char('t') && c[9] == QLatin1Char('s'))
return QScriptGrammar::T_RESERVED_WORD;
}
} break;
case 12: {
if (check_reserved) {
if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('y')
&& c[2] == QLatin1Char('n') && c[3] == QLatin1Char('c')
&& c[4] == QLatin1Char('h') && c[5] == QLatin1Char('r')
&& c[6] == QLatin1Char('o') && c[7] == QLatin1Char('n')
&& c[8] == QLatin1Char('i') && c[9] == QLatin1Char('z')
&& c[10] == QLatin1Char('e') && c[11] == QLatin1Char('d'))
return QScriptGrammar::T_RESERVED_WORD;
}
} break;
} // switch
return -1;
}
int QScript::Lexer::lex()
{
int token = 0;
state = Start;
ushort stringType = 0; // either single or double quotes
pos8 = pos16 = 0;
done = false;
terminator = false;
// did we push a token on the stack previously ?
// (after an automatic semicolon insertion)
if (stackToken >= 0) {
setDone(Other);
token = stackToken;
stackToken = -1;
}
while (!done) {
switch (state) {
case Start:
if (isWhiteSpace()) {
// do nothing
} else if (current == '/' && next1 == '/') {
recordStartPos();
shift(1);
state = InSingleLineComment;
} else if (current == '/' && next1 == '*') {
recordStartPos();
shift(1);
state = InMultiLineComment;
} else if (current == 0) {
syncProhibitAutomaticSemicolon();
if (!terminator && !delimited && !prohibitAutomaticSemicolon) {
// automatic semicolon insertion if program incomplete
token = QScriptGrammar::T_SEMICOLON;
stackToken = 0;
setDone(Other);
} else {
setDone(Eof);
}
} else if (isLineTerminator()) {
shiftWindowsLineBreak();
yylineno++;
yycolumn = 0;
bol = true;
terminator = true;
syncProhibitAutomaticSemicolon();
if (restrKeyword) {
token = QScriptGrammar::T_SEMICOLON;
setDone(Other);
}
} else if (current == '"' || current == '\'') {
recordStartPos();
state = InString;
stringType = current;
} else if (isIdentLetter(current)) {
recordStartPos();
record16(current);
state = InIdentifier;
} else if (current == '0') {
recordStartPos();
record8(current);
state = InNum0;
} else if (isDecimalDigit(current)) {
recordStartPos();
record8(current);
state = InNum;
} else if (current == '.' && isDecimalDigit(next1)) {
recordStartPos();
record8(current);
state = InDecimal;
} else {
recordStartPos();
token = matchPunctuator(current, next1, next2, next3);
if (token != -1) {
if (terminator && !delimited && !prohibitAutomaticSemicolon
&& (token == QScriptGrammar::T_PLUS_PLUS
|| token == QScriptGrammar::T_MINUS_MINUS)) {
// automatic semicolon insertion
stackToken = token;
token = QScriptGrammar::T_SEMICOLON;
}
setDone(Other);
}
else {
setDone(Bad);
err = IllegalCharacter;
errmsg = QLatin1String("Illegal character");
}
}
break;
case InString:
if (current == stringType) {
shift(1);
setDone(String);
} else if (current == 0 || isLineTerminator()) {
setDone(Bad);
err = UnclosedStringLiteral;
errmsg = QLatin1String("Unclosed string at end of line");
} else if (current == '\\') {
state = InEscapeSequence;
} else {
record16(current);
}
break;
// Escape Sequences inside of strings
case InEscapeSequence:
if (isOctalDigit(current)) {
if (current >= '0' && current <= '3' &&
isOctalDigit(next1) && isOctalDigit(next2)) {
record16(convertOctal(current, next1, next2));
shift(2);
state = InString;
} else if (isOctalDigit(current) &&
isOctalDigit(next1)) {
record16(convertOctal('0', current, next1));
shift(1);
state = InString;
} else if (isOctalDigit(current)) {
record16(convertOctal('0', '0', current));
state = InString;
} else {
setDone(Bad);
err = IllegalEscapeSequence;
errmsg = QLatin1String("Illegal escape squence");
}
} else if (current == 'x')
state = InHexEscape;
else if (current == 'u')
state = InUnicodeEscape;
else {
record16(singleEscape(current));
state = InString;
}
break;
case InHexEscape:
if (isHexDigit(current) && isHexDigit(next1)) {
state = InString;
record16(QLatin1Char(convertHex(current, next1)));
shift(1);
} else if (current == stringType) {
record16(QLatin1Char('x'));
shift(1);
setDone(String);
} else {
record16(QLatin1Char('x'));
record16(current);
state = InString;
}
break;
case InUnicodeEscape:
if (isHexDigit(current) && isHexDigit(next1) &&
isHexDigit(next2) && isHexDigit(next3)) {
record16(convertUnicode(current, next1, next2, next3));
shift(3);
state = InString;
} else if (current == stringType) {
record16(QLatin1Char('u'));
shift(1);
setDone(String);
} else {
setDone(Bad);
err = IllegalUnicodeEscapeSequence;
errmsg = QLatin1String("Illegal unicode escape sequence");
}
break;
case InSingleLineComment:
if (isLineTerminator()) {
shiftWindowsLineBreak();
yylineno++;
yycolumn = 0;
terminator = true;
bol = true;
if (restrKeyword) {
token = QScriptGrammar::T_SEMICOLON;
setDone(Other);
} else
state = Start;
} else if (current == 0) {
setDone(Eof);
}
break;
case InMultiLineComment:
if (current == 0) {
setDone(Bad);
err = UnclosedComment;
errmsg = QLatin1String("Unclosed comment at end of file");
} else if (isLineTerminator()) {
shiftWindowsLineBreak();
yylineno++;
} else if (current == '*' && next1 == '/') {
state = Start;
shift(1);
}
break;
case InIdentifier:
if (isIdentLetter(current) || isDecimalDigit(current)) {
record16(current);
break;
}
setDone(Identifier);
break;
case InNum0:
if (current == 'x' || current == 'X') {
record8(current);
state = InHex;
} else if (current == '.') {
record8(current);
state = InDecimal;
} else if (current == 'e' || current == 'E') {
record8(current);
state = InExponentIndicator;
} else if (isOctalDigit(current)) {
record8(current);
state = InOctal;
} else if (isDecimalDigit(current)) {
record8(current);
state = InDecimal;
} else {
setDone(Number);
}
break;
case InHex:
if (isHexDigit(current))
record8(current);
else
setDone(Hex);
break;
case InOctal:
if (isOctalDigit(current)) {
record8(current);
} else if (isDecimalDigit(current)) {
record8(current);
state = InDecimal;
} else {
setDone(Octal);
}
break;
case InNum:
if (isDecimalDigit(current)) {
record8(current);
} else if (current == '.') {
record8(current);
state = InDecimal;
} else if (current == 'e' || current == 'E') {
record8(current);
state = InExponentIndicator;
} else {
setDone(Number);
}
break;
case InDecimal:
if (isDecimalDigit(current)) {
record8(current);
} else if (current == 'e' || current == 'E') {
record8(current);
state = InExponentIndicator;
} else {
setDone(Number);
}
break;
case InExponentIndicator:
if (current == '+' || current == '-') {
record8(current);
} else if (isDecimalDigit(current)) {
record8(current);
state = InExponent;
} else {
setDone(Bad);
err = IllegalExponentIndicator;
errmsg = QLatin1String("Illegal syntax for exponential number");
}
break;
case InExponent:
if (isDecimalDigit(current)) {
record8(current);
} else {
setDone(Number);
}
break;
default:
Q_ASSERT_X(0, "Lexer::lex", "Unhandled state in switch statement");
}
// move on to the next character
if (!done)
shift(1);
if (state != Start && state != InSingleLineComment)
bol = false;
}
// no identifiers allowed directly after numeric literal, e.g. "3in" is bad
if ((state == Number || state == Octal || state == Hex)
&& isIdentLetter(current)) {
state = Bad;
err = IllegalIdentifier;
errmsg = QLatin1String("Identifier cannot start with numeric literal");
}
// terminate string
buffer8[pos8] = '\0';
double dval = 0;
if (state == Number) {
dval = qstrtod(buffer8, 0, 0);
} else if (state == Hex) { // scan hex numbers
dval = QScript::integerFromString(buffer8, pos8, 16);
state = Number;
} else if (state == Octal) { // scan octal number
dval = QScript::integerFromString(buffer8, pos8, 8);
state = Number;
}
restrKeyword = false;
delimited = false;
switch (parenthesesState) {
case IgnoreParentheses:
break;
case CountParentheses:
if (token == QScriptGrammar::T_RPAREN) {
--parenthesesCount;
if (parenthesesCount == 0)
parenthesesState = BalancedParentheses;
} else if (token == QScriptGrammar::T_LPAREN) {
++parenthesesCount;
}
break;
case BalancedParentheses:
parenthesesState = IgnoreParentheses;
break;
}
switch (state) {
case Eof:
return 0;
case Other:
if(token == QScriptGrammar::T_RBRACE || token == QScriptGrammar::T_SEMICOLON)
delimited = true;
return token;
case Identifier:
if ((token = findReservedWord(buffer16, pos16)) < 0) {
/* TODO: close leak on parse error. same holds true for String */
qsyylval = QString(buffer16, pos16);
return QScriptGrammar::T_IDENTIFIER;
}
if (token == QScriptGrammar::T_CONTINUE || token == QScriptGrammar::T_BREAK
|| token == QScriptGrammar::T_RETURN || token == QScriptGrammar::T_THROW) {
restrKeyword = true;
} else if (token == QScriptGrammar::T_IF || token == QScriptGrammar::T_FOR
|| token == QScriptGrammar::T_WHILE || token == QScriptGrammar::T_WITH) {
parenthesesState = CountParentheses;
parenthesesCount = 0;
} else if (token == QScriptGrammar::T_DO) {
parenthesesState = BalancedParentheses;
}
return token;
case String:
qsyylval = QString(buffer16, pos16);
return QScriptGrammar::T_STRING_LITERAL;
case Number:
qsyylval = dval;
return QScriptGrammar::T_NUMERIC_LITERAL;
case Bad:
return -1;
default:
Q_ASSERT(!"unhandled numeration value in switch");
return -1;
}
}
bool QScript::Lexer::isWhiteSpace() const
{
return (current == ' ' || current == '\t' ||
current == 0x0b || current == 0x0c);
}
bool QScript::Lexer::isLineTerminator() const
{
return (current == '\n' || current == '\r');
}
bool QScript::Lexer::isIdentLetter(ushort c)
{
/* TODO: allow other legitimate unicode chars */
return ((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| c == '$'
|| c == '_');
}
bool QScript::Lexer::isDecimalDigit(ushort c)
{
return (c >= '0' && c <= '9');
}
bool QScript::Lexer::isHexDigit(ushort c) const
{
return ((c >= '0' && c <= '9')
|| (c >= 'a' && c <= 'f')
|| (c >= 'A' && c <= 'F'));
}
bool QScript::Lexer::isOctalDigit(ushort c) const
{
return (c >= '0' && c <= '7');
}
int QScript::Lexer::matchPunctuator(ushort c1, ushort c2,
ushort c3, ushort c4)
{
if (c1 == '>' && c2 == '>' && c3 == '>' && c4 == '=') {
shift(4);
return QScriptGrammar::T_GT_GT_GT_EQ;
} else if (c1 == '=' && c2 == '=' && c3 == '=') {
shift(3);
return QScriptGrammar::T_EQ_EQ_EQ;
} else if (c1 == '!' && c2 == '=' && c3 == '=') {
shift(3);
return QScriptGrammar::T_NOT_EQ_EQ;
} else if (c1 == '>' && c2 == '>' && c3 == '>') {
shift(3);
return QScriptGrammar::T_GT_GT_GT;
} else if (c1 == '<' && c2 == '<' && c3 == '=') {
shift(3);
return QScriptGrammar::T_LT_LT_EQ;
} else if (c1 == '>' && c2 == '>' && c3 == '=') {
shift(3);
return QScriptGrammar::T_GT_GT_EQ;
} else if (c1 == '<' && c2 == '=') {
shift(2);
return QScriptGrammar::T_LE;
} else if (c1 == '>' && c2 == '=') {
shift(2);
return QScriptGrammar::T_GE;
} else if (c1 == '!' && c2 == '=') {
shift(2);
return QScriptGrammar::T_NOT_EQ;
} else if (c1 == '+' && c2 == '+') {
shift(2);
return QScriptGrammar::T_PLUS_PLUS;
} else if (c1 == '-' && c2 == '-') {
shift(2);
return QScriptGrammar::T_MINUS_MINUS;
} else if (c1 == '=' && c2 == '=') {
shift(2);
return QScriptGrammar::T_EQ_EQ;
} else if (c1 == '+' && c2 == '=') {
shift(2);
return QScriptGrammar::T_PLUS_EQ;
} else if (c1 == '-' && c2 == '=') {
shift(2);
return QScriptGrammar::T_MINUS_EQ;
} else if (c1 == '*' && c2 == '=') {
shift(2);
return QScriptGrammar::T_STAR_EQ;
} else if (c1 == '/' && c2 == '=') {
shift(2);
return QScriptGrammar::T_DIVIDE_EQ;
} else if (c1 == '&' && c2 == '=') {
shift(2);
return QScriptGrammar::T_AND_EQ;
} else if (c1 == '^' && c2 == '=') {
shift(2);
return QScriptGrammar::T_XOR_EQ;
} else if (c1 == '%' && c2 == '=') {
shift(2);
return QScriptGrammar::T_REMAINDER_EQ;
} else if (c1 == '|' && c2 == '=') {
shift(2);
return QScriptGrammar::T_OR_EQ;
} else if (c1 == '<' && c2 == '<') {
shift(2);
return QScriptGrammar::T_LT_LT;
} else if (c1 == '>' && c2 == '>') {
shift(2);
return QScriptGrammar::T_GT_GT;
} else if (c1 == '&' && c2 == '&') {
shift(2);
return QScriptGrammar::T_AND_AND;
} else if (c1 == '|' && c2 == '|') {
shift(2);
return QScriptGrammar::T_OR_OR;
}
switch(c1) {
case '=': shift(1); return QScriptGrammar::T_EQ;
case '>': shift(1); return QScriptGrammar::T_GT;
case '<': shift(1); return QScriptGrammar::T_LT;
case ',': shift(1); return QScriptGrammar::T_COMMA;
case '!': shift(1); return QScriptGrammar::T_NOT;
case '~': shift(1); return QScriptGrammar::T_TILDE;
case '?': shift(1); return QScriptGrammar::T_QUESTION;
case ':': shift(1); return QScriptGrammar::T_COLON;
case '.': shift(1); return QScriptGrammar::T_DOT;
case '+': shift(1); return QScriptGrammar::T_PLUS;
case '-': shift(1); return QScriptGrammar::T_MINUS;
case '*': shift(1); return QScriptGrammar::T_STAR;
case '/': shift(1); return QScriptGrammar::T_DIVIDE_;
case '&': shift(1); return QScriptGrammar::T_AND;
case '|': shift(1); return QScriptGrammar::T_OR;
case '^': shift(1); return QScriptGrammar::T_XOR;
case '%': shift(1); return QScriptGrammar::T_REMAINDER;
case '(': shift(1); return QScriptGrammar::T_LPAREN;
case ')': shift(1); return QScriptGrammar::T_RPAREN;
case '{': shift(1); return QScriptGrammar::T_LBRACE;
case '}': shift(1); return QScriptGrammar::T_RBRACE;
case '[': shift(1); return QScriptGrammar::T_LBRACKET;
case ']': shift(1); return QScriptGrammar::T_RBRACKET;
case ';': shift(1); return QScriptGrammar::T_SEMICOLON;
default: return -1;
}
}
ushort QScript::Lexer::singleEscape(ushort c) const
{
switch(c) {
case 'b':
return 0x08;
case 't':
return 0x09;
case 'n':
return 0x0A;
case 'v':
return 0x0B;
case 'f':
return 0x0C;
case 'r':
return 0x0D;
case '"':
return 0x22;
case '\'':
return 0x27;
case '\\':
return 0x5C;
default:
return c;
}
}
ushort QScript::Lexer::convertOctal(ushort c1, ushort c2,
ushort c3) const
{
return ((c1 - '0') * 64 + (c2 - '0') * 8 + c3 - '0');
}
unsigned char QScript::Lexer::convertHex(ushort c)
{
if (c >= '0' && c <= '9')
return (c - '0');
else if (c >= 'a' && c <= 'f')
return (c - 'a' + 10);
else
return (c - 'A' + 10);
}
unsigned char QScript::Lexer::convertHex(ushort c1, ushort c2)
{
return ((convertHex(c1) << 4) + convertHex(c2));
}
QChar QScript::Lexer::convertUnicode(ushort c1, ushort c2,
ushort c3, ushort c4)
{
return QChar((convertHex(c3) << 4) + convertHex(c4),
(convertHex(c1) << 4) + convertHex(c2));
}
void QScript::Lexer::record8(ushort c)
{
Q_ASSERT(c <= 0xff);
// enlarge buffer if full
if (pos8 >= size8 - 1) {
char *tmp = new char[2 * size8];
memcpy(tmp, buffer8, size8 * sizeof(char));
delete [] buffer8;
buffer8 = tmp;
size8 *= 2;
}
buffer8[pos8++] = (char) c;
}
void QScript::Lexer::record16(QChar c)
{
// enlarge buffer if full
if (pos16 >= size16 - 1) {
QChar *tmp = new QChar[2 * size16];
memcpy(tmp, buffer16, size16 * sizeof(QChar));
delete [] buffer16;
buffer16 = tmp;
size16 *= 2;
}
buffer16[pos16++] = c;
}
void QScript::Lexer::recordStartPos()
{
startlineno = yylineno;
startcolumn = yycolumn;
}
bool QScript::Lexer::scanRegExp(RegExpBodyPrefix prefix)
{
pos16 = 0;
bool lastWasEscape = false;
if (prefix == EqualPrefix)
record16(QLatin1Char('='));
while (1) {
if (isLineTerminator() || current == 0) {
errmsg = QLatin1String("Unterminated regular expression literal");
return false;
}
else if (current != '/' || lastWasEscape == true)
{
record16(current);
lastWasEscape = !lastWasEscape && (current == '\\');
}
else {
pattern = QString(buffer16, pos16);
pos16 = 0;
shift(1);
break;
}
shift(1);
}
flags = 0;
while (isIdentLetter(current)) {
record16(current);
shift(1);
}
return true;
}
void QScript::Lexer::syncProhibitAutomaticSemicolon()
{
if (parenthesesState == BalancedParentheses) {
// we have seen something like "if (foo)", which means we should
// never insert an automatic semicolon at this point, since it would
// then be expanded into an empty statement (ECMA-262 7.9.1)
prohibitAutomaticSemicolon = true;
parenthesesState = IgnoreParentheses;
} else {
prohibitAutomaticSemicolon = false;
}
}
class Translator;
class QScriptParser: protected QScriptGrammar
{
public:
QVariant val;
struct Location {
int startLine;
int startColumn;
int endLine;
int endColumn;
};
public:
QScriptParser();
~QScriptParser();
bool parse(QScript::Lexer *lexer,
const QString &fileName,
Translator *translator);
inline QString errorMessage() const
{ return error_message; }
inline int errorLineNumber() const
{ return error_lineno; }
inline int errorColumnNumber() const
{ return error_column; }
protected:
inline void reallocateStack();
inline QVariant &sym(int index)
{ return sym_stack [tos + index - 1]; }
inline Location &loc(int index)
{ return location_stack [tos + index - 2]; }
protected:
int tos;
int stack_size;
QVector<QVariant> sym_stack;
int *state_stack;
Location *location_stack;
QString error_message;
int error_lineno;
int error_column;
};
inline void QScriptParser::reallocateStack()
{
if (! stack_size)
stack_size = 128;
else
stack_size <<= 1;
sym_stack.resize(stack_size);
state_stack = reinterpret_cast<int*> (qRealloc(state_stack, stack_size * sizeof(int)));
location_stack = reinterpret_cast<Location*> (qRealloc(location_stack, stack_size * sizeof(Location)));
}
inline static bool automatic(QScript::Lexer *lexer, int token)
{
return (token == QScriptGrammar::T_RBRACE)
|| (token == 0)
|| lexer->prevTerminator();
}
QScriptParser::QScriptParser():
tos(0),
stack_size(0),
sym_stack(0),
state_stack(0),
location_stack(0)
{
}
QScriptParser::~QScriptParser()
{
if (stack_size) {
qFree(state_stack);
qFree(location_stack);
}
}
static inline QScriptParser::Location location(QScript::Lexer *lexer)
{
QScriptParser::Location loc;
loc.startLine = lexer->startLineNo();
loc.startColumn = lexer->startColumnNo();
loc.endLine = lexer->endLineNo();
loc.endColumn = lexer->endColumnNo();
return loc;
}
bool QScriptParser::parse(QScript::Lexer *lexer,
const QString &fileName,
Translator *translator)
{
const int INITIAL_STATE = 0;
int yytoken = -1;
int saved_yytoken = -1;
int identLineNo = -1;
reallocateStack();
tos = 0;
state_stack[++tos] = INITIAL_STATE;
while (true)
{
const int state = state_stack [tos];
if (yytoken == -1 && - TERMINAL_COUNT != action_index [state])
{
if (saved_yytoken == -1)
{
yytoken = lexer->lex();
location_stack [tos] = location(lexer);
}
else
{
yytoken = saved_yytoken;
saved_yytoken = -1;
}
}
int act = t_action (state, yytoken);
if (act == ACCEPT_STATE)
return true;
else if (act > 0)
{
if (++tos == stack_size)
reallocateStack();
sym_stack [tos] = lexer->val ();
state_stack [tos] = act;
location_stack [tos] = location(lexer);
yytoken = -1;
}
else if (act < 0)
{
int r = - act - 1;
tos -= rhs [r];
act = state_stack [tos++];
switch (r) {
case 1: {
sym(1) = sym(1).toByteArray();
identLineNo = lexer->startLineNo();
} break;
case 7: {
bool rx = lexer->scanRegExp(QScript::Lexer::NoPrefix);
if (!rx) {
error_message = lexer->errorMessage();
error_lineno = lexer->startLineNo();
error_column = lexer->startColumnNo();
return false;
}
} break;
case 8: {
bool rx = lexer->scanRegExp(QScript::Lexer::EqualPrefix);
if (!rx) {
error_message = lexer->errorMessage();
error_lineno = lexer->startLineNo();
error_column = lexer->startColumnNo();
return false;
}
} break;
case 66: {
QString name = sym(1).toString();
if ((name == QLatin1String("qsTranslate")) || (name == QLatin1String("QT_TRANSLATE_NOOP"))) {
QVariantList args = sym(2).toList();
if (args.size() < 2) {
qWarning("%s:%d: %s() requires at least two arguments",
qPrintable(fileName), identLineNo, qPrintable(name));
} else {
if ((args.at(0).type() != QVariant::String)
|| (args.at(1).type() != QVariant::String)) {
qWarning("%s:%d: %s(): both arguments must be literal strings",
qPrintable(fileName), identLineNo, qPrintable(name));
} else {
QString context = args.at(0).toString();
QString text = args.at(1).toString();
QString comment = args.value(2).toString();
QString extracomment;
bool plural = (args.size() > 4);
recordMessage(translator, context, text, comment, extracomment,
plural, fileName, identLineNo);
}
}
} else if ((name == QLatin1String("qsTr")) || (name == QLatin1String("QT_TR_NOOP"))) {
QVariantList args = sym(2).toList();
if (args.size() < 1) {
qWarning("%s:%d: %s() requires at least one argument",
qPrintable(fileName), identLineNo, qPrintable(name));
} else {
if (args.at(0).type() != QVariant::String) {
qWarning("%s:%d: %s(): text to translate must be a literal string",
qPrintable(fileName), identLineNo, qPrintable(name));
} else {
QString context = QFileInfo(fileName).baseName();
QString text = args.at(0).toString();
QString comment = args.value(1).toString();
QString extracomment;
bool plural = (args.size() > 2);
recordMessage(translator, context, text, comment, extracomment,
plural, fileName, identLineNo);
}
}
}
} break;
case 70: {
sym(1) = QVariantList();
} break;
case 71: {
sym(1) = sym(2);
} break;
case 72: {
sym(1) = QVariantList() << sym(1);
} break;
case 73: {
sym(1) = sym(1).toList() << sym(3);
} break;
case 94: {
if ((sym(1).type() == QVariant::String) || (sym(3).type() == QVariant::String))
sym(1) = sym(1).toString() + sym(3).toString();
else
sym(1) = QVariant();
} break;
} // switch
state_stack [tos] = nt_action (act, lhs [r] - TERMINAL_COUNT);
if (rhs[r] > 1) {
location_stack[tos - 1].endLine = location_stack[tos + rhs[r] - 2].endLine;
location_stack[tos - 1].endColumn = location_stack[tos + rhs[r] - 2].endColumn;
location_stack[tos] = location_stack[tos + rhs[r] - 1];
}
}
else
{
if (saved_yytoken == -1 && automatic (lexer, yytoken) && t_action (state, T_AUTOMATIC_SEMICOLON) > 0)
{
saved_yytoken = yytoken;
yytoken = T_SEMICOLON;
continue;
}
else if ((state == INITIAL_STATE) && (yytoken == 0)) {
// accept empty input
yytoken = T_SEMICOLON;
continue;
}
int ers = state;
int shifts = 0;
int reduces = 0;
int expected_tokens [3];
for (int tk = 0; tk < TERMINAL_COUNT; ++tk)
{
int k = t_action (ers, tk);
if (! k)
continue;
else if (k < 0)
++reduces;
else if (spell [tk])
{
if (shifts < 3)
expected_tokens [shifts] = tk;
++shifts;
}
}
error_message.clear ();
if (shifts && shifts < 3)
{
bool first = true;
for (int s = 0; s < shifts; ++s)
{
if (first)
error_message += QLatin1String ("Expected ");
else
error_message += QLatin1String (", ");
first = false;
error_message += QLatin1String("`");
error_message += QLatin1String (spell [expected_tokens [s]]);
error_message += QLatin1String("'");
}
}
if (error_message.isEmpty())
error_message = lexer->errorMessage();
error_lineno = lexer->startLineNo();
error_column = lexer->startColumnNo();
return false;
}
}
return false;
}
bool loadQScript(Translator &translator, QIODevice &dev, ConversionData &cd)
{
QTextStream ts(&dev);
QByteArray codecName;
if (!cd.m_codecForSource.isEmpty())
codecName = cd.m_codecForSource;
else
codecName = translator.codecName(); // Just because it should be latin1 already
ts.setCodec(QTextCodec::codecForName(codecName));
ts.setAutoDetectUnicode(true);
QString code = ts.readAll();
QScript::Lexer lexer;
lexer.setCode(code, /*lineNumber=*/1);
QScriptParser parser;
if (!parser.parse(&lexer, cd.m_sourceFileName, &translator)) {
qWarning("%s:%d: %s", qPrintable(cd.m_sourceFileName), parser.errorLineNumber(),
qPrintable(parser.errorMessage()));
return false;
}
// Java uses UTF-16 internally and Jambi makes UTF-8 for tr() purposes of it.
translator.setCodecName("UTF-8");
return true;
}
bool saveQScript(const Translator &translator, QIODevice &dev, ConversionData &cd)
{
Q_UNUSED(dev);
Q_UNUSED(translator);
cd.appendError(QLatin1String("Cannot save .js files"));
return false;
}
int initQScript()
{
Translator::FileFormat format;
format.extension = QLatin1String("js");
format.fileType = Translator::FileFormat::SourceCode;
format.priority = 0;
format.description = QObject::tr("Qt Script source files");
format.loader = &loadQScript;
format.saver = &saveQScript;
Translator::registerFileFormat(format);
return 1;
}
Q_CONSTRUCTOR_FUNCTION(initQScript)
QT_END_NAMESPACE
| RLovelett/qt | tools/linguist/shared/qscript.cpp | C++ | lgpl-2.1 | 84,936 |
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE file.
#include "libcef/common/scheme_registrar_impl.h"
#include <string>
#include "libcef/common/content_client.h"
#include "base/bind.h"
#include "base/logging.h"
CefSchemeRegistrarImpl::CefSchemeRegistrarImpl()
: supported_thread_id_(base::PlatformThread::CurrentId()) {
}
bool CefSchemeRegistrarImpl::AddCustomScheme(
const CefString& scheme_name,
bool is_standard,
bool is_local,
bool is_display_isolated) {
if (!VerifyContext())
return false;
const std::string& scheme = scheme_name;
if (is_standard)
standard_schemes_.push_back(scheme);
CefContentClient::SchemeInfo scheme_info = {
scheme, is_standard, is_local, is_display_isolated};
CefContentClient::Get()->AddCustomScheme(scheme_info);
return true;
}
void CefSchemeRegistrarImpl::GetStandardSchemes(
std::vector<std::string>* standard_schemes) {
if (!VerifyContext())
return;
if (standard_schemes_.empty())
return;
standard_schemes->insert(standard_schemes->end(), standard_schemes_.begin(),
standard_schemes_.end());
}
bool CefSchemeRegistrarImpl::VerifyRefCount() {
return (GetRefCt() == 1);
}
void CefSchemeRegistrarImpl::Detach() {
if (VerifyContext())
supported_thread_id_ = base::kInvalidThreadId;
}
bool CefSchemeRegistrarImpl::VerifyContext() {
if (base::PlatformThread::CurrentId() != supported_thread_id_) {
// This object should only be accessed from the thread that created it.
NOTREACHED();
return false;
}
return true;
}
| desura/desura-cef3-full | libcef/common/scheme_registrar_impl.cc | C++ | lgpl-2.1 | 1,711 |
#include "archive.hh"
#include "binary-cache-store.hh"
#include "compression.hh"
#include "derivations.hh"
#include "fs-accessor.hh"
#include "globals.hh"
#include "nar-info.hh"
#include "sync.hh"
#include "remote-fs-accessor.hh"
#include "nar-info-disk-cache.hh"
#include "nar-accessor.hh"
#include "json.hh"
#include "thread-pool.hh"
#include <chrono>
#include <future>
#include <regex>
#include <nlohmann/json.hpp>
namespace nix {
BinaryCacheStore::BinaryCacheStore(const Params & params)
: Store(params)
{
if (secretKeyFile != "")
secretKey = std::unique_ptr<SecretKey>(new SecretKey(readFile(secretKeyFile)));
StringSink sink;
sink << narVersionMagic1;
narMagic = *sink.s;
}
void BinaryCacheStore::init()
{
std::string cacheInfoFile = "nix-cache-info";
auto cacheInfo = getFile(cacheInfoFile);
if (!cacheInfo) {
upsertFile(cacheInfoFile, "StoreDir: " + storeDir + "\n", "text/x-nix-cache-info");
} else {
for (auto & line : tokenizeString<Strings>(*cacheInfo, "\n")) {
size_t colon = line.find(':');
if (colon == std::string::npos) continue;
auto name = line.substr(0, colon);
auto value = trim(line.substr(colon + 1, std::string::npos));
if (name == "StoreDir") {
if (value != storeDir)
throw Error(format("binary cache '%s' is for Nix stores with prefix '%s', not '%s'")
% getUri() % value % storeDir);
} else if (name == "WantMassQuery") {
wantMassQuery.setDefault(value == "1" ? "true" : "false");
} else if (name == "Priority") {
priority.setDefault(fmt("%d", std::stoi(value)));
}
}
}
}
void BinaryCacheStore::getFile(const std::string & path,
Callback<std::shared_ptr<std::string>> callback) noexcept
{
try {
callback(getFile(path));
} catch (...) { callback.rethrow(); }
}
void BinaryCacheStore::getFile(const std::string & path, Sink & sink)
{
std::promise<std::shared_ptr<std::string>> promise;
getFile(path,
{[&](std::future<std::shared_ptr<std::string>> result) {
try {
promise.set_value(result.get());
} catch (...) {
promise.set_exception(std::current_exception());
}
}});
auto data = promise.get_future().get();
sink((unsigned char *) data->data(), data->size());
}
std::shared_ptr<std::string> BinaryCacheStore::getFile(const std::string & path)
{
StringSink sink;
try {
getFile(path, sink);
} catch (NoSuchBinaryCacheFile &) {
return nullptr;
}
return sink.s;
}
std::string BinaryCacheStore::narInfoFileFor(const StorePath & storePath)
{
return storePathToHash(printStorePath(storePath)) + ".narinfo";
}
void BinaryCacheStore::writeNarInfo(ref<NarInfo> narInfo)
{
auto narInfoFile = narInfoFileFor(narInfo->path);
upsertFile(narInfoFile, narInfo->to_string(*this), "text/x-nix-narinfo");
auto hashPart = storePathToHash(printStorePath(narInfo->path));
{
auto state_(state.lock());
state_->pathInfoCache.upsert(hashPart, PathInfoCacheValue { .value = std::shared_ptr<NarInfo>(narInfo) });
}
if (diskCache)
diskCache->upsertNarInfo(getUri(), hashPart, std::shared_ptr<NarInfo>(narInfo));
}
void BinaryCacheStore::addToStore(const ValidPathInfo & info, const ref<std::string> & nar,
RepairFlag repair, CheckSigsFlag checkSigs, std::shared_ptr<FSAccessor> accessor)
{
if (!repair && isValidPath(info.path)) return;
/* Verify that all references are valid. This may do some .narinfo
reads, but typically they'll already be cached. */
for (auto & ref : info.references)
try {
if (ref != info.path)
queryPathInfo(ref);
} catch (InvalidPath &) {
throw Error("cannot add '%s' to the binary cache because the reference '%s' is not valid",
printStorePath(info.path), printStorePath(ref));
}
assert(nar->compare(0, narMagic.size(), narMagic) == 0);
auto narInfo = make_ref<NarInfo>(info);
narInfo->narSize = nar->size();
narInfo->narHash = hashString(htSHA256, *nar);
if (info.narHash && info.narHash != narInfo->narHash)
throw Error("refusing to copy corrupted path '%1%' to binary cache", printStorePath(info.path));
auto accessor_ = std::dynamic_pointer_cast<RemoteFSAccessor>(accessor);
auto narAccessor = makeNarAccessor(nar);
if (accessor_)
accessor_->addToCache(printStorePath(info.path), *nar, narAccessor);
/* Optionally write a JSON file containing a listing of the
contents of the NAR. */
if (writeNARListing) {
std::ostringstream jsonOut;
{
JSONObject jsonRoot(jsonOut);
jsonRoot.attr("version", 1);
{
auto res = jsonRoot.placeholder("root");
listNar(res, narAccessor, "", true);
}
}
upsertFile(storePathToHash(printStorePath(info.path)) + ".ls", jsonOut.str(), "application/json");
}
/* Compress the NAR. */
narInfo->compression = compression;
auto now1 = std::chrono::steady_clock::now();
auto narCompressed = compress(compression, *nar, parallelCompression);
auto now2 = std::chrono::steady_clock::now();
narInfo->fileHash = hashString(htSHA256, *narCompressed);
narInfo->fileSize = narCompressed->size();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now2 - now1).count();
printMsg(lvlTalkative, "copying path '%1%' (%2% bytes, compressed %3$.1f%% in %4% ms) to binary cache",
printStorePath(narInfo->path), narInfo->narSize,
((1.0 - (double) narCompressed->size() / nar->size()) * 100.0),
duration);
narInfo->url = "nar/" + narInfo->fileHash.to_string(Base32, false) + ".nar"
+ (compression == "xz" ? ".xz" :
compression == "bzip2" ? ".bz2" :
compression == "br" ? ".br" :
"");
/* Optionally maintain an index of DWARF debug info files
consisting of JSON files named 'debuginfo/<build-id>' that
specify the NAR file and member containing the debug info. */
if (writeDebugInfo) {
std::string buildIdDir = "/lib/debug/.build-id";
if (narAccessor->stat(buildIdDir).type == FSAccessor::tDirectory) {
ThreadPool threadPool(25);
auto doFile = [&](std::string member, std::string key, std::string target) {
checkInterrupt();
nlohmann::json json;
json["archive"] = target;
json["member"] = member;
// FIXME: or should we overwrite? The previous link may point
// to a GC'ed file, so overwriting might be useful...
if (fileExists(key)) return;
printMsg(lvlTalkative, "creating debuginfo link from '%s' to '%s'", key, target);
upsertFile(key, json.dump(), "application/json");
};
std::regex regex1("^[0-9a-f]{2}$");
std::regex regex2("^[0-9a-f]{38}\\.debug$");
for (auto & s1 : narAccessor->readDirectory(buildIdDir)) {
auto dir = buildIdDir + "/" + s1;
if (narAccessor->stat(dir).type != FSAccessor::tDirectory
|| !std::regex_match(s1, regex1))
continue;
for (auto & s2 : narAccessor->readDirectory(dir)) {
auto debugPath = dir + "/" + s2;
if (narAccessor->stat(debugPath).type != FSAccessor::tRegular
|| !std::regex_match(s2, regex2))
continue;
auto buildId = s1 + s2;
std::string key = "debuginfo/" + buildId;
std::string target = "../" + narInfo->url;
threadPool.enqueue(std::bind(doFile, std::string(debugPath, 1), key, target));
}
}
threadPool.process();
}
}
/* Atomically write the NAR file. */
if (repair || !fileExists(narInfo->url)) {
stats.narWrite++;
upsertFile(narInfo->url, *narCompressed, "application/x-nix-nar");
} else
stats.narWriteAverted++;
stats.narWriteBytes += nar->size();
stats.narWriteCompressedBytes += narCompressed->size();
stats.narWriteCompressionTimeMs += duration;
/* Atomically write the NAR info file.*/
if (secretKey) narInfo->sign(*this, *secretKey);
writeNarInfo(narInfo);
stats.narInfoWrite++;
}
bool BinaryCacheStore::isValidPathUncached(const StorePath & storePath)
{
// FIXME: this only checks whether a .narinfo with a matching hash
// part exists. So ‘f4kb...-foo’ matches ‘f4kb...-bar’, even
// though they shouldn't. Not easily fixed.
return fileExists(narInfoFileFor(storePath));
}
void BinaryCacheStore::narFromPath(const StorePath & storePath, Sink & sink)
{
auto info = queryPathInfo(storePath).cast<const NarInfo>();
uint64_t narSize = 0;
LambdaSink wrapperSink([&](const unsigned char * data, size_t len) {
sink(data, len);
narSize += len;
});
auto decompressor = makeDecompressionSink(info->compression, wrapperSink);
try {
getFile(info->url, *decompressor);
} catch (NoSuchBinaryCacheFile & e) {
throw SubstituteGone(e.what());
}
decompressor->finish();
stats.narRead++;
//stats.narReadCompressedBytes += nar->size(); // FIXME
stats.narReadBytes += narSize;
}
void BinaryCacheStore::queryPathInfoUncached(const StorePath & storePath,
Callback<std::shared_ptr<const ValidPathInfo>> callback) noexcept
{
auto uri = getUri();
auto storePathS = printStorePath(storePath);
auto act = std::make_shared<Activity>(*logger, lvlTalkative, actQueryPathInfo,
fmt("querying info about '%s' on '%s'", storePathS, uri), Logger::Fields{storePathS, uri});
PushActivity pact(act->id);
auto narInfoFile = narInfoFileFor(storePath);
auto callbackPtr = std::make_shared<decltype(callback)>(std::move(callback));
getFile(narInfoFile,
{[=](std::future<std::shared_ptr<std::string>> fut) {
try {
auto data = fut.get();
if (!data) return (*callbackPtr)(nullptr);
stats.narInfoRead++;
(*callbackPtr)((std::shared_ptr<ValidPathInfo>)
std::make_shared<NarInfo>(*this, *data, narInfoFile));
(void) act; // force Activity into this lambda to ensure it stays alive
} catch (...) {
callbackPtr->rethrow();
}
}});
}
StorePath BinaryCacheStore::addToStore(const string & name, const Path & srcPath,
bool recursive, HashType hashAlgo, PathFilter & filter, RepairFlag repair)
{
// FIXME: some cut&paste from LocalStore::addToStore().
/* Read the whole path into memory. This is not a very scalable
method for very large paths, but `copyPath' is mainly used for
small files. */
StringSink sink;
Hash h;
if (recursive) {
dumpPath(srcPath, sink, filter);
h = hashString(hashAlgo, *sink.s);
} else {
auto s = readFile(srcPath);
dumpString(s, sink);
h = hashString(hashAlgo, s);
}
ValidPathInfo info(makeFixedOutputPath(recursive, h, name));
addToStore(info, sink.s, repair, CheckSigs, nullptr);
return std::move(info.path);
}
StorePath BinaryCacheStore::addTextToStore(const string & name, const string & s,
const StorePathSet & references, RepairFlag repair)
{
ValidPathInfo info(computeStorePathForText(name, s, references));
info.references = cloneStorePathSet(references);
if (repair || !isValidPath(info.path)) {
StringSink sink;
dumpString(s, sink);
addToStore(info, sink.s, repair, CheckSigs, nullptr);
}
return std::move(info.path);
}
ref<FSAccessor> BinaryCacheStore::getFSAccessor()
{
return make_ref<RemoteFSAccessor>(ref<Store>(shared_from_this()), localNarCache);
}
void BinaryCacheStore::addSignatures(const StorePath & storePath, const StringSet & sigs)
{
/* Note: this is inherently racy since there is no locking on
binary caches. In particular, with S3 this unreliable, even
when addSignatures() is called sequentially on a path, because
S3 might return an outdated cached version. */
auto narInfo = make_ref<NarInfo>((NarInfo &) *queryPathInfo(storePath));
narInfo->sigs.insert(sigs.begin(), sigs.end());
auto narInfoFile = narInfoFileFor(narInfo->path);
writeNarInfo(narInfo);
}
std::shared_ptr<std::string> BinaryCacheStore::getBuildLog(const StorePath & path)
{
auto drvPath = path.clone();
if (!path.isDerivation()) {
try {
auto info = queryPathInfo(path);
// FIXME: add a "Log" field to .narinfo
if (!info->deriver) return nullptr;
drvPath = info->deriver->clone();
} catch (InvalidPath &) {
return nullptr;
}
}
auto logPath = "log/" + std::string(baseNameOf(printStorePath(drvPath)));
debug("fetching build log from binary cache '%s/%s'", getUri(), logPath);
return getFile(logPath);
}
}
| ehmry/nix | src/libstore/binary-cache-store.cc | C++ | lgpl-2.1 | 13,452 |
// ---------------------------------------------------------------------
//
// Copyright (C) 2003 - 2013 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// same as find_cell_1, but for the alternative algorithm
// take a 2d mesh and check that we can find an arbitrary point's cell
// in it
#include "../tests.h"
#include <deal.II/base/logstream.h>
#include <deal.II/grid/tria.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>
#include <deal.II/grid/grid_tools.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/tria_boundary_lib.h>
#include <deal.II/fe/mapping_q.h>
#include <fstream>
void check (Triangulation<2> &tria)
{
MappingQ<2> map(3); // Let's take a higher order mapping
Point<2> p (1./3., 1./2.);
std::pair<Triangulation<2>::active_cell_iterator, Point<2> >
cell = GridTools::find_active_cell_around_point (map, tria, p);
deallog << cell.first << std::endl;
for (unsigned int v=0; v<GeometryInfo<2>::vertices_per_cell; ++v)
deallog << "<" << cell.first->vertex(v) << "> ";
deallog << "[ " << cell.second << "] ";
deallog << std::endl;
Assert (p.distance (cell.first->center()) < cell.first->diameter()/2,
ExcInternalError());
}
int main ()
{
std::ofstream logfile("output");
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
{
Triangulation<2> coarse_grid;
GridGenerator::hyper_cube (coarse_grid);
coarse_grid.refine_global (2);
check (coarse_grid);
}
{
Triangulation<2> coarse_grid;
GridGenerator::hyper_ball (coarse_grid);
static const HyperBallBoundary<2> boundary;
coarse_grid.set_boundary (0, boundary);
coarse_grid.refine_global (2);
check (coarse_grid);
}
}
| flow123d/dealii | tests/bits/find_cell_alt_1.cc | C++ | lgpl-2.1 | 2,263 |
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt3Support module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "q3grid.h"
#include "qlayout.h"
#include "qapplication.h"
QT_BEGIN_NAMESPACE
/*!
\class Q3Grid
\brief The Q3Grid widget provides simple geometry management of its children.
\compat
The grid places its widgets either in columns or in rows depending
on its orientation.
The number of rows \e or columns is defined in the constructor.
All the grid's children will be placed and sized in accordance
with their sizeHint() and sizePolicy().
Use setMargin() to add space around the grid itself, and
setSpacing() to add space between the widgets.
\sa Q3VBox Q3HBox QGridLayout
*/
/*!
\typedef Q3Grid::Direction
\internal
*/
/*!
Constructs a grid widget with parent \a parent, called \a name.
If \a orient is \c Horizontal, \a n specifies the number of
columns. If \a orient is \c Vertical, \a n specifies the number of
rows. The widget flags \a f are passed to the Q3Frame constructor.
*/
Q3Grid::Q3Grid(int n, Qt::Orientation orient, QWidget *parent, const char *name,
Qt::WindowFlags f)
: Q3Frame(parent, name, f)
{
int nCols, nRows;
if (orient == Qt::Horizontal) {
nCols = n;
nRows = -1;
} else {
nCols = -1;
nRows = n;
}
(new QGridLayout(this, nRows, nCols, 0, 0, name))->setAutoAdd(true);
}
/*!
Constructs a grid widget with parent \a parent, called \a name.
\a n specifies the number of columns. The widget flags \a f are
passed to the Q3Frame constructor.
*/
Q3Grid::Q3Grid(int n, QWidget *parent, const char *name, Qt::WindowFlags f)
: Q3Frame(parent, name, f)
{
(new QGridLayout(this, -1, n, 0, 0, name))->setAutoAdd(true);
}
/*!
Sets the spacing between the child widgets to \a space.
*/
void Q3Grid::setSpacing(int space)
{
if (layout())
layout()->setSpacing(space);
}
/*!\reimp
*/
void Q3Grid::frameChanged()
{
if (layout())
layout()->setMargin(frameWidth());
}
/*!
\reimp
*/
QSize Q3Grid::sizeHint() const
{
QWidget *mThis = (QWidget*)this;
QApplication::sendPostedEvents(mThis, QEvent::ChildInserted);
return Q3Frame::sizeHint();
}
QT_END_NAMESPACE
| nonrational/qt-everywhere-opensource-src-4.8.6 | src/qt3support/widgets/q3grid.cpp | C++ | lgpl-2.1 | 4,161 |
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "debuggerplugin.h"
#include "debuggerstartparameters.h"
#include "debuggeractions.h"
#include "debuggerinternalconstants.h"
#include "debuggercore.h"
#include "debuggerkitconfigwidget.h"
#include "debuggerdialogs.h"
#include "debuggerengine.h"
#include "debuggeritemmanager.h"
#include "debuggermainwindow.h"
#include "debuggerrunconfigurationaspect.h"
#include "debuggerruncontrol.h"
#include "debuggerstringutils.h"
#include "debuggeroptionspage.h"
#include "debuggerkitinformation.h"
#include "memoryagent.h"
#include "breakhandler.h"
#include "breakwindow.h"
#include "disassemblerlines.h"
#include "logwindow.h"
#include "moduleswindow.h"
#include "moduleshandler.h"
#include "registerwindow.h"
#include "snapshotwindow.h"
#include "stackhandler.h"
#include "stackwindow.h"
#include "sourcefileswindow.h"
#include "threadswindow.h"
#include "watchhandler.h"
#include "watchwindow.h"
#include "watchutils.h"
#include "unstartedappwatcherdialog.h"
#include "debuggertooltipmanager.h"
#include "localsandexpressionswindow.h"
#include "loadcoredialog.h"
#include "sourceutils.h"
#include <debugger/shared/hostutils.h>
#include "snapshothandler.h"
#include "threadshandler.h"
#include "commonoptionspage.h"
#include "gdb/startgdbserverdialog.h"
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/find/itemviewfind.h>
#include <coreplugin/imode.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
#include <coreplugin/messagebox.h>
#include <coreplugin/messagemanager.h>
#include <coreplugin/modemanager.h>
#include <cppeditor/cppeditorconstants.h>
#include <cpptools/cppmodelmanager.h>
#include <extensionsystem/invoker.h>
#include <projectexplorer/localapplicationrunconfiguration.h>
#include <projectexplorer/buildmanager.h>
#include <projectexplorer/taskhub.h>
#include <projectexplorer/toolchain.h>
#include <projectexplorer/devicesupport/deviceprocesslist.h>
#include <projectexplorer/devicesupport/deviceprocessesdialog.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projecttree.h>
#include <projectexplorer/projectexplorersettings.h>
#include <projectexplorer/project.h>
#include <projectexplorer/session.h>
#include <projectexplorer/target.h>
#include <texteditor/texteditor.h>
#include <texteditor/fontsettings.h>
#include <texteditor/texteditorsettings.h>
#include <utils/basetreeview.h>
#include <utils/hostosinfo.h>
#include <utils/proxyaction.h>
#include <utils/qtcassert.h>
#include <utils/savedaction.h>
#include <utils/statuslabel.h>
#include <utils/styledbar.h>
#include <utils/winutils.h>
#include <QApplication>
#include <QCheckBox>
#include <QComboBox>
#include <QDockWidget>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QInputDialog>
#include <QMessageBox>
#include <QTextBlock>
#include <QToolButton>
#include <QtPlugin>
#include <QTreeWidget>
#include <QVBoxLayout>
#ifdef WITH_TESTS
#include <QTest>
#include <QSignalSpy>
#include <QTestEventLoop>
//#define WITH_BENCHMARK
#ifdef WITH_BENCHMARK
#include <valgrind/callgrind.h>
#endif
#endif // WITH_TESTS
#include <climits>
#define DEBUG_STATE 1
#ifdef DEBUG_STATE
//# define STATE_DEBUG(s)
// do { QString msg; QTextStream ts(&msg); ts << s;
// showMessage(msg, LogDebug); } while (0)
# define STATE_DEBUG(s) do { qDebug() << s; } while (0)
#else
# define STATE_DEBUG(s)
#endif
/*!
\namespace Debugger
Debugger plugin namespace
*/
/*!
\namespace Debugger::Internal
Internal namespace of the Debugger plugin
\internal
*/
/*!
\class Debugger::DebuggerEngine
\brief The DebuggerEngine class is the base class of a debugger engine.
\note The Debugger process itself and any helper processes like
gdbserver are referred to as 'Engine', whereas the debugged process
is referred to as 'Inferior'.
Transitions marked by '---' are done in the individual engines.
Transitions marked by '+-+' are done in the base DebuggerEngine.
Transitions marked by '*' are done asynchronously.
The GdbEngine->setupEngine() function is described in more detail below.
The engines are responsible for local roll-back to the last
acknowledged state before calling notify*Failed. I.e. before calling
notifyEngineSetupFailed() any process started during setupEngine()
so far must be terminated.
\code
DebuggerNotReady
progressmanager/progressmanager.cpp +
EngineSetupRequested
+
(calls *Engine->setupEngine())
| |
| |
{notify- {notify-
Engine- Engine-
SetupOk} SetupFailed}
+ +
+ `+-+-+> EngineSetupFailed
+ +
+ [calls RunControl->startFailed]
+ +
+ DebuggerFinished
v
EngineSetupOk
+
[calls RunControl->StartSuccessful]
+
InferiorSetupRequested
+
(calls *Engine->setupInferior())
| |
| |
{notify- {notify-
Inferior- Inferior-
SetupOk} SetupFailed}
+ +
+ ` +-+-> InferiorSetupFailed +-+-+-+-+-+->.
+ +
InferiorSetupOk +
+ +
EngineRunRequested +
+ +
(calls *Engine->runEngine()) +
/ | | \ +
/ | | \ +
| (core) | (attach) | | +
| | | | +
{notify- {notifyER&- {notifyER&- {notify- +
Inferior- Inferior- Inferior- EngineRun- +
Unrunnable} StopOk} RunOk} Failed} +
+ + + + +
InferiorUnrunnable + InferiorRunOk + +
+ + +
InferiorStopOk EngineRunFailed +
+ v
`-+-+-+-+-+-+-+-+-+-+-+>-+
+
+
#Interrupt@InferiorRunOk# +
+ +
InferiorStopRequested +
#SpontaneousStop + +
@InferiorRunOk# (calls *Engine-> +
+ interruptInferior()) +
{notify- | | +
Spontaneous- {notify- {notify- +
Inferior- Inferior- Inferior- +
StopOk} StopOk} StopFailed} +
+ + + +
+ + + +
InferiorStopOk + +
+ + +
+ + +
+ + +
#Stop@InferiorUnrunnable# + +
#Creator Close Event# + +
+ + +
InferiorShutdownRequested +
+ +
(calls *Engine->shutdownInferior()) +
| | +
{notify- {notify- +
Inferior- Inferior- +
ShutdownOk} ShutdownFailed} +
+ + +
+ + +
#Inferior exited# + + +
| + + +
{notifyInferior- + + +
Exited} + + +
+ + + +
InferiorExitOk + + +
+ + + +
InferiorShutdownOk InferiorShutdownFailed +
* * +
EngineShutdownRequested +
+ +
(calls *Engine->shutdownEngine()) <+-+-+-+-+-+-+-+-+-+-+-+-+-+'
| |
| |
{notify- {notify-
Engine- Engine-
ShutdownOk} ShutdownFailed}
+ +
EngineShutdownOk EngineShutdownFailed
* *
DebuggerFinished
\endcode */
/* Here is a matching graph as a GraphViz graph. View it using
* \code
grep "^sg1:" debuggerplugin.cpp | cut -c5- | dot -osg1.ps -Tps && gv sg1.ps
sg1: digraph DebuggerStates {
sg1: DebuggerNotReady -> EngineSetupRequested
sg1: EngineSetupRequested -> EngineSetupOk [ label="notifyEngineSetupOk", style="dashed" ];
sg1: EngineSetupRequested -> EngineSetupFailed [ label= "notifyEngineSetupFailed", style="dashed"];
sg1: EngineSetupFailed -> DebuggerFinished [ label= "RunControl::StartFailed" ];
sg1: EngineSetupOk -> InferiorSetupRequested [ label= "RunControl::StartSuccessful" ];
sg1: InferiorSetupRequested -> InferiorSetupOk [ label="notifyInferiorSetupOk", style="dashed" ];
sg1: InferiorSetupRequested -> InferiorSetupFailed [ label="notifyInferiorFailed", style="dashed" ];
sg1: InferiorSetupOk -> EngineRunRequested
sg1: InferiorSetupFailed -> EngineShutdownRequested
sg1: EngineRunRequested -> InferiorUnrunnable [ label="notifyInferiorUnrunnable", style="dashed" ];
sg1: EngineRunRequested -> InferiorStopOk [ label="notifyEngineRunAndInferiorStopOk", style="dashed" ];
sg1: EngineRunRequested -> InferiorRunOk [ label="notifyEngineRunAndInferiorRunOk", style="dashed" ];
sg1: EngineRunRequested -> EngineRunFailed [ label="notifyEngineRunFailed", style="dashed" ];
sg1: EngineRunFailed -> EngineShutdownRequested
sg1: InferiorRunOk -> InferiorStopOk [ label="SpontaneousStop\nnotifyInferiorSpontaneousStop", style="dashed" ];
sg1: InferiorRunOk -> InferiorStopRequested [ label="User stop\nEngine::interruptInferior", style="dashed"];
sg1: InferiorStopRequested -> InferiorStopOk [ label="notifyInferiorStopOk", style="dashed" ];
sg1: InferiorStopRequested -> InferiorShutdownRequested [ label="notifyInferiorStopFailed", style="dashed" ];
sg1: InferiorStopOk -> InferiorRunRequested [ label="User\nEngine::continueInferior" ];
sg1: InferiorRunRequested -> InferiorRunOk [ label="notifyInferiorRunOk", style="dashed"];
sg1: InferiorRunRequested -> InferiorRunFailed [ label="notifyInferiorRunFailed", style="dashed"];
sg1: InferiorRunFailed -> InferiorStopOk
sg1: InferiorStopOk -> InferiorShutdownRequested [ label="Close event" ];
sg1: InferiorUnrunnable -> InferiorShutdownRequested [ label="Close event" ];
sg1: InferiorShutdownRequested -> InferiorShutdownOk [ label= "Engine::shutdownInferior\nnotifyInferiorShutdownOk", style="dashed" ];
sg1: InferiorShutdownRequested -> InferiorShutdownFailed [ label="Engine::shutdownInferior\nnotifyInferiorShutdownFailed", style="dashed" ];
sg1: InferiorExited -> InferiorExitOk [ label="notifyInferiorExited", style="dashed"];
sg1: InferiorExitOk -> InferiorShutdownOk
sg1: InferiorShutdownOk -> EngineShutdownRequested
sg1: InferiorShutdownFailed -> EngineShutdownRequested
sg1: EngineShutdownRequested -> EngineShutdownOk [ label="Engine::shutdownEngine\nnotifyEngineShutdownOk", style="dashed" ];
sg1: EngineShutdownRequested -> EngineShutdownFailed [ label="Engine::shutdownEngine\nnotifyEngineShutdownFailed", style="dashed" ];
sg1: EngineShutdownOk -> DebuggerFinished [ style = "dotted" ];
sg1: EngineShutdownFailed -> DebuggerFinished [ style = "dotted" ];
sg1: }
* \endcode */
// Additional signalling: {notifyInferiorIll} {notifyEngineIll}
/*!
\class Debugger::Internal::GdbEngine
\brief The GdbEngine class implements Debugger::Engine driving a GDB
executable.
GdbEngine specific startup. All happens in EngineSetupRequested state:
\list
\li Transitions marked by '---' are done in the individual adapters.
\li Transitions marked by '+-+' are done in the GdbEngine.
\endlist
\code
GdbEngine::setupEngine()
+
(calls *Adapter->startAdapter())
| |
| `---> handleAdapterStartFailed()
| +
| {notifyEngineSetupFailed}
|
handleAdapterStarted()
+
{notifyEngineSetupOk}
GdbEngine::setupInferior()
+
(calls *Adapter->prepareInferior())
| |
| `---> handlePrepareInferiorFailed()
| +
| {notifyInferiorSetupFailed}
|
handleInferiorPrepared()
+
{notifyInferiorSetupOk}
\endcode */
using namespace Core;
using namespace Debugger::Constants;
using namespace Debugger::Internal;
using namespace ExtensionSystem;
using namespace ProjectExplorer;
using namespace TextEditor;
using namespace Utils;
namespace CC = Core::Constants;
namespace PE = ProjectExplorer::Constants;
namespace Debugger {
namespace Internal {
// To be passed through margin menu action's data
struct BreakpointMenuContextData : public ContextData
{
enum Mode
{
Breakpoint,
MessageTracePoint
};
BreakpointMenuContextData() : mode(Breakpoint) {}
Mode mode;
};
struct TestCallBack
{
TestCallBack() : receiver(0), slot(0) {}
TestCallBack(QObject *ob, const char *s) : receiver(ob), slot(s) {}
QObject *receiver;
const char *slot;
QVariant cookie;
};
} // namespace Internal
} // namespace Debugger
Q_DECLARE_METATYPE(Debugger::Internal::BreakpointMenuContextData)
Q_DECLARE_METATYPE(Debugger::Internal::TestCallBack)
namespace Debugger {
namespace Internal {
void addCdbOptionPages(QList<IOptionsPage*> *opts);
void addGdbOptionPages(QList<IOptionsPage*> *opts);
static QToolButton *toolButton(QAction *action)
{
QToolButton *button = new QToolButton;
button->setDefaultAction(action);
return button;
}
static void setProxyAction(ProxyAction *proxy, Core::Id id)
{
proxy->setAction(ActionManager::command(id)->action());
}
static QToolButton *toolButton(Core::Id id)
{
return toolButton(ActionManager::command(id)->action());
}
///////////////////////////////////////////////////////////////////////
//
// DummyEngine
//
///////////////////////////////////////////////////////////////////////
class DummyEngine : public DebuggerEngine
{
Q_OBJECT
public:
DummyEngine() : DebuggerEngine(DebuggerStartParameters()) {}
~DummyEngine() {}
void setupEngine() {}
void setupInferior() {}
void runEngine() {}
void shutdownEngine() {}
void shutdownInferior() {}
bool hasCapability(unsigned cap) const;
bool acceptsBreakpoint(BreakpointModelId) const { return false; }
bool acceptsDebuggerCommands() const { return false; }
void selectThread(ThreadId) {}
};
bool DummyEngine::hasCapability(unsigned cap) const
{
// This can only be a first approximation of what to expect when running.
Project *project = ProjectTree::currentProject();
if (!project)
return 0;
Target *target = project->activeTarget();
QTC_ASSERT(target, return 0);
RunConfiguration *activeRc = target->activeRunConfiguration();
QTC_ASSERT(activeRc, return 0);
// This is a non-started Cdb or Gdb engine:
if (activeRc->extraAspect<Debugger::DebuggerRunConfigurationAspect>()->useCppDebugger())
return cap & (WatchpointByAddressCapability
| BreakConditionCapability
| TracePointCapability
| OperateNativeMixed
| OperateByInstructionCapability);
// This is a Qml or unknown engine.
return cap & AddWatcherCapability;
}
///////////////////////////////////////////////////////////////////////
//
// DebugMode
//
///////////////////////////////////////////////////////////////////////
class DebugMode : public IMode
{
public:
DebugMode()
{
setObjectName(QLatin1String("DebugMode"));
setContext(Context(C_DEBUGMODE, CC::C_NAVIGATION_PANE));
setDisplayName(DebuggerPlugin::tr("Debug"));
setIcon(QIcon(QLatin1String(":/debugger/images/mode_debug.png")));
setPriority(85);
setId(MODE_DEBUG);
}
~DebugMode()
{
delete m_widget;
}
};
///////////////////////////////////////////////////////////////////////
//
// Misc
//
///////////////////////////////////////////////////////////////////////
static QWidget *addSearch(BaseTreeView *treeView, const QString &title,
const char *objectName)
{
QAction *act = action(UseAlternatingRowColors);
treeView->setAlternatingRowColors(act->isChecked());
QObject::connect(act, &QAction::toggled,
treeView, &BaseTreeView::setAlternatingRowColorsHelper);
QWidget *widget = ItemViewFind::createSearchableWrapper(treeView);
widget->setObjectName(QLatin1String(objectName));
widget->setWindowTitle(title);
return widget;
}
static std::function<bool(const Kit *)> cdbMatcher(char wordWidth = 0)
{
return [wordWidth](const Kit *k) -> bool {
if (DebuggerKitInformation::engineType(k) != CdbEngineType
|| !DebuggerKitInformation::isValidDebugger(k)) {
return false;
}
if (wordWidth) {
const ToolChain *tc = ToolChainKitInformation::toolChain(k);
return tc && wordWidth == tc->targetAbi().wordWidth();
}
return true;
};
}
// Find a CDB kit for debugging unknown processes.
// On a 64bit OS, prefer a 64bit debugger.
static Kit *findUniversalCdbKit()
{
if (Utils::is64BitWindowsSystem()) {
if (Kit *cdb64Kit = KitManager::find(cdbMatcher(64)))
return cdb64Kit;
}
return KitManager::find(cdbMatcher());
}
static bool currentTextEditorPosition(ContextData *data)
{
BaseTextEditor *textEditor = BaseTextEditor::currentTextEditor();
if (!textEditor)
return false;
const TextDocument *document = textEditor->textDocument();
QTC_ASSERT(document, return false);
data->fileName = document->filePath().toString();
if (document->property(Constants::OPENED_WITH_DISASSEMBLY).toBool()) {
int lineNumber = textEditor->currentLine();
QString line = textEditor->textDocument()->plainText()
.section(QLatin1Char('\n'), lineNumber - 1, lineNumber - 1);
data->address = DisassemblerLine::addressFromDisassemblyLine(line);
} else {
data->lineNumber = textEditor->currentLine();
}
return true;
}
///////////////////////////////////////////////////////////////////////
//
// DebuggerPluginPrivate
//
///////////////////////////////////////////////////////////////////////
static DebuggerPluginPrivate *dd = 0;
/*!
\class Debugger::Internal::DebuggerCore
This is the "internal" interface of the debugger plugin that's
used by debugger views and debugger engines. The interface is
implemented in DebuggerPluginPrivate.
*/
/*!
\class Debugger::Internal::DebuggerPluginPrivate
Implementation of DebuggerCore.
*/
class DebuggerPluginPrivate : public QObject
{
Q_OBJECT
public:
explicit DebuggerPluginPrivate(DebuggerPlugin *plugin);
~DebuggerPluginPrivate();
bool initialize(const QStringList &arguments, QString *errorMessage);
void extensionsInitialized();
void aboutToShutdown();
void connectEngine(DebuggerEngine *engine);
void disconnectEngine() { connectEngine(0); }
DebuggerEngine *dummyEngine();
void setThreads(const QStringList &list, int index)
{
const bool state = m_threadBox->blockSignals(true);
m_threadBox->clear();
foreach (const QString &item, list)
m_threadBox->addItem(item);
m_threadBox->setCurrentIndex(index);
m_threadBox->blockSignals(state);
}
DebuggerRunControl *attachToRunningProcess(Kit *kit, DeviceProcessItem process);
void writeSettings()
{
m_debuggerSettings->writeSettings();
m_mainWindow->writeSettings();
}
void selectThread(int index)
{
ThreadId id = m_currentEngine->threadsHandler()->threadAt(index);
m_currentEngine->selectThread(id);
}
void breakpointSetMarginActionTriggered()
{
const QAction *action = qobject_cast<const QAction *>(sender());
QTC_ASSERT(action, return);
const BreakpointMenuContextData data =
action->data().value<BreakpointMenuContextData>();
QString message;
if (data.mode == BreakpointMenuContextData::MessageTracePoint) {
if (data.address) {
//: Message tracepoint: Address hit.
message = tr("0x%1 hit").arg(data.address, 0, 16);
} else {
//: Message tracepoint: %1 file, %2 line %3 function hit.
message = tr("%1:%2 %3() hit").arg(QFileInfo(data.fileName).fileName()).
arg(data.lineNumber).
arg(cppFunctionAt(data.fileName, data.lineNumber));
}
QInputDialog dialog; // Create wide input dialog.
dialog.setWindowFlags(dialog.windowFlags()
& ~(Qt::WindowContextHelpButtonHint|Qt::MSWindowsFixedSizeDialogHint));
dialog.resize(600, dialog.height());
dialog.setWindowTitle(tr("Add Message Tracepoint"));
dialog.setLabelText (tr("Message:"));
dialog.setTextValue(message);
if (dialog.exec() != QDialog::Accepted || dialog.textValue().isEmpty())
return;
message = dialog.textValue();
}
if (data.address)
toggleBreakpointByAddress(data.address, message);
else
toggleBreakpointByFileAndLine(data.fileName, data.lineNumber, message);
}
void breakpointRemoveMarginActionTriggered()
{
const QAction *act = qobject_cast<QAction *>(sender());
QTC_ASSERT(act, return);
BreakpointModelId id = act->data().value<BreakpointModelId>();
m_breakHandler->removeBreakpoint(id);
}
void breakpointEnableMarginActionTriggered()
{
const QAction *act = qobject_cast<QAction *>(sender());
QTC_ASSERT(act, return);
BreakpointModelId id = act->data().value<BreakpointModelId>();
breakHandler()->setEnabled(id, true);
}
void breakpointDisableMarginActionTriggered()
{
const QAction *act = qobject_cast<QAction *>(sender());
QTC_ASSERT(act, return);
BreakpointModelId id = act->data().value<BreakpointModelId>();
breakHandler()->setEnabled(id, false);
}
void updateWatchersHeader(int section, int, int newSize)
{
m_watchersView->header()->resizeSection(section, newSize);
m_returnView->header()->resizeSection(section, newSize);
}
void sourceFilesDockToggled(bool on)
{
if (on && m_currentEngine->state() == InferiorStopOk)
m_currentEngine->reloadSourceFiles();
}
void modulesDockToggled(bool on)
{
if (on && m_currentEngine->state() == InferiorStopOk)
m_currentEngine->reloadModules();
}
void registerDockToggled(bool on)
{
if (on && m_currentEngine->state() == InferiorStopOk)
m_currentEngine->reloadRegisters();
}
void synchronizeBreakpoints()
{
showMessage(QLatin1String("ATTEMPT SYNC"), LogDebug);
for (int i = 0, n = m_snapshotHandler->size(); i != n; ++i) {
if (DebuggerEngine *engine = m_snapshotHandler->at(i))
engine->attemptBreakpointSynchronization();
}
}
void editorOpened(Core::IEditor *editor);
void updateBreakMenuItem(Core::IEditor *editor);
void setBusyCursor(bool busy);
void requestMark(TextEditor::TextEditorWidget *widget, int lineNumber,
TextEditor::TextMarkRequestKind kind);
void requestContextMenu(TextEditor::TextEditorWidget *widget,
int lineNumber, QMenu *menu);
void activatePreviousMode();
void activateDebugMode();
void toggleBreakpoint();
void toggleBreakpointByFileAndLine(const QString &fileName, int lineNumber,
const QString &tracePointMessage = QString());
void toggleBreakpointByAddress(quint64 address,
const QString &tracePointMessage = QString());
void onModeChanged(Core::IMode *mode);
void onCoreAboutToOpen();
void showSettingsDialog();
void updateDebugWithoutDeployMenu();
void debugProject();
void debugProjectWithoutDeploy();
void debugProjectBreakMain();
void startAndDebugApplication();
void startRemoteCdbSession();
void startRemoteServer();
void attachToRemoteServer();
void attachToProcess(bool startServerOnly);
void attachToRunningApplication();
void attachToUnstartedApplicationDialog();
void attachToFoundProcess();
void continueOnAttach(Debugger::DebuggerState state);
void attachToQmlPort();
Q_SLOT void runScheduled();
void attachCore();
void enableReverseDebuggingTriggered(const QVariant &value);
void showStatusMessage(const QString &msg, int timeout = -1);
DebuggerMainWindow *mainWindow() const { return m_mainWindow; }
bool isDockVisible(const QString &objectName) const
{
QDockWidget *dock = mainWindow()->findChild<QDockWidget *>(objectName);
return dock && dock->toggleViewAction()->isChecked();
}
void runControlStarted(DebuggerEngine *engine);
void runControlFinished(DebuggerEngine *engine);
void remoteCommand(const QStringList &options, const QStringList &);
void displayDebugger(DebuggerEngine *engine, bool updateEngine = true);
void dumpLog();
void cleanupViews();
void setInitialState();
void fontSettingsChanged(const TextEditor::FontSettings &settings);
void updateState(DebuggerEngine *engine);
void updateWatchersWindow(bool showWatch, bool showReturn);
void onCurrentProjectChanged(ProjectExplorer::Project *project);
void sessionLoaded();
void aboutToUnloadSession();
void aboutToSaveSession();
void coreShutdown();
#ifdef WITH_TESTS
public slots:
void testLoadProject(const QString &proFile, const TestCallBack &cb);
void testProjectLoaded(ProjectExplorer::Project *project);
void testProjectEvaluated();
void testProjectBuilt(bool success);
void testUnloadProject();
void testFinished();
void testRunProject(const DebuggerStartParameters &sp, const TestCallBack &cb);
void testRunControlFinished();
// void testStateMachine1();
// void testStateMachine2();
// void testStateMachine3();
void testBenchmark1();
public:
Project *m_testProject;
bool m_testSuccess;
QList<TestCallBack> m_testCallbacks;
#endif
public slots:
void updateDebugActions();
void handleExecDetach()
{
currentEngine()->resetLocation();
currentEngine()->detachDebugger();
}
void handleExecContinue()
{
currentEngine()->resetLocation();
currentEngine()->continueInferior();
}
void handleExecInterrupt()
{
currentEngine()->resetLocation();
currentEngine()->requestInterruptInferior();
}
void handleAbort()
{
currentEngine()->resetLocation();
currentEngine()->abortDebugger();
}
void handleReset()
{
currentEngine()->resetLocation();
currentEngine()->resetInferior();
}
void handleExecStep()
{
if (currentEngine()->state() == DebuggerNotReady) {
debugProjectBreakMain();
} else {
currentEngine()->resetLocation();
if (boolSetting(OperateByInstruction))
currentEngine()->executeStepI();
else
currentEngine()->executeStep();
}
}
void handleExecNext()
{
if (currentEngine()->state() == DebuggerNotReady) {
debugProjectBreakMain();
} else {
currentEngine()->resetLocation();
if (boolSetting(OperateByInstruction))
currentEngine()->executeNextI();
else
currentEngine()->executeNext();
}
}
void handleExecStepOut()
{
currentEngine()->resetLocation();
currentEngine()->executeStepOut();
}
void handleExecReturn()
{
currentEngine()->resetLocation();
currentEngine()->executeReturn();
}
void handleExecJumpToLine()
{
currentEngine()->resetLocation();
ContextData data;
if (currentTextEditorPosition(&data))
currentEngine()->executeJumpToLine(data);
}
void handleExecRunToLine()
{
currentEngine()->resetLocation();
ContextData data;
if (currentTextEditorPosition(&data))
currentEngine()->executeRunToLine(data);
}
void handleExecRunToSelectedFunction()
{
BaseTextEditor *textEditor = BaseTextEditor::currentTextEditor();
QTC_ASSERT(textEditor, return);
QTextCursor cursor = textEditor->textCursor();
QString functionName = cursor.selectedText();
if (functionName.isEmpty()) {
const QTextBlock block = cursor.block();
const QString line = block.text();
foreach (const QString &str, line.trimmed().split(QLatin1Char('('))) {
QString a;
for (int i = str.size(); --i >= 0; ) {
if (!str.at(i).isLetterOrNumber())
break;
a = str.at(i) + a;
}
if (!a.isEmpty()) {
functionName = a;
break;
}
}
}
if (functionName.isEmpty()) {
showStatusMessage(tr("No function selected."));
} else {
showStatusMessage(tr("Running to function \"%1\".")
.arg(functionName));
currentEngine()->resetLocation();
currentEngine()->executeRunToFunction(functionName);
}
}
void slotEditBreakpoint()
{
const QAction *act = qobject_cast<QAction *>(sender());
QTC_ASSERT(act, return);
const BreakpointModelId id = act->data().value<BreakpointModelId>();
QTC_ASSERT(id > 0, return);
BreakTreeView::editBreakpoint(id, ICore::dialogParent());
}
void slotRunToLine()
{
const QAction *action = qobject_cast<const QAction *>(sender());
QTC_ASSERT(action, return);
const BreakpointMenuContextData data = action->data().value<BreakpointMenuContextData>();
currentEngine()->executeRunToLine(data);
}
void slotJumpToLine()
{
const QAction *action = qobject_cast<const QAction *>(sender());
QTC_ASSERT(action, return);
const BreakpointMenuContextData data = action->data().value<BreakpointMenuContextData>();
currentEngine()->executeJumpToLine(data);
}
void slotDisassembleFunction()
{
const QAction *action = qobject_cast<const QAction *>(sender());
QTC_ASSERT(action, return);
const StackFrame frame = action->data().value<StackFrame>();
QTC_ASSERT(!frame.function.isEmpty(), return);
currentEngine()->openDisassemblerView(Location(frame));
}
void handleAddToWatchWindow()
{
// Requires a selection, but that's the only case we want anyway.
BaseTextEditor *textEditor = BaseTextEditor::currentTextEditor();
if (!textEditor)
return;
QTextCursor tc = textEditor->textCursor();
QString exp;
if (tc.hasSelection()) {
exp = tc.selectedText();
} else {
int line, column;
exp = cppExpressionAt(textEditor->editorWidget(), tc.position(), &line, &column);
}
if (currentEngine()->hasCapability(WatchComplexExpressionsCapability))
exp = removeObviousSideEffects(exp);
else
exp = fixCppExpression(exp);
if (exp.isEmpty())
return;
currentEngine()->watchHandler()->watchVariable(exp);
}
void handleExecExit()
{
currentEngine()->exitDebugger();
}
void handleFrameDown()
{
currentEngine()->frameDown();
}
void handleFrameUp()
{
currentEngine()->frameUp();
}
void handleOperateByInstructionTriggered(bool operateByInstructionTriggered)
{
// Go to source only if we have the file.
if (currentEngine()->stackHandler()->currentIndex() >= 0) {
const StackFrame frame = currentEngine()->stackHandler()->currentFrame();
if (operateByInstructionTriggered || frame.isUsable())
currentEngine()->gotoLocation(Location(frame, true));
}
}
void showMessage(const QString &msg, int channel, int timeout = -1);
bool parseArgument(QStringList::const_iterator &it,
const QStringList::const_iterator &cend, QString *errorMessage);
bool parseArguments(const QStringList &args, QString *errorMessage);
void parseCommandLineArguments();
void updateQmlActions() {
action(QmlUpdateOnSave)->setEnabled(boolSetting(ShowQmlObjectTree));
}
public:
DebuggerMainWindow *m_mainWindow;
DebuggerRunControlFactory *m_debuggerRunControlFactory;
Id m_previousMode;
QList<DebuggerStartParameters> m_scheduledStarts;
ProxyAction *m_visibleStartAction;
ProxyAction *m_hiddenStopAction;
QAction *m_startAction;
QAction *m_debugWithoutDeployAction;
QAction *m_startAndDebugApplicationAction;
QAction *m_startRemoteServerAction;
QAction *m_attachToRunningApplication;
QAction *m_attachToUnstartedApplication;
QAction *m_attachToQmlPortAction;
QAction *m_attachToRemoteServerAction;
QAction *m_startRemoteCdbAction;
QAction *m_attachToCoreAction;
QAction *m_detachAction;
QAction *m_continueAction;
QAction *m_exitAction; // On application output button if "Stop" is possible
QAction *m_interruptAction; // On the fat debug button if "Pause" is possible
QAction *m_undisturbableAction; // On the fat debug button if nothing can be done
QAction *m_abortAction;
QAction *m_stepAction;
QAction *m_stepOutAction;
QAction *m_runToLineAction; // In the debug menu
QAction *m_runToSelectedFunctionAction;
QAction *m_jumpToLineAction; // In the Debug menu.
QAction *m_returnFromFunctionAction;
QAction *m_nextAction;
QAction *m_watchAction1; // In the Debug menu.
QAction *m_watchAction2; // In the text editor context menu.
QAction *m_breakAction;
QAction *m_reverseDirectionAction;
QAction *m_frameUpAction;
QAction *m_frameDownAction;
QAction *m_resetAction;
QToolButton *m_reverseToolButton;
QIcon m_startIcon;
QIcon m_exitIcon;
QIcon m_continueIcon;
QIcon m_interruptIcon;
QIcon m_locationMarkIcon;
QIcon m_resetIcon;
StatusLabel *m_statusLabel;
QComboBox *m_threadBox;
BaseTreeView *m_breakView;
BaseTreeView *m_returnView;
BaseTreeView *m_localsView;
BaseTreeView *m_watchersView;
BaseTreeView *m_inspectorView;
BaseTreeView *m_registerView;
BaseTreeView *m_modulesView;
BaseTreeView *m_snapshotView;
BaseTreeView *m_sourceFilesView;
BaseTreeView *m_stackView;
BaseTreeView *m_threadsView;
QWidget *m_breakWindow;
BreakHandler *m_breakHandler;
QWidget *m_returnWindow;
QWidget *m_localsWindow;
QWidget *m_watchersWindow;
QWidget *m_inspectorWindow;
QWidget *m_registerWindow;
QWidget *m_modulesWindow;
QWidget *m_snapshotWindow;
QWidget *m_sourceFilesWindow;
QWidget *m_stackWindow;
QWidget *m_threadsWindow;
LogWindow *m_logWindow;
LocalsAndExpressionsWindow *m_localsAndExpressionsWindow;
bool m_busy;
QString m_lastPermanentStatusMessage;
mutable CPlusPlus::Snapshot m_codeModelSnapshot;
DebuggerPlugin *m_plugin;
SnapshotHandler *m_snapshotHandler;
bool m_shuttingDown;
DebuggerEngine *m_currentEngine;
DebuggerSettings *m_debuggerSettings;
QStringList m_arguments;
DebuggerToolTipManager m_toolTipManager;
CommonOptionsPage *m_commonOptionsPage;
DummyEngine *m_dummyEngine;
const QSharedPointer<GlobalDebuggerOptions> m_globalDebuggerOptions;
};
DebuggerPluginPrivate::DebuggerPluginPrivate(DebuggerPlugin *plugin) :
m_dummyEngine(0),
m_globalDebuggerOptions(new GlobalDebuggerOptions)
{
qRegisterMetaType<WatchData>("WatchData");
qRegisterMetaType<ContextData>("ContextData");
qRegisterMetaType<DebuggerStartParameters>("DebuggerStartParameters");
QTC_CHECK(!dd);
dd = this;
m_plugin = plugin;
m_startRemoteCdbAction = 0;
m_shuttingDown = false;
m_statusLabel = 0;
m_threadBox = 0;
m_breakWindow = 0;
m_breakHandler = 0;
m_returnWindow = 0;
m_localsWindow = 0;
m_watchersWindow = 0;
m_inspectorWindow = 0;
m_registerWindow = 0;
m_modulesWindow = 0;
m_snapshotWindow = 0;
m_sourceFilesWindow = 0;
m_stackWindow = 0;
m_threadsWindow = 0;
m_logWindow = 0;
m_localsAndExpressionsWindow = 0;
m_mainWindow = 0;
m_snapshotHandler = 0;
m_currentEngine = 0;
m_debuggerSettings = 0;
m_reverseToolButton = 0;
m_startAction = 0;
m_debugWithoutDeployAction = 0;
m_startAndDebugApplicationAction = 0;
m_attachToRemoteServerAction = 0;
m_attachToRunningApplication = 0;
m_attachToUnstartedApplication = 0;
m_attachToQmlPortAction = 0;
m_startRemoteCdbAction = 0;
m_attachToCoreAction = 0;
m_detachAction = 0;
m_commonOptionsPage = 0;
}
DebuggerPluginPrivate::~DebuggerPluginPrivate()
{
delete m_debuggerSettings;
m_debuggerSettings = 0;
// Mainwindow will be deleted by debug mode.
delete m_snapshotHandler;
m_snapshotHandler = 0;
delete m_breakHandler;
m_breakHandler = 0;
}
DebuggerEngine *DebuggerPluginPrivate::dummyEngine()
{
if (!m_dummyEngine) {
m_dummyEngine = new DummyEngine;
m_dummyEngine->setParent(this);
m_dummyEngine->setObjectName(_("DummyEngine"));
}
return m_dummyEngine;
}
static QString msgParameterMissing(const QString &a)
{
return DebuggerPlugin::tr("Option \"%1\" is missing the parameter.").arg(a);
}
bool DebuggerPluginPrivate::parseArgument(QStringList::const_iterator &it,
const QStringList::const_iterator &cend, QString *errorMessage)
{
const QString &option = *it;
// '-debug <pid>'
// '-debug <exe>[,server=<server:port>][,core=<core>][,kit=<kit>]'
if (*it == _("-debug")) {
++it;
if (it == cend) {
*errorMessage = msgParameterMissing(*it);
return false;
}
Kit *kit = 0;
DebuggerStartParameters sp;
qulonglong pid = it->toULongLong();
if (pid) {
sp.startMode = AttachExternal;
sp.closeMode = DetachAtClose;
sp.attachPID = pid;
sp.displayName = tr("Process %1").arg(sp.attachPID);
sp.startMessage = tr("Attaching to local process %1.").arg(sp.attachPID);
} else {
sp.startMode = StartExternal;
QStringList args = it->split(QLatin1Char(','));
foreach (const QString &arg, args) {
QString key = arg.section(QLatin1Char('='), 0, 0);
QString val = arg.section(QLatin1Char('='), 1, 1);
if (val.isEmpty()) {
if (key.isEmpty()) {
continue;
} else if (sp.executable.isEmpty()) {
sp.executable = key;
} else {
*errorMessage = DebuggerPlugin::tr("Only one executable allowed.");
return false;
}
}
if (key == QLatin1String("server")) {
sp.startMode = AttachToRemoteServer;
sp.remoteChannel = val;
sp.displayName = tr("Remote: \"%1\"").arg(sp.remoteChannel);
sp.startMessage = tr("Attaching to remote server %1.").arg(sp.remoteChannel);
} else if (key == QLatin1String("core")) {
sp.startMode = AttachCore;
sp.closeMode = DetachAtClose;
sp.coreFile = val;
sp.displayName = tr("Core file \"%1\"").arg(sp.coreFile);
sp.startMessage = tr("Attaching to core file %1.").arg(sp.coreFile);
} else if (key == QLatin1String("kit")) {
kit = KitManager::find(Id::fromString(val));
}
}
}
if (!DebuggerRunControlFactory::fillParametersFromKit(&sp, kit, errorMessage))
return false;
if (sp.startMode == StartExternal) {
sp.displayName = tr("Executable file \"%1\"").arg(sp.executable);
sp.startMessage = tr("Debugging file %1.").arg(sp.executable);
}
m_scheduledStarts.append(sp);
return true;
}
// -wincrashevent <event-handle>:<pid>. A handle used for
// a handshake when attaching to a crashed Windows process.
// This is created by $QTC/src/tools/qtcdebugger/main.cpp:
// args << QLatin1String("-wincrashevent")
// << QString::fromLatin1("%1:%2").arg(argWinCrashEvent).arg(argProcessId);
if (*it == _("-wincrashevent")) {
++it;
if (it == cend) {
*errorMessage = msgParameterMissing(*it);
return false;
}
DebuggerStartParameters sp;
if (!DebuggerRunControlFactory::fillParametersFromKit(&sp, findUniversalCdbKit(), errorMessage))
return false;
sp.startMode = AttachCrashedExternal;
sp.crashParameter = it->section(QLatin1Char(':'), 0, 0);
sp.attachPID = it->section(QLatin1Char(':'), 1, 1).toULongLong();
sp.displayName = tr("Crashed process %1").arg(sp.attachPID);
sp.startMessage = tr("Attaching to crashed process %1").arg(sp.attachPID);
if (!sp.attachPID) {
*errorMessage = DebuggerPlugin::tr("The parameter \"%1\" of option \"%2\" "
"does not match the pattern <handle>:<pid>.").arg(*it, option);
return false;
}
m_scheduledStarts.append(sp);
return true;
}
*errorMessage = DebuggerPlugin::tr("Invalid debugger option: %1").arg(option);
return false;
}
bool DebuggerPluginPrivate::parseArguments(const QStringList &args,
QString *errorMessage)
{
const QStringList::const_iterator cend = args.constEnd();
for (QStringList::const_iterator it = args.constBegin(); it != cend; ++it)
if (!parseArgument(it, cend, errorMessage))
return false;
return true;
}
void DebuggerPluginPrivate::parseCommandLineArguments()
{
QString errorMessage;
if (!parseArguments(m_arguments, &errorMessage)) {
errorMessage = tr("Error evaluating command line arguments: %1")
.arg(errorMessage);
qWarning("%s\n", qPrintable(errorMessage));
MessageManager::write(errorMessage);
}
if (!m_scheduledStarts.isEmpty())
QTimer::singleShot(0, this, SLOT(runScheduled()));
}
bool DebuggerPluginPrivate::initialize(const QStringList &arguments,
QString *errorMessage)
{
Q_UNUSED(errorMessage);
m_arguments = arguments;
if (!m_arguments.isEmpty())
connect(KitManager::instance(), &KitManager::kitsLoaded,
this, &DebuggerPluginPrivate::parseCommandLineArguments);
// Cpp/Qml ui setup
m_mainWindow = new DebuggerMainWindow;
TaskHub::addCategory(Debugger::Constants::TASK_CATEGORY_DEBUGGER_DEBUGINFO,
tr("Debug Information"));
TaskHub::addCategory(Debugger::Constants::TASK_CATEGORY_DEBUGGER_RUNTIME,
tr("Debugger Runtime"));
return true;
}
void setConfigValue(const QByteArray &name, const QVariant &value)
{
ICore::settings()->setValue(_("DebugMode/" + name), value);
}
QVariant configValue(const QByteArray &name)
{
return ICore::settings()->value(_("DebugMode/" + name));
}
void DebuggerPluginPrivate::onCurrentProjectChanged(Project *project)
{
RunConfiguration *activeRc = 0;
if (project) {
Target *target = project->activeTarget();
if (target)
activeRc = target->activeRunConfiguration();
if (!activeRc)
return;
}
for (int i = 0, n = m_snapshotHandler->size(); i != n; ++i) {
// Run controls might be deleted during exit.
if (DebuggerEngine *engine = m_snapshotHandler->at(i)) {
DebuggerRunControl *runControl = engine->runControl();
RunConfiguration *rc = runControl->runConfiguration();
if (rc == activeRc) {
m_snapshotHandler->setCurrentIndex(i);
updateState(engine);
return;
}
}
}
// If we have a running debugger, don't touch it.
if (m_snapshotHandler->size())
return;
// No corresponding debugger found. So we are ready to start one.
m_interruptAction->setEnabled(false);
m_continueAction->setEnabled(false);
m_exitAction->setEnabled(false);
QString whyNot;
const bool canRun = ProjectExplorerPlugin::canRun(project, DebugRunMode, &whyNot);
m_startAction->setEnabled(canRun);
m_startAction->setToolTip(whyNot);
m_debugWithoutDeployAction->setEnabled(canRun);
setProxyAction(m_visibleStartAction, Core::Id(Constants::DEBUG));
}
void DebuggerPluginPrivate::debugProject()
{
ProjectExplorerPlugin::runProject(SessionManager::startupProject(), DebugRunMode);
}
void DebuggerPluginPrivate::debugProjectWithoutDeploy()
{
ProjectExplorerPlugin::runProject(SessionManager::startupProject(), DebugRunMode, true);
}
void DebuggerPluginPrivate::debugProjectBreakMain()
{
ProjectExplorerPlugin::runProject(SessionManager::startupProject(), DebugRunModeWithBreakOnMain);
}
void DebuggerPluginPrivate::startAndDebugApplication()
{
DebuggerStartParameters sp;
if (StartApplicationDialog::run(ICore::dialogParent(), &sp))
DebuggerRunControlFactory::createAndScheduleRun(sp);
}
void DebuggerPluginPrivate::attachCore()
{
AttachCoreDialog dlg(ICore::dialogParent());
const QString lastExternalKit = configValue("LastExternalKit").toString();
if (!lastExternalKit.isEmpty())
dlg.setKitId(Id::fromString(lastExternalKit));
dlg.setLocalExecutableFile(configValue("LastExternalExecutableFile").toString());
dlg.setLocalCoreFile(configValue("LastLocalCoreFile").toString());
dlg.setRemoteCoreFile(configValue("LastRemoteCoreFile").toString());
dlg.setOverrideStartScript(configValue("LastExternalStartScript").toString());
dlg.setForceLocalCoreFile(configValue("LastForceLocalCoreFile").toBool());
if (dlg.exec() != QDialog::Accepted)
return;
setConfigValue("LastExternalExecutableFile", dlg.localExecutableFile());
setConfigValue("LastLocalCoreFile", dlg.localCoreFile());
setConfigValue("LastRemoteCoreFile", dlg.remoteCoreFile());
setConfigValue("LastExternalKit", dlg.kit()->id().toSetting());
setConfigValue("LastExternalStartScript", dlg.overrideStartScript());
setConfigValue("LastForceLocalCoreFile", dlg.forcesLocalCoreFile());
QString display = dlg.useLocalCoreFile() ? dlg.localCoreFile() : dlg.remoteCoreFile();
DebuggerStartParameters sp;
bool res = DebuggerRunControlFactory::fillParametersFromKit(&sp, dlg.kit());
QTC_ASSERT(res, return);
sp.masterEngineType = DebuggerKitInformation::engineType(dlg.kit());
sp.executable = dlg.localExecutableFile();
sp.coreFile = dlg.localCoreFile();
sp.displayName = tr("Core file \"%1\"").arg(display);
sp.startMode = AttachCore;
sp.closeMode = DetachAtClose;
sp.overrideStartScript = dlg.overrideStartScript();
DebuggerRunControlFactory::createAndScheduleRun(sp);
}
void DebuggerPluginPrivate::startRemoteCdbSession()
{
const QByteArray connectionKey = "CdbRemoteConnection";
DebuggerStartParameters sp;
Kit *kit = findUniversalCdbKit();
QTC_ASSERT(kit, return);
bool res = DebuggerRunControlFactory::fillParametersFromKit(&sp, kit);
QTC_ASSERT(res, return);
sp.startMode = AttachToRemoteServer;
sp.closeMode = KillAtClose;
StartRemoteCdbDialog dlg(ICore::dialogParent());
QString previousConnection = configValue(connectionKey).toString();
if (previousConnection.isEmpty())
previousConnection = QLatin1String("localhost:1234");
dlg.setConnection(previousConnection);
if (dlg.exec() != QDialog::Accepted)
return;
sp.remoteChannel = dlg.connection();
setConfigValue(connectionKey, sp.remoteChannel);
DebuggerRunControlFactory::createAndScheduleRun(sp);
}
void DebuggerPluginPrivate::attachToRemoteServer()
{
DebuggerStartParameters sp;
sp.startMode = AttachToRemoteServer;
if (StartApplicationDialog::run(ICore::dialogParent(), &sp)) {
sp.closeMode = KillAtClose;
sp.serverStartScript.clear();
DebuggerRunControlFactory::createAndScheduleRun(sp);
}
}
void DebuggerPluginPrivate::startRemoteServer()
{
attachToProcess(true);
}
void DebuggerPluginPrivate::attachToRunningApplication()
{
attachToProcess(false);
}
void DebuggerPluginPrivate::attachToProcess(bool startServerOnly)
{
const DebuggerKitChooser::Mode mode = startServerOnly ?
DebuggerKitChooser::RemoteDebugging : DebuggerKitChooser::LocalDebugging;
DebuggerKitChooser *kitChooser = new DebuggerKitChooser(mode);
DeviceProcessesDialog *dlg = new DeviceProcessesDialog(kitChooser, ICore::dialogParent());
dlg->addAcceptButton(ProjectExplorer::DeviceProcessesDialog::tr("&Attach to Process"));
dlg->showAllDevices();
if (dlg->exec() == QDialog::Rejected) {
delete dlg;
return;
}
dlg->setAttribute(Qt::WA_DeleteOnClose);
Kit *kit = kitChooser->currentKit();
QTC_ASSERT(kit, return);
IDevice::ConstPtr device = DeviceKitInformation::device(kit);
QTC_ASSERT(device, return);
if (device->type() != PE::DESKTOP_DEVICE_TYPE) {
GdbServerStarter *starter = new GdbServerStarter(dlg, startServerOnly);
starter->run();
} else {
attachToRunningProcess(kit, dlg->currentProcess());
}
}
void DebuggerPluginPrivate::attachToUnstartedApplicationDialog()
{
UnstartedAppWatcherDialog *dlg = new UnstartedAppWatcherDialog(ICore::dialogParent());
connect(dlg, &QDialog::finished, dlg, &QObject::deleteLater);
connect(dlg, &UnstartedAppWatcherDialog::processFound, this, &DebuggerPluginPrivate::attachToFoundProcess);
dlg->show();
}
void DebuggerPluginPrivate::attachToFoundProcess()
{
UnstartedAppWatcherDialog *dlg = qobject_cast<UnstartedAppWatcherDialog *>(QObject::sender());
if (!dlg)
return;
DebuggerRunControl *rc = attachToRunningProcess(dlg->currentKit(), dlg->currentProcess());
if (!rc)
return;
if (dlg->hideOnAttach())
connect(rc, &RunControl::finished, dlg, &UnstartedAppWatcherDialog::startWatching);
if (dlg->continueOnAttach()) {
connect(currentEngine(), &DebuggerEngine::stateChanged,
this, &DebuggerPluginPrivate::continueOnAttach);
}
}
void DebuggerPluginPrivate::continueOnAttach(Debugger::DebuggerState state)
{
// wait for state when we can continue
if (state != InferiorStopOk)
return;
// disconnect and continue
disconnect(currentEngine(), &DebuggerEngine::stateChanged,
this, &DebuggerPluginPrivate::continueOnAttach);
handleExecContinue();
}
DebuggerRunControl *DebuggerPluginPrivate::attachToRunningProcess(Kit *kit,
DeviceProcessItem process)
{
QTC_ASSERT(kit, return 0);
IDevice::ConstPtr device = DeviceKitInformation::device(kit);
QTC_ASSERT(device, return 0);
if (process.pid == 0) {
Core::AsynchronousMessageBox::warning(tr("Warning"),
tr("Cannot attach to process with PID 0"));
return 0;
}
bool isWindows = false;
if (const ToolChain *tc = ToolChainKitInformation::toolChain(kit))
isWindows = tc->targetAbi().os() == Abi::WindowsOS;
if (isWindows && isWinProcessBeingDebugged(process.pid)) {
Core::AsynchronousMessageBox::warning(tr("Process Already Under Debugger Control"),
tr("The process %1 is already under the control of a debugger.\n"
"Qt Creator cannot attach to it.").arg(process.pid));
return 0;
}
if (device->type() != PE::DESKTOP_DEVICE_TYPE) {
Core::AsynchronousMessageBox::warning(tr("Not a Desktop Device Type"),
tr("It is only possible to attach to a locally running process."));
return 0;
}
DebuggerStartParameters sp;
bool res = DebuggerRunControlFactory::fillParametersFromKit(&sp, kit);
QTC_ASSERT(res, return 0);
sp.attachPID = process.pid;
sp.displayName = tr("Process %1").arg(process.pid);
sp.executable = process.exe;
sp.startMode = AttachExternal;
sp.closeMode = DetachAtClose;
return DebuggerRunControlFactory::createAndScheduleRun(sp);
}
void DebuggerPlugin::attachExternalApplication(RunControl *rc)
{
DebuggerStartParameters sp;
sp.attachPID = rc->applicationProcessHandle().pid();
sp.displayName = tr("Process %1").arg(sp.attachPID);
sp.startMode = AttachExternal;
sp.closeMode = DetachAtClose;
sp.toolChainAbi = rc->abi();
Kit *kit = 0;
if (const RunConfiguration *runConfiguration = rc->runConfiguration())
if (const Target *target = runConfiguration->target())
kit = target->kit();
bool res = DebuggerRunControlFactory::fillParametersFromKit(&sp, kit);
QTC_ASSERT(res, return);
DebuggerRunControlFactory::createAndScheduleRun(sp);
}
void DebuggerPluginPrivate::attachToQmlPort()
{
DebuggerStartParameters sp;
AttachToQmlPortDialog dlg(ICore::mainWindow());
const QVariant qmlServerPort = configValue("LastQmlServerPort");
if (qmlServerPort.isValid())
dlg.setPort(qmlServerPort.toInt());
else
dlg.setPort(sp.qmlServerPort);
const Id kitId = Id::fromSetting(configValue("LastProfile"));
if (kitId.isValid())
dlg.setKitId(kitId);
if (dlg.exec() != QDialog::Accepted)
return;
Kit *kit = dlg.kit();
QTC_ASSERT(kit, return);
bool res = DebuggerRunControlFactory::fillParametersFromKit(&sp, kit);
QTC_ASSERT(res, return);
setConfigValue("LastQmlServerPort", dlg.port());
setConfigValue("LastProfile", kit->id().toSetting());
IDevice::ConstPtr device = DeviceKitInformation::device(kit);
if (device) {
sp.connParams = device->sshParameters();
sp.qmlServerAddress = device->qmlProfilerHost();
}
sp.qmlServerPort = dlg.port();
sp.startMode = AttachToRemoteProcess;
sp.closeMode = KillAtClose;
sp.languages = QmlLanguage;
sp.masterEngineType = QmlEngineType;
//
// get files from all the projects in the session
//
QList<Project *> projects = SessionManager::projects();
if (Project *startupProject = SessionManager::startupProject()) {
// startup project first
projects.removeOne(startupProject);
projects.insert(0, startupProject);
}
QStringList sourceFiles;
foreach (Project *project, projects)
sourceFiles << project->files(Project::ExcludeGeneratedFiles);
sp.projectSourceDirectory =
!projects.isEmpty() ? projects.first()->projectDirectory().toString() : QString();
sp.projectSourceFiles = sourceFiles;
sp.sysRoot = SysRootKitInformation::sysRoot(kit).toString();
DebuggerRunControlFactory::createAndScheduleRun(sp);
}
void DebuggerPluginPrivate::enableReverseDebuggingTriggered(const QVariant &value)
{
QTC_ASSERT(m_reverseToolButton, return);
m_reverseToolButton->setVisible(value.toBool());
m_reverseDirectionAction->setChecked(false);
m_reverseDirectionAction->setEnabled(value.toBool());
}
void DebuggerPluginPrivate::runScheduled()
{
foreach (const DebuggerStartParameters &sp, m_scheduledStarts)
DebuggerRunControlFactory::createAndScheduleRun(sp);
}
void DebuggerPluginPrivate::editorOpened(IEditor *editor)
{
if (auto widget = qobject_cast<TextEditorWidget *>(editor->widget())) {
connect(widget, &TextEditorWidget::markRequested,
this, &DebuggerPluginPrivate::requestMark);
connect(widget, &TextEditorWidget::markContextMenuRequested,
this, &DebuggerPluginPrivate::requestContextMenu);
}
}
void DebuggerPluginPrivate::updateBreakMenuItem(IEditor *editor)
{
BaseTextEditor *textEditor = qobject_cast<BaseTextEditor *>(editor);
m_breakAction->setEnabled(textEditor != 0);
}
void DebuggerPluginPrivate::requestContextMenu(TextEditorWidget *widget,
int lineNumber, QMenu *menu)
{
BreakpointMenuContextData args;
args.lineNumber = lineNumber;
bool contextUsable = true;
BreakpointModelId id = BreakpointModelId();
TextDocument *document = widget->textDocument();
args.fileName = document->filePath().toString();
if (document->property(Constants::OPENED_WITH_DISASSEMBLY).toBool()) {
QString line = document->plainText()
.section(QLatin1Char('\n'), lineNumber - 1, lineNumber - 1);
BreakpointResponse needle;
needle.type = BreakpointByAddress;
needle.address = DisassemblerLine::addressFromDisassemblyLine(line);
args.address = needle.address;
needle.lineNumber = -1;
id = breakHandler()->findSimilarBreakpoint(needle);
contextUsable = args.address != 0;
} else {
id = breakHandler()
->findBreakpointByFileAndLine(args.fileName, lineNumber);
if (!id)
id = breakHandler()->findBreakpointByFileAndLine(args.fileName, lineNumber, false);
}
if (id) {
// Remove existing breakpoint.
QAction *act = new QAction(menu);
act->setData(QVariant::fromValue(id));
act->setText(tr("Remove Breakpoint %1").arg(id.toString()));
connect(act, &QAction::triggered,
this, &DebuggerPluginPrivate::breakpointRemoveMarginActionTriggered);
menu->addAction(act);
// Enable/disable existing breakpoint.
act = new QAction(menu);
act->setData(QVariant::fromValue(id));
if (breakHandler()->isEnabled(id)) {
act->setText(tr("Disable Breakpoint %1").arg(id.toString()));
connect(act, &QAction::triggered,
this, &DebuggerPluginPrivate::breakpointDisableMarginActionTriggered);
} else {
act->setText(tr("Enable Breakpoint %1").arg(id.toString()));
connect(act, &QAction::triggered,
this, &DebuggerPluginPrivate::breakpointEnableMarginActionTriggered);
}
menu->addAction(act);
// Edit existing breakpoint.
act = new QAction(menu);
act->setText(tr("Edit Breakpoint %1...").arg(id.toString()));
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::slotEditBreakpoint);
act->setData(QVariant::fromValue(id));
menu->addAction(act);
} else {
// Handle non-existing breakpoint.
const QString text = args.address
? tr("Set Breakpoint at 0x%1").arg(args.address, 0, 16)
: tr("Set Breakpoint at Line %1").arg(lineNumber);
QAction *act = new QAction(text, menu);
act->setData(QVariant::fromValue(args));
act->setEnabled(contextUsable);
connect(act, &QAction::triggered,
this, &DebuggerPluginPrivate::breakpointSetMarginActionTriggered);
menu->addAction(act);
// Message trace point
args.mode = BreakpointMenuContextData::MessageTracePoint;
const QString tracePointText = args.address
? tr("Set Message Tracepoint at 0x%1...").arg(args.address, 0, 16)
: tr("Set Message Tracepoint at Line %1...").arg(lineNumber);
act = new QAction(tracePointText, menu);
act->setData(QVariant::fromValue(args));
act->setEnabled(contextUsable);
connect(act, &QAction::triggered,
this, &DebuggerPluginPrivate::breakpointSetMarginActionTriggered);
menu->addAction(act);
}
// Run to, jump to line below in stopped state.
if (currentEngine()->state() == InferiorStopOk && contextUsable) {
menu->addSeparator();
if (currentEngine()->hasCapability(RunToLineCapability)) {
const QString runText = args.address
? DebuggerEngine::tr("Run to Address 0x%1").arg(args.address, 0, 16)
: DebuggerEngine::tr("Run to Line %1").arg(args.lineNumber);
QAction *runToLineAction = new QAction(runText, menu);
runToLineAction->setData(QVariant::fromValue(args));
connect(runToLineAction, &QAction::triggered, this, &DebuggerPluginPrivate::slotRunToLine);
menu->addAction(runToLineAction);
}
if (currentEngine()->hasCapability(JumpToLineCapability)) {
const QString jumpText = args.address
? DebuggerEngine::tr("Jump to Address 0x%1").arg(args.address, 0, 16)
: DebuggerEngine::tr("Jump to Line %1").arg(args.lineNumber);
QAction *jumpToLineAction = new QAction(jumpText, menu);
jumpToLineAction->setData(QVariant::fromValue(args));
connect(jumpToLineAction, &QAction::triggered, this, &DebuggerPluginPrivate::slotJumpToLine);
menu->addAction(jumpToLineAction);
}
// Disassemble current function in stopped state.
if (currentEngine()->state() == InferiorStopOk
&& currentEngine()->hasCapability(DisassemblerCapability)) {
StackFrame frame;
frame.function = cppFunctionAt(args.fileName, lineNumber);
frame.line = 42; // trick gdb into mixed mode.
if (!frame.function.isEmpty()) {
const QString text = tr("Disassemble Function \"%1\"")
.arg(frame.function);
QAction *disassembleAction = new QAction(text, menu);
disassembleAction->setData(QVariant::fromValue(frame));
connect(disassembleAction, &QAction::triggered, this, &DebuggerPluginPrivate::slotDisassembleFunction);
menu->addAction(disassembleAction );
}
}
}
}
void DebuggerPluginPrivate::toggleBreakpoint()
{
BaseTextEditor *textEditor = BaseTextEditor::currentTextEditor();
QTC_ASSERT(textEditor, return);
const int lineNumber = textEditor->currentLine();
if (textEditor->property(Constants::OPENED_WITH_DISASSEMBLY).toBool()) {
QString line = textEditor->textDocument()->plainText()
.section(QLatin1Char('\n'), lineNumber - 1, lineNumber - 1);
quint64 address = DisassemblerLine::addressFromDisassemblyLine(line);
toggleBreakpointByAddress(address);
} else if (lineNumber >= 0) {
toggleBreakpointByFileAndLine(textEditor->document()->filePath().toString(), lineNumber);
}
}
void DebuggerPluginPrivate::toggleBreakpointByFileAndLine(const QString &fileName,
int lineNumber, const QString &tracePointMessage)
{
BreakHandler *handler = m_breakHandler;
BreakpointModelId id =
handler->findBreakpointByFileAndLine(fileName, lineNumber, true);
if (!id)
id = handler->findBreakpointByFileAndLine(fileName, lineNumber, false);
if (id) {
handler->removeBreakpoint(id);
} else {
BreakpointParameters data(BreakpointByFileAndLine);
if (boolSetting(BreakpointsFullPathByDefault))
data.pathUsage = BreakpointUseFullPath;
data.tracepoint = !tracePointMessage.isEmpty();
data.message = tracePointMessage;
data.fileName = fileName;
data.lineNumber = lineNumber;
handler->appendBreakpoint(data);
}
}
void DebuggerPluginPrivate::toggleBreakpointByAddress(quint64 address,
const QString &tracePointMessage)
{
BreakHandler *handler = m_breakHandler;
BreakpointModelId id = handler->findBreakpointByAddress(address);
if (id) {
handler->removeBreakpoint(id);
} else {
BreakpointParameters data(BreakpointByAddress);
data.tracepoint = !tracePointMessage.isEmpty();
data.message = tracePointMessage;
data.address = address;
handler->appendBreakpoint(data);
}
}
void DebuggerPluginPrivate::requestMark(TextEditorWidget *widget, int lineNumber,
TextMarkRequestKind kind)
{
if (kind != BreakpointRequest)
return;
TextDocument *document = widget->textDocument();
if (document->property(Constants::OPENED_WITH_DISASSEMBLY).toBool()) {
QString line = document->plainText()
.section(QLatin1Char('\n'), lineNumber - 1, lineNumber - 1);
quint64 address = DisassemblerLine::addressFromDisassemblyLine(line);
toggleBreakpointByAddress(address);
} else {
toggleBreakpointByFileAndLine(document->filePath().toString(), lineNumber);
}
}
// If updateEngine is set, the engine will update its threads/modules and so forth.
void DebuggerPluginPrivate::displayDebugger(DebuggerEngine *engine, bool updateEngine)
{
QTC_ASSERT(engine, return);
disconnectEngine();
connectEngine(engine);
if (updateEngine)
engine->updateAll();
engine->updateViews();
}
void DebuggerPluginPrivate::connectEngine(DebuggerEngine *engine)
{
if (!engine)
engine = dummyEngine();
if (m_currentEngine == engine)
return;
if (m_currentEngine)
m_currentEngine->resetLocation();
m_currentEngine = engine;
m_localsView->setModel(engine->watchModel());
m_modulesView->setModel(engine->modulesModel());
m_registerView->setModel(engine->registerModel());
m_returnView->setModel(engine->watchModel());
m_sourceFilesView->setModel(engine->sourceFilesModel());
m_stackView->setModel(engine->stackModel());
m_threadsView->setModel(engine->threadsModel());
m_watchersView->setModel(engine->watchModel());
m_inspectorView->setModel(engine->watchModel());
mainWindow()->setEngineDebugLanguages(engine->startParameters().languages);
}
static void changeFontSize(QWidget *widget, qreal size)
{
QFont font = widget->font();
font.setPointSizeF(size);
widget->setFont(font);
}
void DebuggerPluginPrivate::fontSettingsChanged
(const TextEditor::FontSettings &settings)
{
if (!boolSetting(FontSizeFollowsEditor))
return;
qreal size = settings.fontZoom() * settings.fontSize() / 100.;
changeFontSize(m_breakWindow, size);
changeFontSize(m_logWindow, size);
changeFontSize(m_localsWindow, size);
changeFontSize(m_modulesWindow, size);
//changeFontSize(m_consoleWindow, size);
changeFontSize(m_registerWindow, size);
changeFontSize(m_returnWindow, size);
changeFontSize(m_sourceFilesWindow, size);
changeFontSize(m_stackWindow, size);
changeFontSize(m_threadsWindow, size);
changeFontSize(m_watchersWindow, size);
changeFontSize(m_inspectorWindow, size);
}
void DebuggerPluginPrivate::cleanupViews()
{
m_reverseDirectionAction->setChecked(false);
m_reverseDirectionAction->setEnabled(false);
const bool closeSource = boolSetting(CloseSourceBuffersOnExit);
const bool closeMemory = boolSetting(CloseMemoryBuffersOnExit);
QList<IDocument *> toClose;
foreach (IDocument *document, DocumentModel::openedDocuments()) {
const bool isMemory = document->property(Constants::OPENED_WITH_DISASSEMBLY).toBool();
if (document->property(Constants::OPENED_BY_DEBUGGER).toBool()) {
bool keepIt = true;
if (document->isModified())
keepIt = true;
else if (document->filePath().toString().contains(_("qeventdispatcher")))
keepIt = false;
else if (isMemory)
keepIt = !closeMemory;
else
keepIt = !closeSource;
if (keepIt)
document->setProperty(Constants::OPENED_BY_DEBUGGER, false);
else
toClose.append(document);
}
}
EditorManager::closeDocuments(toClose);
}
void DebuggerPluginPrivate::setBusyCursor(bool busy)
{
//STATE_DEBUG("BUSY FROM: " << m_busy << " TO: " << busy);
if (busy == m_busy)
return;
m_busy = busy;
QCursor cursor(busy ? Qt::BusyCursor : Qt::ArrowCursor);
m_breakWindow->setCursor(cursor);
//m_consoleWindow->setCursor(cursor);
m_localsWindow->setCursor(cursor);
m_modulesWindow->setCursor(cursor);
m_logWindow->setCursor(cursor);
m_registerWindow->setCursor(cursor);
m_returnWindow->setCursor(cursor);
m_sourceFilesWindow->setCursor(cursor);
m_stackWindow->setCursor(cursor);
m_threadsWindow->setCursor(cursor);
m_watchersWindow->setCursor(cursor);
m_snapshotWindow->setCursor(cursor);
}
void DebuggerPluginPrivate::setInitialState()
{
m_watchersWindow->setVisible(false);
m_returnWindow->setVisible(false);
setBusyCursor(false);
m_reverseDirectionAction->setChecked(false);
m_reverseDirectionAction->setEnabled(false);
m_toolTipManager.closeAllToolTips();
m_startAndDebugApplicationAction->setEnabled(true);
m_attachToQmlPortAction->setEnabled(true);
m_attachToCoreAction->setEnabled(true);
m_attachToRemoteServerAction->setEnabled(true);
m_attachToRunningApplication->setEnabled(true);
m_attachToUnstartedApplication->setEnabled(true);
m_detachAction->setEnabled(false);
m_watchAction1->setEnabled(true);
m_watchAction2->setEnabled(true);
m_breakAction->setEnabled(false);
//m_snapshotAction->setEnabled(false);
action(OperateByInstruction)->setEnabled(false);
m_exitAction->setEnabled(false);
m_abortAction->setEnabled(false);
m_resetAction->setEnabled(false);
m_interruptAction->setEnabled(false);
m_continueAction->setEnabled(false);
m_stepAction->setEnabled(true);
m_stepOutAction->setEnabled(false);
m_runToLineAction->setEnabled(false);
m_runToSelectedFunctionAction->setEnabled(true);
m_returnFromFunctionAction->setEnabled(false);
m_jumpToLineAction->setEnabled(false);
m_nextAction->setEnabled(true);
action(AutoDerefPointers)->setEnabled(true);
action(ExpandStack)->setEnabled(false);
}
void DebuggerPluginPrivate::updateWatchersWindow(bool showWatch, bool showReturn)
{
m_watchersWindow->setVisible(showWatch);
m_returnWindow->setVisible(showReturn);
}
void DebuggerPluginPrivate::updateState(DebuggerEngine *engine)
{
QTC_ASSERT(engine, return);
QTC_ASSERT(m_watchersView->model(), return);
QTC_ASSERT(m_returnView->model(), return);
QTC_ASSERT(!engine->isSlaveEngine(), return);
m_threadBox->setCurrentIndex(engine->threadsHandler()->currentThreadIndex());
engine->watchHandler()->updateWatchersWindow();
const DebuggerState state = engine->state();
//showMessage(QString::fromLatin1("PLUGIN SET STATE: ")
// + DebuggerEngine::stateName(state), LogStatus);
//qDebug() << "PLUGIN SET STATE: " << state;
static DebuggerState previousState = DebuggerNotReady;
if (state == previousState)
return;
bool actionsEnabled = DebuggerEngine::debuggerActionsEnabled(state);
if (state == DebuggerNotReady) {
QTC_ASSERT(false, /* We use the Core's m_debugAction here */);
// F5 starts debugging. It is "startable".
m_interruptAction->setEnabled(false);
m_continueAction->setEnabled(false);
m_exitAction->setEnabled(false);
m_startAction->setEnabled(true);
m_debugWithoutDeployAction->setEnabled(true);
setProxyAction(m_visibleStartAction, Core::Id(Constants::DEBUG));
m_hiddenStopAction->setAction(m_undisturbableAction);
} else if (state == InferiorStopOk) {
// F5 continues, Shift-F5 kills. It is "continuable".
m_interruptAction->setEnabled(false);
m_continueAction->setEnabled(true);
m_exitAction->setEnabled(true);
m_startAction->setEnabled(false);
m_debugWithoutDeployAction->setEnabled(false);
setProxyAction(m_visibleStartAction, Core::Id(Constants::CONTINUE));
m_hiddenStopAction->setAction(m_exitAction);
m_localsAndExpressionsWindow->setShowLocals(true);
} else if (state == InferiorRunOk) {
// Shift-F5 interrupts. It is also "interruptible".
m_interruptAction->setEnabled(true);
m_continueAction->setEnabled(false);
m_exitAction->setEnabled(true);
m_startAction->setEnabled(false);
m_debugWithoutDeployAction->setEnabled(false);
setProxyAction(m_visibleStartAction, Core::Id(Constants::INTERRUPT));
m_hiddenStopAction->setAction(m_interruptAction);
m_localsAndExpressionsWindow->setShowLocals(false);
} else if (state == DebuggerFinished) {
Project *project = SessionManager::startupProject();
const bool canRun = ProjectExplorerPlugin::canRun(project, DebugRunMode);
// We don't want to do anything anymore.
m_interruptAction->setEnabled(false);
m_continueAction->setEnabled(false);
m_exitAction->setEnabled(false);
m_startAction->setEnabled(canRun);
m_debugWithoutDeployAction->setEnabled(canRun);
setProxyAction(m_visibleStartAction, Core::Id(Constants::DEBUG));
m_hiddenStopAction->setAction(m_undisturbableAction);
m_codeModelSnapshot = CPlusPlus::Snapshot();
setBusyCursor(false);
cleanupViews();
} else if (state == InferiorUnrunnable) {
// We don't want to do anything anymore.
m_interruptAction->setEnabled(false);
m_continueAction->setEnabled(false);
m_exitAction->setEnabled(true);
m_startAction->setEnabled(false);
m_debugWithoutDeployAction->setEnabled(false);
m_visibleStartAction->setAction(m_undisturbableAction);
m_hiddenStopAction->setAction(m_exitAction);
// show locals in core dumps
m_localsAndExpressionsWindow->setShowLocals(true);
} else {
// Everything else is "undisturbable".
m_interruptAction->setEnabled(false);
m_continueAction->setEnabled(false);
m_exitAction->setEnabled(false);
m_startAction->setEnabled(false);
m_debugWithoutDeployAction->setEnabled(false);
m_visibleStartAction->setAction(m_undisturbableAction);
m_hiddenStopAction->setAction(m_undisturbableAction);
}
m_startAndDebugApplicationAction->setEnabled(true);
m_attachToQmlPortAction->setEnabled(true);
m_attachToCoreAction->setEnabled(true);
m_attachToRemoteServerAction->setEnabled(true);
m_attachToRunningApplication->setEnabled(true);
m_attachToUnstartedApplication->setEnabled(true);
m_threadBox->setEnabled(state == InferiorStopOk || state == InferiorUnrunnable);
const bool isCore = engine->startParameters().startMode == AttachCore;
const bool stopped = state == InferiorStopOk;
const bool detachable = stopped && !isCore;
m_detachAction->setEnabled(detachable);
if (stopped)
QApplication::alert(mainWindow(), 3000);
const bool canReverse = engine->hasCapability(ReverseSteppingCapability)
&& boolSetting(EnableReverseDebugging);
m_reverseDirectionAction->setEnabled(canReverse);
m_watchAction1->setEnabled(true);
m_watchAction2->setEnabled(true);
m_breakAction->setEnabled(true);
const bool canOperateByInstruction = engine->hasCapability(OperateByInstructionCapability)
&& (stopped || isCore);
action(OperateByInstruction)->setEnabled(canOperateByInstruction);
m_abortAction->setEnabled(state != DebuggerNotReady
&& state != DebuggerFinished);
m_resetAction->setEnabled((stopped || state == DebuggerNotReady)
&& engine->hasCapability(ResetInferiorCapability));
m_stepAction->setEnabled(stopped || state == DebuggerNotReady);
m_nextAction->setEnabled(stopped || state == DebuggerNotReady);
m_stepAction->setToolTip(QString());
m_nextAction->setToolTip(QString());
m_stepOutAction->setEnabled(stopped);
m_runToLineAction->setEnabled(stopped && engine->hasCapability(RunToLineCapability));
m_runToSelectedFunctionAction->setEnabled(stopped);
m_returnFromFunctionAction->
setEnabled(stopped && engine->hasCapability(ReturnFromFunctionCapability));
const bool canJump = stopped && engine->hasCapability(JumpToLineCapability);
m_jumpToLineAction->setEnabled(canJump);
const bool canDeref = actionsEnabled && engine->hasCapability(AutoDerefPointersCapability);
action(AutoDerefPointers)->setEnabled(canDeref);
action(AutoDerefPointers)->setEnabled(true);
action(ExpandStack)->setEnabled(actionsEnabled);
const bool notbusy = state == InferiorStopOk
|| state == DebuggerNotReady
|| state == DebuggerFinished
|| state == InferiorUnrunnable;
setBusyCursor(!notbusy);
}
void DebuggerPluginPrivate::updateDebugActions()
{
//if we're currently debugging the actions are controlled by engine
if (m_currentEngine->state() != DebuggerNotReady)
return;
Project *project = SessionManager::startupProject();
QString whyNot;
const bool canRun = ProjectExplorerPlugin::canRun(project, DebugRunMode, &whyNot);
m_startAction->setEnabled(canRun);
m_startAction->setToolTip(whyNot);
m_debugWithoutDeployAction->setEnabled(canRun);
// Step into/next: Start and break at 'main' unless a debugger is running.
if (m_snapshotHandler->currentIndex() < 0) {
QString toolTip;
const bool canRunAndBreakMain
= ProjectExplorerPlugin::canRun(project, DebugRunModeWithBreakOnMain, &toolTip);
m_stepAction->setEnabled(canRunAndBreakMain);
m_nextAction->setEnabled(canRunAndBreakMain);
if (canRunAndBreakMain) {
QTC_ASSERT(project, return ; );
toolTip = tr("Start \"%1\" and break at function \"main()\"")
.arg(project->displayName());
}
m_stepAction->setToolTip(toolTip);
m_nextAction->setToolTip(toolTip);
}
}
void DebuggerPluginPrivate::onCoreAboutToOpen()
{
m_mainWindow->onModeChanged(ModeManager::currentMode());
}
void DebuggerPluginPrivate::onModeChanged(IMode *mode)
{
// FIXME: This one gets always called, even if switching between modes
// different then the debugger mode. E.g. Welcome and Help mode and
// also on shutdown.
m_mainWindow->onModeChanged(mode);
if (mode->id() != Constants::MODE_DEBUG) {
m_toolTipManager.leavingDebugMode();
return;
}
if (IEditor *editor = EditorManager::currentEditor())
editor->widget()->setFocus();
m_toolTipManager.debugModeEntered();
}
void DebuggerPluginPrivate::showSettingsDialog()
{
ICore::showOptionsDialog(DEBUGGER_SETTINGS_CATEGORY, DEBUGGER_COMMON_SETTINGS_ID);
}
void DebuggerPluginPrivate::updateDebugWithoutDeployMenu()
{
const bool state = ProjectExplorerPlugin::projectExplorerSettings().deployBeforeRun;
m_debugWithoutDeployAction->setVisible(state);
}
void DebuggerPluginPrivate::dumpLog()
{
QString fileName = QFileDialog::getSaveFileName(ICore::mainWindow(),
tr("Save Debugger Log"), QDir::tempPath());
if (fileName.isEmpty())
return;
FileSaver saver(fileName);
if (!saver.hasError()) {
QTextStream ts(saver.file());
ts << m_logWindow->inputContents();
ts << "\n\n=======================================\n\n";
ts << m_logWindow->combinedContents();
saver.setResult(&ts);
}
saver.finalize(ICore::mainWindow());
}
/*! Activates the previous mode when the current mode is the debug mode. */
void DebuggerPluginPrivate::activatePreviousMode()
{
if (ModeManager::currentMode() == ModeManager::mode(MODE_DEBUG)
&& m_previousMode.isValid()) {
ModeManager::activateMode(m_previousMode);
m_previousMode = Id();
}
}
void DebuggerPluginPrivate::activateDebugMode()
{
m_reverseDirectionAction->setChecked(false);
m_reverseDirectionAction->setEnabled(false);
m_previousMode = ModeManager::currentMode()->id();
ModeManager::activateMode(MODE_DEBUG);
}
void DebuggerPluginPrivate::sessionLoaded()
{
m_breakHandler->loadSessionData();
dummyEngine()->watchHandler()->loadSessionData();
DebuggerToolTipManager::loadSessionData();
}
void DebuggerPluginPrivate::aboutToUnloadSession()
{
m_toolTipManager.sessionAboutToChange();
}
void DebuggerPluginPrivate::aboutToSaveSession()
{
dummyEngine()->watchHandler()->saveSessionData();
m_breakHandler->saveSessionData();
DebuggerToolTipManager::saveSessionData();
}
void DebuggerPluginPrivate::showStatusMessage(const QString &msg0, int timeout)
{
showMessage(msg0, LogStatus);
QString msg = msg0;
msg.remove(QLatin1Char('\n'));
m_statusLabel->showStatusMessage(msg, timeout);
}
void DebuggerPluginPrivate::coreShutdown()
{
m_shuttingDown = true;
}
const CPlusPlus::Snapshot &cppCodeModelSnapshot()
{
if (dd->m_codeModelSnapshot.isEmpty() && action(UseCodeModel)->isChecked())
dd->m_codeModelSnapshot = CppTools::CppModelManager::instance()->snapshot();
return dd->m_codeModelSnapshot;
}
void setSessionValue(const QByteArray &key, const QVariant &value)
{
SessionManager::setValue(QString::fromUtf8(key), value);
}
QVariant sessionValue(const QByteArray &key)
{
return SessionManager::value(QString::fromUtf8(key));
}
QTreeView *inspectorView()
{
return dd->m_inspectorView;
}
void DebuggerPluginPrivate::showMessage(const QString &msg, int channel, int timeout)
{
//qDebug() << "PLUGIN OUTPUT: " << channel << msg;
//ConsoleWindow *cw = m_consoleWindow;
QTC_ASSERT(m_logWindow, return);
switch (channel) {
case StatusBar:
// This will append to m_logWindow's output pane, too.
showStatusMessage(msg, timeout);
break;
case LogMiscInput:
m_logWindow->showInput(LogMisc, msg);
m_logWindow->showOutput(LogMisc, msg);
break;
case LogInput:
m_logWindow->showInput(LogInput, msg);
m_logWindow->showOutput(LogInput, msg);
break;
case LogError:
m_logWindow->showInput(LogError, QLatin1String("ERROR: ") + msg);
m_logWindow->showOutput(LogError, QLatin1String("ERROR: ") + msg);
break;
default:
m_logWindow->showOutput(channel, msg);
break;
}
}
void createNewDock(QWidget *widget)
{
QDockWidget *dockWidget = dd->m_mainWindow->createDockWidget(CppLanguage, widget);
dockWidget->setWindowTitle(widget->windowTitle());
dockWidget->setFeatures(QDockWidget::DockWidgetClosable);
dockWidget->show();
}
static QString formatStartParameters(DebuggerStartParameters &sp)
{
QString rc;
QTextStream str(&rc);
str << "Start parameters: '" << sp.displayName << "' mode: " << sp.startMode
<< "\nABI: " << sp.toolChainAbi.toString() << '\n';
str << "Languages: ";
if (sp.languages == AnyLanguage)
str << "any";
if (sp.languages & CppLanguage)
str << "c++ ";
if (sp.languages & QmlLanguage)
str << "qml";
str << '\n';
if (!sp.executable.isEmpty()) {
str << "Executable: " << QDir::toNativeSeparators(sp.executable)
<< ' ' << sp.processArgs;
if (sp.useTerminal)
str << " [terminal]";
str << '\n';
if (!sp.workingDirectory.isEmpty())
str << "Directory: " << QDir::toNativeSeparators(sp.workingDirectory)
<< '\n';
}
QString cmd = sp.debuggerCommand;
if (!cmd.isEmpty())
str << "Debugger: " << QDir::toNativeSeparators(cmd) << '\n';
if (!sp.coreFile.isEmpty())
str << "Core: " << QDir::toNativeSeparators(sp.coreFile) << '\n';
if (sp.attachPID > 0)
str << "PID: " << sp.attachPID << ' ' << sp.crashParameter << '\n';
if (!sp.projectSourceDirectory.isEmpty()) {
str << "Project: " << QDir::toNativeSeparators(sp.projectSourceDirectory);
if (!sp.projectBuildDirectory.isEmpty())
str << " (built: " << QDir::toNativeSeparators(sp.projectBuildDirectory)
<< ')';
str << '\n';
}
if (!sp.qmlServerAddress.isEmpty())
str << "QML server: " << sp.qmlServerAddress << ':'
<< sp.qmlServerPort << '\n';
if (!sp.remoteChannel.isEmpty()) {
str << "Remote: " << sp.remoteChannel << '\n';
if (!sp.remoteSourcesDir.isEmpty())
str << "Remote sources: " << sp.remoteSourcesDir << '\n';
if (!sp.remoteMountPoint.isEmpty())
str << "Remote mount point: " << sp.remoteMountPoint
<< " Local: " << sp.localMountDir << '\n';
}
str << "Sysroot: " << sp.sysRoot << '\n';
str << "Debug Source Location: " << sp.debugSourceLocation.join(QLatin1Char(':')) << '\n';
return rc;
}
void DebuggerPluginPrivate::runControlStarted(DebuggerEngine *engine)
{
activateDebugMode();
const QString message = tr("Starting debugger \"%1\" for ABI \"%2\"...")
.arg(engine->objectName())
.arg(engine->startParameters().toolChainAbi.toString());
showStatusMessage(message);
showMessage(formatStartParameters(engine->startParameters()), LogDebug);
showMessage(m_debuggerSettings->dump(), LogDebug);
m_snapshotHandler->appendSnapshot(engine);
connectEngine(engine);
}
void DebuggerPluginPrivate::runControlFinished(DebuggerEngine *engine)
{
showStatusMessage(tr("Debugger finished."));
m_snapshotHandler->removeSnapshot(engine);
if (m_snapshotHandler->size() == 0) {
// Last engine quits.
disconnectEngine();
if (boolSetting(SwitchModeOnExit))
activatePreviousMode();
} else {
// Connect to some existing engine.
m_snapshotHandler->activateSnapshot(0);
}
action(OperateByInstruction)->setValue(QVariant(false));
m_logWindow->clearUndoRedoStacks();
}
void DebuggerPluginPrivate::remoteCommand(const QStringList &options,
const QStringList &)
{
if (options.isEmpty())
return;
QString errorMessage;
if (!parseArguments(options, &errorMessage)) {
qWarning("%s", qPrintable(errorMessage));
return;
}
runScheduled();
}
QMessageBox *showMessageBox(int icon, const QString &title,
const QString &text, int buttons)
{
QMessageBox *mb = new QMessageBox(QMessageBox::Icon(icon),
title, text, QMessageBox::StandardButtons(buttons),
ICore::mainWindow());
mb->setAttribute(Qt::WA_DeleteOnClose);
mb->setTextInteractionFlags(Qt::TextSelectableByMouse);
mb->show();
return mb;
}
bool isNativeMixedEnabled()
{
static bool enabled = qEnvironmentVariableIsSet("QTC_DEBUGGER_NATIVE_MIXED");
return enabled;
}
bool isNativeMixedActive()
{
return isNativeMixedEnabled() && boolSetting(OperateNativeMixed);
}
void DebuggerPluginPrivate::extensionsInitialized()
{
const QKeySequence debugKey = QKeySequence(UseMacShortcuts ? tr("Ctrl+Y") : tr("F5"));
QSettings *settings = Core::ICore::settings();
m_debuggerSettings = new DebuggerSettings;
m_debuggerSettings->readSettings();
connect(ICore::instance(), &ICore::coreAboutToClose, this, &DebuggerPluginPrivate::coreShutdown);
const Context globalcontext(CC::C_GLOBAL);
const Context cppDebuggercontext(C_CPPDEBUGGER);
const Context cppeditorcontext(CppEditor::Constants::CPPEDITOR_ID);
m_startIcon = QIcon(_(":/debugger/images/debugger_start_small.png"));
m_startIcon.addFile(QLatin1String(":/debugger/images/debugger_start.png"));
m_exitIcon = QIcon(_(":/debugger/images/debugger_stop_small.png"));
m_exitIcon.addFile(QLatin1String(":/debugger/images/debugger_stop.png"));
m_continueIcon = QIcon(QLatin1String(":/debugger/images/debugger_continue_small.png"));
m_continueIcon.addFile(QLatin1String(":/debugger/images/debugger_continue.png"));
m_interruptIcon = QIcon(_(Core::Constants::ICON_PAUSE));
m_interruptIcon.addFile(QLatin1String(":/debugger/images/debugger_interrupt.png"));
m_locationMarkIcon = QIcon(_(":/debugger/images/location_16.png"));
m_resetIcon = QIcon(_(":/debugger/images/debugger_restart_small.png:"));
m_resetIcon.addFile(QLatin1String(":/debugger/images/debugger_restart.png"));
m_busy = false;
m_statusLabel = new StatusLabel;
m_logWindow = new LogWindow;
m_logWindow->setObjectName(QLatin1String(DOCKWIDGET_OUTPUT));
m_breakHandler = new BreakHandler;
m_breakView = new BreakTreeView;
m_breakView->setSettings(settings, "Debugger.BreakWindow");
m_breakView->setModel(m_breakHandler->model());
m_breakWindow = addSearch(m_breakView, tr("Breakpoints"), DOCKWIDGET_BREAK);
m_modulesView = new ModulesTreeView;
m_modulesView->setSettings(settings, "Debugger.ModulesView");
m_modulesWindow = addSearch(m_modulesView, tr("Modules"), DOCKWIDGET_MODULES);
m_registerView = new RegisterTreeView;
m_registerView->setSettings(settings, "Debugger.RegisterView");
m_registerWindow = addSearch(m_registerView, tr("Registers"), DOCKWIDGET_REGISTER);
m_stackView = new StackTreeView;
m_stackView->setSettings(settings, "Debugger.StackView");
m_stackWindow = addSearch(m_stackView, tr("Stack"), DOCKWIDGET_STACK);
m_sourceFilesView = new SourceFilesTreeView;
m_sourceFilesView->setSettings(settings, "Debugger.SourceFilesView");
m_sourceFilesWindow = addSearch(m_sourceFilesView, tr("Source Files"), DOCKWIDGET_SOURCE_FILES);
m_threadsView = new ThreadsTreeView;
m_threadsView->setSettings(settings, "Debugger.ThreadsView");
m_threadsWindow = addSearch(m_threadsView, tr("Threads"), DOCKWIDGET_THREADS);
m_returnView = new WatchTreeView(ReturnType); // No settings.
m_returnWindow = addSearch(m_returnView, tr("Locals and Expressions"), "CppDebugReturn");
m_localsView = new WatchTreeView(LocalsType);
m_localsView->setSettings(settings, "Debugger.LocalsView");
m_localsWindow = addSearch(m_localsView, tr("Locals and Expressions"), "CppDebugLocals");
m_watchersView = new WatchTreeView(WatchersType); // No settings.
m_watchersWindow = addSearch(m_watchersView, tr("Locals and Expressions"), "CppDebugWatchers");
m_inspectorView = new WatchTreeView(InspectType);
m_inspectorView->setSettings(settings, "Debugger.LocalsView"); // sic! same as locals view.
m_inspectorWindow = addSearch(m_inspectorView, tr("Locals and Expressions"), "Inspector");
// Snapshot
m_snapshotHandler = new SnapshotHandler;
m_snapshotView = new SnapshotTreeView(m_snapshotHandler);
m_snapshotView->setSettings(settings, "Debugger.SnapshotView");
m_snapshotView->setModel(m_snapshotHandler->model());
m_snapshotWindow = addSearch(m_snapshotView, tr("Snapshots"), DOCKWIDGET_SNAPSHOTS);
// Watchers
connect(m_localsView->header(), &QHeaderView::sectionResized,
this, &DebuggerPluginPrivate::updateWatchersHeader, Qt::QueuedConnection);
QAction *act = 0;
act = m_continueAction = new QAction(tr("Continue"), this);
act->setIcon(m_continueIcon);
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecContinue);
act = m_exitAction = new QAction(tr("Stop Debugger"), this);
act->setIcon(m_exitIcon);
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecExit);
act = m_interruptAction = new QAction(tr("Interrupt"), this);
act->setIcon(m_interruptIcon);
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecInterrupt);
// A "disabled pause" seems to be a good choice.
act = m_undisturbableAction = new QAction(tr("Debugger is Busy"), this);
act->setIcon(m_interruptIcon);
act->setEnabled(false);
act = m_abortAction = new QAction(tr("Abort Debugging"), this);
act->setToolTip(tr("Aborts debugging and "
"resets the debugger to the initial state."));
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleAbort);
act = m_resetAction = new QAction(tr("Restart Debugging"),this);
act->setToolTip(tr("Restart the debugging session."));
act->setIcon(m_resetIcon);
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleReset);
act = m_nextAction = new QAction(tr("Step Over"), this);
act->setIcon(QIcon(QLatin1String(":/debugger/images/debugger_stepover_small.png")));
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecNext);
act = m_stepAction = new QAction(tr("Step Into"), this);
act->setIcon(QIcon(QLatin1String(":/debugger/images/debugger_stepinto_small.png")));
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecStep);
act = m_stepOutAction = new QAction(tr("Step Out"), this);
act->setIcon(QIcon(QLatin1String(":/debugger/images/debugger_stepout_small.png")));
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecStepOut);
act = m_runToLineAction = new QAction(tr("Run to Line"), this);
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecRunToLine);
act = m_runToSelectedFunctionAction =
new QAction(tr("Run to Selected Function"), this);
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecRunToSelectedFunction);
act = m_returnFromFunctionAction =
new QAction(tr("Immediately Return From Inner Function"), this);
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecReturn);
act = m_jumpToLineAction = new QAction(tr("Jump to Line"), this);
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecJumpToLine);
m_breakAction = new QAction(tr("Toggle Breakpoint"), this);
act = m_watchAction1 = new QAction(tr("Add Expression Evaluator"), this);
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleAddToWatchWindow);
act = m_watchAction2 = new QAction(tr("Add Expression Evaluator"), this);
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleAddToWatchWindow);
//m_snapshotAction = new QAction(tr("Create Snapshot"), this);
//m_snapshotAction->setProperty(Role, RequestCreateSnapshotRole);
//m_snapshotAction->setIcon(
// QIcon(__(":/debugger/images/debugger_snapshot_small.png")));
act = m_reverseDirectionAction =
new QAction(tr("Reverse Direction"), this);
act->setCheckable(true);
act->setChecked(false);
act->setCheckable(false);
act->setIcon(QIcon(QLatin1String(":/debugger/images/debugger_reversemode_16.png")));
act->setIconVisibleInMenu(false);
act = m_frameDownAction = new QAction(tr("Move to Called Frame"), this);
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleFrameDown);
act = m_frameUpAction = new QAction(tr("Move to Calling Frame"), this);
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleFrameUp);
connect(action(OperateByInstruction), SIGNAL(triggered(bool)),
SLOT(handleOperateByInstructionTriggered(bool)));
ActionContainer *debugMenu = ActionManager::actionContainer(PE::M_DEBUG);
// Dock widgets
QDockWidget *dock = 0;
dock = m_mainWindow->createDockWidget(CppLanguage, m_modulesWindow);
connect(dock->toggleViewAction(), &QAction::toggled,
this, &DebuggerPluginPrivate::modulesDockToggled, Qt::QueuedConnection);
dock = m_mainWindow->createDockWidget(CppLanguage, m_registerWindow);
connect(dock->toggleViewAction(), &QAction::toggled,
this, &DebuggerPluginPrivate::registerDockToggled, Qt::QueuedConnection);
dock = m_mainWindow->createDockWidget(CppLanguage, m_sourceFilesWindow);
connect(dock->toggleViewAction(), &QAction::toggled,
this, &DebuggerPluginPrivate::sourceFilesDockToggled, Qt::QueuedConnection);
dock = m_mainWindow->createDockWidget(AnyLanguage, m_logWindow);
dock->setProperty(DOCKWIDGET_DEFAULT_AREA, Qt::TopDockWidgetArea);
m_mainWindow->createDockWidget(CppLanguage, m_breakWindow);
m_mainWindow->createDockWidget(CppLanguage, m_snapshotWindow);
m_mainWindow->createDockWidget(CppLanguage, m_stackWindow);
m_mainWindow->createDockWidget(CppLanguage, m_threadsWindow);
m_localsAndExpressionsWindow = new LocalsAndExpressionsWindow(
m_localsWindow, m_inspectorWindow, m_returnWindow,
m_watchersWindow);
m_localsAndExpressionsWindow->setObjectName(QLatin1String(DOCKWIDGET_WATCHERS));
m_localsAndExpressionsWindow->setWindowTitle(m_localsWindow->windowTitle());
dock = m_mainWindow->createDockWidget(CppLanguage, m_localsAndExpressionsWindow);
dock->setProperty(DOCKWIDGET_DEFAULT_AREA, Qt::RightDockWidgetArea);
m_mainWindow->addStagedMenuEntries();
// Register factory of DebuggerRunControl.
m_debuggerRunControlFactory = new DebuggerRunControlFactory(m_plugin);
m_plugin->addAutoReleasedObject(m_debuggerRunControlFactory);
// The main "Start Debugging" action.
act = m_startAction = new QAction(this);
QIcon debuggerIcon(QLatin1String(":/projectexplorer/images/debugger_start_small.png"));
debuggerIcon.addFile(QLatin1String(":/projectexplorer/images/debugger_start.png"));
act->setIcon(debuggerIcon);
act->setText(tr("Start Debugging"));
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::debugProject);
act = m_debugWithoutDeployAction = new QAction(this);
act->setText(tr("Start Debugging Without Deployment"));
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::debugProjectWithoutDeploy);
act = m_startAndDebugApplicationAction = new QAction(this);
act->setText(tr("Start and Debug External Application..."));
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::startAndDebugApplication);
act = m_attachToCoreAction = new QAction(this);
act->setText(tr("Load Core File..."));
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::attachCore);
act = m_attachToRemoteServerAction = new QAction(this);
act->setText(tr("Attach to Remote Debug Server..."));
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::attachToRemoteServer);
act = m_startRemoteServerAction = new QAction(this);
act->setText(tr("Start Remote Debug Server Attached to Process..."));
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::startRemoteServer);
act = m_attachToRunningApplication = new QAction(this);
act->setText(tr("Attach to Running Application..."));
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::attachToRunningApplication);
act = m_attachToUnstartedApplication = new QAction(this);
act->setText(tr("Attach to Unstarted Application..."));
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::attachToUnstartedApplicationDialog);
act = m_attachToQmlPortAction = new QAction(this);
act->setText(tr("Attach to QML Port..."));
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::attachToQmlPort);
if (HostOsInfo::isWindowsHost()) {
m_startRemoteCdbAction = new QAction(tr("Attach to Remote CDB Session..."), this);
connect(m_startRemoteCdbAction, &QAction::triggered,
this, &DebuggerPluginPrivate::startRemoteCdbSession);
}
act = m_detachAction = new QAction(this);
act->setText(tr("Detach Debugger"));
connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecDetach);
// "Start Debugging" sub-menu
// groups:
// G_DEFAULT_ONE
// G_START_LOCAL
// G_START_REMOTE
// G_START_QML
Command *cmd = 0;
ActionContainer *mstart = ActionManager::actionContainer(PE::M_DEBUG_STARTDEBUGGING);
cmd = ActionManager::registerAction(m_startAction, Constants::DEBUG, globalcontext);
cmd->setDescription(tr("Start Debugging"));
cmd->setDefaultKeySequence(debugKey);
cmd->setAttribute(Command::CA_UpdateText);
mstart->addAction(cmd, CC::G_DEFAULT_ONE);
m_visibleStartAction = new ProxyAction(this);
m_visibleStartAction->initialize(cmd->action());
m_visibleStartAction->setAttribute(ProxyAction::UpdateText);
m_visibleStartAction->setAttribute(ProxyAction::UpdateIcon);
m_visibleStartAction->setAction(cmd->action());
ModeManager::addAction(m_visibleStartAction, Constants::P_ACTION_DEBUG);
cmd = ActionManager::registerAction(m_debugWithoutDeployAction,
"Debugger.DebugWithoutDeploy", globalcontext);
cmd->setAttribute(Command::CA_Hide);
mstart->addAction(cmd, CC::G_DEFAULT_ONE);
cmd = ActionManager::registerAction(m_attachToRunningApplication,
"Debugger.AttachToRemoteProcess", globalcontext);
cmd->setDescription(tr("Attach to Running Application"));
mstart->addAction(cmd, Debugger::Constants::G_GENERAL);
cmd = ActionManager::registerAction(m_attachToUnstartedApplication,
"Debugger.AttachToUnstartedProcess", globalcontext);
cmd->setDescription(tr("Attach to Unstarted Application"));
mstart->addAction(cmd, Debugger::Constants::G_GENERAL);
cmd = ActionManager::registerAction(m_startAndDebugApplicationAction,
"Debugger.StartAndDebugApplication", globalcontext);
cmd->setAttribute(Command::CA_Hide);
mstart->addAction(cmd, Debugger::Constants::G_GENERAL);
cmd = ActionManager::registerAction(m_attachToCoreAction,
"Debugger.AttachCore", globalcontext);
cmd->setAttribute(Command::CA_Hide);
mstart->addAction(cmd, Constants::G_GENERAL);
cmd = ActionManager::registerAction(m_attachToRemoteServerAction,
"Debugger.AttachToRemoteServer", globalcontext);
cmd->setAttribute(Command::CA_Hide);
mstart->addAction(cmd, Constants::G_SPECIAL);
cmd = ActionManager::registerAction(m_startRemoteServerAction,
"Debugger.StartRemoteServer", globalcontext);
cmd->setDescription(tr("Start Gdbserver"));
mstart->addAction(cmd, Constants::G_SPECIAL);
if (m_startRemoteCdbAction) {
cmd = ActionManager::registerAction(m_startRemoteCdbAction,
"Debugger.AttachRemoteCdb", globalcontext);
cmd->setAttribute(Command::CA_Hide);
mstart->addAction(cmd, Constants::G_SPECIAL);
}
mstart->addSeparator(globalcontext, Constants::G_START_QML);
cmd = ActionManager::registerAction(m_attachToQmlPortAction,
"Debugger.AttachToQmlPort", globalcontext);
cmd->setAttribute(Command::CA_Hide);
mstart->addAction(cmd, Constants::G_START_QML);
cmd = ActionManager::registerAction(m_detachAction,
"Debugger.Detach", globalcontext);
cmd->setAttribute(Command::CA_Hide);
debugMenu->addAction(cmd, CC::G_DEFAULT_ONE);
cmd = ActionManager::registerAction(m_interruptAction,
Constants::INTERRUPT, globalcontext);
cmd->setDescription(tr("Interrupt Debugger"));
debugMenu->addAction(cmd, CC::G_DEFAULT_ONE);
cmd = ActionManager::registerAction(m_continueAction,
Constants::CONTINUE, globalcontext);
cmd->setDefaultKeySequence(debugKey);
debugMenu->addAction(cmd, CC::G_DEFAULT_ONE);
cmd = ActionManager::registerAction(m_exitAction,
Constants::STOP, globalcontext);
debugMenu->addAction(cmd, CC::G_DEFAULT_ONE);
m_hiddenStopAction = new ProxyAction(this);
m_hiddenStopAction->initialize(cmd->action());
m_hiddenStopAction->setAttribute(ProxyAction::UpdateText);
m_hiddenStopAction->setAttribute(ProxyAction::UpdateIcon);
cmd = ActionManager::registerAction(m_hiddenStopAction,
Constants::HIDDEN_STOP, globalcontext);
cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Shift+Ctrl+Y") : tr("Shift+F5")));
cmd = ActionManager::registerAction(m_abortAction,
Constants::ABORT, globalcontext);
cmd->setDescription(tr("Reset Debugger"));
debugMenu->addAction(cmd, CC::G_DEFAULT_ONE);
cmd = ActionManager::registerAction(m_resetAction,
Constants::RESET, globalcontext);
cmd->setDescription(tr("Restart Debugging"));
debugMenu->addAction(cmd, CC::G_DEFAULT_ONE);
debugMenu->addSeparator(globalcontext);
cmd = ActionManager::registerAction(m_nextAction,
Constants::NEXT, globalcontext);
cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Ctrl+Shift+O") : tr("F10")));
cmd->setAttribute(Command::CA_Hide);
cmd->setAttribute(Command::CA_UpdateText);
debugMenu->addAction(cmd);
cmd = ActionManager::registerAction(m_stepAction,
Constants::STEP, globalcontext);
cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Ctrl+Shift+I") : tr("F11")));
cmd->setAttribute(Command::CA_Hide);
cmd->setAttribute(Command::CA_UpdateText);
debugMenu->addAction(cmd);
cmd = ActionManager::registerAction(m_stepOutAction,
Constants::STEPOUT, cppDebuggercontext);
cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Ctrl+Shift+T") : tr("Shift+F11")));
cmd->setAttribute(Command::CA_Hide);
debugMenu->addAction(cmd);
cmd = ActionManager::registerAction(m_runToLineAction,
"Debugger.RunToLine", cppDebuggercontext);
cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Shift+F8") : tr("Ctrl+F10")));
cmd->setAttribute(Command::CA_Hide);
debugMenu->addAction(cmd);
cmd = ActionManager::registerAction(m_runToSelectedFunctionAction,
"Debugger.RunToSelectedFunction", cppDebuggercontext);
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+F6")));
cmd->setAttribute(Command::CA_Hide);
// Don't add to menu by default as keeping its enabled state
// and text up-to-date is a lot of hassle.
// debugMenu->addAction(cmd);
cmd = ActionManager::registerAction(m_jumpToLineAction,
"Debugger.JumpToLine", cppDebuggercontext);
cmd->setAttribute(Command::CA_Hide);
debugMenu->addAction(cmd);
cmd = ActionManager::registerAction(m_returnFromFunctionAction,
"Debugger.ReturnFromFunction", cppDebuggercontext);
cmd->setAttribute(Command::CA_Hide);
debugMenu->addAction(cmd);
cmd = ActionManager::registerAction(m_reverseDirectionAction,
Constants::REVERSE, cppDebuggercontext);
cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? QString() : tr("F12")));
cmd->setAttribute(Command::CA_Hide);
debugMenu->addAction(cmd);
debugMenu->addSeparator(globalcontext);
//cmd = ActionManager::registerAction(m_snapshotAction,
// "Debugger.Snapshot", cppDebuggercontext);
//cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+D,Ctrl+S")));
//cmd->setAttribute(Command::CA_Hide);
//debugMenu->addAction(cmd);
cmd = ActionManager::registerAction(m_frameDownAction,
"Debugger.FrameDown", cppDebuggercontext);
ActionManager::registerAction(m_frameUpAction,
"Debugger.FrameUp", cppDebuggercontext);
cmd = ActionManager::registerAction(action(OperateByInstruction),
Constants::OPERATE_BY_INSTRUCTION, cppDebuggercontext);
cmd->setAttribute(Command::CA_Hide);
debugMenu->addAction(cmd);
if (isNativeMixedEnabled()) {
SavedAction *act = action(OperateNativeMixed);
act->setValue(true);
cmd = ActionManager::registerAction(act,
Constants::OPERATE_NATIVE_MIXED, globalcontext);
cmd->setAttribute(Command::CA_Hide);
debugMenu->addAction(cmd);
connect(cmd->action(), &QAction::triggered,
[this] { currentEngine()->updateAll(); });
}
cmd = ActionManager::registerAction(m_breakAction,
"Debugger.ToggleBreak", globalcontext);
cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("F8") : tr("F9")));
debugMenu->addAction(cmd);
connect(m_breakAction, &QAction::triggered,
this, &DebuggerPluginPrivate::toggleBreakpoint);
debugMenu->addSeparator(globalcontext);
// currently broken
// QAction *qmlUpdateOnSaveDummyAction = new QAction(tr("Apply Changes on Save"), this);
// qmlUpdateOnSaveDummyAction->setCheckable(true);
// qmlUpdateOnSaveDummyAction->setIcon(QIcon(_(":/debugger/images/qml/apply-on-save.png")));
// qmlUpdateOnSaveDummyAction->setEnabled(false);
// cmd = ActionManager::registerAction(qmlUpdateOnSaveDummyAction, Constants::QML_UPDATE_ON_SAVE,
// globalcontext);
// debugMenu->addAction(cmd);
QAction *qmlShowAppOnTopDummyAction = new QAction(tr("Show Application on Top"), this);
qmlShowAppOnTopDummyAction->setCheckable(true);
qmlShowAppOnTopDummyAction->setIcon(QIcon(_(":/debugger/images/qml/app-on-top.png")));
qmlShowAppOnTopDummyAction->setEnabled(false);
cmd = ActionManager::registerAction(qmlShowAppOnTopDummyAction, Constants::QML_SHOW_APP_ON_TOP,
globalcontext);
debugMenu->addAction(cmd);
QAction *qmlSelectDummyAction = new QAction(tr("Select"), this);
qmlSelectDummyAction->setCheckable(true);
qmlSelectDummyAction->setIcon(QIcon(_(":/debugger/images/qml/select.png")));
qmlSelectDummyAction->setEnabled(false);
cmd = ActionManager::registerAction(qmlSelectDummyAction, Constants::QML_SELECTTOOL,
globalcontext);
debugMenu->addAction(cmd);
QAction *qmlZoomDummyAction = new QAction(tr("Zoom"), this);
qmlZoomDummyAction->setCheckable(true);
qmlZoomDummyAction->setIcon(QIcon(_(":/debugger/images/qml/zoom.png")));
qmlZoomDummyAction->setEnabled(false);
cmd = ActionManager::registerAction(qmlZoomDummyAction, Constants::QML_ZOOMTOOL, globalcontext);
debugMenu->addAction(cmd);
debugMenu->addSeparator(globalcontext);
// Don't add '1' to the string as it shows up in the shortcut dialog.
cmd = ActionManager::registerAction(m_watchAction1,
"Debugger.AddToWatch", cppeditorcontext);
//cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+D,Ctrl+W")));
debugMenu->addAction(cmd);
// If the CppEditor plugin is there, we want to add something to
// the editor context menu.
if (ActionContainer *editorContextMenu =
ActionManager::actionContainer(CppEditor::Constants::M_CONTEXT)) {
cmd = editorContextMenu->addSeparator(cppDebuggercontext);
cmd->setAttribute(Command::CA_Hide);
cmd = ActionManager::registerAction(m_watchAction2,
"Debugger.AddToWatch2", cppDebuggercontext);
cmd->action()->setEnabled(true);
editorContextMenu->addAction(cmd);
cmd->setAttribute(Command::CA_Hide);
cmd->setAttribute(Command::CA_NonConfigurable);
// Debugger.AddToWatch is enough.
}
QList<IOptionsPage *> engineOptionPages;
addGdbOptionPages(&engineOptionPages);
addCdbOptionPages(&engineOptionPages);
foreach (IOptionsPage *op, engineOptionPages)
m_plugin->addAutoReleasedObject(op);
m_plugin->addAutoReleasedObject(new LocalsAndExpressionsOptionsPage);
m_plugin->addAutoReleasedObject(new DebuggerOptionsPage);
connect(ModeManager::instance(), &ModeManager::currentModeChanged,
this, &DebuggerPluginPrivate::onModeChanged);
connect(ICore::instance(), &ICore::coreAboutToOpen,
this, &DebuggerPluginPrivate::onCoreAboutToOpen);
connect(ProjectExplorerPlugin::instance(), &ProjectExplorerPlugin::settingsChanged,
this, &DebuggerPluginPrivate::updateDebugWithoutDeployMenu);
// Debug mode setup
DebugMode *debugMode = new DebugMode;
QWidget *widget = m_mainWindow->createContents(debugMode);
Core::IContext *modeContextObject = new Core::IContext(this);
modeContextObject->setContext(Core::Context(CC::C_EDITORMANAGER));
modeContextObject->setWidget(widget);
Core::ICore::addContextObject(modeContextObject);
debugMode->setWidget(widget);
m_plugin->addAutoReleasedObject(debugMode);
//
// Connections
//
// Core
connect(ICore::instance(), &ICore::saveSettingsRequested,
this, &DebuggerPluginPrivate::writeSettings);
// TextEditor
connect(TextEditorSettings::instance(), &TextEditorSettings::fontSettingsChanged,
this, &DebuggerPluginPrivate::fontSettingsChanged);
// ProjectExplorer
connect(SessionManager::instance(), &SessionManager::sessionLoaded,
this, &DebuggerPluginPrivate::sessionLoaded);
connect(SessionManager::instance(), &SessionManager::aboutToSaveSession,
this, &DebuggerPluginPrivate::aboutToSaveSession);
connect(SessionManager::instance(), &SessionManager::aboutToUnloadSession,
this, &DebuggerPluginPrivate::aboutToUnloadSession);
connect(ProjectExplorerPlugin::instance(), &ProjectExplorerPlugin::updateRunActions,
this, &DebuggerPluginPrivate::updateDebugActions);
// EditorManager
connect(EditorManager::instance(), &EditorManager::editorOpened,
this, &DebuggerPluginPrivate::editorOpened);
connect(EditorManager::instance(), &EditorManager::currentEditorChanged,
this, &DebuggerPluginPrivate::updateBreakMenuItem);
// Application interaction
connect(action(SettingsDialog), &QAction::triggered,
this, &DebuggerPluginPrivate::showSettingsDialog);
// QML Actions
connect(action(ShowQmlObjectTree), &SavedAction::valueChanged,
this, &DebuggerPluginPrivate::updateQmlActions);
updateQmlActions();
// Toolbar
QWidget *toolbarContainer = new QWidget;
QHBoxLayout *hbox = new QHBoxLayout(toolbarContainer);
hbox->setMargin(0);
hbox->setSpacing(0);
hbox->addWidget(toolButton(m_visibleStartAction));
hbox->addWidget(toolButton(Constants::STOP));
hbox->addWidget(toolButton(Constants::NEXT));
hbox->addWidget(toolButton(Constants::STEP));
hbox->addWidget(toolButton(Constants::STEPOUT));
hbox->addWidget(toolButton(Constants::RESET));
hbox->addWidget(toolButton(Constants::OPERATE_BY_INSTRUCTION));
if (isNativeMixedEnabled())
hbox->addWidget(toolButton(Constants::OPERATE_NATIVE_MIXED));
//hbox->addWidget(new StyledSeparator);
m_reverseToolButton = toolButton(Constants::REVERSE);
hbox->addWidget(m_reverseToolButton);
//m_reverseToolButton->hide();
hbox->addWidget(new StyledSeparator);
hbox->addWidget(new QLabel(tr("Threads:")));
m_threadBox = new QComboBox;
m_threadBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
connect(m_threadBox, static_cast<void(QComboBox::*)(int)>(&QComboBox::activated),
this, &DebuggerPluginPrivate::selectThread);
hbox->addWidget(m_threadBox);
hbox->addSpacerItem(new QSpacerItem(4, 0));
m_mainWindow->setToolBar(CppLanguage, toolbarContainer);
QWidget *qmlToolbar = new QWidget(m_mainWindow);
hbox = new QHBoxLayout(qmlToolbar);
hbox->setMargin(0);
hbox->setSpacing(0);
// currently broken
//hbox->addWidget(toolButton(Constants::QML_UPDATE_ON_SAVE));
hbox->addWidget(toolButton(Constants::QML_SHOW_APP_ON_TOP));
hbox->addWidget(new StyledSeparator);
hbox->addWidget(toolButton(Constants::QML_SELECTTOOL));
hbox->addWidget(toolButton(Constants::QML_ZOOMTOOL));
hbox->addWidget(new StyledSeparator);
m_mainWindow->setToolBar(QmlLanguage, qmlToolbar);
m_mainWindow->setToolBar(AnyLanguage, m_statusLabel);
connect(action(EnableReverseDebugging), &SavedAction::valueChanged,
this, &DebuggerPluginPrivate::enableReverseDebuggingTriggered);
setInitialState();
connectEngine(0);
connect(SessionManager::instance(), &SessionManager::startupProjectChanged,
this, &DebuggerPluginPrivate::onCurrentProjectChanged);
m_commonOptionsPage = new CommonOptionsPage(m_globalDebuggerOptions);
m_plugin->addAutoReleasedObject(m_commonOptionsPage);
m_globalDebuggerOptions->fromSettings();
m_watchersWindow->setVisible(false);
m_returnWindow->setVisible(false);
// time gdb -i mi -ex 'b debuggerplugin.cpp:800' -ex r -ex q bin/qtcreator.bin
}
DebuggerEngine *currentEngine()
{
return dd->m_currentEngine;
}
SavedAction *action(int code)
{
return dd->m_debuggerSettings->item(code);
}
bool boolSetting(int code)
{
return dd->m_debuggerSettings->item(code)->value().toBool();
}
QString stringSetting(int code)
{
QString raw = dd->m_debuggerSettings->item(code)->value().toString();
return globalMacroExpander()->expand(raw);
}
QStringList stringListSetting(int code)
{
return dd->m_debuggerSettings->item(code)->value().toStringList();
}
BreakHandler *breakHandler()
{
return dd->m_breakHandler;
}
void showModuleSymbols(const QString &moduleName, const Symbols &symbols)
{
QTreeWidget *w = new QTreeWidget;
w->setUniformRowHeights(true);
w->setColumnCount(5);
w->setRootIsDecorated(false);
w->setAlternatingRowColors(true);
w->setSortingEnabled(true);
w->setObjectName(QLatin1String("Symbols.") + moduleName);
QStringList header;
header.append(DebuggerPlugin::tr("Symbol"));
header.append(DebuggerPlugin::tr("Address"));
header.append(DebuggerPlugin::tr("Code"));
header.append(DebuggerPlugin::tr("Section"));
header.append(DebuggerPlugin::tr("Name"));
w->setHeaderLabels(header);
w->setWindowTitle(DebuggerPlugin::tr("Symbols in \"%1\"").arg(moduleName));
foreach (const Symbol &s, symbols) {
QTreeWidgetItem *it = new QTreeWidgetItem;
it->setData(0, Qt::DisplayRole, s.name);
it->setData(1, Qt::DisplayRole, s.address);
it->setData(2, Qt::DisplayRole, s.state);
it->setData(3, Qt::DisplayRole, s.section);
it->setData(4, Qt::DisplayRole, s.demangled);
w->addTopLevelItem(it);
}
createNewDock(w);
}
void showModuleSections(const QString &moduleName, const Sections §ions)
{
QTreeWidget *w = new QTreeWidget;
w->setUniformRowHeights(true);
w->setColumnCount(5);
w->setRootIsDecorated(false);
w->setAlternatingRowColors(true);
w->setSortingEnabled(true);
w->setObjectName(QLatin1String("Sections.") + moduleName);
QStringList header;
header.append(DebuggerPlugin::tr("Name"));
header.append(DebuggerPlugin::tr("From"));
header.append(DebuggerPlugin::tr("To"));
header.append(DebuggerPlugin::tr("Address"));
header.append(DebuggerPlugin::tr("Flags"));
w->setHeaderLabels(header);
w->setWindowTitle(DebuggerPlugin::tr("Sections in \"%1\"").arg(moduleName));
foreach (const Section &s, sections) {
QTreeWidgetItem *it = new QTreeWidgetItem;
it->setData(0, Qt::DisplayRole, s.name);
it->setData(1, Qt::DisplayRole, s.from);
it->setData(2, Qt::DisplayRole, s.to);
it->setData(3, Qt::DisplayRole, s.address);
it->setData(4, Qt::DisplayRole, s.flags);
w->addTopLevelItem(it);
}
createNewDock(w);
}
void DebuggerPluginPrivate::aboutToShutdown()
{
disconnect(SessionManager::instance(),
SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
this, 0);
}
void updateState(DebuggerEngine *engine)
{
dd->updateState(engine);
}
void updateWatchersWindow(bool showWatch, bool showReturn)
{
dd->updateWatchersWindow(showWatch, showReturn);
}
QIcon locationMarkIcon()
{
return dd->m_locationMarkIcon;
}
bool hasSnapshots()
{
return dd->m_snapshotHandler->size();
}
void openTextEditor(const QString &titlePattern0, const QString &contents)
{
if (dd->m_shuttingDown)
return;
QString titlePattern = titlePattern0;
IEditor *editor = EditorManager::openEditorWithContents(
CC::K_DEFAULT_TEXT_EDITOR_ID, &titlePattern, contents.toUtf8(),
EditorManager::IgnoreNavigationHistory);
QTC_ASSERT(editor, return);
}
bool isActiveDebugLanguage(int language)
{
return dd->m_mainWindow->activeDebugLanguages() & language;
}
// void runTest(const QString &fileName);
void showMessage(const QString &msg, int channel, int timeout)
{
dd->showMessage(msg, channel, timeout);
}
bool isReverseDebugging()
{
return dd->m_reverseDirectionAction->isChecked();
}
void runControlStarted(DebuggerEngine *engine)
{
dd->runControlStarted(engine);
}
void runControlFinished(DebuggerEngine *engine)
{
dd->runControlFinished(engine);
}
void displayDebugger(DebuggerEngine *engine, bool updateEngine)
{
dd->displayDebugger(engine, updateEngine);
}
DebuggerLanguages activeLanguages()
{
QTC_ASSERT(dd->m_mainWindow, return AnyLanguage);
return dd->m_mainWindow->activeDebugLanguages();
}
void synchronizeBreakpoints()
{
dd->synchronizeBreakpoints();
}
QWidget *mainWindow()
{
return dd->mainWindow();
}
bool isDockVisible(const QString &objectName)
{
return dd->isDockVisible(objectName);
}
void openMemoryEditor()
{
AddressDialog dialog;
if (dialog.exec() == QDialog::Accepted) {
MemoryViewSetupData data;
data.startAddress = dialog.address();
currentEngine()->openMemoryView(data);
}
}
void setThreads(const QStringList &list, int index)
{
dd->setThreads(list, index);
}
QSharedPointer<Internal::GlobalDebuggerOptions> globalDebuggerOptions()
{
return dd->m_globalDebuggerOptions;
}
} // namespace Internal
///////////////////////////////////////////////////////////////////////
//
// DebuggerPlugin
//
///////////////////////////////////////////////////////////////////////
/*!
\class Debugger::DebuggerPlugin
This is the "external" interface of the debugger plugin that's visible
from Qt Creator core. The internal interface to global debugger
functionality that is used by debugger views and debugger engines
is DebuggerCore, implemented in DebuggerPluginPrivate.
*/
DebuggerPlugin::DebuggerPlugin()
{
setObjectName(QLatin1String("DebuggerPlugin"));
addObject(this);
dd = new DebuggerPluginPrivate(this);
}
DebuggerPlugin::~DebuggerPlugin()
{
delete dd;
dd = 0;
}
bool DebuggerPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
// Menu groups
const Context globalcontext(CC::C_GLOBAL);
ActionContainer *mstart = ActionManager::actionContainer(PE::M_DEBUG_STARTDEBUGGING);
mstart->appendGroup(Constants::G_GENERAL);
mstart->appendGroup(Constants::G_SPECIAL);
mstart->appendGroup(Constants::G_START_QML);
// Separators
mstart->addSeparator(globalcontext, Constants::G_GENERAL);
mstart->addSeparator(globalcontext, Constants::G_SPECIAL);
addAutoReleasedObject(new DebuggerItemManager);
DebuggerItemManager::restoreDebuggers();
KitManager::registerKitInformation(new DebuggerKitInformation);
return dd->initialize(arguments, errorMessage);
}
IPlugin::ShutdownFlag DebuggerPlugin::aboutToShutdown()
{
removeObject(this);
dd->aboutToShutdown();
return SynchronousShutdown;
}
QObject *DebuggerPlugin::remoteCommand(const QStringList &options,
const QStringList &list)
{
dd->remoteCommand(options, list);
return 0;
}
void DebuggerPlugin::extensionsInitialized()
{
dd->extensionsInitialized();
}
#ifdef WITH_TESTS
void DebuggerPluginPrivate::testLoadProject(const QString &proFile, const TestCallBack &cb)
{
connect(ProjectTree::instance(), &ProjectTree::currentProjectChanged,
this, &DebuggerPluginPrivate::testProjectLoaded);
m_testCallbacks.append(cb);
QString error;
if (ProjectExplorerPlugin::openProject(proFile, &error)) {
// Will end up in callback below due to the connections to
// signal currentProjectChanged().
return;
}
// Project opening failed. Eat the unused callback.
qWarning("Cannot open %s: %s", qPrintable(proFile), qPrintable(error));
QVERIFY(false);
m_testCallbacks.pop_back();
}
void DebuggerPluginPrivate::testProjectLoaded(Project *project)
{
if (!project) {
qWarning("Changed to null project.");
return;
}
m_testProject = project;
connect(project, SIGNAL(proFilesEvaluated()), SLOT(testProjectEvaluated()));
project->configureAsExampleProject(QStringList());
}
void DebuggerPluginPrivate::testProjectEvaluated()
{
QString fileName = m_testProject->projectFilePath().toUserOutput();
QVERIFY(!fileName.isEmpty());
qWarning("Project %s loaded", qPrintable(fileName));
connect(BuildManager::instance(), SIGNAL(buildQueueFinished(bool)),
SLOT(testProjectBuilt(bool)));
ProjectExplorerPlugin::buildProject(m_testProject);
}
void DebuggerPluginPrivate::testProjectBuilt(bool success)
{
QVERIFY(success);
QVERIFY(!m_testCallbacks.isEmpty());
TestCallBack cb = m_testCallbacks.takeLast();
invoke<void>(cb.receiver, cb.slot);
}
void DebuggerPluginPrivate::testUnloadProject()
{
ProjectExplorerPlugin *pe = ProjectExplorerPlugin::instance();
invoke<void>(pe, "unloadProject");
}
//static Target *activeTarget()
//{
// Project *project = ProjectExplorerPlugin::instance()->currentProject();
// return project->activeTarget();
//}
//static Kit *currentKit()
//{
// Target *t = activeTarget();
// if (!t || !t->isEnabled())
// return 0;
// return t->kit();
//}
//static LocalApplicationRunConfiguration *activeLocalRunConfiguration()
//{
// Target *t = activeTarget();
// return t ? qobject_cast<LocalApplicationRunConfiguration *>(t->activeRunConfiguration()) : 0;
//}
void DebuggerPluginPrivate::testRunProject(const DebuggerStartParameters &sp, const TestCallBack &cb)
{
m_testCallbacks.append(cb);
RunControl *rc = DebuggerRunControlFactory::createAndScheduleRun(sp);
connect(rc, &RunControl::finished, this, &DebuggerPluginPrivate::testRunControlFinished);
}
void DebuggerPluginPrivate::testRunControlFinished()
{
QVERIFY(!m_testCallbacks.isEmpty());
TestCallBack cb = m_testCallbacks.takeLast();
ExtensionSystem::invoke<void>(cb.receiver, cb.slot);
}
void DebuggerPluginPrivate::testFinished()
{
QTestEventLoop::instance().exitLoop();
QVERIFY(m_testSuccess);
}
///////////////////////////////////////////////////////////////////////////
//void DebuggerPlugin::testStateMachine()
//{
// dd->testStateMachine1();
//}
//void DebuggerPluginPrivate::testStateMachine1()
//{
// m_testSuccess = true;
// QString proFile = ICore::resourcePath();
// if (Utils::HostOsInfo::isMacHost())
// proFile += QLatin1String("/../..");
// proFile += QLatin1String("/../../tests/manual/debugger/simple/simple.pro");
// testLoadProject(proFile, TestCallBack(this, "testStateMachine2"));
// QVERIFY(m_testSuccess);
// QTestEventLoop::instance().enterLoop(20);
//}
//void DebuggerPluginPrivate::testStateMachine2()
//{
// DebuggerStartParameters sp;
// fillParameters(&sp, currentKit());
// sp.executable = activeLocalRunConfiguration()->executable();
// sp.testCase = TestNoBoundsOfCurrentFunction;
// testRunProject(sp, TestCallBack(this, "testStateMachine3"));
//}
//void DebuggerPluginPrivate::testStateMachine3()
//{
// testUnloadProject();
// testFinished();
//}
///////////////////////////////////////////////////////////////////////////
void DebuggerPlugin::testBenchmark()
{
dd->testBenchmark1();
}
enum FakeEnum { FakeDebuggerCommonSettingsId };
void DebuggerPluginPrivate::testBenchmark1()
{
#ifdef WITH_BENCHMARK
CALLGRIND_START_INSTRUMENTATION;
volatile Core::Id id1 = Core::Id(DEBUGGER_COMMON_SETTINGS_ID);
CALLGRIND_STOP_INSTRUMENTATION;
CALLGRIND_DUMP_STATS;
CALLGRIND_START_INSTRUMENTATION;
volatile FakeEnum id2 = FakeDebuggerCommonSettingsId;
CALLGRIND_STOP_INSTRUMENTATION;
CALLGRIND_DUMP_STATS;
#endif
}
#endif // if WITH_TESTS
} // namespace Debugger
#include "debuggerplugin.moc"
| farseerri/git_code | src/plugins/debugger/debuggerplugin.cpp | C++ | lgpl-2.1 | 133,201 |
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "objectpropertybinding.h"
namespace QmlDesigner {
ObjectPropertyBinding::ObjectPropertyBinding()
{
}
ObjectPropertyBinding::ObjectPropertyBinding(const ModelNode &node)
: m_node(node)
{
}
ModelNode ObjectPropertyBinding::modelNode() const
{
return m_node;
}
bool ObjectPropertyBinding::isValid() const
{
return m_node.isValid();
}
} // namespace QmlDesigner
| gidlbn/dlbn_02 | src/plugins/qmldesigner/designercore/model/objectpropertybinding.cpp | C++ | lgpl-2.1 | 1,611 |
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# 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 terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Fp16(Package):
"""FP16 is a header-only library for
conversion to/from half-precision floating point formats"""
homepage = "https://github.com/Maratyszcza/FP16/"
git = "https://github.com/Maratyszcza/FP16.git"
version('master')
def install(self, spec, prefix):
install_tree('include', prefix.include)
| mfherbst/spack | var/spack/repos/builtin/packages/fp16/package.py | Python | lgpl-2.1 | 1,604 |
/*
* !!!!!
* NOTE: PLEASE ONLY EDIT THIS USING THE NETBEANS IDE 6.0.1 OR HIGHER!!!!
* !!!!!
*
* ... an .xml file is associated with this class. Cheers.
*
* BotConsoleFrame.java
*
* Created on 28 March 2008, 08:35
*/
package org.reprap.gui.botConsole;
import org.reprap.Preferences;
import org.reprap.utilities.Debug;
import javax.swing.JOptionPane;
/**
*
* @author Ed Sells, March 2008
*
* Console to operate the RepRap printer manually.
*
*/
public class BotConsoleFrame extends javax.swing.JFrame {
private static final long serialVersionUID = 1L;
private Thread pollThread = null;
boolean updatePosition = false;
private boolean carryOnPolling = true;
private GenericExtruderTabPanel[] extruderPanels;
double fractionDone = -1;
int layer = -1;
int outOf = -1;
private static BotConsoleFrame bcf = null;
private static int exPanelNumber;
/** Creates new form BotConsoleFrame */
public BotConsoleFrame() {
try {
checkPrefs();
}
catch (Exception e) {
Debug.e("Failure trying to initialise comms in botConsole: " + e);
JOptionPane.showMessageDialog(null, e.getMessage());
return;
}
updatePosition = false;
initComponents();
this.setTitle("RepRap Console");
/*
* Fork off a thread to keep the panels up-to-date
*/
exPanelNumber = 0;
pollThread = new Thread()
{
public void run()
{
Thread.currentThread().setName("GUI Poll");
while(true)
{
try
{
Thread.sleep(1500);
updateProgress();
if(carryOnPolling)
updatePanels();
} catch (InterruptedException ex)
{
// This is normal when shutting down, so ignore
}
}
}
};
pollThread.start();
}
public void handleException(Exception e)
{
}
/**
* The update thread calls this to update everything
* that relies on information from the RepRap machine.
*/
private void updatePanels()
{
int currentExtruder = org.reprap.Main.gui.getPrinter().getExtruder().getID();
try {
org.reprap.Main.gui.getPrinter().selectExtruder(exPanelNumber, true);
} catch (Exception e) {
handleException(e);
}
extruderPanels[exPanelNumber].refreshTemperature();
try {
org.reprap.Main.gui.getPrinter().selectExtruder(currentExtruder, true);
} catch (Exception e) {
handleException(e);
}
exPanelNumber++;
if(exPanelNumber >= extruderPanels.length)
{
xYZTabPanel.refreshTemperature();
exPanelNumber = 0;
}
if(updatePosition)
xYZTabPanel.recordCurrentPosition();
updatePosition = false;
}
public void getPosition()
{
updatePosition = true;
}
/**
* The update thread calls this to update everything
* that is independent of the RepRap machine.
* @param fractionDone
*/
private void updateProgress()
{
printTabFrame1.updateProgress(fractionDone, layer, outOf);
}
public void setFractionDone(double f, int l, int o)
{
if(f >= 0)
fractionDone = f;
if(l >= 0)
layer = l;
if(o >= 0)
outOf = o;
}
/**
* "Suspend" and "resume" the poll thread.
* We don't use the actual suspend call (depricated anyway) to
* prevent resource locking.
*
*/
public void suspendPolling()
{
carryOnPolling = false;
try
{
Thread.sleep(200);
} catch (InterruptedException ex)
{
// This is normal when shutting down, so ignore
}
}
public void resumePolling()
{
try
{
Thread.sleep(200);
} catch (InterruptedException ex)
{
// This is normal when shutting down, so ignore
}
carryOnPolling = true;
}
private void checkPrefs() throws Exception {
// ID the number of extruder
extruderCount = Preferences.loadGlobalInt("NumberOfExtruders");
if (extruderCount < 1)
throw new Exception("A Reprap printer must contain at least one extruder");
}
private void initialiseExtruderPanels() {
extruderPanels = new GenericExtruderTabPanel[extruderCount];
for (int i = 0; i < extruderCount; i++) {
extruderPanels[i] = new GenericExtruderTabPanel();
try {
extruderPanels[i].initialiseExtruders(i);
}
catch (Exception e) {
System.out.println("Failure trying to initialise extruders in botConsole: " + e);
JOptionPane.showMessageDialog(null, e.getMessage());
return;
}
try {
extruderPanels[i].setPrefs();
}
catch (Exception e) {
System.out.println("Problem loading prefs for Extruder " + i);
JOptionPane.showMessageDialog(null, "Problem loading prefs for Extruder " + i);
}
}
}
private void addExtruderPanels() {
xYZTabPanel = new org.reprap.gui.botConsole.XYZTabPanel();
jTabbedPane1.addTab("XYZ", xYZTabPanel);
for (int i = 0; i < extruderCount; i++) {
//jTabbedPane1.addTab("Extruder " + i, extruderPanels[i]);
jTabbedPane1.addTab(extruderPanels[i].getExtruder().getMaterial(), extruderPanels[i]);
}
pack();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jTabbedPane1 = new javax.swing.JTabbedPane();
initialiseExtruderPanels();
printTabFrame1 = new org.reprap.gui.botConsole.PrintTabFrame(false);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTabbedPane1.setRequestFocusEnabled(false);
jTabbedPane1.addTab("Print", printTabFrame1);
addExtruderPanels();
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(jTabbedPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 750, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap(5, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(jTabbedPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 430, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap(5, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
bcf = new BotConsoleFrame();
bcf.setVisible(true);
bcf.printTabFrame1.setConsoleFrame(bcf);
bcf.xYZTabPanel.setConsoleFrame(bcf);
for(int i = 0; i < bcf.extruderPanels.length; i++)
bcf.extruderPanels[i].setConsoleFrame(bcf);
}
});
}
public static BotConsoleFrame getBotConsoleFrame()
{
return bcf;
}
//
// public static org.reprap.gui.botConsole.XYZTabPanel XYZ()
// {
// return bcf.xYZTabPanel;
// }
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTabbedPane jTabbedPane1;
private org.reprap.gui.botConsole.PrintTabFrame printTabFrame1;
// End of variables declaration//GEN-END:variables
private org.reprap.gui.botConsole.XYZTabPanel xYZTabPanel;
// private static int motorID = 0;
// public static int getMotorID() {
// motorID++;
// return motorID;
// }
public static PrintTabFrame getPrintTabFrame()
{
return bcf.printTabFrame1;
}
public static XYZTabPanel getXYZTabPanel()
{
return bcf.xYZTabPanel;
}
public static GenericExtruderTabPanel getGenericExtruderTabPanel(int i)
{
if(i >= 0 && i < bcf.extruderPanels.length)
return bcf.extruderPanels[i];
Debug.e("getGenericExtruderTabPanel - extruder out of range: " + i);
return bcf.extruderPanels[0];
}
private int extruderCount;
//private int currentExtruder;
}
| alex1818/host | src/org/reprap/gui/botConsole/BotConsoleFrame.java | Java | lgpl-2.1 | 9,111 |
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qmljseditoractionhandler.h"
#include "qmljseditorconstants.h"
#include "qmljseditor.h"
#include <coreplugin/icore.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <QDebug>
#include <QAction>
#include <QMessageBox>
namespace QmlJSEditor {
namespace Internal {
QmlJSEditorActionHandler::QmlJSEditorActionHandler()
: TextEditor::TextEditorActionHandler(QmlJSEditor::Constants::C_QMLJSEDITOR_ID, Format)
{
}
void QmlJSEditorActionHandler::createActions()
{
TextEditor::TextEditorActionHandler::createActions();
}
} // namespace Internal
} // namespace QmlJSEditor
| mornelon/QtCreator_compliments | src/plugins/qmljseditor/qmljseditoractionhandler.cpp | C++ | lgpl-2.1 | 2,052 |
/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_SYMBOLIZER_HPP
#define MAPNIK_SYMBOLIZER_HPP
// mapnik
#include <mapnik/config.hpp>
#include <mapnik/path_expression.hpp>
#include <mapnik/image_compositing.hpp>
#include <mapnik/simplify.hpp>
// boost
#include <memory>
// stl
#include <vector>
#include <string>
namespace agg { struct trans_affine; }
namespace mapnik
{
// fwd declares
// TODO - move these transform declares to own header
namespace detail { struct transform_node; }
typedef std::vector<detail::transform_node> transform_list;
typedef std::shared_ptr<transform_list> transform_list_ptr;
typedef transform_list_ptr transform_type;
class feature_impl;
MAPNIK_DECL void evaluate_transform(agg::trans_affine& tr, feature_impl const& feature,
transform_type const& trans_expr);
class MAPNIK_DECL symbolizer_base
{
public:
symbolizer_base();
symbolizer_base(symbolizer_base const& other);
void set_comp_op(composite_mode_e comp_op);
composite_mode_e comp_op() const;
void set_transform(transform_type const& );
transform_type const& get_transform() const;
std::string get_transform_string() const;
void set_clip(bool clip);
bool clip() const;
void set_simplify_algorithm(simplify_algorithm_e algorithm);
simplify_algorithm_e simplify_algorithm() const;
void set_simplify_tolerance(double simplify_tolerance);
double simplify_tolerance() const;
void set_smooth(double smooth);
double smooth() const;
private:
composite_mode_e comp_op_;
transform_type affine_transform_;
bool clip_;
simplify_algorithm_e simplify_algorithm_value_;
double simplify_tolerance_value_;
double smooth_value_;
};
class MAPNIK_DECL symbolizer_with_image
{
public:
path_expression_ptr const& get_filename() const;
void set_filename(path_expression_ptr const& filename);
void set_opacity(float opacity);
float get_opacity() const;
void set_image_transform(transform_type const& tr);
transform_type const& get_image_transform() const;
std::string get_image_transform_string() const;
protected:
symbolizer_with_image(path_expression_ptr filename = path_expression_ptr());
symbolizer_with_image(symbolizer_with_image const& rhs);
path_expression_ptr image_filename_;
float image_opacity_;
transform_type image_transform_;
};
}
#endif // MAPNIK_SYMBOLIZER_HPP
| yiqingj/work | include/mapnik/symbolizer.hpp | C++ | lgpl-2.1 | 3,393 |
// This file was generated by the Gtk# code generator.
// Any changes made will be lost if regenerated.
namespace Gst {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
#region Autogenerated code
[StructLayout(LayoutKind.Sequential)]
public partial struct CustomMeta : IEquatable<CustomMeta> {
public Gst.Meta Meta;
public static Gst.CustomMeta Zero = new Gst.CustomMeta ();
public static Gst.CustomMeta New(IntPtr raw) {
if (raw == IntPtr.Zero)
return Gst.CustomMeta.Zero;
return (Gst.CustomMeta) Marshal.PtrToStructure (raw, typeof (Gst.CustomMeta));
}
[DllImport("gstreamer-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr gst_custom_meta_get_structure(IntPtr raw);
public Gst.Structure Structure {
get {
IntPtr this_as_native = System.Runtime.InteropServices.Marshal.AllocHGlobal (System.Runtime.InteropServices.Marshal.SizeOf (this));
System.Runtime.InteropServices.Marshal.StructureToPtr (this, this_as_native, false);
IntPtr raw_ret = gst_custom_meta_get_structure(this_as_native);
Gst.Structure ret = raw_ret == IntPtr.Zero ? null : (Gst.Structure) GLib.Opaque.GetOpaque (raw_ret, typeof (Gst.Structure), false);
ReadNative (this_as_native, ref this);
System.Runtime.InteropServices.Marshal.FreeHGlobal (this_as_native);
return ret;
}
}
[DllImport("gstreamer-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)]
static extern bool gst_custom_meta_has_name(IntPtr raw, IntPtr name);
public bool HasName(string name) {
IntPtr this_as_native = System.Runtime.InteropServices.Marshal.AllocHGlobal (System.Runtime.InteropServices.Marshal.SizeOf (this));
System.Runtime.InteropServices.Marshal.StructureToPtr (this, this_as_native, false);
IntPtr native_name = GLib.Marshaller.StringToPtrGStrdup (name);
bool raw_ret = gst_custom_meta_has_name(this_as_native, native_name);
bool ret = raw_ret;
ReadNative (this_as_native, ref this);
System.Runtime.InteropServices.Marshal.FreeHGlobal (this_as_native);
GLib.Marshaller.Free (native_name);
return ret;
}
static void ReadNative (IntPtr native, ref Gst.CustomMeta target)
{
target = New (native);
}
public bool Equals (CustomMeta other)
{
return true && Meta.Equals (other.Meta);
}
public override bool Equals (object other)
{
return other is CustomMeta && Equals ((CustomMeta) other);
}
public override int GetHashCode ()
{
return this.GetType ().FullName.GetHashCode () ^ Meta.GetHashCode ();
}
private static GLib.GType GType {
get { return GLib.GType.Pointer; }
}
#endregion
}
}
| gstreamer-sharp/gstreamer-sharp | sources/generated/Gst/CustomMeta.cs | C# | lgpl-2.1 | 2,690 |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyBxPython(PythonPackage):
"""The bx-python project is a python library and associated set of scripts
to allow for rapid implementation of genome scale analyses."""
homepage = "https://github.com/bxlab/bx-python"
pypi = "bx-python/bx-python-0.8.8.tar.gz"
version('0.8.8', sha256='ad0808ab19c007e8beebadc31827e0d7560ac0e935f1100fb8cc93607400bb47')
version('0.7.4',
sha256='1066d1e56d062d0661f23c19942eb757bd7ab7cb8bc7d89a72fdc3931c995cb4',
url="https://github.com/bxlab/bx-python/archive/v0.7.4.tar.gz", deprecated=True)
depends_on('python@2.4:2.7', type=('build', 'run'), when='@:0.7')
depends_on('python@2.7:2.8,3.5:', type=('build', 'run'), when='@0.8:')
depends_on('py-setuptools', type='build')
depends_on('py-python-lzo', type=('build', 'run'), when='@:0.7')
depends_on('py-cython', type='build', when='@0.8:')
depends_on('py-numpy', type=('build', 'run'))
depends_on('py-six', type=('build', 'run'), when='@0.8:')
| LLNL/spack | var/spack/repos/builtin/packages/py-bx-python/package.py | Python | lgpl-2.1 | 1,225 |
///////////////////////////////////////////////////////////////////////////////
// Name: src/gtk/infobar.cpp
// Purpose: wxInfoBar implementation for GTK
// Author: Vadim Zeitlin
// Created: 2009-09-27
// RCS-ID: $Id$
// Copyright: (c) 2009 Vadim Zeitlin <vadim@wxwidgets.org>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// for compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#include "wx/infobar.h"
#if wxUSE_INFOBAR && defined(wxHAS_NATIVE_INFOBAR)
#ifndef WX_PRECOMP
#endif // WX_PRECOMP
#include "wx/vector.h"
#include "wx/stockitem.h"
#include "wx/gtk/private.h"
#include "wx/gtk/private/messagetype.h"
// ----------------------------------------------------------------------------
// local classes
// ----------------------------------------------------------------------------
class wxInfoBarGTKImpl
{
public:
wxInfoBarGTKImpl()
{
m_label = NULL;
m_close = NULL;
}
// label for the text shown in the bar
GtkWidget *m_label;
// the default close button, NULL if not needed (m_buttons is not empty) or
// not created yet
GtkWidget *m_close;
// information about the buttons added using AddButton()
struct Button
{
Button(GtkWidget *button_, int id_)
: button(button_),
id(id_)
{
}
GtkWidget *button;
int id;
};
typedef wxVector<Button> Buttons;
Buttons m_buttons;
};
// ----------------------------------------------------------------------------
// local functions
// ----------------------------------------------------------------------------
namespace
{
inline bool UseNative()
{
#ifdef __WXGTK3__
return true;
#else
// native GtkInfoBar widget is only available in GTK+ 2.18 and later
return gtk_check_version(2, 18, 0) == 0;
#endif
}
} // anonymous namespace
extern "C"
{
static void wxgtk_infobar_response(GtkInfoBar * WXUNUSED(infobar),
gint btnid,
wxInfoBar *win)
{
win->GTKResponse(btnid);
}
static void wxgtk_infobar_close(GtkInfoBar * WXUNUSED(infobar),
wxInfoBar *win)
{
win->GTKResponse(wxID_CANCEL);
}
} // extern "C" section with GTK+ callbacks
// ============================================================================
// wxInfoBar implementation
// ============================================================================
bool wxInfoBar::Create(wxWindow *parent, wxWindowID winid)
{
if ( !UseNative() )
return wxInfoBarGeneric::Create(parent, winid);
m_impl = new wxInfoBarGTKImpl;
// this control is created initially hidden
Hide();
if ( !CreateBase(parent, winid) )
return false;
// create the info bar widget itself
m_widget = gtk_info_bar_new();
wxCHECK_MSG( m_widget, false, "failed to create GtkInfoBar" );
g_object_ref(m_widget);
// also create a label which will be used to show our message
m_impl->m_label = gtk_label_new("");
gtk_widget_show(m_impl->m_label);
GtkWidget * const
contentArea = gtk_info_bar_get_content_area(GTK_INFO_BAR(m_widget));
wxCHECK_MSG( contentArea, false, "failed to get GtkInfoBar content area" );
gtk_container_add(GTK_CONTAINER(contentArea), m_impl->m_label);
// finish creation and connect to all the signals we're interested in
m_parent->DoAddChild(this);
PostCreation(wxDefaultSize);
GTKConnectWidget("response", G_CALLBACK(wxgtk_infobar_response));
GTKConnectWidget("close", G_CALLBACK(wxgtk_infobar_close));
return true;
}
wxInfoBar::~wxInfoBar()
{
delete m_impl;
}
void wxInfoBar::ShowMessage(const wxString& msg, int flags)
{
if ( !UseNative() )
{
wxInfoBarGeneric::ShowMessage(msg, flags);
return;
}
// if we don't have any buttons, create a standard close one to give the
// user at least some way to close the bar
if ( m_impl->m_buttons.empty() && !m_impl->m_close )
{
m_impl->m_close = GTKAddButton(wxID_CLOSE);
}
GtkMessageType type;
if ( wxGTKImpl::ConvertMessageTypeFromWX(flags, &type) )
gtk_info_bar_set_message_type(GTK_INFO_BAR(m_widget), type);
gtk_label_set_text(GTK_LABEL(m_impl->m_label), wxGTK_CONV(msg));
if ( !IsShown() )
Show();
UpdateParent();
}
void wxInfoBar::Dismiss()
{
if ( !UseNative() )
{
wxInfoBarGeneric::Dismiss();
return;
}
Hide();
UpdateParent();
}
void wxInfoBar::GTKResponse(int btnid)
{
wxCommandEvent event(wxEVT_COMMAND_BUTTON_CLICKED, btnid);
event.SetEventObject(this);
if ( !HandleWindowEvent(event) )
Dismiss();
}
GtkWidget *wxInfoBar::GTKAddButton(wxWindowID btnid, const wxString& label)
{
// as GTK+ lays out the buttons vertically, adding another button changes
// our best size (at least in vertical direction)
InvalidateBestSize();
GtkWidget *button = gtk_info_bar_add_button
(
GTK_INFO_BAR(m_widget),
(label.empty()
? GTKConvertMnemonics(wxGetStockGtkID(btnid))
: label).utf8_str(),
btnid
);
wxASSERT_MSG( button, "unexpectedly failed to add button to info bar" );
return button;
}
void wxInfoBar::AddButton(wxWindowID btnid, const wxString& label)
{
if ( !UseNative() )
{
wxInfoBarGeneric::AddButton(btnid, label);
return;
}
// if we had created the default close button before, remove it now that we
// have some user-defined button
if ( m_impl->m_close )
{
gtk_widget_destroy(m_impl->m_close);
m_impl->m_close = NULL;
}
GtkWidget * const button = GTKAddButton(btnid, label);
if ( button )
m_impl->m_buttons.push_back(wxInfoBarGTKImpl::Button(button, btnid));
}
void wxInfoBar::RemoveButton(wxWindowID btnid)
{
if ( !UseNative() )
{
wxInfoBarGeneric::RemoveButton(btnid);
return;
}
// as in the generic version, look for the button starting from the end
wxInfoBarGTKImpl::Buttons& buttons = m_impl->m_buttons;
for ( wxInfoBarGTKImpl::Buttons::reverse_iterator i = buttons.rbegin();
i != buttons.rend();
++i )
{
if (i->id == btnid)
{
gtk_widget_destroy(i->button);
buttons.erase(i.base());
// see comment in GTKAddButton()
InvalidateBestSize();
return;
}
}
wxFAIL_MSG( wxString::Format("button with id %d not found", btnid) );
}
void wxInfoBar::DoApplyWidgetStyle(GtkRcStyle *style)
{
wxInfoBarGeneric::DoApplyWidgetStyle(style);
if ( UseNative() )
GTKApplyStyle(m_impl->m_label, style);
}
#endif // wxUSE_INFOBAR
| enachb/freetel-code | src/wxWidgets-2.9.4/src/gtk/infobar.cpp | C++ | lgpl-2.1 | 7,415 |
<?php
/*
* LegionPE
*
* Copyright (C) 2015 PEMapModder and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PEMapModder
*/
namespace legionpe\theta\command;
use legionpe\theta\BasePlugin;
use legionpe\theta\lang\Phrases;
use legionpe\theta\Session;
use legionpe\theta\utils\MUtils;
use pocketmine\command\CommandSender;
use pocketmine\Player;
class RestartCommand extends ThetaCommand{
public function __construct(BasePlugin $main){
parent::__construct($main, "restart", "Check server restart time", "/restart", ["rst"]);
}
public function execute(CommandSender $sender, $commandLabel, array $args){
$leftTicks = $this->getMain()->getServer()->getTick() - $this->getMain()->getRestartTime();
$leftSecs = $leftTicks / 20;
$string = MUtils::time_secsToString((int) $leftSecs);
if($sender instanceof Player and ($ses = $this->getSession($sender)) instanceof Session){
$ses->translate(Phrases::CMD_RESTART_RESPONSE, ["time" => $string]);
}else{
$sender->sendMessage(Phrases::VAR_em . $string . Phrases::VAR_info . " left before server restart");
}
}
}
| LegionPE/LegionPE-Theta-Base | src/legionpe/theta/command/RestartCommand.php | PHP | lgpl-3.0 | 1,320 |
import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate()
mobileTemplate.setCreatureName('greck_smuggler')
mobileTemplate.setLevel(25)
mobileTemplate.setDifficulty(Difficulty.NORMAL)
mobileTemplate.setMinSpawnDistance(4)
mobileTemplate.setMaxSpawnDistance(8)
mobileTemplate.setDeathblow(False)
mobileTemplate.setScale(1)
mobileTemplate.setSocialGroup("olag greck")
mobileTemplate.setAssistRange(6)
mobileTemplate.setStalker(True)
mobileTemplate.setOptionsBitmask(128)
templates = Vector()
templates.add('object/mobile/shared_greck_thug_f_01.iff')
templates.add('object/mobile/shared_greck_thug_f_02.iff')
templates.add('object/mobile/shared_greck_thug_f_03.iff')
templates.add('object/mobile/shared_greck_thug_m_01.iff')
templates.add('object/mobile/shared_greck_thug_m_02.iff')
templates.add('object/mobile/shared_greck_thug_m_03.iff')
templates.add('object/mobile/shared_greck_thug_m_04.iff')
templates.add('object/mobile/shared_greck_thug_m_05.iff')
mobileTemplate.setTemplates(templates)
weaponTemplates = Vector()
weapontemplate = WeaponTemplate('object/weapon/melee/unarmed/shared_unarmed_default.iff', WeaponType.UNARMED, 1.0, 6, 'kinetic')
weaponTemplates.add(weapontemplate)
mobileTemplate.setWeaponTemplateVector(weaponTemplates)
attacks = Vector()
mobileTemplate.setDefaultAttack('meleeHit')
mobileTemplate.setAttacks(attacks)
lootPoolNames_1 = ['Junk']
lootPoolChances_1 = [100]
lootGroupChance_1 = 100
mobileTemplate.addToLootGroups(lootPoolNames_1,lootPoolChances_1,lootGroupChance_1)
core.spawnService.addMobileTemplate('greck_smuggler', mobileTemplate)
return | ProjectSWGCore/NGECore2 | scripts/mobiles/corellia/greck_smuggler.py | Python | lgpl-3.0 | 1,924 |
import re
from vFense.operations._constants import vFensePlugins
VALID_NOTIFICATION_PLUGINS = (
vFensePlugins.RV_PLUGIN, vFensePlugins.MONITORING_PLUGIN
)
INSTALL = 'install'
UNINSTALL = 'uninstall'
REBOOT = 'reboot'
SHUTDOWN = 'shutdown'
PASS = 'pass'
FAIL = 'fail'
CPU = 'cpu'
MEM = 'mem'
FS = 'filesystem'
VALID_RV_NOTIFICATIONS = (INSTALL, UNINSTALL, REBOOT, SHUTDOWN)
VALID_MONITORING_NOTIFICATIONS = (CPU, MEM, FS)
VALID_NOTIFICATIONS = VALID_RV_NOTIFICATIONS + VALID_MONITORING_NOTIFICATIONS
VALID_STATUSES_TO_ALERT_ON = (PASS, FAIL)
class NotificationCollections():
Notifications = 'notifications'
NotificationsHistory = 'notifications_history'
NotificationPlugins = 'notification_plugins'
class NotificationKeys():
NotificationId = 'notification_id'
NotificationType = 'notification_type'
RuleName = 'rule_name'
RuleDescription = 'rule_description'
CreatedBy = 'created_by'
CreatedTime = 'created_time'
ModifiedBy = 'modified_by'
ModifiedTime = 'modified_time'
Plugin = 'plugin'
User = 'user'
Group = 'group'
AllAgents = 'all_agents'
Agents = 'agents'
Tags = 'tags'
CustomerName = 'customer_name'
AppThreshold = 'app_threshold'
RebootThreshold = 'reboot_threshold'
ShutdownThreshold = 'shutdown_threshold'
CpuThreshold = 'cpu_threshold'
MemThreshold = 'mem_threshold'
FileSystemThreshold = 'filesystem_threshold'
FileSystem = 'filesystem'
class NotificationIndexes():
CustomerName = 'customer_name'
RuleNameAndCustomer = 'rule_name_and_customer'
NotificationTypeAndCustomer = 'notification_type_and_customer'
AppThresholdAndCustomer = 'app_threshold_and_customer'
RebootThresholdAndCustomer = 'reboot_threshold_and_customer'
ShutdownThresholdAndCustomer = 'shutdown_threshold_and_customer'
MemThresholdAndCustomer = 'mem_threshold_and_customer'
CpuThresholdAndCustomer = 'cpu_threshold_and_customer'
FileSystemThresholdAndFileSystemAndCustomer = (
'fs_threshold_and_fs_and_customer'
)
class NotificationHistoryKeys():
Id = 'id'
NotificationId = 'notification_id'
AlertSent = 'alert_sent'
AlertSentTime = 'alert_sent_time'
class NotificationHistoryIndexes():
NotificationId = 'notification_id'
class NotificationPluginKeys():
Id = 'id'
CustomerName = 'customer_name'
PluginName = 'plugin_name'
CreatedTime = 'created_time'
ModifiedTime = 'modified_time'
CreatedBy = 'created_by'
ModifiedBy = 'modified_by'
UserName = 'username'
Password = 'password'
Server = 'server'
Port = 'port'
IsTls = 'is_tls'
IsSsl = 'is_ssl'
FromEmail = 'from_email'
ToEmail = 'to_email'
class NotificationPluginIndexes():
CustomerName = 'customer_name'
def return_notif_type_from_operation(oper_type):
if re.search(r'^install', oper_type):
oper_type = INSTALL
elif re.search(r'^uninstall', oper_type):
oper_type = UNINSTALL
elif oper_type == REBOOT:
oper_type = REBOOT
elif oper_type == SHUTDOWN:
oper_type = SHUTDOWN
return(oper_type)
| dtklein/vFense | tp/src/notifications/__init__.py | Python | lgpl-3.0 | 3,134 |
//
// ValidationException.cs
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2008-2011 Novell Inc. http://novell.com
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace System.ComponentModel.DataAnnotations
{
[Serializable]
public class ValidationException : Exception
{
public ValidationException ()
{
}
public ValidationException (string message)
: base (message)
{
}
public ValidationException (string message, Exception innerException)
: base (message, innerException)
{
}
public ValidationException (string errorMessage, ValidationAttribute validatingAttribute, object value)
: base (errorMessage)
{
ValidationAttribute = validatingAttribute;
Value = value;
}
protected ValidationException (SerializationInfo info, StreamingContext context)
: base (info, context)
{
throw new NotImplementedException ();
}
#if NET_4_0
public ValidationException (ValidationResult validationResult, ValidationAttribute validatingAttribute, object value)
: this (validationResult != null ? validationResult.ErrorMessage : null, validatingAttribute, value)
{
this.ValidationResult = validationResult;
}
public ValidationResult ValidationResult { get; private set; }
#endif
public ValidationAttribute ValidationAttribute { get; private set; }
public object Value { get; private set; }
#if !NET_4_5
[SecurityPermission (SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData (SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException ();
}
#endif
}
}
| edwinspire/VSharp | class/System.ComponentModel.DataAnnotations/System.ComponentModel.DataAnnotations/ValidationException.cs | C# | lgpl-3.0 | 2,799 |
def itemTemplate():
return ['object/tangible/component/weapon/lightsaber/shared_lightsaber_module_force_crystal.iff']
def customItemName():
return "Shard Of The Serpent"
def biolink():
return 1
def customColor1():
return 3
def lootDescriptor():
return 'rarebuffitem'
def itemStats():
stats =['proc_name','towCrystalUberCombat','towCrystalUberCombat']
stats +=['effectname','Harmonious Counteraction','Harmonious Counteraction']
stats +=['duration','180','180']
stats +=['cooldown','3600','3600']
return stats | agry/NGECore2 | scripts/loot/lootItems/rarelootchest/shard_of_the_serpent.py | Python | lgpl-3.0 | 538 |
/*
* Copyright 2010-2015 Bastian Eicher
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.IO;
using System.Linq;
using System.Net;
using JetBrains.Annotations;
using Microsoft.Win32;
using NanoByte.Common;
using NanoByte.Common.Native;
using NanoByte.Common.Storage;
using NanoByte.Common.Tasks;
using ZeroInstall.DesktopIntegration.Properties;
using ZeroInstall.Store;
namespace ZeroInstall.DesktopIntegration.Windows
{
/// <summary>
/// Contains control logic for applying <see cref="AccessPoints.AppAlias"/> on Windows systems.
/// </summary>
public static class AppAlias
{
#region Constants
/// <summary>The HKCU/HKLM registry key for storing application lookup paths.</summary>
public const string RegKeyAppPaths = @"Software\Microsoft\Windows\CurrentVersion\App Paths";
#endregion
#region Create
/// <summary>
/// Creates an application alias in the current system.
/// </summary>
/// <param name="target">The application being integrated.</param>
/// <param name="command">The command within <paramref name="target"/> the alias shall point to; can be <see langword="null"/>.</param>
/// <param name="aliasName">The name of the alias to be created.</param>
/// <param name="machineWide">Create the alias machine-wide instead of just for the current user.</param>
/// <param name="handler">A callback object used when the the user is to be informed about the progress of long-running operations such as downloads.</param>
/// <exception cref="OperationCanceledException">The user canceled the task.</exception>
/// <exception cref="IOException">A problem occurs while writing to the filesystem or registry.</exception>
/// <exception cref="WebException">A problem occured while downloading additional data (such as icons).</exception>
/// <exception cref="UnauthorizedAccessException">Write access to the filesystem or registry is not permitted.</exception>
public static void Create(FeedTarget target, [CanBeNull] string command, [NotNull] string aliasName, bool machineWide, [NotNull] ITaskHandler handler)
{
#region Sanity checks
if (string.IsNullOrEmpty(aliasName)) throw new ArgumentNullException("aliasName");
if (handler == null) throw new ArgumentNullException("handler");
#endregion
if (string.IsNullOrEmpty(aliasName) || aliasName.IndexOfAny(Path.GetInvalidFileNameChars()) != -1)
throw new IOException(string.Format(Resources.NameInvalidChars, aliasName));
string stubDirPath = Locations.GetIntegrationDirPath("0install.net", machineWide, "desktop-integration", "aliases");
string stubFilePath = Path.Combine(stubDirPath, aliasName + ".exe");
target.BuildRunStub(stubFilePath, handler, needsTerminal: true, command: command);
AddToPath(stubDirPath, machineWide);
AddToAppPaths(aliasName + ".exe", stubFilePath, machineWide);
}
/// <summary>
/// Adds a directory to the system's search path.
/// </summary>
/// <param name="directory">The directory to add to the search path.</param>
/// <param name="machineWide"><see langword="true"/> to use the machine-wide path variable; <see langword="false"/> for the per-user variant.</param>
private static void AddToPath(string directory, bool machineWide)
{
var variableTarget = machineWide ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User;
string existingValue = Environment.GetEnvironmentVariable("PATH", variableTarget);
if (existingValue == null || !existingValue.Contains(directory))
{
Environment.SetEnvironmentVariable("PATH", existingValue + Path.PathSeparator + directory, variableTarget);
WindowsUtils.NotifyEnvironmentChanged();
}
}
/// <summary>
/// Adds an EXE to the AppPath registry key.
/// </summary>
/// <param name="exeName">The name of the EXE file to add (including the file ending).</param>
/// <param name="exePath">The full path to the EXE file.</param>
/// <param name="machineWide"><see langword="true"/> to use the machine-wide registry key; <see langword="false"/> for the per-user variant.</param>
private static void AddToAppPaths(string exeName, string exePath, bool machineWide)
{
// Only Windows 7 and newer support per-user AppPaths
if (!machineWide && !WindowsUtils.IsWindows7) return;
var hive = machineWide ? Registry.LocalMachine : Registry.CurrentUser;
using (var appPathsKey = hive.CreateSubKeyChecked(RegKeyAppPaths))
using (var exeKey = appPathsKey.CreateSubKeyChecked(exeName))
exeKey.SetValue("", exePath);
}
#endregion
#region Remove
/// <summary>
/// Removes an application alias from the current system.
/// </summary>
/// <param name="aliasName">The name of the alias to be removed.</param>
/// <param name="machineWide">The alias was created machine-wide instead of just for the current user.</param>
/// <exception cref="IOException">A problem occurs while writing to the filesystem or registry.</exception>
/// <exception cref="UnauthorizedAccessException">Write access to the filesystem or registry is not permitted.</exception>
public static void Remove(string aliasName, bool machineWide)
{
#region Sanity checks
if (string.IsNullOrEmpty(aliasName)) throw new ArgumentNullException("aliasName");
#endregion
string stubDirPath = Locations.GetIntegrationDirPath("0install.net", machineWide, "desktop-integration", "aliases");
string stubFilePath = Path.Combine(stubDirPath, aliasName + ".exe");
RemoveFromAppPaths(aliasName + ".exe", machineWide);
if (File.Exists(stubFilePath)) File.Delete(stubFilePath);
}
/// <summary>
/// Removes an EXE from the AppPath registry key.
/// </summary>
/// <param name="exeName">The name of the EXE file to add (including the file ending).</param>
/// <param name="machineWide"><see langword="true"/> to use the machine-wide registry key; <see langword="false"/> for the per-user variant.</param>
private static void RemoveFromAppPaths(string exeName, bool machineWide)
{
var hive = machineWide ? Registry.LocalMachine : Registry.CurrentUser;
using (var appPathsKey = hive.OpenSubKey(RegKeyAppPaths, writable: true))
{
if (appPathsKey != null && appPathsKey.GetSubKeyNames().Contains(exeName))
appPathsKey.DeleteSubKey(exeName);
}
}
#endregion
}
}
| OneGet/0install-win | src/Backend/DesktopIntegration/Windows/AppAlias.cs | C# | lgpl-3.0 | 7,765 |
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <BWAPI.h>
#include "BasicAIModule.h"
namespace BWAPI { Game* Broodwar; }
BOOL APIENTRY DllMain( HANDLE ,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
int i = 0;
i++;
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
BWAPI::BWAPI_init();
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
extern "C" __declspec(dllexport) BWAPI::AIModule* newAIModule(BWAPI::Game* game)
{
BWAPI::Broodwar=game;
return new BasicAIModule();
} | simingl/IM_Debug_Terran_GA_Micro | BasicAIModule/Source/Dll.cpp | C++ | lgpl-3.0 | 668 |
/*
* Copyright 2005 Joe Walker
*
* Licensed 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.directwebremoting.convert;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import org.directwebremoting.extend.Converter;
import org.directwebremoting.extend.InboundContext;
import org.directwebremoting.extend.MarshallException;
import org.directwebremoting.extend.Property;
import org.directwebremoting.extend.TypeHintContext;
import org.directwebremoting.impl.FieldProperty;
/**
* Convert a Javascript associative array into a JavaBean
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class ObjectConverter extends BasicObjectConverter implements Converter
{
/**
* Do we force accessibility for private fields
* @param force "true|false" to set the force accessibility flag
*/
public void setForce(String force)
{
this.force = Boolean.valueOf(force).booleanValue();
}
/* (non-Javadoc)
* @see org.directwebremoting.extend.NamedConverter#getPropertyMapFromObject(java.lang.Object, boolean, boolean)
*/
public Map getPropertyMapFromObject(Object example, boolean readRequired, boolean writeRequired) throws MarshallException
{
Class clazz = example.getClass();
return getPropertyMapFromClass(clazz, readRequired, writeRequired);
}
/* (non-Javadoc)
* @see org.directwebremoting.extend.NamedConverter#getPropertyMap(java.lang.Class, boolean, boolean)
*/
public Map getPropertyMapFromClass(Class type, boolean readRequired, boolean writeRequired)
{
Map allFields = new HashMap();
while (type != Object.class)
{
Field[] fields = type.getDeclaredFields();
fieldLoop:
for (int i = 0; i < fields.length; i++)
{
Field field = fields[i];
String name = field.getName();
// We don't marshall getClass()
if ("class".equals(name))
{
continue fieldLoop;
}
// Access rules mean we might not want to do this one
if (!isAllowedByIncludeExcludeRules(name))
{
continue fieldLoop;
}
if (!Modifier.isPublic(field.getModifiers()))
{
if (force)
{
field.setAccessible(true);
}
else
{
continue fieldLoop;
}
}
allFields.put(name, new FieldProperty(field));
}
type = type.getSuperclass();
}
return allFields;
}
/* (non-Javadoc)
* @see org.directwebremoting.convert.BasicObjectConverter#createTypeHintContext(org.directwebremoting.extend.InboundContext, org.directwebremoting.extend.Property)
*/
protected TypeHintContext createTypeHintContext(InboundContext inctx, Property property)
{
return inctx.getCurrentTypeHintContext();
}
/**
* Do we force accessibillity for hidden fields
*/
private boolean force = false;
}
| simeshev/parabuild-ci | 3rdparty/dwr-2.0.1/src/java/org/directwebremoting/convert/ObjectConverter.java | Java | lgpl-3.0 | 3,798 |
#include <QtGui>
#include <QStringList>
#include "treeitem.h"
#include "treemodel.h"
TreeModel::TreeModel(const QStringList &headers, const QString &data,
QObject *parent): QAbstractItemModel(parent)
{
QVector<QVariant> rootData;
foreach (QString header, headers)
rootData << header;
rootItem = new TreeItem(rootData);
setupModelData(data.split(QString("\n")), rootItem);
}
TreeModel::~TreeModel()
{
delete rootItem;
}
int TreeModel::columnCount(const QModelIndex &parent) const
{
if (parent.isValid())
return static_cast<TreeItem*>(parent.internalPointer())->columnCount();
else
return rootItem->columnCount();
}
QVariant TreeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (role != Qt::DisplayRole)
return QVariant();
TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
return item->data(index.column());
}
Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return 0;
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
}
bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (role != Qt::EditRole)
return false;
TreeItem *item = getItem(index);
bool result = item->setData(index.column(), value);
if (result)
emit dataChanged(index, index);
return result;
}
bool TreeModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role)
{
if (role != Qt::EditRole || orientation != Qt::Horizontal)
return false;
bool result = rootItem->setData(section, value);
if (result)
emit headerDataChanged(orientation, section, section);
return result;
}
bool TreeModel::insertColumns(int position, int columns, const QModelIndex &parent)
{
bool success;
beginInsertColumns(parent, position, position + columns - 1);
success = rootItem->insertColumns(position, columns);
endInsertColumns();
return success;
}
bool TreeModel::removeColumns(int position, int columns, const QModelIndex &parent)
{
bool success;
beginRemoveColumns(parent, position, position + columns - 1);
success = rootItem->removeColumns(position, columns);
endRemoveColumns();
if (rootItem->columnCount() == 0)
removeRows(0, rowCount());
return success;
}
bool TreeModel::insertRows(int position, int rows, const QModelIndex &parent)
{
TreeItem *parentItem = getItem(parent);
bool success;
beginInsertRows(parent, position, position + rows - 1);
success = parentItem->insertChildren(position, rows, rootItem->columnCount());
endInsertRows();
return success;
}
bool TreeModel::removeRows(int position, int rows, const QModelIndex &parent)
{
TreeItem *parentItem = getItem(parent);
bool success = true;
beginRemoveRows(parent, position, position + rows - 1);
success = parentItem->removeChildren(position, rows);
endRemoveRows();
return success;
}
TreeItem *TreeModel::getItem(const QModelIndex &index) const
{
if (index.isValid())
{
TreeItem *item = static_cast<TreeItem*>(index.internalPointer());
if (item) return item;
}
return rootItem;
}
QVariant TreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return rootItem->data(section);
return QVariant();
}
QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent)
const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
TreeItem *parentItem = getItem(parent);
if (!parent.isValid())
parentItem = rootItem;
else
parentItem = static_cast<TreeItem*>(parent.internalPointer());
TreeItem *childItem = parentItem->child(row);
if (childItem)
return createIndex(row, column, childItem);
else
return QModelIndex();
}
QModelIndex TreeModel::parent(const QModelIndex &index) const
{
if (!index.isValid())
return QModelIndex();
TreeItem *childItem = getItem(index);
TreeItem *parentItem = childItem->parent();
if (parentItem == rootItem)
return QModelIndex();
return createIndex(parentItem->row(), 0, parentItem);//row() == childNumber()
}
int TreeModel::rowCount(const QModelIndex &parent) const
{
TreeItem *parentItem = getItem(parent);
if (parent.column() > 0)
return 0;
if (!parent.isValid())
parentItem = rootItem;
else
parentItem = static_cast<TreeItem*>(parent.internalPointer());
return parentItem->childCount();
}
void TreeModel::setupModelData(const QStringList &lines, TreeItem *parent)
{
QList<TreeItem*> parents;
QList<int> indentations;
parents << parent;
indentations << 0;
int number = 0;
while (number < lines.count())
{
int position = 0;
while (position < lines[number].length())
{
if (lines[number].mid(position, 1) != " ")
break;
position++;
}
QString lineData = lines[number].mid(position).trimmed();
if (!lineData.isEmpty())
{
// Read the column data from the rest of the line.
QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts);
QList<QVariant> columnData;
for (int column = 0; column < columnStrings.count(); ++column)
columnData << columnStrings[column];
if (position > indentations.last())
{
// The last child of the current parent is now the new parent
// unless the current parent has no children.
if (parents.last()->childCount() > 0)
{
parents << parents.last()->child(parents.last()->childCount()-1);
indentations << position;
}
}
else
{
while (position < indentations.last() && parents.count() > 0)
{
parents.pop_back();
indentations.pop_back();
}
}
// Append a new item to the current parent's list of children.
TreeItem *parent = parents.last();
parent->insertChildren(parent->childCount(), 1, rootItem->columnCount());
for (int column = 0; column < columnData.size(); ++column)
parent->child(parent->childCount() - 1)->setData(column, columnData[column]);
}
number++;
}
}
| newdebug/NewDebug | Qt/3DDigitalSystemMan/ScriptManager/treemodel.cpp | C++ | lgpl-3.0 | 6,914 |
/*
QMPlay2 is a video and audio player.
Copyright (C) 2010-2022 Błażej Szczygieł
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <ModuleCommon.hpp>
bool ModuleCommon::set()
{
return true;
}
ModuleCommon::~ModuleCommon()
{
if (module)
{
module->mutex.lock();
module->instances.removeOne(this);
module->mutex.unlock();
}
}
void ModuleCommon::SetModule(Module &m)
{
if (!module)
{
module = &m;
module->mutex.lock();
module->instances.append(this);
module->mutex.unlock();
set();
}
}
| arthurzam/QMPlay2 | src/qmplay2/ModuleCommon.cpp | C++ | lgpl-3.0 | 1,226 |
/*
* Copyright © <Pascal Fares @ ISSAE - Cnam Liban>
* 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. »
*/
package pcasem;
/**
*
* @author pascalfares
*/
public class Consommateur extends Thread {
private TampCirc Tampon;
private Integer Valeur_Lue;
public Consommateur(TampCirc Tampon) {
this.Tampon = Tampon;
}
//////////////////////////////////////////////////////////
public void run() {
while (true) {
Valeur_Lue = ((Integer)Tampon.Consommer());
// System.out.println(" --- Consommateur " + Thread.currentThread().getName() + " lit " +((Integer)Tampon.Consommer()).toString() );
System.out.println(" --- Consommateur " + Thread.currentThread().getName() + " lit " + Valeur_Lue);
// verifier le timeout
//if (Valeur_Lue == null) break;
try {
Thread.sleep((int)(Math.random()*200)); // sleep : en ms
} catch (InterruptedException e) {}
}
}
}
| ljug/java-tutorials | ACCOV/TPJanvier2017/PCaSem/src/pcasem/Consommateur.java | Java | lgpl-3.0 | 1,991 |
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty count_paragraphs modifier plugin
*
* Type: modifier<br>
* Name: count_paragraphs<br>
* Purpose: count the number of paragraphs in a text
*
* @link http://www.smarty.net/manual/en/language.modifier.count.paragraphs.php
* count_paragraphs (Smarty online manual)
* @author Uwe Tews
*
* @param string $input input string
* @return string with compiled code
*/
// NOTE: The parser does pass all parameter as strings which could be directly inserted into the compiled code string
function smarty_modifiercompiler_count_paragraphs($input)
{
// count \r or \n characters
return '(preg_match_all(\'#[\r\n]+#\', ' . $input . ', $tmp)+1)';
}
?> | croll/captainhook | mod/smarty/smarty/libs/plugins/modifiercompiler.count_paragraphs.php | PHP | lgpl-3.0 | 806 |
# -*- coding: iso-8859-1 -*-
#
# Copyright (C) 2009 Rene Liebscher
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License along with
# this program; if not, see <http://www.gnu.org/licenses/>.
#
"""Documentation
"""
__revision__ = "$Id: __init__.py,v 1.2 2009/08/07 07:19:18 rliebscher Exp $"
| arruda/pyfuzzy | fuzzy/doc/structure/dot/__init__.py | Python | lgpl-3.0 | 826 |
//
// GEO2DLineStringGeometry.hpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 11/30/12.
//
//
#ifndef __G3MiOSSDK__GEO2DLineStringGeometry__
#define __G3MiOSSDK__GEO2DLineStringGeometry__
#include "GEOGeometry2D.hpp"
class Geodetic2D;
#include <vector>
class GEO2DLineStringGeometry : public GEOGeometry2D {
private:
std::vector<Geodetic2D*>* _coordinates;
protected:
std::vector<GEOSymbol*>* createSymbols(const GEOSymbolizer* symbolizer) const;
public:
GEO2DLineStringGeometry(std::vector<Geodetic2D*>* coordinates) :
_coordinates(coordinates)
{
}
~GEO2DLineStringGeometry();
const std::vector<Geodetic2D*>* getCoordinates() const {
return _coordinates;
}
};
#endif
| ccarducci/Ushahidi_local | G3MiOSSDK/Commons/GEO/GEO2DLineStringGeometry.hpp | C++ | lgpl-3.0 | 713 |
// Copyright (C) 2000-2007, Luca Padovani <padovani@sti.uniurb.it>.
//
// This file is part of GtkMathView, a flexible, high-quality rendering
// engine for MathML documents.
//
// GtkMathView is free software; you can redistribute it and/or modify it
// either under the terms of the GNU Lesser General Public License version
// 3 as published by the Free Software Foundation (the "LGPL") or, at your
// option, under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation (the "GPL"). If you do not
// alter this notice, a recipient may use your version of this file under
// either the GPL or the LGPL.
//
// GtkMathView 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 LGPL or
// the GPL for more details.
//
// You should have received a copy of the LGPL and of the GPL along with
// this program in the files COPYING-LGPL-3 and COPYING-GPL-2; if not, see
// <http://www.gnu.org/licenses/>.
#ifndef __MathMLPhantomElement_hh__
#define __MathMLPhantomElement_hh__
#include "MathMLEmbellishment.hh"
#include "MathMLNormalizingContainerElement.hh"
class MathMLPhantomElement
: public MathMLNormalizingContainerElement, public MathMLEmbellishment
{
public:
MathMLPhantomElement(const SmartPtr<class MathMLNamespaceContext>&);
virtual ~MathMLPhantomElement();
public:
static SmartPtr<MathMLPhantomElement> create(const SmartPtr<class MathMLNamespaceContext>& view)
{ return new MathMLPhantomElement(view); }
virtual AreaRef format(class FormattingContext&);
virtual bool IsSpaceLike(void) const;
virtual SmartPtr<class MathMLOperatorElement> getCoreOperator(void);
};
#endif // __MathMLPhantomElement_hh__
| khaledhosny/libmathview | src/engine/MathMLPhantomElement.hh | C++ | lgpl-3.0 | 1,812 |
// <copyright file="CompositePredicate.cs" company="Allors bvba">
// Copyright (c) Allors bvba. All rights reserved.
// Licensed under the LGPL license. See LICENSE file in the project root for full license information.
// </copyright>
namespace Allors.Database.Adapters.Npgsql
{
using System;
using System.Collections.Generic;
using System.Linq;
using Allors.Meta;
internal abstract class CompositePredicate : Predicate, ICompositePredicate
{
protected CompositePredicate(ExtentFiltered extent)
{
this.Extent = extent;
this.Filters = new List<Predicate>(4);
if (extent.Strategy != null)
{
var allorsObject = extent.Strategy.GetObject();
if (extent.AssociationType != null)
{
var role = extent.AssociationType.RoleType;
if (role.IsMany)
{
this.AddContains(role, allorsObject);
}
else
{
this.AddEquals(role, allorsObject);
}
}
else
{
var association = extent.RoleType.AssociationType;
if (association.IsMany)
{
this.AddContains(association, allorsObject);
}
else
{
this.AddEquals(association, allorsObject);
}
}
}
}
internal override bool Include
{
get
{
foreach (var filter in this.Filters)
{
if (filter.Include)
{
return true;
}
}
return false;
}
}
protected ExtentFiltered Extent { get; }
protected List<Predicate> Filters { get; }
public ICompositePredicate AddAnd()
{
this.Extent.FlushCache();
var allFilter = new AndPredicate(this.Extent);
this.Filters.Add(allFilter);
return allFilter;
}
public ICompositePredicate AddBetween(IRoleType role, object firstValue, object secondValue)
{
this.Extent.FlushCache();
if (firstValue is IRoleType betweenRoleA && secondValue is IRoleType betweenRoleB)
{
this.Filters.Add(new RoleBetweenRole(this.Extent, role, betweenRoleA, betweenRoleB));
}
else if (firstValue is IAssociationType betweenAssociationA && secondValue is IAssociationType betweenAssociationB)
{
throw new NotImplementedException();
}
else
{
this.Filters.Add(new RoleBetweenValue(this.Extent, role, firstValue, secondValue));
}
return this;
}
public ICompositePredicate AddContainedIn(IRoleType role, Allors.Extent containingExtent)
{
this.Extent.FlushCache();
this.Filters.Add(new RoleContainedInExtent(this.Extent, role, containingExtent));
return this;
}
public ICompositePredicate AddContainedIn(IRoleType role, IEnumerable<IObject> containingEnumerable)
{
this.Extent.FlushCache();
this.Filters.Add(new RoleContainedInEnumerable(this.Extent, role, containingEnumerable));
return this;
}
public ICompositePredicate AddContainedIn(IAssociationType association, Allors.Extent containingExtent)
{
this.Extent.FlushCache();
this.Filters.Add(new AssociationContainedInExtent(this.Extent, association, containingExtent));
return this;
}
public ICompositePredicate AddContainedIn(IAssociationType association, IEnumerable<IObject> containingEnumerable)
{
this.Extent.FlushCache();
this.Filters.Add(new AssociationContainedInEnumerable(this.Extent, association, containingEnumerable));
return this;
}
public ICompositePredicate AddContains(IRoleType role, IObject containedObject)
{
this.Extent.FlushCache();
this.Filters.Add(new RoleContains(this.Extent, role, containedObject));
return this;
}
public ICompositePredicate AddContains(IAssociationType association, IObject containedObject)
{
this.Extent.FlushCache();
this.Filters.Add(new AssociationContains(this.Extent, association, containedObject));
return this;
}
public ICompositePredicate AddEquals(IObject allorsObject)
{
this.Extent.FlushCache();
this.Filters.Add(new Equals(allorsObject));
return this;
}
public ICompositePredicate AddEquals(IRoleType role, object obj)
{
this.Extent.FlushCache();
if (obj is IRoleType equalsRole)
{
this.Filters.Add(new RoleEqualsRole(this.Extent, role, equalsRole));
}
else if (obj is IAssociationType equalsAssociation)
{
throw new NotImplementedException();
}
else
{
this.Filters.Add(new RoleEqualsValue(this.Extent, role, obj));
}
return this;
}
public ICompositePredicate AddEquals(IAssociationType association, IObject allorsObject)
{
this.Extent.FlushCache();
this.Filters.Add(new AssociationEquals(this.Extent, association, allorsObject));
return this;
}
public ICompositePredicate AddExists(IRoleType role)
{
this.Extent.FlushCache();
this.Filters.Add(new RoleExists(this.Extent, role));
return this;
}
public ICompositePredicate AddExists(IAssociationType association)
{
this.Extent.FlushCache();
this.Filters.Add(new AssociationExists(this.Extent, association));
return this;
}
public ICompositePredicate AddGreaterThan(IRoleType role, object value)
{
this.Extent.FlushCache();
if (value is IRoleType greaterThanRole)
{
this.Filters.Add(new RoleGreaterThanRole(this.Extent, role, greaterThanRole));
}
else if (value is IAssociationType greaterThanAssociation)
{
throw new NotImplementedException();
}
else
{
this.Filters.Add(new RoleGreaterThanValue(this.Extent, role, value));
}
return this;
}
public ICompositePredicate AddInstanceof(IComposite type)
{
this.Extent.FlushCache();
this.Filters.Add(new InstanceOf(type, GetConcreteSubClasses(type)));
return this;
}
public ICompositePredicate AddInstanceof(IRoleType role, IComposite type)
{
this.Extent.FlushCache();
this.Filters.Add(new RoleInstanceof(this.Extent, role, type, GetConcreteSubClasses(type)));
return this;
}
public ICompositePredicate AddInstanceof(IAssociationType association, IComposite type)
{
this.Extent.FlushCache();
this.Filters.Add(new AssociationInstanceOf(this.Extent, association, type, GetConcreteSubClasses(type)));
return this;
}
public ICompositePredicate AddLessThan(IRoleType role, object value)
{
this.Extent.FlushCache();
if (value is IRoleType lessThanRole)
{
this.Filters.Add(new RoleLessThanRole(this.Extent, role, lessThanRole));
}
else if (value is IAssociationType lessThanAssociation)
{
throw new NotImplementedException();
}
else
{
this.Filters.Add(new RoleLessThanValue(this.Extent, role, value));
}
return this;
}
public ICompositePredicate AddLike(IRoleType role, string value)
{
this.Extent.FlushCache();
this.Filters.Add(new RoleLike(this.Extent, role, value));
return this;
}
public ICompositePredicate AddNot()
{
this.Extent.FlushCache();
var noneFilter = new Not(this.Extent);
this.Filters.Add(noneFilter);
return noneFilter;
}
public ICompositePredicate AddOr()
{
this.Extent.FlushCache();
var anyFilter = new Or(this.Extent);
this.Filters.Add(anyFilter);
return anyFilter;
}
internal static IObjectType[] GetConcreteSubClasses(IObjectType type)
{
if (type.IsInterface)
{
return ((IInterface)type).Subclasses.ToArray();
}
var concreteSubclasses = new IObjectType[1];
concreteSubclasses[0] = type;
return concreteSubclasses;
}
internal override void Setup(ExtentStatement statement)
{
foreach (var filter in this.Filters)
{
filter.Setup(statement);
}
}
}
}
| Allors/allors2 | Platform/Database/Adapters/Allors.Database.Adapters.Npgsql/Predicates/CompositePredicate.cs | C# | lgpl-3.0 | 9,590 |
/**
* SPDX-FileCopyrightText: © 2014 Liferay, Inc. <https://liferay.com>
* SPDX-License-Identifier: LGPL-3.0-or-later
*/
Loader.define(
'local-require/to-url',
['module', 'require'],
(module, require) => {
module.exports = require.toUrl('local-require/to-url');
}
);
| ipeychev/lfr-amd-loader | src/loader/__tests__/__fixtures__/loader/local-require/to-url.js | JavaScript | lgpl-3.0 | 278 |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <owner name="Mike Krüger" email="mike@icsharpcode.net"/>
// <version>$Revision$</version>
// </file>
using System;
using System.Windows.Forms;
namespace ICSharpCode.Core.WinForms
{
public class MenuCheckBox : ToolStripMenuItem , IStatusUpdate
{
object caller;
Codon codon;
string description = String.Empty;
ICheckableMenuCommand menuCommand = null;
void CreateMenuCommand()
{
if (menuCommand == null) {
try {
menuCommand = (ICheckableMenuCommand)codon.AddIn.CreateObject(codon.Properties["class"]);
} catch (Exception e) {
MessageService.ShowError(e, "Can't create menu command : " + codon.Id);
}
}
}
public ICheckableMenuCommand MenuCommand {
get {
CreateMenuCommand();
return menuCommand;
}
}
public string Description {
get {
return description;
}
set {
description = value;
}
}
public MenuCheckBox(string text)
{
this.RightToLeft = RightToLeft.Inherit;
Text = text;
}
public MenuCheckBox(Codon codon, object caller)
{
this.RightToLeft = RightToLeft.Inherit;
this.caller = caller;
this.codon = codon;
UpdateText();
}
protected override void OnClick(System.EventArgs e)
{
base.OnClick(e);
if (codon != null) {
MenuCommand.Run();
Checked = MenuCommand.IsChecked;
}
}
public override bool Enabled {
get {
if (codon == null) {
return base.Enabled;
}
ConditionFailedAction failedAction = codon.GetFailedAction(caller);
return failedAction != ConditionFailedAction.Disable;
}
}
public virtual void UpdateStatus()
{
if (codon != null) {
ConditionFailedAction failedAction = codon.GetFailedAction(caller);
this.Visible = failedAction != ConditionFailedAction.Exclude;
if (menuCommand == null && !string.IsNullOrEmpty(codon.Properties["checked"])) {
Checked = string.Equals(StringParser.Parse(codon.Properties["checked"]),
bool.TrueString, StringComparison.OrdinalIgnoreCase);
} else {
CreateMenuCommand();
if (menuCommand != null) {
Checked = menuCommand.IsChecked;
}
}
}
}
public virtual void UpdateText()
{
if (codon != null) {
Text = StringParser.Parse(codon.Properties["label"]);
}
}
}
}
| kingjiang/SharpDevelopLite | src/Main/ICSharpCode.Core.WinForms/Menu/MenuCheckBox.cs | C# | lgpl-3.0 | 2,415 |
/// <reference name="MicrosoftAjax.debug.js" />
/// <reference path="../ExtenderBase/BaseScripts.js" />
/// <reference path="../Common/Common.js" />
/// <reference path="../Animation/Animations.js" />
/// <reference path="../Animation/AnimationBehavior.js" />
(function() {
var scriptName = "ExtendedPopup";
function execute() {
Type.registerNamespace('Sys.Extended.UI');
Sys.Extended.UI.PopupBehavior = function(element) {
/// <summary>
/// The PopupBehavior is used to show/hide an element at a position
/// relative to another element
/// </summary>
/// <param name="element" type="Sys.UI.DomElement" mayBeNull="false" domElement="true">
/// The DOM element the behavior is associated with
/// </param>
Sys.Extended.UI.PopupBehavior.initializeBase(this, [element]);
this._x = 0;
this._y = 0;
this._positioningMode = Sys.Extended.UI.PositioningMode.Absolute;
this._parentElement = null;
this._parentElementID = null;
this._moveHandler = null;
this._firstPopup = true;
this._originalParent = null;
this._visible = false;
// Generic animation behaviors that automatically build animations
// from JSON descriptions
this._onShow = null;
this._onHide = null;
// Create handlers for the animation ended events
this._onShowEndedHandler = Function.createDelegate(this, this._onShowEnded);
this._onHideEndedHandler = Function.createDelegate(this, this._onHideEnded);
}
Sys.Extended.UI.PopupBehavior.prototype = {
initialize: function() {
/// <summary>
/// Initialize the PopupBehavior
/// </summary>
Sys.Extended.UI.PopupBehavior.callBaseMethod(this, 'initialize');
this._hidePopup();
this.get_element().style.position = "absolute";
},
dispose: function() {
/// <summary>
/// Dispose the PopupBehavior
/// </summary>
var element = this.get_element();
if (element) {
if (this._visible) {
this.hide();
}
if (this._originalParent) {
element.parentNode.removeChild(element);
this._originalParent.appendChild(element);
this._originalParent = null;
}
// Remove expando properties
element._hideWindowedElementsIFrame = null;
}
this._parentElement = null;
// Remove the animation ended events and wipe the animations
// (we don't need to dispose them because that will happen
// automatically in our base dispose)
if (this._onShow && this._onShow.get_animation()) {
this._onShow.get_animation().remove_ended(this._onShowEndedHandler);
}
this._onShow = null;
if (this._onHide && this._onHide.get_animation()) {
this._onHide.get_animation().remove_ended(this._onHideEndedHandler);
}
this._onHide = null;
Sys.Extended.UI.PopupBehavior.callBaseMethod(this, 'dispose');
},
show: function() {
/// <summary>
/// Show the popup
/// </summary>
// Ignore requests to hide multiple times
if (this._visible) {
return;
}
var eventArgs = new Sys.CancelEventArgs();
this.raiseShowing(eventArgs);
if (eventArgs.get_cancel()) {
return;
}
// Either show the popup or play an animation that does
// (note: even if we're animating, we still show and position
// the popup before hiding it again and playing the animation
// which makes the animation much simpler)
this._visible = true;
var element = this.get_element();
$common.setVisible(element, true);
this.setupPopup();
if (this._onShow) {
$common.setVisible(element, false);
this.onShow();
} else {
this.raiseShown(Sys.EventArgs.Empty);
}
},
hide: function() {
/// <summary>
/// Hide the popup
/// </summary>
// Ignore requests to hide multiple times
if (!this._visible) {
return;
}
var eventArgs = new Sys.CancelEventArgs();
this.raiseHiding(eventArgs);
if (eventArgs.get_cancel()) {
return;
}
// Either hide the popup or play an animation that does
this._visible = false;
if (this._onHide) {
this.onHide();
} else {
this._hidePopup();
this._hideCleanup();
}
},
getBounds: function() {
/// <summary>
/// Get the expected bounds of the popup relative to its parent
/// </summary>
/// <returns type="Sys.UI.Bounds" mayBeNull="false">
/// Bounds of the popup relative to its parent
/// </returns>
/// <remarks>
/// The actual final position can only be calculated after it is
/// initially set and we can verify it doesn't bleed off the edge
/// of the screen.
/// </remarks>
var element = this.get_element();
// offsetParent (doc element if absolutely positioned or no offsetparent available)
var offsetParent = element.offsetParent || document.documentElement;
// diff = difference in position between element's offsetParent and the element we will attach popup to.
// this is basically so we can position the popup in the right spot even though it may not be absolutely positioned
var diff;
var parentBounds;
if (this.get_parentElement()) {
// we will be positioning the element against the assigned parent
parentBounds = $common.getBounds(this.get_parentElement());
var offsetParentLocation = $common.getLocation(offsetParent);
diff = { x: parentBounds.x - offsetParentLocation.x, y: parentBounds.y - offsetParentLocation.y };
} else {
// we will be positioning the element against the offset parent by default, since no parent element given
parentBounds = $common.getBounds(offsetParent);
diff = { x: 0, y: 0 };
}
// width/height of the element, needed for calculations that involve width like centering
var width = element.offsetWidth - (element.clientLeft ? element.clientLeft * 2 : 0);
var height = element.offsetHeight - (element.clientTop ? element.clientTop * 2 : 0);
// Setting the width causes the element to grow by border+passing every
// time. But not setting it causes strange behavior in safari. Just set it once.
if (this._firstpopup) {
element.style.width = width + "px";
this._firstpopup = false;
}
var position, pos;
switch (this._positioningMode) {
case Sys.Extended.UI.PositioningMode.Center:
pos = {
x: Math.round(parentBounds.width / 2 - width / 2),
y: Math.round(parentBounds.height / 2 - height / 2),
altX: Math.round(parentBounds.width / 2 - width / 2),
altY: Math.round(parentBounds.height / 2 - height / 2)
};
break;
case Sys.Extended.UI.PositioningMode.BottomLeft:
pos = {
x: 0,
y: parentBounds.height,
altX: parentBounds.width - width,
altY: 0 - height
}
break;
case Sys.Extended.UI.PositioningMode.BottomRight:
pos = {
x: parentBounds.width - width,
y: parentBounds.height,
altX: 0,
altY: 0 - height
}
break;
case Sys.Extended.UI.PositioningMode.TopLeft:
pos = {
x: 0,
y: -element.offsetHeight,
altX: parentBounds.width - width,
altY: parentBounds.height
}
break;
case Sys.Extended.UI.PositioningMode.TopRight:
pos = {
x: parentBounds.width - width,
y: -element.offsetHeight,
altX: 0,
altY: parentBounds.height
}
break;
case Sys.Extended.UI.PositioningMode.Right:
pos = {
x: parentBounds.width,
y: 0,
altX: -element.offsetWidth,
altY: parentBounds.height - height
}
break;
case Sys.Extended.UI.PositioningMode.Left:
pos = {
x: -element.offsetWidth,
y: 0,
altX: parentBounds.width,
altY: parentBounds.height - height
}
break;
default:
pos = { x: 0, y: 0, altX: 0, altY: 0 };
}
pos.x += this._x + diff.x;
pos.altX += this._x + diff.x;
pos.y += this._y + diff.y;
pos.altY += this._y + diff.y;
position = this._verifyPosition(pos, width, height, parentBounds);
return new Sys.UI.Bounds(position.x, position.y, width, height);
},
_verifyPosition: function(pos, elementWidth, elementHeight, parentBounds) {
/// <summary>
/// Checks whether the popup is entirely visible and attempts to change its position to make it entirely visihle.
/// </summary>
var newX = 0, newY = 0;
var windowBounds = this._getWindowBounds();
// Check horizontal positioning
if (!((pos.x + elementWidth > windowBounds.x + windowBounds.width) || (pos.x < windowBounds.x))) {
newX = pos.x;
} else {
newX = pos.altX;
if (pos.altX < windowBounds.x) {
if (pos.x > pos.altX) {
newX = pos.x;
}
} else if (windowBounds.width + windowBounds.x - pos.altX < elementWidth) {
var xDiff = pos.x > pos.altX ? Math.abs(windowBounds.x - pos.x) : (windowBounds.x - pos.x);
if (xDiff < elementWidth - windowBounds.width - windowBounds.x + pos.altX) {
newX = pos.x;
}
}
}
// Check vertical positioning
if (!((pos.y + elementHeight > windowBounds.y + windowBounds.height) || (pos.y < windowBounds.y))) {
newY = pos.y;
} else {
newY = pos.altY;
if (pos.altY < windowBounds.y) {
if (windowBounds.y - pos.altY > elementHeight - windowBounds.height - windowBounds.y + pos.y) {
newY = pos.y;
}
} else if (windowBounds.height + windowBounds.y - pos.altY < elementHeight) {
if (windowBounds.y - pos.y < elementHeight - windowBounds.height - windowBounds.y + pos.altY) {
newY = pos.y;
}
}
}
return { x: newX, y: newY };
},
_getWindowBounds: function() {
var bounds = {
x: this._getWindowScrollLeft(),
y: this._getWindowScrollTop(),
width: this._getWindowWidth(),
height: this._getWindowHeight()
};
return bounds;
},
_getWindowHeight: function() {
var windowHeight = 0;
if (document.documentElement && document.documentElement.clientHeight) {
windowHeight = document.documentElement.clientHeight;
}
else if (document.body && document.body.clientHeight) {
windowHeight = document.body.clientHeight;
}
return windowHeight;
},
_getWindowWidth: function() {
var windowWidth = 0;
if (document.documentElement && document.documentElement.clientWidth) {
windowWidth = document.documentElement.clientWidth;
}
else if (document.body && document.body.clientWidth) {
windowWidth = document.body.clientWidth;
}
return windowWidth;
},
_getWindowScrollTop: function() {
var scrollTop = 0;
if (typeof (window.pageYOffset) == 'number') {
scrollTop = window.pageYOffset;
}
if (document.body && document.body.scrollTop) {
scrollTop = document.body.scrollTop;
}
else if (document.documentElement && document.documentElement.scrollTop) {
scrollTop = document.documentElement.scrollTop;
}
return scrollTop;
},
_getWindowScrollLeft: function() {
var scrollLeft = 0;
if (typeof (window.pageXOffset) == 'number') {
scrollLeft = window.pageXOffset;
}
else if (document.body && document.body.scrollLeft) {
scrollLeft = document.body.scrollLeft;
}
else if (document.documentElement && document.documentElement.scrollLeft) {
scrollLeft = document.documentElement.scrollLeft;
}
return scrollLeft;
},
adjustPopupPosition: function(bounds) {
/// <summary>
/// Adjust the position of the popup after it's originally bet set
/// to make sure that it's visible on the page.
/// </summary>
/// <param name="bounds" type="Sys.UI.Bounds" mayBeNull="true" optional="true">
/// Original bounds of the parent element
/// </param>
var element = this.get_element();
if (!bounds) {
bounds = this.getBounds();
}
// Get the new bounds now that we've shown the popup
var newPosition = $common.getBounds(element);
var updateNeeded = false;
if (newPosition.x < 0) {
bounds.x -= newPosition.x;
updateNeeded = true;
}
if (newPosition.y < 0) {
bounds.y -= newPosition.y;
updateNeeded = true;
}
// If the popup was off the screen, reposition it
if (updateNeeded) {
$common.setLocation(element, bounds);
}
},
addBackgroundIFrame: function() {
/// <summary>
/// Add an empty IFRAME behind the popup (for IE6 only) so that SELECT, etc., won't
/// show through the popup.
/// </summary>
// Get the child frame
var element = this.get_element();
if ((Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.version < 7)) {
var childFrame = element._hideWindowedElementsIFrame;
// Create the child frame if it wasn't found
if (!childFrame) {
childFrame = document.createElement("iframe");
childFrame.src = "javascript:'<html></html>';";
childFrame.style.position = "absolute";
childFrame.style.display = "none";
childFrame.scrolling = "no";
childFrame.frameBorder = "0";
childFrame.tabIndex = "-1";
childFrame.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";
element.parentNode.insertBefore(childFrame, element);
element._hideWindowedElementsIFrame = childFrame;
this._moveHandler = Function.createDelegate(this, this._onMove);
Sys.UI.DomEvent.addHandler(element, "move", this._moveHandler);
}
// Position the frame exactly behind the element
$common.setBounds(childFrame, $common.getBounds(element));
childFrame.style.left = element.style.left;
childFrame.style.top = element.style.top;
childFrame.style.display = element.style.display;
if (element.currentStyle && element.currentStyle.zIndex) {
childFrame.style.zIndex = element.currentStyle.zIndex;
} else if (element.style.zIndex) {
childFrame.style.zIndex = element.style.zIndex;
}
}
},
setupPopup: function() {
/// <summary>
/// Position the popup relative to its parent
/// </summary>
var element = this.get_element();
var bounds = this.getBounds();
$common.setLocation(element, bounds);
// Tweak the position, set the zIndex, and add the background iframe in IE6
this.adjustPopupPosition(bounds);
element.style.zIndex = 1000;
this.addBackgroundIFrame();
},
_hidePopup: function() {
/// <summary>
/// Internal hide implementation
/// </summary>
var element = this.get_element();
$common.setVisible(element, false);
if (element.originalWidth) {
element.style.width = element.originalWidth + "px";
element.originalWidth = null;
}
},
_hideCleanup: function() {
/// <summary>
/// Perform cleanup after hiding the element
/// </summary>
var element = this.get_element();
// Remove the tracking handler
if (this._moveHandler) {
Sys.UI.DomEvent.removeHandler(element, "move", this._moveHandler);
this._moveHandler = null;
}
// Hide the child frame
if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
var childFrame = element._hideWindowedElementsIFrame;
if (childFrame) {
childFrame.style.display = "none";
}
}
this.raiseHidden(Sys.EventArgs.Empty);
},
_onMove: function() {
/// <summary>
/// Track the popup's movements so the hidden IFrame (IE6 only) can
/// be moved along with it
/// </summary>
var element = this.get_element();
if (element._hideWindowedElementsIFrame) {
element.parentNode.insertBefore(element._hideWindowedElementsIFrame, element);
element._hideWindowedElementsIFrame.style.top = element.style.top;
element._hideWindowedElementsIFrame.style.left = element.style.left;
}
},
get_onShow: function() {
/// <value type="String" mayBeNull="true">
/// Generic OnShow Animation's JSON definition
/// </value>
return this._onShow ? this._onShow.get_json() : null;
},
set_onShow: function(value) {
if (!this._onShow) {
this._onShow = new Sys.Extended.UI.Animation.GenericAnimationBehavior(this.get_element());
this._onShow.initialize();
}
this._onShow.set_json(value);
var animation = this._onShow.get_animation();
if (animation) {
animation.add_ended(this._onShowEndedHandler);
}
this.raisePropertyChanged('onShow');
},
get_onShowBehavior: function() {
/// <value type="Sys.Extended.UI.Animation.GenericAnimationBehavior">
/// Generic OnShow Animation's behavior
/// </value>
return this._onShow;
},
onShow: function() {
/// <summary>
/// Play the OnShow animation
/// </summary>
/// <returns />
if (this._onShow) {
if (this._onHide) {
this._onHide.quit();
}
this._onShow.play();
}
},
_onShowEnded: function() {
/// <summary>
/// Handler for the OnShow Animation's Ended event
/// </summary>
// Make sure the popup is where it belongs
this.adjustPopupPosition();
this.addBackgroundIFrame();
this.raiseShown(Sys.EventArgs.Empty);
},
get_onHide: function() {
/// <value type="String" mayBeNull="true">
/// Generic OnHide Animation's JSON definition
/// </value>
return this._onHide ? this._onHide.get_json() : null;
},
set_onHide: function(value) {
if (!this._onHide) {
this._onHide = new Sys.Extended.UI.Animation.GenericAnimationBehavior(this.get_element());
this._onHide.initialize();
}
this._onHide.set_json(value);
var animation = this._onHide.get_animation();
if (animation) {
animation.add_ended(this._onHideEndedHandler);
}
this.raisePropertyChanged('onHide');
},
get_onHideBehavior: function() {
/// <value type="Sys.Extended.UI.Animation.GenericAnimationBehavior">
/// Generic OnHide Animation's behavior
/// </value>
return this._onHide;
},
onHide: function() {
/// <summary>
/// Play the OnHide animation
/// </summary>
/// <returns />
if (this._onHide) {
if (this._onShow) {
this._onShow.quit();
}
this._onHide.play();
}
},
_onHideEnded: function() {
/// <summary>
/// Handler for the OnHide Animation's Ended event
/// </summary>
this._hideCleanup();
},
get_parentElement: function() {
/// <value type="Sys.UI.DomElement" domElement="true">
/// Parent dom element.
/// </value>
if (!this._parentElement && this._parentElementID) {
this.set_parentElement($get(this._parentElementID));
//Sys.Debug.assert(this._parentElement != null, String.format(Sys.Extended.UI.Resources.PopupExtender_NoParentElement, this._parentElementID));
}
return this._parentElement;
},
set_parentElement: function(element) {
this._parentElement = element;
this.raisePropertyChanged('parentElement');
},
get_parentElementID: function() {
/// <value type="String">
/// Parent dom element.
/// </value>
if (this._parentElement) {
return this._parentElement.id
}
return this._parentElementID;
},
set_parentElementID: function(elementID) {
this._parentElementID = elementID;
if (this.get_isInitialized()) {
this.set_parentElement($get(elementID));
}
},
get_positioningMode: function() {
/// <value type="Sys.Extended.UI.PositioningMode">
/// Positioning mode.
/// </value>
return this._positioningMode;
},
set_positioningMode: function(mode) {
this._positioningMode = mode;
this.raisePropertyChanged('positioningMode');
},
get_x: function() {
/// <value type="Number">
/// X coordinate.
/// </value>
return this._x;
},
set_x: function(value) {
if (value != this._x) {
this._x = value;
// Reposition the popup if it's already showing
if (this._visible) {
this.setupPopup();
}
this.raisePropertyChanged('x');
}
},
get_y: function() {
/// <value type="Number">
/// Y coordinate.
/// </value>
return this._y;
},
set_y: function(value) {
if (value != this._y) {
this._y = value;
// Reposition the popup if it's already showing
if (this._visible) {
this.setupPopup();
}
this.raisePropertyChanged('y');
}
},
get_visible: function() {
/// <value type="Boolean" mayBeNull="false">
/// Whether or not the popup is currently visible
/// </value>
return this._visible;
},
add_showing: function(handler) {
/// <summary>
/// Add an event handler for the showing event
/// </summary>
/// <param name="handler" type="Function" mayBeNull="false">
/// Event handler
/// </param>
/// <returns />
this.get_events().addHandler('showing', handler);
},
remove_showing: function(handler) {
/// <summary>
/// Remove an event handler from the showing event
/// </summary>
/// <param name="handler" type="Function" mayBeNull="false">
/// Event handler
/// </param>
/// <returns />
this.get_events().removeHandler('showing', handler);
},
raiseShowing: function(eventArgs) {
/// <summary>
/// Raise the showing event
/// </summary>
/// <param name="eventArgs" type="Sys.CancelEventArgs" mayBeNull="false">
/// Event arguments for the showing event
/// </param>
/// <returns />
var handler = this.get_events().getHandler('showing');
if (handler) {
handler(this, eventArgs);
}
},
add_shown: function(handler) {
/// <summary>
/// Add an event handler for the shown event
/// </summary>
/// <param name="handler" type="Function" mayBeNull="false">
/// Event handler
/// </param>
/// <returns />
this.get_events().addHandler('shown', handler);
},
remove_shown: function(handler) {
/// <summary>
/// Remove an event handler from the shown event
/// </summary>
/// <param name="handler" type="Function" mayBeNull="false">
/// Event handler
/// </param>
/// <returns />
this.get_events().removeHandler('shown', handler);
},
raiseShown: function(eventArgs) {
/// <summary>
/// Raise the shown event
/// </summary>
/// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="false">
/// Event arguments for the shown event
/// </param>
/// <returns />
var handler = this.get_events().getHandler('shown');
if (handler) {
handler(this, eventArgs);
}
},
add_hiding: function(handler) {
/// <summary>
/// Add an event handler for the hiding event
/// </summary>
/// <param name="handler" type="Function" mayBeNull="false">
/// Event handler
/// </param>
/// <returns />
this.get_events().addHandler('hiding', handler);
},
remove_hiding: function(handler) {
/// <summary>
/// Remove an event handler from the hiding event
/// </summary>
/// <param name="handler" type="Function" mayBeNull="false">
/// Event handler
/// </param>
/// <returns />
this.get_events().removeHandler('hiding', handler);
},
raiseHiding: function(eventArgs) {
/// <summary>
/// Raise the hiding event
/// </summary>
/// <param name="eventArgs" type="Sys.CancelEventArgs" mayBeNull="false">
/// Event arguments for the hiding event
/// </param>
/// <returns />
var handler = this.get_events().getHandler('hiding');
if (handler) {
handler(this, eventArgs);
}
},
add_hidden: function(handler) {
/// <summary>
/// Add an event handler for the hidden event
/// </summary>
/// <param name="handler" type="Function" mayBeNull="false">
/// Event handler
/// </param>
/// <returns />
this.get_events().addHandler('hidden', handler);
},
remove_hidden: function(handler) {
/// <summary>
/// Remove an event handler from the hidden event
/// </summary>
/// <param name="handler" type="Function" mayBeNull="false">
/// Event handler
/// </param>
/// <returns />
this.get_events().removeHandler('hidden', handler);
},
raiseHidden: function(eventArgs) {
/// <summary>
/// Raise the hidden event
/// </summary>
/// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="false">
/// Event arguments for the hidden event
/// </param>
/// <returns />
var handler = this.get_events().getHandler('hidden');
if (handler) {
handler(this, eventArgs);
}
}
}
Sys.Extended.UI.PopupBehavior.registerClass('Sys.Extended.UI.PopupBehavior', Sys.Extended.UI.BehaviorBase);
Sys.registerComponent(Sys.Extended.UI.PopupBehavior, { name: "popup" });
//Sys.Extended.UI.PopupBehavior.descriptor = {
// properties: [ {name: 'parentElement', attributes: [ Sys.Attributes.Element, true ] },
// {name: 'positioningMode', type: Sys.Extended.UI.PositioningMode},
// {name: 'x', type: Number},
// {name: 'y', type: Number} ],
// events: [ {name: 'show'},
// {name: 'hide'} ]
//}
Sys.Extended.UI.PositioningMode = function() {
/// <summary>
/// Positioning mode describing how the popup should be positioned
/// relative to its specified parent
/// </summary>
/// <field name="Absolute" type="Number" integer="true" />
/// <field name="Center" type="Number" integer="true" />
/// <field name="BottomLeft" type="Number" integer="true" />
/// <field name="BottomRight" type="Number" integer="true" />
/// <field name="TopLeft" type="Number" integer="true" />
/// <field name="TopRight" type="Number" integer="true" />
/// <field name="Right" type="Number" integer="true" />
/// <field name="Left" type="Number" integer="true" />
throw Error.invalidOperation();
}
Sys.Extended.UI.PositioningMode.prototype = {
Absolute: 0,
Center: 1,
BottomLeft: 2,
BottomRight: 3,
TopLeft: 4,
TopRight: 5,
Right: 6,
Left: 7
}
Sys.Extended.UI.PositioningMode.registerEnum('Sys.Extended.UI.PositioningMode');
} // execute
if (window.Sys && Sys.loader) {
Sys.loader.registerScript(scriptName, ["ExtendedAnimations", "ExtendedAnimationBehavior"], execute);
}
else {
execute();
}
})();
| consumentor/Server | trunk/tools/AspNetAjaxLibraryBeta0911/Scripts/extended/PopupExtender/PopupBehavior.debug.js | JavaScript | lgpl-3.0 | 30,754 |
#include "firtex/search/IndexFeature.h"
FX_NS_USE(index);
FX_NS_DEF(search);
SETUP_STREAM_LOGGER(search, IndexFeature);
IndexFeature::IndexFeature()
: m_nTotalTermCount(0)
, m_nTotalDocCount(0)
{
}
IndexFeature::~IndexFeature()
{
}
void IndexFeature::init(const IndexReaderPtr& pIndexReader)
{
m_nTotalDocCount = (uint64_t)pIndexReader->getDocCount();
FX_STREAM_LOG(TRACE) << "Total doc count: "
<< m_nTotalDocCount << FIRTEX_ENDL;
IndexMeta indexMeta = pIndexReader->getIndexMeta();
m_nTotalTermCount = 0;
for (size_t i = 0; i < indexMeta.size(); ++i)
{
const FieldMeta& fieldMeta = indexMeta[i];
m_fieldsAvgLength.insert(make_pair(fieldMeta.fieldName,
(uint32_t)(fieldMeta.totalTermCount / m_nTotalDocCount)));
FX_STREAM_LOG(TRACE) << "Average field length: field: "
<< fieldMeta.fieldName << ", length: "
<< fieldMeta.totalTermCount/m_nTotalDocCount
<< FIRTEX_ENDL;
m_nTotalTermCount += fieldMeta.totalTermCount;
}
FX_STREAM_LOG(TRACE) << "Total term count: "
<< m_nTotalTermCount << FIRTEX_ENDL;
m_pIndexReader = pIndexReader;
}
FX_NS_END
| ruijieguo/firtex2 | src/search/IndexFeature.cpp | C++ | lgpl-3.0 | 1,305 |
/*
Copyright (C) 2010 by Claas Wilke (claaswilke@gmx.net)
This file is part of the XML Model Instance Plug-in of Dresden OCL2 for Eclipse.
Dresden OCL2 for Eclipse 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 3 of the License, or (at your option)
any later version.
Dresden OCL2 for Eclipse 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 Dresden OCL2 for Eclipse. If not, see <http://www.gnu.org/licenses/>.
*/
package org.dresdenocl.modelinstancetype.xml.internal.modelinstance;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import org.apache.log4j.Logger;
import org.eclipse.osgi.util.NLS;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.dresdenocl.essentialocl.types.CollectionType;
import org.dresdenocl.model.IModel;
import org.dresdenocl.model.ModelAccessException;
import org.dresdenocl.modelinstancetype.exception.TypeNotFoundInModelException;
import org.dresdenocl.modelinstancetype.types.IModelInstanceBoolean;
import org.dresdenocl.modelinstancetype.types.IModelInstanceElement;
import org.dresdenocl.modelinstancetype.types.IModelInstanceEnumerationLiteral;
import org.dresdenocl.modelinstancetype.types.IModelInstanceFactory;
import org.dresdenocl.modelinstancetype.types.IModelInstanceInteger;
import org.dresdenocl.modelinstancetype.types.IModelInstanceObject;
import org.dresdenocl.modelinstancetype.types.IModelInstanceReal;
import org.dresdenocl.modelinstancetype.types.IModelInstanceString;
import org.dresdenocl.modelinstancetype.types.base.BasisJavaModelInstanceFactory;
import org.dresdenocl.modelinstancetype.xml.XmlModelInstanceTypePlugin;
import org.dresdenocl.modelinstancetype.xml.internal.msg.XmlModelInstanceTypeMessages;
import org.dresdenocl.pivotmodel.Enumeration;
import org.dresdenocl.pivotmodel.EnumerationLiteral;
import org.dresdenocl.pivotmodel.PrimitiveType;
import org.dresdenocl.pivotmodel.Property;
import org.dresdenocl.pivotmodel.Type;
/**
* <p>
* {@link IModelInstanceFactory} implementation for {@link XmlModelInstance}s.
* </p>
*
* @author Claas Wilke
*/
public class XmlModelInstanceFactory extends BasisJavaModelInstanceFactory {
/** The {@link Logger} for this class. */
private static final Logger LOGGER = XmlModelInstanceTypePlugin
.getLogger(XmlModelInstanceFactory.class);
/**
* The {@link IModel} for whose {@link Type}s {@link IModelInstanceElement}s
* shall be created.
*/
private IModel model;
/**
* The cached {@link IModelInstanceObject}s of this
* {@link XmlModelInstanceFactory} identified by their adapted {@link Node}.
*/
private Map<Node, IModelInstanceObject> cacheModelInstanceObjects = new WeakHashMap<Node, IModelInstanceObject>();
/**
* <p>
* Creates a new {@link XmlModelInstanceFactory}.
* </p>
*
* @param model
* The {@link IModel} for whose {@link Type}s
* {@link IModelInstanceElement}s shall be created.
*/
public XmlModelInstanceFactory(IModel model) {
if (model == null) {
throw new IllegalArgumentException(
"Parameter 'model' must not be null.");
}
// no else.
this.model = model;
}
/*
* (non-Javadoc)
*
* @see org.dresdenocl.modelbus.modelinstance.types.IModelInstanceFactory
* #createModelInstanceElement(java.lang.Object)
*/
@Override
public IModelInstanceElement createModelInstanceElement(Object adapted)
throws TypeNotFoundInModelException {
/* Probably debug the entry of this method. */
if (LOGGER.isDebugEnabled()) {
String msg;
msg = "createModelInstanceElement("; //$NON-NLS-1$
msg += "adapted = " + adapted; //$NON-NLS-1$
msg += ")"; //$NON-NLS-1$
LOGGER.debug(msg);
}
// no else.
IModelInstanceElement result;
if (adapted instanceof Node) {
Node node;
node = (Node) adapted;
result = this.createModelInstanceElement(node);
}
else {
throw new IllegalArgumentException(
NLS.bind(
XmlModelInstanceTypeMessages.XmlModelInstanceFactory_UnknownClassOfAdaptee,
adapted.getClass().getCanonicalName()));
}
/* Probably debug the exit of this method. */
if (LOGGER.isDebugEnabled()) {
String msg;
msg = "createModelInstanceElement(Object) - exit"; //$NON-NLS-1$
LOGGER.debug(msg);
}
// no else.
return result;
}
/*
* (non-Javadoc)
*
* @see org.dresdenocl.modelbus.modelinstance.types.IModelInstanceFactory
* #createModelInstanceElement(java.lang.Object,
* org.dresdenocl.pivotmodel.Type)
*/
@SuppressWarnings("unchecked")
@Override
public IModelInstanceElement createModelInstanceElement(Object adapted,
Type type) {
/* Probably debug the entry of this method. */
if (LOGGER.isDebugEnabled()) {
String msg;
msg = "createModelInstanceElement("; //$NON-NLS-1$
msg += "adapted = " + adapted; //$NON-NLS-1$
msg += "type = " + type; //$NON-NLS-1$
msg += ")"; //$NON-NLS-1$
LOGGER.debug(msg);
}
// no else.
IModelInstanceElement result;
if (adapted == null || adapted instanceof Node) {
Node node;
node = null;
if (adapted != null) {
node = (Node) adapted;
}
// no else.
/* Probably adapt a literal. */
if (type instanceof Enumeration) {
result = this.createModelInstanceEnumerationLiteral(node,
(Enumeration) type);
}
/* Else probably adapt a primitive type. */
else if (type instanceof PrimitiveType) {
switch (((PrimitiveType) type).getKind()) {
case BOOLEAN:
result = this.createModelInstanceBoolean(node, type);
break;
case INTEGER:
result = this.createModelInstanceInteger(node, type);
break;
case REAL:
result = this.createModelInstanceReal(node, type);
break;
case STRING:
result = this.createModelInstanceString(node, type);
break;
default:
throw new IllegalArgumentException(
NLS.bind(
XmlModelInstanceTypeMessages.XmlModelInstanceFactory_UnknownClassOfAdaptee,
adapted.getClass().getCanonicalName()));
}
// end select.
}
else {
/* Probably use a cached result. */
if (this.cacheModelInstanceObjects.containsKey(node)) {
result = this.cacheModelInstanceObjects.get(node);
}
else {
result = this.createModelInstanceObject(node, type);
/* Add the result to the cache. */
this.cacheModelInstanceObjects.put(node,
(IModelInstanceObject) result);
}
// end else.
}
}
else if (type instanceof CollectionType
&& adapted instanceof Collection<?>) {
result = BasisJavaModelInstanceFactory
.createModelInstanceCollection(
(Collection<IModelInstanceElement>) adapted,
(CollectionType) type);
}
else {
throw new IllegalArgumentException(
NLS.bind(
XmlModelInstanceTypeMessages.XmlModelInstanceFactory_UnknownClassOfAdaptee,
adapted.getClass().getCanonicalName()));
}
/* Probably debug the exit of this method. */
if (LOGGER.isDebugEnabled()) {
String msg;
msg = "createModelInstanceElement(Object, Set<Type>) - exit"; //$NON-NLS-1$
LOGGER.debug(msg);
}
// no else.
return result;
}
/**
* <p>
* Creates an {@link IModelInstanceBoolean} for a given {@link Node} and a
* given {@link Type}.
*
* @param node
* The {@link Node} that shall be adapted.
* @param type
* The {@link Type} of the {@link IModelInstanceBoolean} in the
* {@link IModel}.
* @return The created {@link IModelInstanceBoolean}.
*/
private IModelInstanceBoolean createModelInstanceBoolean(Node node,
Type type) {
IModelInstanceBoolean result;
/*
* Use the java basis types here because the adaptation of a node would
* not help. If you adapt a node, cast it to boolean and then to string,
* you have to alter the nodes' value to get the right result such as
* 'true', 'false' or null in all other cases!
*/
if (node == null || node.getTextContent() == null) {
result = super.createModelInstanceBoolean(null);
}
else if (node.getTextContent().trim().equalsIgnoreCase("true")) {
result = super.createModelInstanceBoolean(true);
}
else if (node.getTextContent().trim().equalsIgnoreCase("false")) {
result = super.createModelInstanceBoolean(false);
}
else {
result = super.createModelInstanceBoolean(null);
}
return result;
}
/**
* <p>
* Creates an {@link IModelInstanceElement} for a given {@link Node}.
*
* @param node
* The {@link Node} that shall be adapted.
* @return The created {@link IModelInstanceElement}.
* @throws TypeNotFoundInModelException
* Thrown, if now {@link Type} in the {@link IModel} can be
* found that matches to the given {@link Node}.
*/
private IModelInstanceElement createModelInstanceElement(Node node)
throws TypeNotFoundInModelException {
IModelInstanceElement result;
Type type;
type = this.findTypeOfNode(node);
result = (IModelInstanceElement) this.createModelInstanceElement(node,
type);
return result;
}
/**
* <p>
* Creates an {@link IModelInstanceEnumerationLiteral} for the given
* {@link Node} and the given {@link Enumeration}.
* </p>
*
* @param node
* The {@link Node} for that an
* {@link IModelInstanceEnumerationLiteral} shall be created.
* @param enumeration
* The {@link Enumeration} type for that the
* {@link IModelInstanceEnumerationLiteral} shall be created.
* @return The created {@link IModelInstanceEnumerationLiteral}.
*/
private IModelInstanceEnumerationLiteral createModelInstanceEnumerationLiteral(
Node node, Enumeration enumeration) {
IModelInstanceEnumerationLiteral result;
if (node == null || node.getTextContent() == null) {
result = super.createModelInstanceEnumerationLiteral(null);
}
else {
EnumerationLiteral literal;
literal = null;
/* Try to find a literal that matches to the node's value. */
for (EnumerationLiteral aLiteral : enumeration.getOwnedLiteral()) {
if (aLiteral.getName().equalsIgnoreCase(
node.getTextContent().trim())) {
literal = aLiteral;
break;
}
// no else.
}
// end for.
result = super.createModelInstanceEnumerationLiteral(literal);
}
return result;
}
/**
* <p>
* Creates an {@link IModelInstanceInteger} for a given {@link Node} and a
* given {@link Type}.
*
* @param node
* The {@link Node} that shall be adapted.
* @param type
* The {@link Type} of the {@link IModelInstanceInteger} in the
* {@link IModel}.
* @return The created {@link IModelInstanceInteger}.
*/
private IModelInstanceInteger createModelInstanceInteger(Node node,
Type type) {
IModelInstanceInteger result;
/*
* Use the java basis types here because the adaptation of a node would
* not help. If you adapt a node, cast it to integer and then to string,
* you have to alter the nodes' value to get the right result such as
* '1' except of '1.23', or null in many cases!
*/
if (node == null || node.getTextContent() == null) {
result = super.createModelInstanceInteger(null);
}
else {
Long longValue;
try {
longValue = new Double(
Double.parseDouble(node.getTextContent())).longValue();
}
catch (NumberFormatException e) {
longValue = null;
}
result = super.createModelInstanceInteger(longValue);
}
return result;
}
/**
* <p>
* Creates an {@link IModelInstanceReal} for a given {@link Node} and a
* given {@link Type}.
*
* @param node
* The {@link Node} that shall be adapted.
* @param type
* The {@link Type} of the {@link IModelInstanceReal} in the
* {@link IModel}.
* @return The created {@link IModelInstanceReal}.
*/
private IModelInstanceReal createModelInstanceReal(Node node, Type type) {
IModelInstanceReal result;
/*
* Use the java basis types here because the adaptation of a node would
* not help. If you adapt a node, cast it to real and then to string,
* you have to alter the nodes' value to get the right result such as
* '1' except of '1.0', or null in many cases!
*/
if (node == null || node.getTextContent() == null) {
result = super.createModelInstanceReal(null);
}
else {
Double doubleValue;
try {
doubleValue = new Double(Double.parseDouble(node
.getTextContent()));
}
catch (NumberFormatException e) {
doubleValue = null;
}
result = super.createModelInstanceReal(doubleValue);
}
return result;
}
/**
* <p>
* Creates an {@link IModelInstanceString} for a given {@link Node} and a
* given {@link Type}.
*
* @param node
* The {@link Node} that shall be adapted.
* @param type
* The {@link Type} of the {@link IModelInstanceString} in the
* {@link IModel}.
* @return The created {@link IModelInstanceString}.
*/
private IModelInstanceString createModelInstanceString(Node node, Type type) {
IModelInstanceString result;
/*
* Use the java basis types here because the adaptation of a node would
* not help. If you adapt a node, cast it to integer and then to string,
* you have to alter the nodes' value to get the right result such as
* 'truefalse' except of null!
*/
if (node == null || node.getTextContent() == null) {
result = super.createModelInstanceString(null);
}
else {
result = super.createModelInstanceString(node.getTextContent());
}
return result;
}
/**
* <p>
* Creates an {@link XmlModelInstanceObject} for a given {@link Node} and a
* given {@link Type}.
*
* @param node
* The {@link Node} that shall be adapted.
* @param type
* The {@link Type} of the {@link XmlModelInstanceObject} in the
* {@link IModel}.
* @return The created {@link XmlModelInstanceObject}.
*/
private XmlModelInstanceObject createModelInstanceObject(Node node,
Type type) {
XmlModelInstanceObject result;
result = new XmlModelInstanceObject(node, type, type, this);
return result;
}
private Type findTypeOfNode(Node node) throws TypeNotFoundInModelException {
Type result;
result = null;
/* Collect all parent nodes. */
List<Node> parents;
parents = new ArrayList<Node>();
Node aNode;
aNode = node;
while (aNode != null) {
if (aNode == aNode.getParentNode() || aNode instanceof Document) {
break;
}
else {
parents.add(aNode);
aNode = aNode.getParentNode();
}
}
// end while.
if (parents.size() != 0) {
/* Try to find the type of the root node. */
Type rootType;
rootType = this
.findTypeOfRootNode(parents.remove(parents.size() - 1));
if (rootType != null) {
result = rootType;
/* Take the next node, try to find its property and its type. */
while (parents.size() > 0) {
List<Property> properties;
properties = result.allProperties();
aNode = parents.remove(parents.size() - 1);
result = null;
for (Property property : properties) {
if (property.getName().equalsIgnoreCase(
aNode.getNodeName().trim())) {
if (property.getType() instanceof CollectionType) {
result = ((CollectionType) property.getType())
.getElementType();
}
else {
result = property.getType();
}
break;
}
// no else.
}
// end for.
}
}
// no else (root type not found).
}
// no else (no parent node found).
if (result == null) {
throw new TypeNotFoundInModelException(
NLS.bind(
XmlModelInstanceTypeMessages.XmlModelInstanceFactory_UnknownTypeOfAdaptee,
node));
}
// no else.
return result;
}
/**
* <p>
* A helper method that searches for the {@link Type} of a given
* {@link Node} in the {@link IModel}.
* </p>
*
* @param node
* The {@link Node} for that a {@link Type} shall be found.
* @return The found {@link Type}.
*/
private Type findTypeOfRootNode(Node node)
throws TypeNotFoundInModelException {
Type result;
result = null;
String nodeName;
nodeName = node.getNodeName();
List<String> pathName;
pathName = new ArrayList<String>();
pathName.add(nodeName);
/* FIXME Claas: Probably handle the node's name space. */
try {
result = this.model.findType(pathName);
/* FIXME Lars: Try to handle the namespace */
if (result == null) {
String typeName = pathName.get(pathName.size() - 1);
while (typeName.contains(":")) {
typeName = pathName.remove(pathName.size() - 1);
typeName = typeName.substring(typeName.indexOf(":") + 1);
pathName.add(typeName);
result = this.model.findType(pathName);
if (result != null) {
break;
}
}
}
/*
* FIXME Claas: This is a very hacky dependency to the XSD
* meta-model and should be fixed in the Meta-model instead.
*/
/*
* change the first character into an upper case character and try
* again.
*/
if (result == null) {
String typeName = pathName.remove(pathName.size() - 1);
pathName.add(typeName.substring(0, 1).toUpperCase()
+ typeName.substring(1, typeName.length()));
result = this.model.findType(pathName);
}
// no else.
/*
* FIXME Claas: This is a very hacky dependency to the XSD
* meta-model and should be fixed in the Meta-model instead.
*/
/* Add a 'Type' to the node name and try again. */
if (result == null) {
pathName.add(pathName.remove(pathName.size() - 1) + "Type");
result = this.model.findType(pathName);
}
// no else.
}
// end try.
catch (ModelAccessException e) {
throw new TypeNotFoundInModelException(
NLS.bind(
XmlModelInstanceTypeMessages.XmlModelInstanceFactory_UnknownTypeOfAdaptee,
node), e);
}
// end catch.
return result;
}
} | dresden-ocl/dresdenocl | plugins/org.dresdenocl.modelinstancetype.xml/src/org/dresdenocl/modelinstancetype/xml/internal/modelinstance/XmlModelInstanceFactory.java | Java | lgpl-3.0 | 19,025 |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using JetBrains.Annotations;
namespace NetMQ
{
/// <summary>
/// This static class serves to provide extension methods for IOutgoingSocket.
/// </summary>
public static class OutgoingSocketExtensions
{
/// <summary>
/// Block until the message is can be sent.
/// </summary>
/// <remarks>
/// The call blocks until the message can be sent and cannot be interrupted.
/// Wether the message can be sent depends on the socket type.
/// </remarks>
/// <param name="socket">The socket to send the message on.</param>
/// <param name="msg">An object with message's data to send.</param>
/// <param name="more">Indicate if another frame is expected after this frame</param>
public static void Send(this IOutgoingSocket socket, ref Msg msg, bool more)
{
var result = socket.TrySend(ref msg, SendReceiveConstants.InfiniteTimeout, more);
Debug.Assert(result);
}
#region Sending Byte Array
#region Blocking
/// <summary>
/// Transmit a byte-array of data over this socket, block until frame is sent.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="data">the byte-array of data to send</param>
/// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param>
public static void SendFrame([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data, bool more = false)
{
SendFrame(socket, data, data.Length, more);
}
/// <summary>
/// Transmit a byte-array of data over this socket, block until frame is sent.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="data">the byte-array of data to send</param>
/// <param name="length">the number of bytes to send from <paramref name="data"/>.</param>
/// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param>
public static void SendFrame([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data, int length, bool more = false)
{
var msg = new Msg();
msg.InitPool(length);
Buffer.BlockCopy(data, 0, msg.Data, 0, data.Length);
socket.Send(ref msg, more);
msg.Close();
}
/// <summary>
/// Transmit a byte-array of data over this socket, block until frame is sent.
/// Send more frame, another frame must be sent after this frame. Use to chain Send methods.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="data">the byte-array of data to send</param>
[NotNull]
public static IOutgoingSocket SendMoreFrame([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data)
{
SendFrame(socket, data, true);
return socket;
}
/// <summary>
/// Transmit a byte-array of data over this socket, block until frame is sent.
/// Send more frame, another frame must be sent after this frame. Use to chain Send methods.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="data">the byte-array of data to send</param>
/// <param name="length">the number of bytes to send from <paramref name="data"/>.</param>
[NotNull]
public static IOutgoingSocket SendMoreFrame([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data, int length)
{
SendFrame(socket, data, length, true);
return socket;
}
#endregion
#region Timeout
/// <summary>
/// Attempt to transmit a single frame on <paramref cref="socket"/>.
/// If message cannot be sent within <paramref name="timeout"/>, return <c>false</c>.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="timeout">The maximum period of time to try to send a message.</param>
/// <param name="data">the byte-array of data to send</param>
/// <param name="length">the number of bytes to send from <paramref name="data"/>.</param>
/// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param>
/// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
public static bool TrySendFrame([NotNull] this IOutgoingSocket socket, TimeSpan timeout, [NotNull] byte[] data, int length, bool more = false)
{
var msg = new Msg();
msg.InitPool(length);
Buffer.BlockCopy(data, 0, msg.Data, 0, data.Length);
if (!socket.TrySend(ref msg, timeout, more))
{
msg.Close();
return false;
}
msg.Close();
return true;
}
/// <summary>
/// Attempt to transmit a single frame on <paramref cref="socket"/>.
/// If message cannot be sent within <paramref name="timeout"/>, return <c>false</c>.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="timeout">The maximum period of time to try to send a message.</param>
/// <param name="data">the byte-array of data to send</param>
/// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param>
/// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
public static bool TrySendFrame([NotNull] this IOutgoingSocket socket, TimeSpan timeout, [NotNull] byte[] data, bool more = false)
{
return TrySendFrame(socket, timeout, data, data.Length, more);
}
#endregion
#region Immediate
/// <summary>
/// Attempt to transmit a single frame on <paramref cref="socket"/>.
/// If message cannot be sent immediately, return <c>false</c>.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="data">the byte-array of data to send</param>
/// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param>
/// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
public static bool TrySendFrame([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data,
bool more = false)
{
return TrySendFrame(socket, TimeSpan.Zero, data, more);
}
/// <summary>
/// Attempt to transmit a single frame on <paramref cref="socket"/>.
/// If message cannot be sent immediately, return <c>false</c>.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="data">the byte-array of data to send</param>
/// <param name="length">the number of bytes to send from <paramref name="data"/>.</param>
/// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param>
/// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
public static bool TrySendFrame([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data, int length,
bool more = false)
{
return TrySendFrame(socket, TimeSpan.Zero, data, length, more);
}
#endregion
#region Obsolete
/// <summary>
/// Transmit a byte-array of data over this socket.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="data">the byte-array of data to send</param>
/// <param name="length">the number of bytes to send from <paramref name="data"/>.</param>
/// <param name="options">options to control how the data is sent</param>
[Obsolete("Use SendFrame or TrySendFrame")]
public static void Send([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data, int length, SendReceiveOptions options)
{
var msg = new Msg();
msg.InitPool(length);
Buffer.BlockCopy(data, 0, msg.Data, 0, length);
socket.Send(ref msg, options);
msg.Close();
}
/// <summary>
/// Transmit a byte-array of data over this socket.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="data">the byte-array of data to send</param>
/// <param name="length">the number of bytes to send</param>
/// <param name="dontWait">if true, return immediately without waiting for the send operation to complete (optional: default is false)</param>
/// <param name="sendMore">set this flag to true to signal that you will be immediately sending another message (optional: default is false)</param>
[Obsolete("Use SendFrame or TrySendFrame")]
public static void Send([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data, int length, bool dontWait = false, bool sendMore = false)
{
var options = SendReceiveOptions.None;
if (dontWait)
{
options |= SendReceiveOptions.DontWait;
}
if (sendMore)
{
options |= SendReceiveOptions.SendMore;
}
socket.Send(data, length, options);
}
/// <summary>
/// Transmit a byte-array of data over this socket.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="data">the byte-array of data to send</param>
[Obsolete("Use SendFrame or TrySendFrame")]
public static void Send([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data)
{
socket.Send(data, data.Length);
}
/// <summary>
/// Transmit a string-message of data over this socket, while indicating that more is to come
/// (the SendMore flag is set to true).
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="data">the byte-array of data to send</param>
/// <param name="dontWait">if true, return immediately without waiting for the send operation to complete (optional: default is false)</param>
/// <returns>a reference to this IOutgoingSocket so that method-calls may be chained together</returns>
[NotNull]
[Obsolete("Use SendMoreFrame or TrySendFrame")]
public static IOutgoingSocket SendMore([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data, bool dontWait = false)
{
socket.Send(data, data.Length, dontWait, true);
return socket;
}
/// <summary>
/// Transmit a string-message of data over this socket, while indicating that more is to come
/// (the SendMore flag is set to true).
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="data">the byte-array of data to send</param>
/// <param name="length">the number of bytes to send</param>
/// <param name="dontWait">if true, return immediately without waiting for the send operation to complete (optional: default is false)</param>
/// <returns>a reference to this IOutgoingSocket so that method-calls may be chained together</returns>
[NotNull]
[Obsolete("Use SendMoreFrame or TrySendFrame")]
public static IOutgoingSocket SendMore([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data, int length, bool dontWait = false)
{
socket.Send(data, length, dontWait, true);
return socket;
}
#endregion
#endregion
#region Sending a multipart message as byte arrays
#region Blocking
/// <summary>
/// Send multiple frames on <paramref cref="socket"/>, blocking until all frames are sent.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="frames">frames to transmit</param>
public static void SendMultipartBytes([NotNull] this IOutgoingSocket socket, params byte[][] frames)
{
SendMultipartBytes(socket, (IEnumerable<byte[]>)frames);
}
/// <summary>
/// Send multiple frames on <paramref cref="socket"/>, blocking until all frames are sent.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="frames">frames to transmit</param>
public static void SendMultipartBytes([NotNull] this IOutgoingSocket socket, IEnumerable<byte[]> frames)
{
var enumerator = frames.GetEnumerator();
try
{
// move to the first emlement, if false frames is empty
if (!enumerator.MoveNext())
{
throw new ArgumentException("frames is empty", "frames");
}
var current = enumerator.Current;
// we always one item back to make sure we send the last frame without the more flag
while (enumerator.MoveNext())
{
// this is a more frame
socket.SendMoreFrame(current);
current = enumerator.Current;
}
// sending the last frame
socket.SendFrame(current);
}
finally
{
enumerator.Dispose();
}
}
#endregion
#region Timeout
/// <summary>
/// Attempt to transmit a mulitple frames on <paramref cref="socket"/>.
/// If frames cannot be sent within <paramref name="timeout"/>, return <c>false</c>.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="frames">frames to transmit</param>
public static bool TrySendMultipartBytes([NotNull] this IOutgoingSocket socket, TimeSpan timeout, params byte[][] frames)
{
return TrySendMultipartBytes(socket, timeout, (IEnumerable<byte[]>)frames);
}
/// <summary>
/// Attempt to transmit a mulitple frames on <paramref cref="socket"/>.
/// If frames cannot be sent within <paramref name="timeout"/>, return <c>false</c>.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="timeout">The maximum period of time to try to send a message.</param>
/// <param name="frames">frames to transmit</param>
public static bool TrySendMultipartBytes([NotNull] this IOutgoingSocket socket, TimeSpan timeout,
IEnumerable<byte[]> frames)
{
var enumerator = frames.GetEnumerator();
try
{
// move to the first emlement, if false frames is empty
if (!enumerator.MoveNext())
{
throw new ArgumentException("frames is empty", "frames");
}
var current = enumerator.Current;
// only the first frame need to be sent with a timeout
if (!enumerator.MoveNext())
{
return socket.TrySendFrame(timeout, current);
}
else
{
bool sentSuccessfully = socket.TrySendFrame(timeout, current, true);
if (!sentSuccessfully)
return false;
}
// fetching the second frame
current = enumerator.Current;
// we always one item back to make sure we send the last frame without the more flag
while (enumerator.MoveNext())
{
// this is a more frame
socket.SendMoreFrame(current);
current = enumerator.Current;
}
// sending the last frame
socket.SendFrame(current);
return true;
}
finally
{
enumerator.Dispose();
}
}
#endregion
#region Immediate
/// <summary>
/// Attempt to transmit a mulitple frames on <paramref cref="socket"/>.
/// If frames cannot be sent immediatly, return <c>false</c>.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="frames">frames to transmit</param>
public static bool TrySendMultipartBytes([NotNull] this IOutgoingSocket socket, params byte[][] frames)
{
return TrySendMultipartBytes(socket, TimeSpan.Zero, (IEnumerable<byte[]>)frames);
}
/// <summary>
/// Attempt to transmit a mulitple frames on <paramref cref="socket"/>.
/// If frames cannot be sent immediatly, return <c>false</c>.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="frames">frames to transmit</param>
public static bool TrySendMultipartBytes([NotNull] this IOutgoingSocket socket, IEnumerable<byte[]> frames)
{
return TrySendMultipartBytes(socket, TimeSpan.Zero, frames);
}
#endregion
#endregion
#region Sending Strings
#region Blocking
/// <summary>
/// Transmit a string over this socket, block until frame is sent.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="message">the string to send</param>
/// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param>
public static void SendFrame([NotNull] this IOutgoingSocket socket, [NotNull] string message, bool more = false)
{
var msg = new Msg();
// Count the number of bytes required to encode the string.
// Note that non-ASCII strings may not have an equal number of characters
// and bytes. The encoding must be queried for this answer.
// With this number, request a buffer from the pool.
msg.InitPool(SendReceiveConstants.DefaultEncoding.GetByteCount(message));
// Encode the string into the buffer
SendReceiveConstants.DefaultEncoding.GetBytes(message, 0, message.Length, msg.Data, 0);
socket.Send(ref msg, more);
msg.Close();
}
/// <summary>
/// Transmit a string over this socket, block until frame is sent.
/// Send more frame, another frame must be sent after this frame. Use to chain Send methods.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="message">the string to send</param>
[NotNull]
public static IOutgoingSocket SendMoreFrame([NotNull] this IOutgoingSocket socket, [NotNull] string message)
{
SendFrame(socket, message, true);
return socket;
}
#endregion
#region Timeout
/// <summary>
/// Attempt to transmit a single string frame on <paramref cref="socket"/>.
/// If message cannot be sent within <paramref name="timeout"/>, return <c>false</c>.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="timeout">The maximum period of time to try to send a message.</param>
/// <param name="message">the string to send</param>
/// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param>
/// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
public static bool TrySendFrame([NotNull] this IOutgoingSocket socket, TimeSpan timeout, [NotNull] string message, bool more = false)
{
var msg = new Msg();
// Count the number of bytes required to encode the string.
// Note that non-ASCII strings may not have an equal number of characters
// and bytes. The encoding must be queried for this answer.
// With this number, request a buffer from the pool.
msg.InitPool(SendReceiveConstants.DefaultEncoding.GetByteCount(message));
// Encode the string into the buffer
SendReceiveConstants.DefaultEncoding.GetBytes(message, 0, message.Length, msg.Data, 0);
if (!socket.TrySend(ref msg, timeout, more))
{
msg.Close();
return false;
}
msg.Close();
return true;
}
#endregion
#region Immediate
/// <summary>
/// Attempt to transmit a single string frame on <paramref cref="socket"/>.
// If message cannot be sent immediately, return <c>false</c>.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="message">the string to send</param>
/// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param>
/// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
public static bool TrySendFrame([NotNull] this IOutgoingSocket socket, [NotNull] string message, bool more = false)
{
return TrySendFrame(socket, TimeSpan.Zero, message, more);
}
#endregion
#region obsolete
/// <summary>
/// Transmit a string-message of data over this socket. The string will be encoded into bytes using the specified Encoding.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="message">a string containing the message to send</param>
/// <param name="encoding">the Encoding to use when converting the message-string into bytes</param>
/// <param name="options">use this to specify which of the DontWait and SendMore flags to set</param>
[Obsolete("Use SendFrame or TrySendFrame")]
public static void Send([NotNull] this IOutgoingSocket socket, [NotNull] string message, [NotNull] Encoding encoding, SendReceiveOptions options)
{
var msg = new Msg();
// Count the number of bytes required to encode the string.
// Note that non-ASCII strings may not have an equal number of characters
// and bytes. The encoding must be queried for this answer.
// With this number, request a buffer from the pool.
msg.InitPool(encoding.GetByteCount(message));
// Encode the string into the buffer
encoding.GetBytes(message, 0, message.Length, msg.Data, 0);
socket.Send(ref msg, options);
msg.Close();
}
/// <summary>
/// Transmit a string-message of data over this socket. The string will be encoded into bytes using the specified Encoding.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="message">a string containing the message to send</param>
/// <param name="encoding">the Encoding to use when converting the message-string into bytes</param>
/// <param name="dontWait">if true, return immediately without waiting for the send operation to complete (optional: default is false)</param>
/// <param name="sendMore">set this flag to true to signal that you will be immediately sending another message (optional: default is false)</param>
[Obsolete("Use SendFrame or TrySendFrame")]
public static void Send([NotNull] this IOutgoingSocket socket, [NotNull] string message, [NotNull] Encoding encoding, bool dontWait = false, bool sendMore = false)
{
var options = SendReceiveOptions.None;
if (dontWait)
{
options |= SendReceiveOptions.DontWait;
}
if (sendMore)
{
options |= SendReceiveOptions.SendMore;
}
socket.Send(message, encoding, options);
}
/// <summary>
/// Transmit a string-message of data over this socket. The string will be encoded into bytes using the default Encoding (ASCII).
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="message">a string containing the message to send</param>
/// <param name="dontWait">if true, return immediately without waiting for the send operation to complete (optional: default is false)</param>
/// <param name="sendMore">set this flag to true to signal that you will be immediately sending another message (optional: default is false)</param>
[Obsolete("Use SendFrame or TrySendFrame")]
public static void Send([NotNull] this IOutgoingSocket socket, [NotNull] string message, bool dontWait = false, bool sendMore = false)
{
Send(socket, message, Encoding.ASCII, dontWait, sendMore);
}
/// <summary>
/// Transmit a string-message of data over this socket, while indicating that more is to come
/// (the SendMore flag is set to true).
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="message">a string containing the message to send</param>
/// <param name="dontWait">if true, return immediately without waiting for the send operation to complete</param>
/// <returns>a reference to this IOutgoingSocket so that method-calls may be chained together</returns>
[NotNull]
[Obsolete("Use SendMoreFrame or TrySendFrame")]
public static IOutgoingSocket SendMore([NotNull] this IOutgoingSocket socket, [NotNull] string message, bool dontWait = false)
{
socket.Send(message, dontWait, true);
return socket;
}
/// <summary>
/// Transmit a string-message of data over this socket and also signal that you are sending more.
/// The string will be encoded into bytes using the specified Encoding.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="message">a string containing the message to send</param>
/// <param name="encoding">the Encoding to use when converting the message-string into bytes</param>
/// <param name="dontWait">if true, return immediately without waiting for the send operation to complete (optional: default is false)</param>
/// <returns>a reference to this IOutgoingSocket so that method-calls may be chained together</returns>
[NotNull]
[Obsolete("Use SendMoreFrame or TrySendFrame")]
public static IOutgoingSocket SendMore([NotNull] this IOutgoingSocket socket, [NotNull] string message, [NotNull] Encoding encoding, bool dontWait = false)
{
socket.Send(message, encoding, dontWait, true);
return socket;
}
#endregion
#endregion
#region Sending a multipart message as NetMQMessage
#region Blocking
/// <summary>
/// Send multiple message on <paramref cref="socket"/>, blocking until all entire message is sent.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="message">message to transmit</param>
public static void SendMultipartMessage([NotNull] this IOutgoingSocket socket, [NotNull] NetMQMessage message)
{
if (message.FrameCount == 0)
throw new ArgumentException("message is empty", "message");
for (int i = 0; i < message.FrameCount - 1; i++)
{
socket.SendMoreFrame(message[i].Buffer, message[i].MessageSize);
}
socket.SendFrame(message.Last.Buffer, message.Last.MessageSize);
}
#endregion
#region Timeout
/// <summary>
/// Attempt to transmit a mulitple message on <paramref cref="socket"/>.
/// If message cannot be sent within <paramref name="timeout"/>, return <c>false</c>.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="message">message to transmit</param>
public static bool TrySendMultipartMessage([NotNull] this IOutgoingSocket socket, TimeSpan timeout, [NotNull] NetMQMessage message)
{
if (message.FrameCount == 0)
throw new ArgumentException("message is empty", "message");
else if (message.FrameCount == 1)
{
return TrySendFrame(socket, timeout, message[0].Buffer, message[0].MessageSize);
}
else
{
bool sentSuccessfully = TrySendFrame(socket, timeout, message[0].Buffer, message[0].MessageSize, true);
if (!sentSuccessfully)
return false;
}
for (int i = 1; i < message.FrameCount - 1; i++)
{
socket.SendMoreFrame(message[i].Buffer, message[i].MessageSize);
}
socket.SendFrame(message.Last.Buffer, message.Last.MessageSize);
return true;
}
#endregion
#region Immediate
/// <summary>
/// Attempt to transmit a mulitple message on <paramref cref="socket"/>.
/// If frames cannot be sent immediatly, return <c>false</c>.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="message">message to transmit</param>
public static bool TrySendMultipartMessage([NotNull] this IOutgoingSocket socket, [NotNull] NetMQMessage message)
{
return TrySendMultipartMessage(socket, TimeSpan.Zero, message);
}
#endregion
#region obsolete
/// <summary>
/// Transmit a message over this socket.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="message">the NetMQMessage that contains the frames of data to send</param>
/// <param name="dontWait">if true, return immediately without waiting for the send operation to complete (optional: default is false)</param>
[Obsolete("Use TrySendMultipartMessage or SendMultipartMessage")]
public static void SendMessage([NotNull] this IOutgoingSocket socket, [NotNull] NetMQMessage message, bool dontWait = false)
{
for (int i = 0; i < message.FrameCount - 1; i++)
{
socket.Send(message[i].Buffer, message[i].MessageSize, dontWait, true);
}
socket.Send(message.Last.Buffer, message.Last.MessageSize, dontWait);
}
#endregion
#endregion
#region Sending an empty frame
private static readonly byte[] s_empty = new byte[0];
#region Blocking
/// <summary>
/// Transmit an empty frame over this socket, block until frame is sent.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param>
public static void SendFrameEmpty([NotNull] this IOutgoingSocket socket, bool more = false)
{
SendFrame(socket, s_empty, more);
}
/// <summary>
/// Transmit an empty frame over this socket, block until frame is sent.
/// Send more frame, another frame must be sent after this frame. Use to chain Send methods.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
public static void SendMoreFrameEmpty([NotNull] this IOutgoingSocket socket)
{
SendFrame(socket, s_empty, true);
}
#endregion
#region Timeout
/// <summary>
/// Attempt to transmit an empty frame on <paramref cref="socket"/>.
/// If message cannot be sent within <paramref name="timeout"/>, return <c>false</c>.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="timeout">The maximum period of time to try to send a message.</param>
/// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param>
/// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
public static bool TrySendFrameEmpty([NotNull] this IOutgoingSocket socket, TimeSpan timeout, bool more = false)
{
return TrySendFrame(socket, timeout, s_empty, more);
}
#endregion
#region Immediate
/// <summary>
/// Attempt to transmit an empty frame on <paramref cref="socket"/>.
/// If message cannot be sent immediately, return <c>false</c>.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param>
/// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns>
public static bool TrySendFrameEmpty([NotNull] this IOutgoingSocket socket, bool more = false)
{
return TrySendFrame(socket, s_empty, more);
}
#endregion
#endregion
#region Sending Signals
/// <summary>
/// Transmit a status-signal over this socket.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="status">a byte that contains the status signal to send</param>
private static void Signal([NotNull] this IOutgoingSocket socket, byte status)
{
long signalValue = 0x7766554433221100L + status;
Msg msg = new Msg();
msg.InitPool(8);
NetworkOrderBitsConverter.PutInt64(signalValue, msg.Data);
socket.Send(ref msg, false);
msg.Close();
}
/// <summary>
/// Attempt to transmit a status-signal over this socket.
/// If signal cannot be sent immediately, return <c>false</c>.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
/// <param name="status">a byte that contains the status signal to send</param>
private static bool TrySignal([NotNull] this IOutgoingSocket socket, byte status)
{
long signalValue = 0x7766554433221100L + status;
Msg msg = new Msg();
msg.InitPool(8);
NetworkOrderBitsConverter.PutInt64(signalValue, msg.Data);
if (!socket.TrySend(ref msg, TimeSpan.Zero, false))
{
msg.Close();
return false;
}
msg.Close();
return true;
}
/// <summary>
/// Transmit a specific status-signal over this socket that indicates OK.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
public static void SignalOK([NotNull] this IOutgoingSocket socket)
{
socket.Signal(0);
}
/// <summary>
/// Attempt to transmit a specific status-signal over this socket that indicates OK.
/// If signal cannot be sent immediately, return <c>false</c>.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
public static bool TrySignalOK([NotNull] this IOutgoingSocket socket)
{
return TrySignal(socket, 0);
}
/// <summary>
/// Transmit a specific status-signal over this socket that indicates there is an error.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
public static void SignalError([NotNull] this IOutgoingSocket socket)
{
socket.Signal(1);
}
/// <summary>
/// Attempt to transmit a specific status-signal over this socket that indicates there is an error.
/// If signal cannot be sent immediately, return <c>false</c>.
/// </summary>
/// <param name="socket">the IOutgoingSocket to transmit on</param>
public static bool TrySignalError([NotNull] this IOutgoingSocket socket)
{
return socket.TrySignal(1);
}
#endregion
}
}
| ashic/netmq | src/NetMQ/OutgoingSocketExtensions.cs | C# | lgpl-3.0 | 38,297 |
/*
* Copyright (c) 2005-2016 Vincent Vandenschrick. All rights reserved.
*
* This file is part of the Jspresso framework.
*
* Jspresso 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 3 of the License, or
* (at your option) any later version.
*
* Jspresso 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 Jspresso. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jspresso.framework.util.spring;
import org.springframework.beans.factory.FactoryBean;
/**
* This is a simple utility bean to get a named null bean.
*
* @author Vincent Vandenschrick
*/
public class NullFactoryBean implements FactoryBean<Object> {
/**
* Returns true.
* <p>
* {@inheritDoc}
*/
@Override
public boolean isSingleton() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public Object getObject() throws Exception {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public Class<Object> getObjectType() {
return Object.class;
}
}
| jspresso/jspresso-ce | util/src/main/java/org/jspresso/framework/util/spring/NullFactoryBean.java | Java | lgpl-3.0 | 1,417 |
from dynamic_graph.sot.application.stabilizer.scenarii.seqplay_lqr_twoDof_coupled_stabilizer import SeqPlayLqrTwoDofCoupledStabilizer
from dynamic_graph.sot.application.stabilizer.scenarii.hrp2_lqr_twoDof_coupled_stabilizer import HRP2LqrTwoDofCoupledStabilizer
from dynamic_graph.sot.core.meta_tasks import GainAdaptive
from dynamic_graph import plug
from dynamic_graph.sot.core.matrix_util import matrixToTuple
from dynamic_graph.sot.core import MatrixToUTheta, HomoToMatrix, HomoToRotation, Multiply_matrix_vector
from numpy import diag
class SeqPlayLqrTwoDofCoupledStabilizerHRP2(SeqPlayLqrTwoDofCoupledStabilizer):
def __init__(self,robot,sequenceFilename,trunkStabilize = False, hands = False, posture =False,forceSeqplay=True):
SeqPlayLqrTwoDofCoupledStabilizer.__init__(self,robot,sequenceFilename,trunkStabilize,hands,posture,forceSeqplay)
def createStabilizedCoMTask (self):
task = HRP2LqrTwoDofCoupledStabilizer(self.robot)
gain = GainAdaptive('gain'+task.name)
plug(self.comRef,task.comRef)
task.waistOriRef.value=(0,)*3
task.flexOriRef.value=(0,)*3
task.comDotRef.value=(0,)*3
task.waistVelRef.value=(0,)*3
task.flexAngVelRef.value=(0,)*3
plug(gain.gain, task.controlGain)
plug(task.error, gain.error)
return (task, gain)
def initTaskPosture(self):
# --- LEAST NORM
weight_ff = 0
weight_leg = 3
weight_knee = 5
weight_chest = 1
weight_chesttilt = 10
weight_head = 0.3
weight_arm = 1
#weight = diag( (weight_ff,)*6 + (weight_leg,)*12 + (weight_chest,)*2 + (weight_head,)*2 + (weight_arm,)*14)
#weight[9,9] = weight_knee
#weight[15,15] = weight_knee
#weight[19,19] = weight_chesttilt
weight = diag( (0,)*6+(1,)*30)
#weight = weight[6:,:]
self.featurePosture.jacobianIN.value = matrixToTuple(weight)
self.featurePostureDes.errorIN.value = self.robot.halfSitting
#mask = '1'*36
#mask = '1'*14+'0'*22
#self.tasks['posture'].controlSelec.value = mask
| amifsud/sot-stabilizer | src/dynamic_graph/sot/application/stabilizer/scenarii/seqplay_lqr_twoDof_coupled_stabilizer_hrp2.py | Python | lgpl-3.0 | 2,157 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'pyweed/gui/uic/SpinnerWidget.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_SpinnerWidget(object):
def setupUi(self, SpinnerWidget):
SpinnerWidget.setObjectName("SpinnerWidget")
SpinnerWidget.resize(306, 207)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(SpinnerWidget.sizePolicy().hasHeightForWidth())
SpinnerWidget.setSizePolicy(sizePolicy)
SpinnerWidget.setStyleSheet("QFrame { background-color: rgba(224,224,224,192)} \n"
"QLabel { background-color: transparent }")
self.verticalLayout = QtWidgets.QVBoxLayout(SpinnerWidget)
self.verticalLayout.setSpacing(0)
self.verticalLayout.setObjectName("verticalLayout")
self.icon = QtWidgets.QLabel(SpinnerWidget)
self.icon.setText("")
self.icon.setAlignment(QtCore.Qt.AlignBottom|QtCore.Qt.AlignHCenter)
self.icon.setObjectName("icon")
self.verticalLayout.addWidget(self.icon)
self.label = QtWidgets.QLabel(SpinnerWidget)
self.label.setText("")
self.label.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop)
self.label.setObjectName("label")
self.verticalLayout.addWidget(self.label)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.cancelButton = QtWidgets.QPushButton(SpinnerWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.cancelButton.sizePolicy().hasHeightForWidth())
self.cancelButton.setSizePolicy(sizePolicy)
self.cancelButton.setObjectName("cancelButton")
self.horizontalLayout.addWidget(self.cancelButton)
self.verticalLayout.addLayout(self.horizontalLayout)
self.verticalLayout.setStretch(0, 1)
self.verticalLayout.setStretch(1, 1)
self.retranslateUi(SpinnerWidget)
QtCore.QMetaObject.connectSlotsByName(SpinnerWidget)
def retranslateUi(self, SpinnerWidget):
_translate = QtCore.QCoreApplication.translate
SpinnerWidget.setWindowTitle(_translate("SpinnerWidget", "Form"))
self.cancelButton.setText(_translate("SpinnerWidget", "Cancel"))
| iris-edu/pyweed | pyweed/gui/uic/SpinnerWidget.py | Python | lgpl-3.0 | 2,674 |
import re
from hashlib import sha256
from vFense.plugins.patching import AppsKey
from vFense.plugins.patching._constants import CommonSeverityKeys
def build_app_id(name, version):
""" Return the 64 character hexdigest of the appid.
The app_id is generated by creating a hexdigest based of the
name and the version of the application.
Args:
app (dict): Dictionary containing the name and version of the
application.
Basic Usage:
>>> from vFense.plugins.patching.utils import build_app_id
>>> name = 'app_name'
>>> version = '2.2.0'
>>> build_app_id(name, version)
Returns:
String
'bab72e94f26a0af32a8e1fc8eef732b99150fac9bc17a720dac06f5474b53f08'
"""
app_id = name.encode('utf8') + version.encode('utf8')
return sha256(app_id).hexdigest()
def build_agent_app_id(agent_id, app_id):
""" Return the 64 character hexdigest of the
appid and agentid combined
Args:
agent_id (str): The 36 character UUID of the agent.
app_id (str): The 64 character hexdigest of the app id
Basic Usage:
>>> vFense.plugins.patching.patching import build_agent_app_id
>>> agent_id = '7f242ab8-a9d7-418f-9ce2-7bcba6c2d9dc'
>>> app_id = '15fa819554aca425d7f699e81a2097898b06f00a0f2dd6e8d51a18405360a6eb'
>>> build_agent_app_id(agent_id, app_id)
Returns:
String
'0009281d779a37cc73919656f6575de471237c3ed99f585160708defe8396d3d'
"""
agent_app_id = agent_id.encode('utf8') + app_id.encode('utf8')
return sha256(agent_app_id).hexdigest()
def get_proper_severity(severity):
if re.search(r'Critical|Important|Security', severity, re.IGNORECASE):
return CommonSeverityKeys.CRITICAL
elif re.search(r'Recommended|Moderate|Low|Bugfix', severity, re.IGNORECASE):
return CommonSeverityKeys.RECOMMENDED
return CommonSeverityKeys.OPTIONAL
| dtklein/vFense | tp/src/plugins/patching/utils/__init__.py | Python | lgpl-3.0 | 1,957 |
package fr.upond.syndic.repository.userRole;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import fr.upond.syndic.repository.IDao;
import fr.upond.syndic.security.model.UserRole;
/**
*
* @author LYES KHERBICHE
*
*/
public class UserRoleDaoImpl implements IDao<UserRole> {
private static final Log logger = LogFactory.getLog(UserRoleDaoImpl.class);
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public List<UserRole> get(UserRole obj) {
return new ArrayList<UserRole>();
}
@Override
public void put(UserRole obj) {
logger.info("===== Insert UserRole =====");
this.sessionFactory.getCurrentSession().save(obj);
}
@Override
public void delete(UserRole obj) {
// to implement
}
@Override
public void upDate(UserRole obj) {
// to implement
}
}
| MM2CSYNDIC/syndic | syndic-repository-core/src/main/java/fr/upond/syndic/repository/userRole/UserRoleDaoImpl.java | Java | lgpl-3.0 | 1,100 |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package orgomg.cwm.resource.relational.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList;
import org.eclipse.emf.ecore.util.InternalEList;
import orgomg.cwm.objectmodel.core.impl.ClassImpl;
import orgomg.cwm.resource.relational.Column;
import orgomg.cwm.resource.relational.NamedColumnSet;
import orgomg.cwm.resource.relational.RelationalPackage;
import orgomg.cwm.resource.relational.SQLDataType;
import orgomg.cwm.resource.relational.SQLStructuredType;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>SQL Structured Type</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link orgomg.cwm.resource.relational.impl.SQLStructuredTypeImpl#getTypeNumber <em>Type Number</em>}</li>
* <li>{@link orgomg.cwm.resource.relational.impl.SQLStructuredTypeImpl#getColumnSet <em>Column Set</em>}</li>
* <li>{@link orgomg.cwm.resource.relational.impl.SQLStructuredTypeImpl#getReferencingColumn <em>Referencing Column</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class SQLStructuredTypeImpl extends ClassImpl implements SQLStructuredType {
/**
* The default value of the '{@link #getTypeNumber() <em>Type Number</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTypeNumber()
* @generated
* @ordered
*/
protected static final long TYPE_NUMBER_EDEFAULT = 0L;
/**
* The cached value of the '{@link #getTypeNumber() <em>Type Number</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTypeNumber()
* @generated
* @ordered
*/
protected long typeNumber = TYPE_NUMBER_EDEFAULT;
/**
* The cached value of the '{@link #getColumnSet() <em>Column Set</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getColumnSet()
* @generated
* @ordered
*/
protected EList<NamedColumnSet> columnSet;
/**
* The cached value of the '{@link #getReferencingColumn() <em>Referencing Column</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getReferencingColumn()
* @generated
* @ordered
*/
protected EList<Column> referencingColumn;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected SQLStructuredTypeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return RelationalPackage.Literals.SQL_STRUCTURED_TYPE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public long getTypeNumber() {
return typeNumber;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setTypeNumber(long newTypeNumber) {
long oldTypeNumber = typeNumber;
typeNumber = newTypeNumber;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, RelationalPackage.SQL_STRUCTURED_TYPE__TYPE_NUMBER, oldTypeNumber, typeNumber));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<NamedColumnSet> getColumnSet() {
if (columnSet == null) {
columnSet = new EObjectWithInverseResolvingEList<NamedColumnSet>(NamedColumnSet.class, this, RelationalPackage.SQL_STRUCTURED_TYPE__COLUMN_SET, RelationalPackage.NAMED_COLUMN_SET__TYPE);
}
return columnSet;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Column> getReferencingColumn() {
if (referencingColumn == null) {
referencingColumn = new EObjectWithInverseResolvingEList<Column>(Column.class, this, RelationalPackage.SQL_STRUCTURED_TYPE__REFERENCING_COLUMN, RelationalPackage.COLUMN__REFERENCED_TABLE_TYPE);
}
return referencingColumn;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case RelationalPackage.SQL_STRUCTURED_TYPE__COLUMN_SET:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getColumnSet()).basicAdd(otherEnd, msgs);
case RelationalPackage.SQL_STRUCTURED_TYPE__REFERENCING_COLUMN:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getReferencingColumn()).basicAdd(otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case RelationalPackage.SQL_STRUCTURED_TYPE__COLUMN_SET:
return ((InternalEList<?>)getColumnSet()).basicRemove(otherEnd, msgs);
case RelationalPackage.SQL_STRUCTURED_TYPE__REFERENCING_COLUMN:
return ((InternalEList<?>)getReferencingColumn()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case RelationalPackage.SQL_STRUCTURED_TYPE__TYPE_NUMBER:
return getTypeNumber();
case RelationalPackage.SQL_STRUCTURED_TYPE__COLUMN_SET:
return getColumnSet();
case RelationalPackage.SQL_STRUCTURED_TYPE__REFERENCING_COLUMN:
return getReferencingColumn();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case RelationalPackage.SQL_STRUCTURED_TYPE__TYPE_NUMBER:
setTypeNumber((Long)newValue);
return;
case RelationalPackage.SQL_STRUCTURED_TYPE__COLUMN_SET:
getColumnSet().clear();
getColumnSet().addAll((Collection<? extends NamedColumnSet>)newValue);
return;
case RelationalPackage.SQL_STRUCTURED_TYPE__REFERENCING_COLUMN:
getReferencingColumn().clear();
getReferencingColumn().addAll((Collection<? extends Column>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case RelationalPackage.SQL_STRUCTURED_TYPE__TYPE_NUMBER:
setTypeNumber(TYPE_NUMBER_EDEFAULT);
return;
case RelationalPackage.SQL_STRUCTURED_TYPE__COLUMN_SET:
getColumnSet().clear();
return;
case RelationalPackage.SQL_STRUCTURED_TYPE__REFERENCING_COLUMN:
getReferencingColumn().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case RelationalPackage.SQL_STRUCTURED_TYPE__TYPE_NUMBER:
return typeNumber != TYPE_NUMBER_EDEFAULT;
case RelationalPackage.SQL_STRUCTURED_TYPE__COLUMN_SET:
return columnSet != null && !columnSet.isEmpty();
case RelationalPackage.SQL_STRUCTURED_TYPE__REFERENCING_COLUMN:
return referencingColumn != null && !referencingColumn.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public int eBaseStructuralFeatureID(int derivedFeatureID, Class<?> baseClass) {
if (baseClass == SQLDataType.class) {
switch (derivedFeatureID) {
case RelationalPackage.SQL_STRUCTURED_TYPE__TYPE_NUMBER: return RelationalPackage.SQL_DATA_TYPE__TYPE_NUMBER;
default: return -1;
}
}
return super.eBaseStructuralFeatureID(derivedFeatureID, baseClass);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public int eDerivedStructuralFeatureID(int baseFeatureID, Class<?> baseClass) {
if (baseClass == SQLDataType.class) {
switch (baseFeatureID) {
case RelationalPackage.SQL_DATA_TYPE__TYPE_NUMBER: return RelationalPackage.SQL_STRUCTURED_TYPE__TYPE_NUMBER;
default: return -1;
}
}
return super.eDerivedStructuralFeatureID(baseFeatureID, baseClass);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (typeNumber: ");
result.append(typeNumber);
result.append(')');
return result.toString();
}
} //SQLStructuredTypeImpl
| dresden-ocl/dresdenocl | plugins/org.dresdenocl.tools.CWM/src/orgomg/cwm/resource/relational/impl/SQLStructuredTypeImpl.java | Java | lgpl-3.0 | 9,279 |
// Copyright (C) 2012 by Antonio El Khoury, CNRS.
//
// This file is part of the roboptim-capsule.
//
// roboptim-capsule 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 3 of the License, or (at your option) any later version.
//
// roboptim-capsule 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 roboptim-capsule. If not, see
// <http://www.gnu.org/licenses/>.
/**
* \brief Declaration of DistanceSegmentPoint class that computes
* the distance between a segment and a point.
*/
#ifndef ROBOPTIM_CAPSULE_DISTANCE_CAPSULE_POINT_HH
# define ROBOPTIM_CAPSULE_DISTANCE_CAPSULE_POINT_HH
# include <roboptim/core/differentiable-function.hh>
# include <roboptim/capsule/types.hh>
namespace roboptim
{
namespace capsule
{
/// \brief Distance to point RobOptim function.
class DistanceCapsulePoint
: public roboptim::DifferentiableFunction
{
public:
/// \brief Constructor.
///
/// \param point point that will be used in computing distance
/// between the capsule and the point.
DistanceCapsulePoint (const point_t& point,
std::string name
= "distance to point");
~DistanceCapsulePoint ();
/// \brief Get point attribute.
virtual const point_t& point () const;
protected:
/// \brief Computes the distance from capsule to a point.
///
/// If the result is negative, the point is inside the capsule,
/// otherwise it is outside the capsule.
///
/// \param argument vector containing the capsule parameters. It
/// contains in this order: the segment first end point
/// coordinates, the segment second end point coordinates, the
/// capsule radius.
virtual void
impl_compute (result_ref result,
const_argument_ref argument) const;
/// \brief Compute of the distance gradient with respect to the
/// capsule parameters.
///
/// \param argument vector containing the capsule parameters. It
/// contains in this order: the segment first end point
/// coordinates, the segment second end point coordinates, the
/// capsule radius.
virtual void
impl_gradient (gradient_ref gradient,
const_argument_ref argument,
size_type functionId = 0) const;
private:
/// \brief Point attribute.
point_t point_;
};
} // end of namespace capsule.
} // end of namespace roboptim.
#endif //! ROBOPTIM_CAPSULE_DISTANCE_CAPSULE_POINT_HH
| roboptim/roboptim-capsule | include/roboptim/capsule/distance-capsule-point.hh | C++ | lgpl-3.0 | 2,895 |
/*
* SonarAnalyzer for .NET
* Copyright (C) 2015-2016 SonarSource SA
* mailto:contact@sonarsource.com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using SonarAnalyzer.Common;
using SonarAnalyzer.Common.Sqale;
using SonarAnalyzer.Helpers;
using Microsoft.CodeAnalysis.CSharp;
using System;
namespace SonarAnalyzer.Rules.CSharp
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
[SqaleConstantRemediation("15min")]
[SqaleSubCharacteristic(SqaleSubCharacteristic.DataReliability)]
[Rule(DiagnosticId, RuleSeverity, Title, IsActivatedByDefault)]
[Tags(Tag.Bug)]
public class WcfNonVoidOneWay : SonarDiagnosticAnalyzer
{
internal const string DiagnosticId = "S3598";
internal const string Title = "One-way \"OperationContract\" methods should have \"void\" return type";
internal const string Description =
"When declaring a Windows Communication Foundation (WCF) \"OperationContract\" method one-way, that service method won't return any result, not " +
"even an underlying empty confirmation message. These are fire-and-forget methods that are useful in event-like communication. Specifying a return " +
"type therefore does not make sense.";
internal const string MessageFormat = "This method can't return any values because it is marked as one-way operation.";
internal const string Category = SonarAnalyzer.Common.Category.Reliability;
internal const Severity RuleSeverity = Severity.Critical;
internal const bool IsActivatedByDefault = true;
internal static readonly DiagnosticDescriptor Rule =
new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category,
RuleSeverity.ToDiagnosticSeverity(), IsActivatedByDefault,
helpLinkUri: DiagnosticId.GetHelpLink(),
description: Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }
protected override void Initialize(SonarAnalysisContext context)
{
context.RegisterSyntaxNodeActionInNonGenerated(
c =>
{
var methodDeclaration = (MethodDeclarationSyntax)c.Node;
var methodSymbol = c.SemanticModel.GetDeclaredSymbol(methodDeclaration);
if (methodSymbol == null ||
methodSymbol.ReturnsVoid)
{
return;
}
AttributeData attribute;
if (!TryGetOperationContract(methodSymbol, out attribute))
{
return;
}
var asyncPattern = attribute.NamedArguments.FirstOrDefault(na => na.Key == "AsyncPattern").Value.Value as bool?;
if (asyncPattern.HasValue &&
asyncPattern.Value)
{
return;
}
var isOneWay = attribute.NamedArguments.FirstOrDefault(na => na.Key == "IsOneWay").Value.Value as bool?;
if (isOneWay.HasValue &&
isOneWay.Value)
{
c.ReportDiagnostic(Diagnostic.Create(Rule, methodDeclaration.ReturnType.GetLocation()));
}
},
SyntaxKind.MethodDeclaration);
}
private static bool TryGetOperationContract(IMethodSymbol methodSymbol, out AttributeData attribute)
{
attribute = methodSymbol.GetAttributes()
.FirstOrDefault(a => a.AttributeClass.Is(KnownType.System_ServiceModel_OperationContractAttribute));
return attribute != null;
}
}
}
| tvsonar/sonarlint-vs | src/SonarAnalyzer.CSharp/Rules/WcfNonVoidOneWay.cs | C# | lgpl-3.0 | 4,697 |
#
# @BEGIN LICENSE
#
# Psi4: an open-source quantum chemistry software package
#
# Copyright (c) 2007-2022 The Psi4 Developers.
#
# The copyrights for code used from other parties are included in
# the corresponding files.
#
# This file is part of Psi4.
#
# Psi4 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, version 3.
#
# Psi4 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 Psi4; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# @END LICENSE
#
# Do not modify this file! It is auto-generated by the document_psifiles
# script, from psi4topdir/psi4/include/psi4/psifiles.h
PSIF_OPTKING = 1 #
PSIF_GRAD = 11 # geometry optimization, geometry, and gradient; currently is an ASCII file like output.grad
PSIF_INTCO = 12 # internal coordinates file, currently is ASCII file like output.intco
PSIF_3INDEX = 16 #
PSIF_SO_TEI = 33 #
PSIF_SO_PK = 34 #
PSIF_OEI = 35 #
PSIF_SO_ERF_TEI = 36 #
PSIF_SO_ERFC_TEI = 37 #
PSIF_SO_R12 = 38 #
PSIF_SO_R12T1 = 39 #
PSIF_DERINFO = 40 #
PSIF_SO_PRESORT = 41 #
PSIF_CIVECT = 43 # CI vector from DETCI along with string and determinant info
PSIF_AO_DGDBX = 44 # B-field derivative AO integrals over GIAO Gaussians -- only bra-ket permutational symmetry holds
PSIF_AO_DGDBY = 45 #
PSIF_AO_DGDBZ = 46 #
PSIF_PSIMRCC_INTEGRALS = 50 #
PSIF_PSIMRCC_RESTART = 51 #
PSIF_MCSCF = 52 #
PSIF_TPDM_HALFTRANS = 53 #
PSIF_DETCAS = 60 #
PSIF_LIBTRANS_DPD = 61 # libtrans: All transformed integrals in DPD format are sent here by default
PSIF_LIBTRANS_A_HT = 62 # libtrans: Alpha half-transformed integrals in DPD format
PSIF_LIBTRANS_B_HT = 63 # libtrans: Beta half-transformed integrals in DPD format
PSIF_LIBDIIS = 64 # Storage for libdiis
PSIF_TPDM_PRESORT = 71 #
PSIF_MO_TEI = 72 #
PSIF_MO_OPDM = 73 #
PSIF_MO_TPDM = 74 #
PSIF_MO_LAG = 75 #
PSIF_AO_OPDM = 76 # PSIF_AO_OPDM also contains AO Lagrangian
PSIF_AO_TPDM = 77 #
PSIF_MO_R12 = 79 #
PSIF_MO_R12T2 = 80 #
PSIF_MO_AA_TEI = 81 #
PSIF_MO_BB_TEI = 82 #
PSIF_MO_AB_TEI = 83 #
PSIF_MO_AA_TPDM = 84 #
PSIF_MO_BB_TPDM = 85 #
PSIF_MO_AB_TPDM = 86 #
PSIF_AA_PRESORT = 87 # AA UHF twopdm presort file
PSIF_BB_PRESORT = 88 # BB UHF twopdm presort file
PSIF_AB_PRESORT = 89 # AB UHF twopdm presort file
PSIF_SO_PKSUPER1 = 92 #
PSIF_SO_PKSUPER2 = 93 #
PSIF_HALFT0 = 94 #
PSIF_HALFT1 = 95 #
PSIF_DFSCF_BJ = 97 # B Matrix containing 3-index tensor in AOs with J^-1/2 for use with DF-SCF
PSIF_CC_INFO = 100 #
PSIF_CC_OEI = 101 #
PSIF_CC_AINTS = 102 #
PSIF_CC_BINTS = 103 #
PSIF_CC_CINTS = 104 #
PSIF_CC_DINTS = 105 #
PSIF_CC_EINTS = 106 #
PSIF_CC_FINTS = 107 #
PSIF_CC_DENOM = 108 #
PSIF_CC_TAMPS = 109 #
PSIF_CC_GAMMA = 110 #
PSIF_CC_MISC = 111 #
PSIF_CC_HBAR = 112 #
PSIF_CC_OEI_NEW = 113 #
PSIF_CC_GAMMA_NEW = 114 #
PSIF_CC_AINTS_NEW = 115 #
PSIF_CC_BINTS_NEW = 116 #
PSIF_CC_CINTS_NEW = 117 #
PSIF_CC_DINTS_NEW = 118 #
PSIF_CC_EINTS_NEW = 119 #
PSIF_CC_FINTS_NEW = 120 #
PSIF_CC_LAMBDA = 121 #
PSIF_CC_RAMPS = 122 #
PSIF_CC_LAMPS = 123 #
PSIF_CC_LR = 124 #
PSIF_CC_DIIS_ERR = 125 #
PSIF_CC_DIIS_AMP = 126 #
PSIF_CC_TMP = 127 #
PSIF_CC_TMP0 = 128 #
PSIF_CC_TMP1 = 129 #
PSIF_CC_TMP2 = 130 #
PSIF_CC_TMP3 = 131 #
PSIF_CC_TMP4 = 132 #
PSIF_CC_TMP5 = 133 #
PSIF_CC_TMP6 = 134 #
PSIF_CC_TMP7 = 135 #
PSIF_CC_TMP8 = 135 #
PSIF_CC_TMP9 = 137 #
PSIF_CC_TMP10 = 138 #
PSIF_CC_TMP11 = 139 #
PSIF_EOM_D = 140 #
PSIF_EOM_CME = 141 #
PSIF_EOM_Cme = 142 #
PSIF_EOM_CMNEF = 143 #
PSIF_EOM_Cmnef = 144 #
PSIF_EOM_CMnEf = 145 #
PSIF_EOM_SIA = 146 #
PSIF_EOM_Sia = 147 #
PSIF_EOM_SIJAB = 148 #
PSIF_EOM_Sijab = 149 #
PSIF_EOM_SIjAb = 150 #
PSIF_EOM_R = 151 # holds residual
PSIF_CC_GLG = 152 # left-hand psi for g.s. parts of cc-density
PSIF_CC_GL = 153 # left-hand psi for e.s. parts of cc-density
PSIF_CC_GR = 154 # right-hand eigenvector for cc-density
PSIF_EOM_TMP1 = 155 # intermediates just for single contractions
PSIF_EOM_TMP0 = 156 # temporary copies of density
PSIF_EOM_TMP_XI = 157 # intermediates for xi computation
PSIF_EOM_XI = 158 # xi = dE/dt amplitudes
PSIF_EOM_TMP = 159 # intermediates used more than once
PSIF_CC3_HET1 = 160 # [H,e^T1]
PSIF_CC3_HC1 = 161 # [H,C1]
PSIF_CC3_HC1ET1 = 162 # [[H,e^T1],C1]
PSIF_CC3_MISC = 163 # various intermediates needed in CC3 codes
PSIF_CC2_HET1 = 164 # [H,e^T1]
PSIF_WK_PK = 165 # File to contain wK pre-sorted integrals for PK
PSIF_SCF_MOS = 180 # Save SCF orbitals for re-use later as guess, etc.
PSIF_DFMP2_AIA = 181 # Unfitted three-index MO ints for DFMP2
PSIF_DFMP2_QIA = 182 # Fitted-three index MO ints for DFMP2
PSIF_ADC = 183 # ADC
PSIF_ADC_SEM = 184 # ADC
PSIF_SAPT_DIMER = 190 # SAPT Two-Body Dimer
PSIF_SAPT_MONOMERA = 191 # SAPT Two-Body Mon A
PSIF_SAPT_MONOMERB = 192 # SAPT Two-Body Mon B
PSIF_SAPT_AA_DF_INTS = 193 # SAPT AA DF Ints
PSIF_SAPT_AB_DF_INTS = 194 # SAPT AB DF Ints
PSIF_SAPT_BB_DF_INTS = 195 # SAPT BB DF Ints
PSIF_SAPT_AMPS = 196 # SAPT Amplitudes
PSIF_SAPT_TEMP = 197 # SAPT Temporary worlds fastest code file
PSIF_SAPT_LRINTS = 198 # SAPT0 2-Body linear response LDA integrals
PSIF_3B_SAPT_TRIMER = 220 # SAPT Three-Body Trimer
PSIF_3B_SAPT_DIMER_AB = 221 # SAPT Three-Body Dimer AB
PSIF_3B_SAPT_DIMER_AC = 222 # SAPT Three-Body Dimer AC
PSIF_3B_SAPT_DIMER_BC = 223 # SAPT Three-Body Dimer BC
PSIF_3B_SAPT_MONOMER_A = 224 # SAPT Three-Body Mon A
PSIF_3B_SAPT_MONOMER_B = 225 # SAPT Three-Body Mon B
PSIF_3B_SAPT_MONOMER_C = 226 # SAPT Three-Body Mon C
PSIF_3B_SAPT_AA_DF_INTS = 227 #
PSIF_3B_SAPT_BB_DF_INTS = 228 #
PSIF_3B_SAPT_CC_DF_INTS = 229 #
PSIF_3B_SAPT_AMPS = 230 #
PSIF_DCC_IJAK = 250 # CEPA/CC (ij|ak)
PSIF_DCC_IJAK2 = 251 # CEPA/CC (ij|ak)
PSIF_DCC_ABCI = 252 # CEPA/CC (ia|bc)
PSIF_DCC_ABCI2 = 253 # CEPA/CC (ia|bc)
PSIF_DCC_ABCI3 = 254 # CEPA/CC (ia|bc)
PSIF_DCC_ABCI4 = 255 # CEPA/CC (ia|bc)
PSIF_DCC_ABCI5 = 256 # CEPA/CC (ia|bc)
PSIF_DCC_ABCD1 = 257 # CEPA/CC (ab|cd)+
PSIF_DCC_ABCD2 = 258 # CEPA/CC (ab|cd)-
PSIF_DCC_IJAB = 259 # CEPA/CC (ij|ab)
PSIF_DCC_IAJB = 260 # CEPA/CC (ia|jb)
PSIF_DCC_IJKL = 261 # CEPA/CC (ij|kl)
PSIF_DCC_OVEC = 262 # CEPA/CC old vectors for diis
PSIF_DCC_EVEC = 263 # CEPA/CC error vectors for diis
PSIF_DCC_R2 = 264 # CEPA/CC residual
PSIF_DCC_TEMP = 265 # CEPA/CC temporary storage
PSIF_DCC_T2 = 266 # CEPA/CC t2 amplitudes
PSIF_DCC_QSO = 267 # DFCC 3-index integrals
PSIF_DCC_SORT_START = 270 # CEPA/CC integral sort starting file number
PSIF_SAPT_CCD = 271 # SAPT2+ CCD Utility File
PSIF_HESS = 272 # Hessian Utility File
PSIF_OCC_DPD = 273 # OCC DPD
PSIF_OCC_DENSITY = 274 # OCC Density
PSIF_OCC_IABC = 275 # OCC out-of-core <IA|BC>
PSIF_DFOCC_INTS = 276 # DFOCC Integrals
PSIF_DFOCC_AMPS = 277 # DFOCC Amplitudes
PSIF_DFOCC_DENS = 278 # DFOCC PDMs
PSIF_DFOCC_IABC = 279 # DFOCC (IA|BC)
PSIF_DFOCC_ABIC = 280 # DFOCC <AB|IC>
PSIF_DFOCC_MIABC = 281 # DFOCC M_iabc
PSIF_DFOCC_TEMP = 282 # DFOCC temporary storage
PSIF_SAD = 300 # A SAD file (File for SAD related quantities
PSIF_CI_HD_FILE = 350 # DETCI H diagonal
PSIF_CI_C_FILE = 351 # DETCI CI coeffs
PSIF_CI_S_FILE = 352 # DETCI sigma coeffs
PSIF_CI_D_FILE = 353 # DETCI D correction vectors
PSIF_DCT_DPD = 400 # DCT DPD handle
PSIF_DCT_DENSITY = 401 # DCT density
| psi4/psi4 | psi4/driver/psifiles.py | Python | lgpl-3.0 | 10,284 |
/* KIARA - Middleware for efficient and QoS/Security-aware invocation of services and exchange of messages
*
* Copyright (C) 2014 Proyectos y Sistemas de Mantenimiento S.L. (eProsima)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*
* @file IDLText.java
* This file contains IDL text.
*
* This file was generated by using the tool Kiaragen.
*
*/
package org.fiware.kiara.serialization.types;
/**
* Class containing the IDL text for all the services.
*
* @author Kiaragen tool.
*
*/
public final class IDLText {
public static final String contents = "# 1 \"src/test/resources/idl/enumeration.idl\"\n# 1 \"<built-in>\"\n# 1 \"<command-line>\"\n# 1 \"/usr/include/stdc-predef.h\" 1 3 4\n# 1 \"<command-line>\" 2\n# 1 \"src/test/resources/idl/enumeration.idl\"\nenum GenericEnumeration {\n first_val,\n second_val,\n third_val\n};\n";
private IDLText() {
throw new UnsupportedOperationException();
}
}
| Fiware/i2nd.KIARA | src/test/java/org/fiware/kiara/serialization/types/IDLText.java | Java | lgpl-3.0 | 1,565 |
<?php
wa('shop');
$type_model = new shopTypeModel();
$types = $type_model->select('id,name')->fetchAll('id', true);
$currencies = wa('shop')->getConfig()->getCurrencies();
foreach ($currencies as &$c) {
$c = $c['title'];
}
unset($c);
$payment_items = $shipping_items = array();
foreach (shopHelper::getPaymentMethods() as $p) {
$payment_items[$p['id']] = $p['name'];
}
foreach (shopHelper::getShippingMethods() as $s) {
$shipping_items[$s['id']] = $s['name'];
}
$stock_model = new shopStockModel();
$public_stocks = $stocks = array();
foreach(shopHelper::getStocks() as $stock_id => $s) {
$stocks[$stock_id] = $s['name'];
if ($s['public']) {
$public_stocks[$stock_id] = $s['name'];
}
}
return array(
'params' => array(
_w('Homepage'),
'title' => array(
'name' => _w('Homepage title <title>'),
'type' => 'input',
),
'meta_keywords' => array(
'name' => _w('Homepage META Keywords'),
'type' => 'input'
),
'meta_description' => array(
'name' => _w('Homepage META Description'),
'type' => 'textarea'
),
'og_title' => array(
'name' => _w('Social sharing Title (og:title)'),
'type' => 'input',
'description' => _w('For detailed information on Open Graph parameters and examples please refer to <a href="http://ogp.me" target="_blank">ogp.me</a>')
),
'og_image' => array(
'name' => _w('Social sharing Image URL (og:image)'),
'type' => 'input'
),
'og_video' => array(
'name' => _w('Social sharing Video URL (og:video)'),
'type' => 'input'
),
'og_description' => array(
'name' => _w('Social sharing Description (og:description)'),
'type' => 'textarea'
),
'og_type' => array(
'name' => _w('Social sharing Type (og:type)'),
'type' => 'input',
'description' => _w('E.g. <b>website</b>.').' '._w('For detailed information on Open Graph parameters and examples please refer to <a href="http://ogp.me" target="_blank">ogp.me</a>')
),
_w('Products'),
'url_type' => array(
'name' => _w('URLs'),
'type' => 'radio_select',
'items' => array(
2 => array(
'name' => _w('Natural'),
'description' => _w('<br>Product URLs: /<strong>category-name/subcategory-name/product-name/</strong><br>Category URLs: /<strong>category-name/subcategory-name/</strong>'),
),
0 => array(
'name' => _w('Mixed'),
'description' => _w('<br>Product URLs: /<strong>product-name/</strong><br>Category URLs: /category/<strong>category-name/subcategory-name/subcategory-name/...</strong>'),
),
1 => array(
'name' => _w('Plain').' (WebAsyst Shop-Script)',
'description' => _w('<br>Product URLs: /product/<strong>product-name/</strong><br>Category URLs: /category/<strong>category-name/</strong>'),
),
)
),
'type_id' => array(
'name' => _w('Published products'),
'type' => 'radio_checkbox',
'items' => array(
0 => array(
'name' => _w('All product types'),
'description' => '',
),
array (
'name' => _w('Selected only'),
'description' => '',
'items' => $types
)
)
),
'currency' => array(
'name' => _w('Default currency'),
'type' => 'select',
'items' => $currencies
),
'stock_id' => array(
'name' => _w('Default stock'),
'description' => _w('Select primary stock to which this storefront is associated with. When you process orders from placed via this storefront, selected stock will be automatically offered for product stock update.'),
'type' => 'select',
'items' => $stocks
),
'public_stocks' => array(
'name' => _w('Visible stocks'),
'type' => 'radio_checkbox',
'items' => array(
0 => array(
'name' => _w('All public stocks'),
'description' => '',
),
array(
'name' => _w('Selected only'),
'description' => '',
'items' => $public_stocks,
)
)
),
'drop_out_of_stock' => array(
'name' => _w('Out-of-stock products'),
'type' => 'radio_select',
'items' => array(
1 => array(
'name' => _w('Force drop out-of-stock products to the bottom of all lists'),
'description' => _w('When enabled, out-of-stock products will be automatically dropped to the bottom of every product list on this storefront, e.g. in product search results, category product filtering, and more.'),
),
2 => array(
'name' => _w('Hide out-of-stock products'),
'description' => _w('Out-of-stock products will remain published, but will be automatically hidden from all product lists on this storefront, e.g. product search results, category product filtering, and others.')
),
0 => array(
'name' => _w('Display as is'),
'description' => _w('All product lists will contain both in-stock and out-of-stock products.'),
)
)
),
_w('Checkout'),
'payment_id' => array(
'name' => _w('Payment options'),
'type' => 'radio_checkbox',
'items' => array(
0 => array(
'name' => _w('All available payment options'),
'description' => '',
),
array (
'name' => _w('Selected only'),
'description' => '',
'items' => $payment_items
)
)
),
'shipping_id' => array(
'name' => _w('Shipping options'),
'type' => 'radio_checkbox',
'items' => array(
0 => array(
'name' => _w('All available shipping options'),
'description' => '',
),
array (
'name' => _w('Selected only'),
'description' => '',
'items' => $shipping_items
)
)
),
'ssl' => array(
'name' => _w('Use HTTPS for checkout and personal accounts'),
'description' => _w('Automatically redirect to secure https:// mode for checkout (/checkout/) and personal account (/my/) pages of your online storefront. Make sure you have valid SSL certificate installed for this domain name before enabling this option.'),
'type' => 'checkbox'
)
),
'vars' => array(
'category.html' => array(
'$category.id' => '',
'$category.name' => '',
'$category.parent_id' => '',
'$category.description' => '',
),
'index.html' => array(
'$content' => _w('Core content loaded according to the requested resource: product, category, search results, static page, etc.'),
),
'product.html' => array(
'$product.id' => _w('Product id. Other elements of <em>$product</em> available in this template are listed below'),
'$product.name' => _w('Product name'),
'$product.summary' => _w('Product summary (brief description)'),
'$product.description' => _w('Product description'),
'$product.rating' => _w('Product average rating (float, 0 to 5)'),
'$product.skus' => _w('Array of product SKUs'),
'$product.images' => _w('Array of product images'),
'$product.categories' => _w('Array of product categories'),
'$product.tags' => _w('Array of product tags'),
'$product.pages' => _w('Array of product static info pages'),
'$product.features' => _w('Array of product features and values'),
'$reviews' => _w('Array of product reviews'),
'$services' => _w('Array of services available for this product'),
/*
'$category' => _w('Conditional! Available only if current context of photo is album. Below are describe keys of this param'),
'$category.id' => '',
'$category.name' => '',
'$category.parent_id' => '',
'$category.description' => '',
*/
),
'search.html' => array(
'$title' => ''
),
'list-table.html' => array(
'$products' => array(
'$id' => '',
'...' => _w('Available vars are listed in the cheat sheet for product.html template')
)
),
'list-thumbs.html' => array(
'$products' => array(
'$id' => '',
'...' => _w('Available vars are listed in the cheat sheet for product.html template')
)
),
'$wa' => array(
'$wa->shop->badgeHtml(<em>$product.code</em>)' => _w('Displays badge of the specified product (<em>$product</em> object)'),
'$wa->shop->cart()' => _w('Returns current cart object'),
'$wa->shop->categories(<em>$id = 0, $depth = null, $tree = false, $params = false, $route = null</em>)' => _w('Returns array of subcategories of the specified category. Omit parent category for the entire array of categories'),
'$wa->shop->category(<em>$category_id</em>)' => _w('Returns category object by <em>$category_id</em>'),
'<em>$category</em>.params()' => _w('Array of custom category parameters'),
'$wa->shop->compare()' => _w('Returns array of products currently added into a comparison list'),
'$wa->shop->crossSelling(<em>$product_id</em>, <em>$limit = 5</em>, <em>$available_only = false</em>)' => _w('Returns array of cross-sell products.<em>$product_id</em> can be either a number (ID of the specified base product) or an array of products IDs').'. '._w('Setting <em>$available_only = true</em> will automatically exclude all out-of-stock products from the return'),
'$wa->shop->currency()' => _w('Returns current currency object'),
'$wa->shop->product(<em>$product_id</em>)' => _w('Returns product object by <em>$product_id</em>').'<br><br> '.
'$product-><strong>productUrl()</strong>: '._w('Returns valid product page URL').'<br>'.
'$product-><strong>upSelling</strong>(<em>$limit = 5</em>, <em>$available_only = false</em>):'._w('Returns array of upsell products for the specified product').'. '._w('Setting <em>$available_only = true</em> will automatically exclude all out-of-stock products from the return').'<br>'.
'$product-><strong>crossSelling</strong>(<em>$limit = 5</em>, <em>$available_only = false</em>):'._w('Returns array of upsell products for the specified product').'. '._w('Setting <em>$available_only = true</em> will automatically exclude all out-of-stock products from the return').'<br><br>'.
'$product.<strong>id</strong>: '._w('Product id. Other elements of <em>$product</em> available in this template are listed below').'<br>'.
'$product.<strong>name</strong>: '._w('Product name').'<br>'.
'$product.<strong>description</strong>: '._w('Product summary (brief description)').'<br>'.
'$product.<strong>rating</strong>: '._w('Product average rating (float, 0 to 5)').'<br>'.
'$product.<strong>skus</strong>: '._w('Array of product SKUs').'<br>'.
'$product.<strong>images</strong>: '._w('Array of product images').'<br>'.
'$product.<strong>categories</strong>: '._w('Array of product categories').'<br>'.
'$product.<strong>tags</strong>: '._w('Array of product tags').'<br>'.
'$product.<strong>pages</strong>: '._w('Array of product static info pages').'<br>'.
'$product.<strong>features</strong>: '._w('Array of product features and values').'<br>'.
'$product.<strong>reviews</strong>: '._w('Array of product reviews').'<br>',
'$wa->shop->productImgHtml($product, $size, $attributes = array())' => _w('Displays specified $product object’s default image'),
'$wa->shop->productImgUrl($product, $size)' => _w('Returns specified $product default image URL'),
'$wa->shop->products(<em>search_conditions</em>[,<em>offset</em>[, <em>limit</em>[, <em>options</em>]]])' => _w('Returns array of products by search criteria, e.g. <em>"tag/new"</em>, <em>"category/12"</em>, <em>"id/1,5,7"</em>, <em>"set/1"</em>, or <em>"*"</em> for all products list.').' '._w('Optional <em>options</em> parameter indicates additional product options, e.g. <em>["params" => 1]</em> to include product custom parameter values into the output.'),
'$wa->shop->productsCount(<em>search_conditions</em>)' => _w('Returns number of products matching specified search conditions, e.g. <em>"tag/new"</em>, <em>"category/12"</em>, <em>"id/1,5,7"</em>, <em>"set/1"</em>, or <em>"*"</em> for all products list.'),
'$wa->shop->productSet(<em>set_id</em>)' => _w('Returns array of products from the specified set.').' '._w('Optional <em>options</em> parameter indicates additional product options, e.g. <em>["params" => 1]</em> to include product custom parameter values into the output.'),
'$wa->shop->ratingHtml(<em>$rating, $size = 10, $show_when_zero = false</em>)' => _w('Displays 1—5 stars rating. $size indicates icon size and can be either 10 or 16'),
'$wa->shop->features(<em>product_ids</em>)' => _w('Returns array of feature values for the specified list of products'),
'$wa->shop->reviews([<em>$limit = 10</em>])' => _w('Returns array of latest product reviews'),
'$wa->shop->stocks()' => _w('Returns array of stocks'),
'$wa->shop->settings("<em>option_id</em>")' => _w('Returns store’s general setting option by <em>option_id</em>, e.g. "name", "email", "country"'),
'$wa->shop->themePath("<em>theme_id</em>")' => _ws('Returns path to theme folder by <em>theme_id</em>'),
),
),
'blocks' => array(
),
);
| neeil1990/almamed | wa-apps/shop/lib/config/site.php | PHP | lgpl-3.0 | 14,862 |
package eiteam.esteemedinnovation.transport.fluid.screw;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTank;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fluids.capability.IFluidTankProperties;
import javax.annotation.Nullable;
public class InputOnlyFluidHandler implements IFluidHandler {
private final FluidTank tank;
InputOnlyFluidHandler(FluidTank tank) {
this.tank = tank;
}
@Override
public IFluidTankProperties[] getTankProperties() {
return tank.getTankProperties();
}
@Override
public int fill(FluidStack resource, boolean doFill) {
return tank.fill(resource, doFill);
}
@Nullable
@Override
public FluidStack drain(FluidStack resource, boolean doDrain) {
return null;
}
@Nullable
@Override
public FluidStack drain(int maxDrain, boolean doDrain) {
return null;
}
}
| Esteemed-Innovation/Flaxbeards-Steam-Power | old/main/java/eiteam/esteemedinnovation/transport/fluid/screw/InputOnlyFluidHandler.java | Java | lgpl-3.0 | 966 |
<?php
$d['bbs']['layout'] = "";
$d['bbs']['skin'] = "_pc/list02";
$d['bbs']['m_skin'] = "";
$d['bbs']['c_skin'] = "";
$d['bbs']['c_mskin'] = "";
$d['bbs']['c_hidden'] = "";
$d['bbs']['c_open'] = "";
$d['bbs']['perm_g_list'] = "";
$d['bbs']['perm_g_view'] = "";
$d['bbs']['perm_g_write'] = "";
$d['bbs']['perm_g_down'] = "";
$d['bbs']['perm_l_list'] = "0";
$d['bbs']['perm_l_view'] = "0";
$d['bbs']['perm_l_write'] = "1";
$d['bbs']['perm_l_down'] = "1";
$d['bbs']['admin'] = "";
$d['bbs']['hitcount'] = "0";
$d['bbs']['recnum'] = "20";
$d['bbs']['sbjcut'] = "40";
$d['bbs']['newtime'] = "24";
$d['bbs']['rss'] = "";
$d['bbs']['sosokmenu'] = "";
$d['bbs']['point1'] = "0";
$d['bbs']['point2'] = "0";
$d['bbs']['point3'] = "0";
$d['bbs']['display'] = "";
$d['bbs']['hidelist'] = "";
$d['bbs']['snsconnect'] = "0";
?> | cubem2013/reservation2013 | _package/rb/modules/bbs/var/var.www.php | PHP | lgpl-3.0 | 813 |
/**
* Copyright (C) 2010-2015 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser Public License as published by the
* Free Software Foundation, either version 3.0 of the License, or (at your
* option) any later version.
*
* EvoSuite 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License along
* with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package org.evosuite.runtime.mock;
/**
* This interface is used to mark a class as an environment mock for a Java API class.
*
* @author arcuri
*
*/
public interface EvoSuiteMock {
}
| SoftwareEngineeringToolDemos/FSE-2011-EvoSuite | runtime/src/main/java/org/evosuite/runtime/mock/EvoSuiteMock.java | Java | lgpl-3.0 | 955 |
#coding: utf-8
"""
@Author: Well
@Date: 2014 - 04 - 16
"""
import time
def login(self, username, password):
browser = self.browser
# 输入用户名
browser.find_element_by_id('user_login').send_keys(username)
# 输入密码
browser.find_element_by_id('user_pass').send_keys(password)
# 点击登录按钮
browser.find_element_by_id('wp-submit').click()
# 等待几秒进行加载
time.sleep(5) | neiltest/neil_test_selenium | selenium_test/test_case/login.py | Python | unlicense | 433 |
# unpack processing
# Reader - ADIwg JSON to internal data structure
# History:
# Stan Smith 2019-09-23 original script
require_relative 'module_identifier'
require_relative 'module_citation'
require_relative 'module_algorithm'
module ADIWG
module Mdtranslator
module Readers
module MdJson
module Processing
def self.unpack(hProcessing, responseObj, inContext = nil)
@MessagePath = ADIWG::Mdtranslator::Readers::MdJson::MdJson
# return nil object if input is empty
if hProcessing.empty?
@MessagePath.issueWarning(990, responseObj, inContext)
return nil
end
# instance classes needed in script
intMetadataClass = InternalMetadata.new
intProcessing = intMetadataClass.newProcessing
outContext = 'process step report'
outContext = inContext + ' > ' + outContext unless inContext.nil?
# processing - identifier {identifier} (required)
if hProcessing.has_key?('identifier')
unless hProcessing['identifier'].empty?
hReturn = Identifier.unpack(hProcessing['identifier'], responseObj, outContext)
unless hReturn.nil?
intProcessing[:identifier] = hReturn
end
end
end
if intProcessing[:identifier].empty?
@MessagePath.issueWarning(991, responseObj, inContext)
end
# processing - software reference
if hProcessing.has_key?('softwareReference')
unless hProcessing['softwareReference'].empty?
hReturn = Citation.unpack(hProcessing['softwareReference'], responseObj, outContext)
unless hReturn.nil?
intProcessing[:softwareReference] = hReturn
end
end
end
# processing - procedure description
if hProcessing.has_key?('procedureDescription')
unless hProcessing['procedureDescription'] == ''
intProcessing[:procedureDescription] = hProcessing['procedureDescription']
end
end
# processing - documentation
if hProcessing.has_key?('documentation')
aCitation = hProcessing['documentation']
aCitation.each do |item|
hCitation = Citation.unpack(item, responseObj, outContext)
unless hCitation.nil?
intProcessing[:documentation] << hCitation
end
end
end
# processing - runtime parameters
if hProcessing.has_key?('runtimeParameters')
unless hProcessing['runtimeParameters'] == ''
intProcessing[:runtimeParameters] = hProcessing['runtimeParameters']
end
end
# processing - algorithm
if hProcessing.has_key?('algorithm')
aAlgorithm = hProcessing['algorithm']
aAlgorithm.each do |item|
hAlgorithm = Algorithm.unpack(item, responseObj, outContext)
unless hAlgorithm.nil?
intProcessing[:algorithms] << hAlgorithm
end
end
end
return intProcessing
end
end
end
end
end
end
| adiwg/mdTranslator | lib/adiwg/mdtranslator/readers/mdJson/modules/module_processing.rb | Ruby | unlicense | 3,891 |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
extract_attributes,
int_or_none,
str_to_int,
unified_strdate,
url_or_none,
)
class YouPornIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?youporn\.com/(?:watch|embed)/(?P<id>\d+)(?:/(?P<display_id>[^/?#&]+))?'
_TESTS = [{
'url': 'http://www.youporn.com/watch/505835/sex-ed-is-it-safe-to-masturbate-daily/',
'md5': '3744d24c50438cf5b6f6d59feb5055c2',
'info_dict': {
'id': '505835',
'display_id': 'sex-ed-is-it-safe-to-masturbate-daily',
'ext': 'mp4',
'title': 'Sex Ed: Is It Safe To Masturbate Daily?',
'description': 'Love & Sex Answers: http://bit.ly/DanAndJenn -- Is It Unhealthy To Masturbate Daily?',
'thumbnail': r're:^https?://.*\.jpg$',
'duration': 210,
'uploader': 'Ask Dan And Jennifer',
'upload_date': '20101217',
'average_rating': int,
'view_count': int,
'categories': list,
'tags': list,
'age_limit': 18,
},
'skip': 'This video has been disabled',
}, {
# Unknown uploader
'url': 'http://www.youporn.com/watch/561726/big-tits-awesome-brunette-on-amazing-webcam-show/?from=related3&al=2&from_id=561726&pos=4',
'info_dict': {
'id': '561726',
'display_id': 'big-tits-awesome-brunette-on-amazing-webcam-show',
'ext': 'mp4',
'title': 'Big Tits Awesome Brunette On amazing webcam show',
'description': 'http://sweetlivegirls.com Big Tits Awesome Brunette On amazing webcam show.mp4',
'thumbnail': r're:^https?://.*\.jpg$',
'uploader': 'Unknown',
'upload_date': '20110418',
'average_rating': int,
'view_count': int,
'categories': list,
'tags': list,
'age_limit': 18,
},
'params': {
'skip_download': True,
},
'skip': '404',
}, {
'url': 'https://www.youporn.com/embed/505835/sex-ed-is-it-safe-to-masturbate-daily/',
'only_matching': True,
}, {
'url': 'http://www.youporn.com/watch/505835',
'only_matching': True,
}, {
'url': 'https://www.youporn.com/watch/13922959/femdom-principal/',
'only_matching': True,
}]
@staticmethod
def _extract_urls(webpage):
return re.findall(
r'<iframe[^>]+\bsrc=["\']((?:https?:)?//(?:www\.)?youporn\.com/embed/\d+)',
webpage)
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
video_id = mobj.group('id')
display_id = mobj.group('display_id') or video_id
definitions = self._download_json(
'https://www.youporn.com/api/video/media_definitions/%s/' % video_id,
display_id)
formats = []
for definition in definitions:
if not isinstance(definition, dict):
continue
video_url = url_or_none(definition.get('videoUrl'))
if not video_url:
continue
f = {
'url': video_url,
'filesize': int_or_none(definition.get('videoSize')),
}
height = int_or_none(definition.get('quality'))
# Video URL's path looks like this:
# /201012/17/505835/720p_1500k_505835/YouPorn%20-%20Sex%20Ed%20Is%20It%20Safe%20To%20Masturbate%20Daily.mp4
# /201012/17/505835/vl_240p_240k_505835/YouPorn%20-%20Sex%20Ed%20Is%20It%20Safe%20To%20Masturbate%20Daily.mp4
# /videos/201703/11/109285532/1080P_4000K_109285532.mp4
# We will benefit from it by extracting some metadata
mobj = re.search(r'(?P<height>\d{3,4})[pP]_(?P<bitrate>\d+)[kK]_\d+', video_url)
if mobj:
if not height:
height = int(mobj.group('height'))
bitrate = int(mobj.group('bitrate'))
f.update({
'format_id': '%dp-%dk' % (height, bitrate),
'tbr': bitrate,
})
f['height'] = height
formats.append(f)
self._sort_formats(formats)
webpage = self._download_webpage(
'http://www.youporn.com/watch/%s' % video_id, display_id,
headers={'Cookie': 'age_verified=1'})
title = self._html_search_regex(
r'(?s)<div[^>]+class=["\']watchVideoTitle[^>]+>(.+?)</div>',
webpage, 'title', default=None) or self._og_search_title(
webpage, default=None) or self._html_search_meta(
'title', webpage, fatal=True)
description = self._html_search_regex(
r'(?s)<div[^>]+\bid=["\']description["\'][^>]*>(.+?)</div>',
webpage, 'description',
default=None) or self._og_search_description(
webpage, default=None)
thumbnail = self._search_regex(
r'(?:imageurl\s*=|poster\s*:)\s*(["\'])(?P<thumbnail>.+?)\1',
webpage, 'thumbnail', fatal=False, group='thumbnail')
duration = int_or_none(self._html_search_meta(
'video:duration', webpage, 'duration', fatal=False))
uploader = self._html_search_regex(
r'(?s)<div[^>]+class=["\']submitByLink["\'][^>]*>(.+?)</div>',
webpage, 'uploader', fatal=False)
upload_date = unified_strdate(self._html_search_regex(
[r'UPLOADED:\s*<span>([^<]+)',
r'Date\s+[Aa]dded:\s*<span>([^<]+)',
r'(?s)<div[^>]+class=["\']videoInfo(?:Date|Time)["\'][^>]*>(.+?)</div>'],
webpage, 'upload date', fatal=False))
age_limit = self._rta_search(webpage)
view_count = None
views = self._search_regex(
r'(<div[^>]+\bclass=["\']js_videoInfoViews["\']>)', webpage,
'views', default=None)
if views:
view_count = str_to_int(extract_attributes(views).get('data-value'))
comment_count = str_to_int(self._search_regex(
r'>All [Cc]omments? \(([\d,.]+)\)',
webpage, 'comment count', default=None))
def extract_tag_box(regex, title):
tag_box = self._search_regex(regex, webpage, title, default=None)
if not tag_box:
return []
return re.findall(r'<a[^>]+href=[^>]+>([^<]+)', tag_box)
categories = extract_tag_box(
r'(?s)Categories:.*?</[^>]+>(.+?)</div>', 'categories')
tags = extract_tag_box(
r'(?s)Tags:.*?</div>\s*<div[^>]+class=["\']tagBoxContent["\'][^>]*>(.+?)</div>',
'tags')
return {
'id': video_id,
'display_id': display_id,
'title': title,
'description': description,
'thumbnail': thumbnail,
'duration': duration,
'uploader': uploader,
'upload_date': upload_date,
'view_count': view_count,
'comment_count': comment_count,
'categories': categories,
'tags': tags,
'age_limit': age_limit,
'formats': formats,
}
| rg3/youtube-dl | youtube_dl/extractor/youporn.py | Python | unlicense | 7,294 |
#!/usr/bin/env python
#
# ESP8266 make firmware image
#
# Arguments: dir of *.bin
#
# (c) vad7
import argparse
import os
argp = argparse.ArgumentParser()
argp.add_argument('flashsize', action='store', help='Flash size, kb')
argp.add_argument('dir', action='store', help='Directory of *.bin')
args = argp.parse_args()
fout_name = args.dir + "firmware.bin"
fout = open(fout_name, "wb")
fin = open(args.dir + "0x00000.bin", "rb")
data = fin.read()
fin.close()
data += b"\xFF" * (0x7000 - len(data))
fin = open(args.dir + "0x07000.bin", "rb")
data2 = fin.read()
fin.close()
data = data + data2
fout.write(data)
fout.flush()
size = os.fstat(fout.fileno()).st_size
fout.close()
print "Make: " + fout_name
if int(args.flashsize) == 512:
webfs = (size + 0xFFF) & 0xFF000
maxota = (0x7B000 / 2) & 0xFF000
else:
webfs = 0x80000
maxota = 0x7B000
print "Firmware size: " + str(size) + ", WebFS addr: " + str(webfs) + ", Max OTA size: " + str(maxota)
print "Space available for OTA: " + str(maxota - size)
| vad7/PowerMeter | bin/make_firmware_image.py | Python | unlicense | 1,000 |
/*jslint nomen: true */
/*jslint plusplus: true */
/*jslint browser: true*/
/*jslint node: true*/
/*global d3, io, nunjucks*/
'use strict';
//
// JavaScript unit
// Add-on for the string and number manipulation
//
// Copyright (c) 2005, 2006, 2007, 2010, 2011 by Ildar Shaimordanov
//
/*
The following code is described in ECMA drafts and
might be implemented in the future of ECMA
*/
if (!String.prototype.repeat) {
/**
* object.x(number)
* object.repeat(number)
* Transform the string object multiplying the string
*
* @param number Amount of repeating
* @return string
* @access public
* @see http://svn.debugger.ru/repos/jslibs/BrowserExtensions/trunk/ext/string.js
* @see http://wiki.ecmascript.org/doku.php?id=harmony:string_extras
*/
String.prototype.repeat = function (n) {
n = Math.max(n || 0, 0);
return new Array(n + 1).join(this.valueOf());
};
}
if (!String.prototype.startsWith) {
/**
* Returns true if the sequence of characters of searchString converted
* to a String match the corresponding characters of this object
* (converted to a String) starting at position. Otherwise returns false.
*
* @param string
* @param integer
* @return bollean
* @acess public
*/
String.prototype.startsWith = function (searchString, position) {
position = Math.max(position || 0, 0);
return this.indexOf(searchString) == position;
};
}
if (!String.prototype.endsWith) {
/**
* Returns true if the sequence of characters of searchString converted
* to a String match the corresponding characters of this object
* (converted to a String) starting at endPosition - length(this).
* Otherwise returns false.
*
* @param string
* @param integer
* @return bollean
* @acess public
*/
String.prototype.endsWith = function (searchString, endPosition) {
endPosition = Math.max(endPosition || 0, 0);
var s = String(searchString);
var pos = this.lastIndexOf(s);
return pos >= 0 && pos == this.length - s.length - endPosition;
};
}
if (!String.prototype.contains) {
/**
* If searchString appears as a substring of the result of converting
* this object to a String, at one or more positions that are greater than
* or equal to position, then return true; otherwise, returns false.
* If position is undefined, 0 is assumed, so as to search all of the String.
*
* @param string
* @param integer
* @return bollean
* @acess public
*/
String.prototype.contains = function (searchString, position) {
position = Math.max(position || 0, 0);
return this.indexOf(searchString) != -1;
};
}
if (!String.prototype.toArray) {
/**
* Returns an Array object with elements corresponding to
* the characters of this object (converted to a String).
*
* @param void
* @return array
* @acess public
*/
String.prototype.toArray = function () {
return this.split('');
};
}
if (!String.prototype.reverse) {
/**
* Returns an Array object with elements corresponding to
* the characters of this object (converted to a String) in reverse order.
*
* @param void
* @return string
* @acess public
*/
String.prototype.reverse = function () {
return this.split('').reverse().join('');
};
}
/*
The following ode is not described in ECMA specs or drafts.
*/
/**
* String.validBrackets(string)
* Checks string to be valid brackets. Valid brackets are:
* quotes - '' "" `' ``
* single - <> {} [] () %% || // \\
* double - miltiline comments
* /** / C/C++ like (without whitespace)
* <??> PHP like
* <%%> ASP like
* (**) Pascal like
*
* @param string Brackets (left and right)
* @return boolean Result of validity of brackets
* @access static
*/
String.validBrackets = function (br) {
if (!br) {
return false;
}
var quot = "''\"\"`'``";
var sgl = "<>{}[]()%%||//\\\\";
var dbl = "/**/<??><%%>(**)";
return (br.length == 2 && (quot + sgl).indexOf(br) != -1) || (br.length == 4 && dbl.indexOf(br) != -1);
};
/**
* object.bracketize(string)
* Transform the string object by setting in frame of valid brackets
*
* @param string Brackets
* @return string Bracketized string
* @access public
*/
String.prototype.brace =
String.prototype.bracketize = function (br) {
var string = this;
if (!String.validBrackets(br)) {
return string;
}
var midPos = br.length / 2;
return br.substr(0, midPos) + string.toString() + br.substr(midPos);
};
/**
* object.unbracketize(string)
* Transform the string object removing the leading and trailing brackets
* If the parameter is not defined the method will try to remove existing valid brackets
*
* @param string Brackets
* @return string Unbracketized string
* @access public
*/
String.prototype.unbrace =
String.prototype.unbracketize = function (br) {
var string = this;
if (!br) {
var len = string.length;
for (var i = 2; i >= 1; i--) {
br = string.substring(0, i) + string.substring(len - i);
if (String.validBrackets(br)) {
return string.substring(i, len - i);
}
}
}
if (!String.validBrackets(br)) {
return string;
}
var midPos = br.length / 2;
var i = string.indexOf(br.substr(0, midPos));
var j = string.lastIndexOf(br.substr(midPos));
if (i == 0 && j == string.length - midPos) {
string = string.substring(i + midPos, j);
}
return string;
};
/**
* object.radix(number, number, string)
* Transform the number object to string in accordance with a scale of notation
* If it is necessary the numeric string will aligned to right and filled by '0' character, by default
*
* @param number Radix of scale of notation (it have to be greater or equal 2 and below or equal 36)
* @param number Width of numeric string
* @param string Padding chacracter (by default, '0')
* @return string Numeric string
* @access public
*/
Number.prototype.radix = function (r, n, c) {
return this.toString(r).padding(-n, c);
// return this.toString(r).padding(-Math.abs(n), c);
};
/**
* object.bin(number, string)
* Transform the number object to string of binary presentation
*
* @param number Width of numeric string
* @param string Padding chacracter (by default, '0')
* @return string Numeric string
* @access public
*/
Number.prototype.bin = function (n, c) {
return this.radix(0x02, n, c);
// return this.radix(0x02, (n) ? n : 16, c);
};
/**
* object.oct(number, string)
* Transform the number object to string of octal presentation
*
* @param number Width of numeric string
* @param string Padding chacracter (by default, '0')
* @return string Numeric string
* @access public
*/
Number.prototype.oct = function (n, c) {
return this.radix(0x08, n, c);
// return this.radix(0x08, (n) ? n : 6, c);
};
/**
* object.dec(number, string)
* Transform the number object to string of decimal presentation
*
* @param number Width of numeric string
* @param string Padding chacracter (by default, '0')
* @return string Numeric string
* @access public
*/
Number.prototype.dec = function (n, c) {
return this.radix(0x0A, n, c);
};
/**
* object.hexl(number, string)
* Transform the number object to string of hexadecimal presentation in lower-case of major characters (0-9 and a-f)
*
* @param number Width of numeric string
* @param string Padding chacracter (by default, '0')
* @return string Numeric string
* @access public
*/
Number.prototype.hexl = function (n, c) {
return this.radix(0x10, n, c);
// return this.radix(0x10, (n) ? n : 4, c);
};
/**
* object.hex(number, string)
* Transform the number object to string of the hexadecimal presentation
* in upper-case of major characters (0-9 and A-F)
*
* @param number Width of numeric string
* @param string Padding chacracter (by default, '0')
* @return string Numeric string
* @access public
*/
Number.prototype.hex = function (n, c) {
return this.radix(0x10, n, c).toUpperCase();
};
/**
* object.human([digits[, true]])
* Transform the number object to string in human-readable format (e.h., 1k, 234M, 5G)
*
* @example
* var n = 1001;
*
* // will output 1.001K
* var h = n.human(3);
*
* // will output 1001.000
* var H = n.human(3, true);
*
* @param integer Optional. Number of digits after the decimal point. Must be in the range 0-20, inclusive.
* @param boolean Optional. If true then use powers of 1024 not 1000
* @return string Human-readable string
* @access public
*/
Number.prototype.human = function (digits, binary) {
var n = Math.abs(this);
var p = this;
var s = '';
var divs = arguments.callee.add(binary);
for (var i = divs.length - 1; i >= 0; i--) {
if (n >= divs[i].d) {
p /= divs[i].d;
s = divs[i].s;
break;
}
}
return p.toFixed(digits) + s;
};
/**
* Subsidiary method.
* Stores suffixes and divisors to use in Number.prototype.human.
*
* @param boolean
* @param string
* @param divisor
* @return array
* @access static
*/
Number.prototype.human.add = function (binary, suffix, divisor) {
var name = binary ? 'div2' : 'div10';
var divs = Number.prototype.human[name] = Number.prototype.human[name] || [];
if (arguments.length < 3) {
return divs;
}
divs.push({
s: suffix,
d: Math.abs(divisor)
});
divs.sort(function (a, b) {
return a.d - b.d;
});
return divs;
};
// Binary prefixes
Number.prototype.human.add(true, 'K', 1 << 10);
Number.prototype.human.add(true, 'M', 1 << 20);
Number.prototype.human.add(true, 'G', 1 << 30);
Number.prototype.human.add(true, 'T', Math.pow(2, 40));
// Decimal prefixes
Number.prototype.human.add(false, 'K', 1e3);
Number.prototype.human.add(false, 'M', 1e6);
Number.prototype.human.add(false, 'G', 1e9);
Number.prototype.human.add(false, 'T', 1e12);
/**
* object.fromHuman([digits[, binary]])
* Transform the human-friendly string to the valid numeriv value
*
* @example
* var n = 1001;
*
* // will output 1.001K
* var h = n.human(3);
*
* // will output 1001
* var m = h.fromHuman(h);
*
* @param boolean Optional. If true then use powers of 1024 not 1000
* @return number
* @access public
*/
Number.fromHuman = function (value, binary) {
var m = String(value).match(/^([\-\+]?\d+\.?\d*)([A-Z])?$/);
if (!m) {
return Number.NaN;
}
if (!m[2]) {
return +m[1];
}
var divs = Number.prototype.human.add(binary);
for (var i = 0; i < divs.length; i++) {
if (divs[i].s == m[2]) {
return m[1] * divs[i].d;
}
}
return Number.NaN;
};
if (!String.prototype.trim) {
/**
* object.trim()
* Transform the string object removing leading and trailing whitespaces
*
* @return string
* @access public
*/
String.prototype.trim = function () {
return this.replace(/(^\s*)|(\s*$)/g, "");
};
}
if (!String.prototype.trimLeft) {
/**
* object.trimLeft()
* Transform the string object removing leading whitespaces
*
* @return string
* @access public
*/
String.prototype.trimLeft = function () {
return this.replace(/(^\s*)/, "");
};
}
if (!String.prototype.trimRight) {
/**
* object.trimRight()
* Transform the string object removing trailing whitespaces
*
* @return string
* @access public
*/
String.prototype.trimRight = function () {
return this.replace(/(\s*$)/g, "");
};
}
/**
* object.dup()
* Transform the string object duplicating the string
*
* @return string
* @access public
*/
String.prototype.dup = function () {
var val = this.valueOf();
return val + val;
};
/**
* object.padding(number, string)
* Transform the string object to string of the actual width filling by the padding character (by default ' ')
* Negative value of width means left padding, and positive value means right one
*
* @param number Width of string
* @param string Padding chacracter (by default, ' ')
* @return string
* @access public
*/
String.prototype.padding = function (n, c) {
var val = this.valueOf();
if (Math.abs(n) <= val.length) {
return val;
}
var m = Math.max((Math.abs(n) - this.length) || 0, 0);
var pad = Array(m + 1).join(String(c || ' ').charAt(0));
// var pad = String(c || ' ').charAt(0).repeat(Math.abs(n) - this.length);
return (n < 0) ? pad + val : val + pad;
// return (n < 0) ? val + pad : pad + val;
};
/**
* object.padLeft(number, string)
* Wrapper for object.padding
* Transform the string object to string of the actual width adding the leading padding character (by default ' ')
*
* @param number Width of string
* @param string Padding chacracter
* @return string
* @access public
*/
String.prototype.padLeft = function (n, c) {
return this.padding(-Math.abs(n), c);
};
/**
* object.alignRight(number, string)
* Wrapper for object.padding
* Synonym for object.padLeft
*
* @param number Width of string
* @param string Padding chacracter
* @return string
* @access public
*/
String.prototype.alignRight = String.prototype.padLeft;
/**
* object.padRight(number, string)
* Wrapper for object.padding
* Transform the string object to string of the actual width adding the trailing padding character (by default ' ')
*
* @param number Width of string
* @param string Padding chacracter
* @return string
* @access public
*/
String.prototype.padRight = function (n, c) {
return this.padding(Math.abs(n), c);
};
/**
* Formats arguments accordingly the formatting string.
* Each occurence of the "{\d+}" substring refers to
* the appropriate argument.
*
* @example
* '{0}is not {1} + {2}'.format('JavaScript', 'Java', 'Script');
*
* @param mixed
* @return string
* @access public
*/
String.prototype.format = function () {
var args = arguments;
return this.replace(/\{(\d+)\}/g, function ($0, $1) {
return args[$1] !== void 0 ? args[$1] : $0;
});
};
/**
* object.alignLeft(number, string)
* Wrapper for object.padding
* Synonym for object.padRight
*
* @param number Width of string
* @param string Padding chacracter
* @return string
* @access public
*/
String.prototype.alignLeft = String.prototype.padRight;
/**
* sprintf(format, argument_list)
*
* The string function like one in C/C++, PHP, Perl
* Each conversion specification is defined as below:
*
* %[index][alignment][padding][width][precision]type
*
* index An optional index specifier that changes the order of the
* arguments in the list to be displayed.
* alignment An optional alignment specifier that says if the result should be
* left-justified or right-justified. The default is
* right-justified; a "-" character here will make it left-justified.
* padding An optional padding specifier that says what character will be
* used for padding the results to the right string size. This may
* be a space character or a "0" (zero character). The default is to
* pad with spaces. An alternate padding character can be specified
* by prefixing it with a single quote ('). See the examples below.
* width An optional number, a width specifier that says how many
* characters (minimum) this conversion should result in.
* precision An optional precision specifier that says how many decimal digits
* should be displayed for floating-point numbers. This option has
* no effect for other types than float.
* type A type specifier that says what type the argument data should be
* treated as. Possible types:
*
* % - a literal percent character. No argument is required.
* b - the argument is treated as an integer, and presented as a binary number.
* c - the argument is treated as an integer, and presented as the character
* with that ASCII value.
* d - the argument is treated as an integer, and presented as a decimal number.
* u - the same as "d".
* f - the argument is treated as a float, and presented as a floating-point.
* o - the argument is treated as an integer, and presented as an octal number.
* s - the argument is treated as and presented as a string.
* x - the argument is treated as an integer and presented as a hexadecimal
* number (with lowercase letters).
* X - the argument is treated as an integer and presented as a hexadecimal
* number (with uppercase letters).
* h - the argument is treated as an integer and presented in human-readable format
* using powers of 1024.
* H - the argument is treated as an integer and presented in human-readable format
* using powers of 1000.
*/
String.prototype.sprintf = function () {
var args = arguments;
var index = 0;
var x;
var ins;
var fn;
/*
* The callback function accepts the following properties
* x.index contains the substring position found at the origin string
* x[0] contains the found substring
* x[1] contains the index specifier (as \d+\$ or \d+#)
* x[2] contains the alignment specifier ("+" or "-" or empty)
* x[3] contains the padding specifier (space char, "0" or defined as '.)
* x[4] contains the width specifier (as \d*)
* x[5] contains the floating-point precision specifier (as \.\d*)
* x[6] contains the type specifier (as [bcdfosuxX])
*/
return this.replace(String.prototype.sprintf.re, function () {
if (arguments[0] == "%%") {
return "%";
}
x = [];
for (var i = 0; i < arguments.length; i++) {
x[i] = arguments[i] || '';
}
x[3] = x[3].slice(-1) || ' ';
ins = args[+x[1] ? x[1] - 1 : index++];
// index++;
return String.prototype.sprintf[x[6]](ins, x);
});
};
String.prototype.sprintf.re = /%%|%(?:(\d+)[\$#])?([+-])?('.|0| )?(\d*)(?:\.(\d+))?([bcdfosuxXhH])/g;
String.prototype.sprintf.b = function (ins, x) {
return Number(ins).bin(x[2] + x[4], x[3]);
};
String.prototype.sprintf.c = function (ins, x) {
return String.fromCharCode(ins).padding(x[2] + x[4], x[3]);
};
String.prototype.sprintf.d =
String.prototype.sprintf.u = function (ins, x) {
return Number(ins).dec(x[2] + x[4], x[3]);
};
String.prototype.sprintf.f = function (ins, x) {
var ins = Number(ins);
// var fn = String.prototype.padding;
if (x[5]) {
ins = ins.toFixed(x[5]);
} else if (x[4]) {
ins = ins.toExponential(x[4]);
} else {
ins = ins.toExponential();
} // Invert sign because this is not number but string
x[2] = x[2] == "-" ? "+" : "-";
return ins.padding(x[2] + x[4], x[3]);
// return fn.call(ins, x[2] + x[4], x[3]);
};
String.prototype.sprintf.o = function (ins, x) {
return Number(ins).oct(x[2] + x[4], x[3]);
};
String.prototype.sprintf.s = function (ins, x) {
return String(ins).padding(x[2] + x[4], x[3]);
};
String.prototype.sprintf.x = function (ins, x) {
return Number(ins).hexl(x[2] + x[4], x[3]);
};
String.prototype.sprintf.X = function (ins, x) {
return Number(ins).hex(x[2] + x[4], x[3]);
};
String.prototype.sprintf.h = function (ins, x) {
var ins = String.prototype.replace.call(ins, /,/g, ''); // Invert sign because this is not number but string
x[2] = x[2] == "-" ? "+" : "-";
return Number(ins).human(x[5], true).padding(x[2] + x[4], x[3]);
};
String.prototype.sprintf.H = function (ins, x) {
var ins = String.prototype.replace.call(ins, /,/g, ''); // Invert sign because this is not number but string
x[2] = x[2] == "-" ? "+" : "-";
return Number(ins).human(x[5], false).padding(x[2] + x[4], x[3]);
};
/**
* compile()
*
* This string function compiles the formatting string to the internal function
* to acelerate an execution a formatting within loops.
*
* @example
* // Standard usage of the sprintf method
* var s = '';
* for (var p in obj) {
* s += '%s = %s'.sprintf(p, obj[p]);
* }
*
* // The more speed usage of the sprintf method
* var sprintf = '%s = %s'.compile();
* var s = '';
* for (var p in obj) {
* s += sprintf(p, obj[p]);
* }
*
* @see String.prototype.sprintf()
*/
String.prototype.compile = function () {
var args = arguments;
var index = 0;
var x;
var ins;
var fn;
/*
* The callback function accepts the following properties
* x.index contains the substring position found at the origin string
* x[0] contains the found substring
* x[1] contains the index specifier (as \d+\$ or \d+#)
* x[2] contains the alignment specifier ("+" or "-" or empty)
* x[3] contains the padding specifier (space char, "0" or defined as '.)
* x[4] contains the width specifier (as \d*)
* x[5] contains the floating-point precision specifier (as \.\d*)
* x[6] contains the type specifier (as [bcdfosuxX])
*/
var result = this.replace(/(\\|")/g, '\\$1').replace(String.prototype.sprintf.re, function () {
if (arguments[0] == "%%") {
return "%";
}
arguments.length = 7;
x = [];
for (var i = 0; i < arguments.length; i++) {
x[i] = arguments[i] || '';
}
x[3] = x[3].slice(-1) || ' ';
ins = x[1] ? x[1] - 1 : index++;
// index++;
return '", String.prototype.sprintf.' + x[6] + '(arguments[' + ins + '], ["' + x.join('", "') + '"]), "';
});
return Function('', 'return ["' + result + '"].join("")');
};
/**
* Considers the string object as URL and returns it's parts separately
*
* @param void
* @return Object
* @access public
*/
String.prototype.parseUrl = function () {
var matches = this.match(arguments.callee.re);
if (!matches) {
return null;
}
var result = {
'scheme': matches[1] || '',
'subscheme': matches[2] || '',
'user': matches[3] || '',
'pass': matches[4] || '',
'host': matches[5],
'port': matches[6] || '',
'path': matches[7] || '',
'query': matches[8] || '',
'fragment': matches[9] || ''
};
return result;
};
String.prototype.parseUrl.re = /^(?:([a-z]+):(?:([a-z]*):)?\/\/)?(?:([^:@]*)(?::([^:@]*))?@)?((?:[a-z0-9_-]+\.)+[a-z]{2,}|localhost|(?:(?:[01]?\d\d?|2[0-4]\d|25[0-5])\.){3}(?:(?:[01]?\d\d?|2[0-4]\d|25[0-5])))(?::(\d+))?(?:([^:\?\#]+))?(?:\?([^\#]+))?(?:\#([^\s]+))?$/i;
String.prototype.camelize = function () {
return this.replace(/([^-]+)|(?:-(.)([^-]+))/mg, function ($0, $1, $2, $3) {
return ($2 || '').toUpperCase() + ($3 || $1).toLowerCase();
});
};
String.prototype.uncamelize = function () {
return this.replace(/[A-Z]/g, function ($0) {
return '-' + $0.toLowerCase();
});
}; | flower1024/nodePoloApi | public/string.js | JavaScript | unlicense | 23,495 |
import sublime
import sublime_plugin
from html.entities import codepoint2name as cp2n
class EncodeHtmlEntities(sublime_plugin.TextCommand):
def run(self, edit, **args):
view = self.view
for sel in view.sel():
buf = []
for pt in range(sel.begin(), sel.end()):
ch = view.substr(pt)
ch_ord = ord(ch)
if (not view.match_selector(pt, ('meta.tag - string, constant.character.entity'))
and ch_ord in cp2n
and not (ch in ('"', "'")
and view.match_selector(pt, 'string'))):
ch = '&%s;' % cp2n[ch_ord]
buf.append(ch)
view.replace(edit, sel, ''.join(buf))
| twolfson/sublime-files | Packages/HTML/encode_html_entities.py | Python | unlicense | 764 |
using System;
using System.Timers;
namespace JWLibrary.FFmpeg
{
class FrameDropChecker : IDisposable
{
#region delegate events
public event EventHandler<EventArgs> FrameDroped;
protected virtual void OnFrameDroped(object sender, EventArgs e)
{
if (FrameDroped != null)
{
FrameDroped(this, e);
}
}
#endregion
#region variable
public int FrameDropCount { get; set; }
public bool IsLimit { get; set; }
private const int FRAME_LIMIT_COUNT = 50;
private Timer _timer;
private int _timerElapsedCount;
#endregion
#region constructor
public FrameDropChecker()
{
_timer = new Timer();
_timer.Interval = 500;
_timer.Elapsed += _timer_Elapsed;
}
public FrameDropChecker(double chkTime)
{
_timer = new Timer();
_timer.Interval = chkTime;
_timer.Elapsed += _timer_Elapsed;
}
#endregion
#region funtions
public void FrameDropCheckStart()
{
_timerElapsedCount = 0;
FrameDropCount = 0;
IsLimit = false;
_timer.Start();
}
public void FrameDropCheckStop()
{
_timer.Enabled = false;
_timer.Stop();
}
#endregion
#region event
private void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (FRAME_LIMIT_COUNT < FrameDropCount)
{
IsLimit = true;
OnFrameDroped(this, new EventArgs());
}
else
{
if (_timerElapsedCount == FRAME_LIMIT_COUNT)
_timerElapsedCount = 0;
}
_timerElapsedCount++;
}
#endregion
#region dispose
public void Dispose()
{
if (_timer != null)
{
_timer.Stop();
_timer.Dispose();
_timer = null;
}
}
#endregion
}
}
| GuyFawkesFromKorea/RSBP | JWLibrary.FFmpeg/FrameDropChecker.cs | C# | unlicense | 2,179 |
// @formatter:off
/*
* Unlicensed, generated by javafx.ftl
*/
package javafx.scene.media;
/**
* {@link Track}建構器延伸(供客製化)
*
* @author JarReflectionDataLoader-1.0.0
* @version jfxrt.jar
* @param <Z> 要建構的物件型態(需繼承{@link Track})
* @param <B> 建構器本身的型態(需繼承{@link TrackMaker})
*/
@javax.annotation.Generated("Generated by javafx.ftl")
@SuppressWarnings("all")
public interface TrackMakerExt<Z extends Track, B extends TrackMaker<Z, B>>
extends jxtn.jfx.makers.AbstractMakerExt<Z, B>
{
// nothing yet
}
| AqD/JXTN | jxtn-jfx-makers/src/javafx/scene/media/TrackMakerExt.java | Java | unlicense | 605 |
/*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed 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 com.thoughtworks.go.server.service.materials;
import java.io.File;
import java.util.List;
import com.thoughtworks.go.config.materials.SubprocessExecutionContext;
import com.thoughtworks.go.domain.materials.Material;
import com.thoughtworks.go.domain.materials.Modification;
import com.thoughtworks.go.domain.materials.Revision;
public class NoOpPoller implements MaterialPoller<Material> {
@Override
public List<Modification> latestModification(Material material, File baseDir, SubprocessExecutionContext execCtx) {
throw new RuntimeException("unknown material type " + material.getDisplayName());
}
@Override
public List<Modification> modificationsSince(Material material, File baseDir, Revision revision, SubprocessExecutionContext execCtx) {
throw new RuntimeException("unknown material type " + material.getDisplayName());
}
@Override
public void checkout(Material material, File baseDir, Revision revision, SubprocessExecutionContext execCtx) {
throw new RuntimeException("unknown material type " + material.getDisplayName());
}
}
| gocd/gocd | server/src/main/java/com/thoughtworks/go/server/service/materials/NoOpPoller.java | Java | apache-2.0 | 1,712 |
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#include <aws/config/model/DeliverConfigSnapshotResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::ConfigService::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
DeliverConfigSnapshotResult::DeliverConfigSnapshotResult()
{
}
DeliverConfigSnapshotResult::DeliverConfigSnapshotResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
DeliverConfigSnapshotResult& DeliverConfigSnapshotResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("configSnapshotId"))
{
m_configSnapshotId = jsonValue.GetString("configSnapshotId");
}
return *this;
}
| cedral/aws-sdk-cpp | aws-cpp-sdk-config/source/model/DeliverConfigSnapshotResult.cpp | C++ | apache-2.0 | 1,479 |
package org.apache.maven.plugin.assembly.mojos;
/*
* 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.
*/
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.assembly.archive.ArchiveExpansionException;
import org.apache.maven.plugin.assembly.utils.AssemblyFileUtils;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.archiver.manager.ArchiverManager;
import org.codehaus.plexus.archiver.manager.NoSuchArchiverException;
import java.io.File;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Unpack project dependencies. Currently supports dependencies of type jar and zip.
*
* @version $Id$
* @deprecated Use org.apache.maven.plugins:maven-dependency-plugin goal: unpack or unpack-dependencies instead.
*/
@Mojo( name = "unpack", requiresDependencyResolution = ResolutionScope.TEST, inheritByDefault = false )
@Deprecated
public class UnpackMojo
extends AbstractMojo
{
/**
*/
@Parameter( defaultValue = "${project}", readonly = true, required = true )
private MavenProject project;
/**
*/
@Component
private ArchiverManager archiverManager;
/**
* Directory to unpack JARs into if needed
*/
@Parameter( defaultValue = "${project.build.directory}/assembly/work", required = true )
protected File workDirectory;
/**
* Unpacks the archive file.
*
* @throws MojoExecutionException
*/
@SuppressWarnings( "ResultOfMethodCallIgnored" )
public void execute()
throws MojoExecutionException, MojoFailureException
{
final Set<Artifact> dependencies = new LinkedHashSet<Artifact>();
if ( project.getArtifact() != null && project.getArtifact().getFile() != null )
{
dependencies.add( project.getArtifact() );
}
@SuppressWarnings( "unchecked" ) final Set<Artifact> projectArtifacts = project.getArtifacts();
if ( projectArtifacts != null )
{
dependencies.addAll( projectArtifacts );
}
for ( final Artifact artifact : dependencies )
{
final String name = artifact.getFile().getName();
final File tempLocation = new File( workDirectory, name.substring( 0, name.lastIndexOf( '.' ) ) );
boolean process = false;
if ( !tempLocation.exists() )
{
tempLocation.mkdirs();
process = true;
}
else if ( artifact.getFile().lastModified() > tempLocation.lastModified() )
{
process = true;
}
if ( process )
{
final File file = artifact.getFile();
try
{
AssemblyFileUtils.unpack( file, tempLocation, archiverManager );
}
catch ( final NoSuchArchiverException e )
{
getLog().info( "Skip unpacking dependency file with unknown extension: " + file.getPath() );
}
catch ( final ArchiveExpansionException e )
{
throw new MojoExecutionException( "Error unpacking dependency file: " + file, e );
}
}
}
}
} | kikinteractive/maven-plugins | maven-assembly-plugin/src/main/java/org/apache/maven/plugin/assembly/mojos/UnpackMojo.java | Java | apache-2.0 | 4,397 |
package a3.a3droid;
/**This class is used in A3Channel and in Service, which implement the interface "TimerInterface".
* After a 2 seconds timeout, it calls TimerInterface.timerFired(int), to notify the timeout fired.
* @author Francesco
*
*/
public class Timer extends Thread{
/**The TimerInterface to notify at timeout firing time.*/
private TimerInterface channel;
/**It indicates why the timeout is needed.
* It is passed in timerFired(int), in order for the TimerInterface to know which timeout fired.
*/
private int reason;
/**The time to wait before timer firing.*/
private int timeToWait;
/**
* @param channel The TimerInterface to notify at timeout firing time.
* @param reason It indicates why the timeout is needed on "channel".
*/
public Timer(TimerInterface channel, int reason){
super();
this.channel = channel;
this.reason = reason;
timeToWait = 2000;
}
/**
* @param timerInterface The TimerInterface to notify at timeout firing time.
* @param reason It indicates why the timeout is needed on "channel".
* @param timeout The time to wait before timer firing.
*/
public Timer(TimerInterface timerInterface, int reason, int timeout) {
// TODO Auto-generated constructor stub
this(timerInterface, reason);
timeToWait = timeout;
}
/**
* It notify timeout firing after a 2s timeout.
*/
@Override
public void run(){
try {
sleep(timeToWait);
channel.timerFired(reason);
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
}
| danilomendonca/A3Droid_Test_MCS | src/a3/a3droid/Timer.java | Java | apache-2.0 | 1,579 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed 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 com.intellij.openapi.diff.impl.dir.actions;
import com.intellij.ide.diff.DirDiffModelHolder;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.diff.impl.dir.DirDiffTableModel;
import com.intellij.openapi.project.DumbAware;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Konstantin Bulenkov
*/
public class DirDiffToolbarActions extends ActionGroup implements DumbAware {
private final AnAction[] myActions;
public DirDiffToolbarActions(DirDiffTableModel model, JComponent panel) {
super("Directory Diff Actions", false);
final List<AnAction> actions = new ArrayList<>(Arrays.asList(
new RefreshDirDiffAction(model),
Separator.getInstance(),
new EnableLeft(model),
new EnableNotEqual(model),
new EnableEqual(model),
new EnableRight(model),
Separator.getInstance(),
ActionManager.getInstance().getAction("DirDiffMenu.CompareNewFilesWithEachOtherAction"),
Separator.getInstance(),
new ChangeCompareModeGroup(model),
Separator.getInstance()));
if (model.isOperationsEnabled()) {
actions.add(new SynchronizeDiff(model, true));
actions.add(new SynchronizeDiff(model, false));
}
actions.addAll(model.getSettings().getExtraActions());
for (AnAction action : actions) {
if (action instanceof ShortcutProvider) {
final ShortcutSet shortcut = ((ShortcutProvider)action).getShortcut();
if (shortcut != null) {
action.registerCustomShortcutSet(shortcut, panel);
}
}
if (action instanceof DirDiffModelHolder) {
((DirDiffModelHolder)action).setModel(model);
}
}
myActions = actions.toArray(AnAction.EMPTY_ARRAY);
}
@NotNull
@Override
public AnAction[] getChildren(@Nullable AnActionEvent e) {
return myActions;
}
}
| msebire/intellij-community | platform/diff-impl/src/com/intellij/openapi/diff/impl/dir/actions/DirDiffToolbarActions.java | Java | apache-2.0 | 2,587 |
(function() {
var Detail;
Detail = function(detailData) {
// 詳細情報を載せるwindow表示(半透明)
var t = windowAnimation(0);
var win = Ti.UI.createWindow({
backgroundColor:'#333333',
borderWidth:1,
borderColor:'#666',
width:"100%",
height:"100%",
borderRadius:5,
opacity:0.92,
transform:t
});
// window開ききったときのアニメーション
var a = Titanium.UI.createAnimation();
a.duration = 200;
a.addEventListener('complete', function() {
var t1 = windowAnimation(1.0);
win.animate({transform:t1, duration:200});
});
// タイトル
titleLabel = Ti.UI.createLabel({
top : 10,
font: { fontsize:20, fontWeight: "bold" },
color:"#ffffff",
layout:"vertical"
});
if (typeof(detailData.title) == "undefined") {
titleLabel.text = '';
} else {
titleLabel.text = detailData.title;
}
win.add(titleLabel);
// 載せる画像
if (detailData.is_image === true) {
imageUrl = "http://images.amazon.com/images/P/" + detailData.asin + ".09._SL200_SCLZZZZZZZ_.jpg";
Ti.API.info(imageUrl);
} else {
imageUrl = "./images/noimage.jpeg";
}
detailImage = Ti.UI.createImageView({
image:imageUrl,
width : Ti.UI.SIZE,
height : 200,
top:50,
backgroundColor:'#ffffff',
layout:"vertical"
});
win.add(detailImage);
var data = [];
data[0] = Ti.UI.createTableViewRow({title:'購入/予約をする', hasChild:true, className:'detail'});
data[1] = Ti.UI.createTableViewRow({title:'チェックリストに入れる', className:'detail'});
data[2] = Ti.UI.createTableViewRow({title:'カレンダーに登録する', className:'detail'});
data[3] = Ti.UI.createTableViewRow({title:'このページを閉じる', className:'detail'});
var menuTableView = Titanium.UI.createTableView({
data:data,
bottom:5,
left:30,
right:30,
height:180,
borderWidth:1,
borderRadius:7,
borderColor:'#999',
layout:"vertical"
});
win.add(menuTableView);
menuTableView.addEventListener('click', function(e){
Ti.API.info(e);
// クローズ
var eventT = windowAnimation(0);
win.close({transform:eventT,duration:300});
// window呼び出し
var index = e.index;
if (index === 0) {
var AmazonDetail = require('ui/AmazonDetail');
var AmazonDetailWin = new AmazonDetail(detailData.asin);
ActiveWinTab.tabs.activeTab.open(AmazonDetailWin);
} else if (index === 1) {
var AmazonDetail = require('ui/AmazonDetail');
var AmazonDetailWin = new AmazonDetail(detailData.asin);
ActiveWinTab.tabs.activeTab.open(AmazonDetailWin);
} else if (index === 2) {
var AmazonDetail = require('ui/AmazonDetail');
var AmazonDetailWin = new AmazonDetail(detailData.asin);
ActiveWinTab.tabs.activeTab.open(AmazonDetailWin);
} else {
}
});
// windowにクリックしたらクローズ
win.addEventListener('click', function(){
var eventT = windowAnimation(0);
win.close({transform:eventT,duration:300});
});
win.open(a);
};
var windowAnimation = function(scaleValue) {
var t = Titanium.UI.create2DMatrix();
t = t.scale(scaleValue);
return t;
}
return module.exports = Detail;
})();
| kirou/books_app_list | sinkancheaker/Resources/ui/Detail.js | JavaScript | apache-2.0 | 3,996 |
/**
* Test for Bidi restrictions on IDNs from RFC 3454
*/
var Cc = Components.classes;
var Ci = Components.interfaces;
var idnService;
function expected_pass(inputIDN)
{
var isASCII = {};
var displayIDN = idnService.convertToDisplayIDN(inputIDN, isASCII);
do_check_eq(displayIDN, inputIDN);
}
function expected_fail(inputIDN)
{
var isASCII = {};
var displayIDN = "";
try {
displayIDN = idnService.convertToDisplayIDN(inputIDN, isASCII);
}
catch(e) {}
do_check_neq(displayIDN, inputIDN);
}
function run_test() {
// add an IDN whitelist pref
var pbi = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefBranch);
pbi.setBoolPref("network.IDN.whitelist.com", true);
idnService = Cc["@mozilla.org/network/idn-service;1"]
.getService(Ci.nsIIDNService);
/*
* In any profile that specifies bidirectional character handling, all
* three of the following requirements MUST be met:
*
* 1) The characters in section 5.8 MUST be prohibited.
*/
// 0340; COMBINING GRAVE TONE MARK
expected_fail("foo\u0340bar.com");
// 0341; COMBINING ACUTE TONE MARK
expected_fail("foo\u0341bar.com");
// 200E; LEFT-TO-RIGHT MARK
expected_fail("foo\200ebar.com");
// 200F; RIGHT-TO-LEFT MARK
// Note: this is an RTL IDN so that it doesn't fail test 2) below
expected_fail("\u200f\u0645\u062B\u0627\u0644.\u0622\u0632\u0645\u0627\u06CC\u0634\u06CC");
// 202A; LEFT-TO-RIGHT EMBEDDING
expected_fail("foo\u202abar.com");
// 202B; RIGHT-TO-LEFT EMBEDDING
expected_fail("foo\u202bbar.com");
// 202C; POP DIRECTIONAL FORMATTING
expected_fail("foo\u202cbar.com");
// 202D; LEFT-TO-RIGHT OVERRIDE
expected_fail("foo\u202dbar.com");
// 202E; RIGHT-TO-LEFT OVERRIDE
expected_fail("foo\u202ebar.com");
// 206A; INHIBIT SYMMETRIC SWAPPING
expected_fail("foo\u206abar.com");
// 206B; ACTIVATE SYMMETRIC SWAPPING
expected_fail("foo\u206bbar.com");
// 206C; INHIBIT ARABIC FORM SHAPING
expected_fail("foo\u206cbar.com");
// 206D; ACTIVATE ARABIC FORM SHAPING
expected_fail("foo\u206dbar.com");
// 206E; NATIONAL DIGIT SHAPES
expected_fail("foo\u206ebar.com");
// 206F; NOMINAL DIGIT SHAPES
expected_fail("foo\u206fbar.com");
/*
* 2) If a string contains any RandALCat character, the string MUST NOT
* contain any LCat character.
*/
// www.מיץpetel.com is invalid
expected_fail("www.\u05DE\u05D9\u05E5petel.com");
// But www.מיץפטל.com is fine because the ltr and rtl characters are in
// different labels
expected_pass("www.\u05DE\u05D9\u05E5\u05E4\u05D8\u05DC.com");
/*
* 3) If a string contains any RandALCat character, a RandALCat
* character MUST be the first character of the string, and a
* RandALCat character MUST be the last character of the string.
*/
// www.1מיץ.com is invalid
expected_fail("www.1\u05DE\u05D9\u05E5.com");
// www.מיץ1.com is invalid
expected_fail("www.\u05DE\u05D9\u05E51.com");
// But www.מיץ1פטל.com is fine
expected_pass("www.\u05DE\u05D9\u05E51\u05E4\u05D8\u05DC.com");
}
| sergecodd/FireFox-OS | B2G/gecko/netwerk/test/unit/test_bug427957.js | JavaScript | apache-2.0 | 3,088 |
/**
* Copyright 2011-2019 Asakusa Framework Team.
*
* Licensed 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 com.asakusafw.info;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Represents a batch parameter definition.
* @since 0.9.1
*/
public class ParameterInfo {
private final String name;
private final String comment;
private final boolean mandatory;
private final String pattern;
/**
* Creates a new instance.
* @param name the parameter name
* @param comment the comment (nullable)
* @param mandatory {@code true} if this parameter is mandatory, otherwise {@code false}
* @param pattern the parameter value pattern in regular expression (nullable)
*/
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public ParameterInfo(
@JsonProperty("name") String name,
@JsonProperty("comment") String comment,
@JsonProperty("mandatory") boolean mandatory,
@JsonProperty("pattern") String pattern) {
this.name = name;
this.comment = comment;
this.mandatory = mandatory;
this.pattern = pattern;
}
/**
* Returns the name.
* @return the name
*/
public String getName() {
return name;
}
/**
* Returns the comment.
* @return the comment, or {@code null} if it is not defined
*/
public String getComment() {
return comment;
}
/**
* Returns whether or not this parameter is mandatory.
* @return {@code true} if this parameter is mandatory, otherwise {@code false}
*/
public boolean isMandatory() {
return mandatory;
}
/**
* Returns the parameter value pattern in regular expression.
* @return the pattern, or {@code null} if it is not defined
*/
public String getPattern() {
return pattern;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Objects.hashCode(name);
result = prime * result + Objects.hashCode(comment);
result = prime * result + Boolean.hashCode(mandatory);
result = prime * result + Objects.hashCode(pattern);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ParameterInfo other = (ParameterInfo) obj;
return Objects.equals(name, other.name)
&& Objects.equals(comment, other.comment)
&& mandatory == other.mandatory
&& Objects.equals(pattern, other.pattern);
}
@Override
public String toString() {
return String.format("parameter(name=%s)", name); //$NON-NLS-1$
}
}
| akirakw/asakusafw | info/model/src/main/java/com/asakusafw/info/ParameterInfo.java | Java | apache-2.0 | 3,504 |
//===--- SILGenPoly.cpp - Function Type Thunks ----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Swift function types can be equivalent or have a subtyping relationship even
// if the SIL-level lowering of the calling convention is different. The
// routines in this file implement thunking between lowered function types.
//
//
// Re-abstraction thunks
// =====================
// After SIL type lowering, generic substitutions become explicit, for example
// the AST type Int -> Int passes the Ints directly, whereas T -> T with Int
// substituted for T will pass the Ints like a T, as an address-only value with
// opaque type metadata. Such a thunk is called a "re-abstraction thunk" -- the
// AST-level type of the function value does not change, only the manner in
// which parameters and results are passed.
//
// Function conversion thunks
// ==========================
// In Swift's AST-level type system, certain types have a subtype relation
// involving a representation change. For example, a concrete type is always
// a subtype of any protocol it conforms to. The upcast from the concrete
// type to an existential type for the protocol requires packaging the
// payload together with type metadata and witness tables.
//
// Between function types, the type A -> B is defined to be a subtype of
// A' -> B' iff A' is a subtype of A, and B is a subtype of B' -- parameters
// are contravariant, and results are covariant.
//
// A subtype conversion of a function value A -> B is performed by wrapping
// the function value in a thunk of type A' -> B'. The thunk takes an A' and
// converts it into an A, calls the inner function value, and converts the
// result from B to B'.
//
// VTable thunks
// =============
//
// If a base class is generic and a derived class substitutes some generic
// parameter of the base with a concrete type, the derived class can override
// methods in the base that involved generic types. In the derived class, a
// method override that involves substituted types will have a different
// SIL lowering than the base method. In this case, the overridden vtable entry
// will point to a thunk which transforms parameters and results and invokes
// the derived method.
//
// Some limited forms of subtyping are also supported for method overrides;
// namely, a derived method's parameter can be a superclass of, or more
// optional than, a parameter of the base, and result can be a subclass of,
// or less optional than, the result of the base.
//
// Witness thunks
// ==============
//
// Currently protocol witness methods are called with an additional generic
// parameter bound to the Self type, and thus always require a thunk.
//
// Thunks for class method witnesses dispatch through the vtable allowing
// inherited witnesses to be overridden in subclasses. Hence a witness thunk
// might require two levels of abstraction difference -- the method might
// override a base class method with more generic types, and the protocol
// requirement may involve associated types which are always concrete in the
// conforming class.
//
// Other thunks
// ============
//
// Foreign-to-native, native-to-foreign thunks for declarations and function
// values are implemented in SILGenBridging.cpp.
//
//===----------------------------------------------------------------------===//
#include "SILGen.h"
#include "Scope.h"
#include "swift/AST/GenericSignatureBuilder.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticsCommon.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/Types.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/TypeLowering.h"
#include "Initialization.h"
#include "LValue.h"
#include "RValue.h"
#include "llvm/Support/Compiler.h"
using namespace swift;
using namespace Lowering;
/// A helper function that pulls an element off the front of an array.
template <class T>
static const T &claimNext(ArrayRef<T> &array) {
assert(!array.empty() && "claiming next from empty array!");
const T &result = array.front();
array = array.slice(1);
return result;
}
namespace {
/// An abstract class for transforming first-class SIL values.
class Transform {
private:
SILGenFunction &SGF;
SILLocation Loc;
public:
Transform(SILGenFunction &SGF, SILLocation loc) : SGF(SGF), Loc(loc) {}
virtual ~Transform() = default;
/// Transform an arbitrary value.
RValue transform(RValue &&input,
AbstractionPattern inputOrigType,
CanType inputSubstType,
AbstractionPattern outputOrigType,
CanType outputSubstType,
SGFContext ctxt);
/// Transform an arbitrary value.
ManagedValue transform(ManagedValue input,
AbstractionPattern inputOrigType,
CanType inputSubstType,
AbstractionPattern outputOrigType,
CanType outputSubstType,
SGFContext ctxt);
/// Transform a metatype value.
ManagedValue transformMetatype(ManagedValue fn,
AbstractionPattern inputOrigType,
CanMetatypeType inputSubstType,
AbstractionPattern outputOrigType,
CanMetatypeType outputSubstType);
/// Transform a tuple value.
ManagedValue transformTuple(ManagedValue input,
AbstractionPattern inputOrigType,
CanTupleType inputSubstType,
AbstractionPattern outputOrigType,
CanTupleType outputSubstType,
SGFContext ctxt);
/// Transform a function value.
ManagedValue transformFunction(ManagedValue fn,
AbstractionPattern inputOrigType,
CanAnyFunctionType inputSubstType,
AbstractionPattern outputOrigType,
CanAnyFunctionType outputSubstType,
const TypeLowering &expectedTL);
};
} // end anonymous namespace
;
static ArrayRef<ProtocolConformanceRef>
collectExistentialConformances(ModuleDecl *M, CanType fromType, CanType toType) {
assert(!fromType.isAnyExistentialType());
auto layout = toType.getExistentialLayout();
auto protocols = layout.getProtocols();
SmallVector<ProtocolConformanceRef, 4> conformances;
for (auto proto : protocols) {
auto conformance =
M->lookupConformance(fromType, proto->getDecl(), nullptr);
conformances.push_back(*conformance);
}
return M->getASTContext().AllocateCopy(conformances);
}
static ArchetypeType *getOpenedArchetype(CanType openedType) {
while (auto metatypeTy = dyn_cast<MetatypeType>(openedType))
openedType = metatypeTy.getInstanceType();
return cast<ArchetypeType>(openedType);
}
static ManagedValue emitTransformExistential(SILGenFunction &SGF,
SILLocation loc,
ManagedValue input,
CanType inputType,
CanType outputType,
SGFContext ctxt) {
assert(inputType != outputType);
SILGenFunction::OpaqueValueState state;
ArchetypeType *openedArchetype = nullptr;
if (inputType->isAnyExistentialType()) {
CanType openedType = ArchetypeType::getAnyOpened(inputType);
SILType loweredOpenedType = SGF.getLoweredType(openedType);
// Unwrap zero or more metatype levels
openedArchetype = getOpenedArchetype(openedType);
state = SGF.emitOpenExistential(loc, input, openedArchetype,
loweredOpenedType, AccessKind::Read);
inputType = openedType;
}
// Build conformance table
CanType fromInstanceType = inputType;
CanType toInstanceType = outputType;
// Look through metatypes
while (isa<MetatypeType>(fromInstanceType) &&
isa<ExistentialMetatypeType>(toInstanceType)) {
fromInstanceType = cast<MetatypeType>(fromInstanceType)
.getInstanceType();
toInstanceType = cast<ExistentialMetatypeType>(toInstanceType)
.getInstanceType();
}
ArrayRef<ProtocolConformanceRef> conformances =
collectExistentialConformances(SGF.SGM.M.getSwiftModule(),
fromInstanceType,
toInstanceType);
// Build result existential
AbstractionPattern opaque = AbstractionPattern::getOpaque();
const TypeLowering &concreteTL = SGF.getTypeLowering(opaque, inputType);
const TypeLowering &expectedTL = SGF.getTypeLowering(outputType);
input = SGF.emitExistentialErasure(
loc, inputType, concreteTL, expectedTL,
conformances, ctxt,
[&](SGFContext C) -> ManagedValue {
if (openedArchetype)
return SGF.manageOpaqueValue(state, loc, C);
return input;
});
return input;
}
/// Apply this transformation to an arbitrary value.
RValue Transform::transform(RValue &&input,
AbstractionPattern inputOrigType,
CanType inputSubstType,
AbstractionPattern outputOrigType,
CanType outputSubstType,
SGFContext ctxt) {
// Fast path: we don't have a tuple.
auto inputTupleType = dyn_cast<TupleType>(inputSubstType);
if (!inputTupleType) {
assert(!isa<TupleType>(outputSubstType) &&
"transformation introduced a tuple?");
auto result = transform(std::move(input).getScalarValue(),
inputOrigType, inputSubstType,
outputOrigType, outputSubstType, ctxt);
return RValue(SGF, Loc, outputSubstType, result);
}
// Okay, we have a tuple. The output type will also be a tuple unless
// there's a subtyping conversion that erases tuples, but that's currently
// not allowed by the typechecker, which considers existential erasure to
// be a conversion relation, not a subtyping one. Anyway, it would be
// possible to support that here, but since it's not currently required...
assert(isa<TupleType>(outputSubstType) &&
"subtype constraint erasing tuple is not currently implemented");
auto outputTupleType = cast<TupleType>(outputSubstType);
assert(inputTupleType->getNumElements() == outputTupleType->getNumElements());
// Pull the r-value apart.
SmallVector<RValue, 8> inputElts;
std::move(input).extractElements(inputElts);
// Emit into the context initialization if it's present and possible
// to split.
SmallVector<InitializationPtr, 4> eltInitsBuffer;
MutableArrayRef<InitializationPtr> eltInits;
auto tupleInit = ctxt.getEmitInto();
if (!ctxt.getEmitInto()
|| !ctxt.getEmitInto()->canSplitIntoTupleElements()) {
tupleInit = nullptr;
} else {
eltInits = tupleInit->splitIntoTupleElements(SGF, Loc, outputTupleType,
eltInitsBuffer);
}
// At this point, if tupleInit is non-null, we must emit all of the
// elements into their corresponding contexts.
assert(tupleInit == nullptr ||
eltInits.size() == inputTupleType->getNumElements());
SmallVector<ManagedValue, 8> outputExpansion;
for (auto eltIndex : indices(inputTupleType->getElementTypes())) {
// Determine the appropriate context for the element.
SGFContext eltCtxt;
if (tupleInit) eltCtxt = SGFContext(eltInits[eltIndex].get());
// Recurse.
RValue outputElt = transform(std::move(inputElts[eltIndex]),
inputOrigType.getTupleElementType(eltIndex),
inputTupleType.getElementType(eltIndex),
outputOrigType.getTupleElementType(eltIndex),
outputTupleType.getElementType(eltIndex),
eltCtxt);
// Force the r-value into its context if necessary.
assert(!outputElt.isInContext() || tupleInit != nullptr);
if (tupleInit && !outputElt.isInContext()) {
std::move(outputElt).forwardInto(SGF, Loc, eltInits[eltIndex].get());
} else {
std::move(outputElt).getAll(outputExpansion);
}
}
// If we emitted into context, be sure to finish the overall initialization.
if (tupleInit) {
tupleInit->finishInitialization(SGF);
return RValue::forInContext();
}
return RValue::withPreExplodedElements(outputExpansion, outputTupleType);
}
// Single @objc protocol value metatypes can be converted to the ObjC
// Protocol class type.
static bool isProtocolClass(Type t) {
auto classDecl = t->getClassOrBoundGenericClass();
if (!classDecl)
return false;
ASTContext &ctx = classDecl->getASTContext();
return (classDecl->getName() == ctx.Id_Protocol &&
classDecl->getModuleContext()->getName() == ctx.Id_ObjectiveC);
};
static ManagedValue emitManagedLoad(SILGenFunction &gen, SILLocation loc,
ManagedValue addr,
const TypeLowering &addrTL) {
// SEMANTIC ARC TODO: When the verifier is finished, revisit this.
auto loadedValue = addrTL.emitLoad(gen.B, loc, addr.forward(gen),
LoadOwnershipQualifier::Take);
return gen.emitManagedRValueWithCleanup(loadedValue, addrTL);
}
/// Apply this transformation to an arbitrary value.
ManagedValue Transform::transform(ManagedValue v,
AbstractionPattern inputOrigType,
CanType inputSubstType,
AbstractionPattern outputOrigType,
CanType outputSubstType,
SGFContext ctxt) {
// Look through inout types.
if (isa<InOutType>(inputSubstType))
inputSubstType = CanType(inputSubstType->getInOutObjectType());
// Load if the result isn't address-only. All the translation routines
// expect this.
if (v.getType().isAddress()) {
auto &inputTL = SGF.getTypeLowering(v.getType());
if (!inputTL.isAddressOnly()) {
v = emitManagedLoad(SGF, Loc, v, inputTL);
}
}
const TypeLowering &expectedTL = SGF.getTypeLowering(outputOrigType,
outputSubstType);
auto loweredResultTy = expectedTL.getLoweredType();
// Nothing to convert
if (v.getType() == loweredResultTy)
return v;
OptionalTypeKind outputOTK, inputOTK;
CanType inputObjectType = inputSubstType.getAnyOptionalObjectType(inputOTK);
CanType outputObjectType = outputSubstType.getAnyOptionalObjectType(outputOTK);
// If the value is less optional than the desired formal type, wrap in
// an optional.
if (outputOTK != OTK_None && inputOTK == OTK_None) {
return SGF.emitInjectOptional(Loc, expectedTL, ctxt,
[&](SGFContext objectCtxt) {
return transform(v, inputOrigType, inputSubstType,
outputOrigType.getAnyOptionalObjectType(),
outputObjectType, objectCtxt);
});
}
// If the value is IUO, but the desired formal type isn't optional, force it.
if (inputOTK == OTK_ImplicitlyUnwrappedOptional
&& outputOTK == OTK_None) {
v = SGF.emitCheckedGetOptionalValueFrom(Loc, v,
SGF.getTypeLowering(v.getType()),
SGFContext());
// Check if we have any more conversions remaining.
if (v.getType() == loweredResultTy)
return v;
inputOTK = OTK_None;
}
// Optional-to-optional conversion.
if (inputOTK != OTK_None && outputOTK != OTK_None) {
// If the conversion is trivial, just cast.
if (SGF.SGM.Types.checkForABIDifferences(v.getType(), loweredResultTy)
== TypeConverter::ABIDifference::Trivial) {
SILValue result = v.getValue();
if (v.getType().isAddress())
result = SGF.B.createUncheckedAddrCast(Loc, result, loweredResultTy);
else
result = SGF.B.createUncheckedBitCast(Loc, result, loweredResultTy);
return ManagedValue(result, v.getCleanup());
}
auto transformOptionalPayload = [&](SILGenFunction &gen,
SILLocation loc,
ManagedValue input,
SILType loweredResultTy,
SGFContext context) -> ManagedValue {
return transform(input,
inputOrigType.getAnyOptionalObjectType(),
inputObjectType,
outputOrigType.getAnyOptionalObjectType(),
outputObjectType,
context);
};
return SGF.emitOptionalToOptional(Loc, v, loweredResultTy,
transformOptionalPayload);
}
// Abstraction changes:
// - functions
if (auto outputFnType = dyn_cast<AnyFunctionType>(outputSubstType)) {
auto inputFnType = cast<AnyFunctionType>(inputSubstType);
return transformFunction(v,
inputOrigType, inputFnType,
outputOrigType, outputFnType,
expectedTL);
}
// - tuples of transformable values
if (auto outputTupleType = dyn_cast<TupleType>(outputSubstType)) {
auto inputTupleType = cast<TupleType>(inputSubstType);
return transformTuple(v,
inputOrigType, inputTupleType,
outputOrigType, outputTupleType,
ctxt);
}
// - metatypes
if (auto outputMetaType = dyn_cast<MetatypeType>(outputSubstType)) {
if (auto inputMetaType = dyn_cast<MetatypeType>(inputSubstType)) {
return transformMetatype(v,
inputOrigType, inputMetaType,
outputOrigType, outputMetaType);
}
}
// Subtype conversions:
// - upcasts
if (outputSubstType->getClassOrBoundGenericClass() &&
inputSubstType->getClassOrBoundGenericClass()) {
auto class1 = inputSubstType->getClassOrBoundGenericClass();
auto class2 = outputSubstType->getClassOrBoundGenericClass();
// CF <-> Objective-C via toll-free bridging.
if ((class1->getForeignClassKind() == ClassDecl::ForeignKind::CFType) ^
(class2->getForeignClassKind() == ClassDecl::ForeignKind::CFType)) {
return ManagedValue(SGF.B.createUncheckedRefCast(Loc,
v.getValue(),
loweredResultTy),
v.getCleanup());
}
if (outputSubstType->isExactSuperclassOf(inputSubstType)) {
// Upcast to a superclass.
return ManagedValue(SGF.B.createUpcast(Loc,
v.getValue(),
loweredResultTy),
v.getCleanup());
} else {
// Unchecked-downcast to a covariant return type.
assert(inputSubstType->isExactSuperclassOf(outputSubstType)
&& "should be inheritance relationship between input and output");
return SGF.emitManagedRValueWithCleanup(
SGF.B.createUncheckedRefCast(Loc, v.forward(SGF), loweredResultTy));
}
}
// - upcasts from an archetype
if (outputSubstType->getClassOrBoundGenericClass()) {
if (auto archetypeType = dyn_cast<ArchetypeType>(inputSubstType)) {
if (archetypeType->getSuperclass()) {
// Replace the cleanup with a new one on the superclass value so we
// always use concrete retain/release operations.
return ManagedValue(SGF.B.createUpcast(Loc,
v.getValue(),
loweredResultTy),
v.getCleanup());
}
}
}
// - metatype to Protocol conversion
if (isProtocolClass(outputSubstType)) {
if (auto metatypeTy = dyn_cast<MetatypeType>(inputSubstType)) {
return SGF.emitProtocolMetatypeToObject(Loc, metatypeTy,
SGF.getLoweredLoadableType(outputSubstType));
}
}
// - metatype to AnyObject conversion
if (outputSubstType->isAnyObject() &&
isa<MetatypeType>(inputSubstType)) {
return SGF.emitClassMetatypeToObject(Loc, v,
SGF.getLoweredLoadableType(outputSubstType));
}
// - existential metatype to AnyObject conversion
if (outputSubstType->isAnyObject() &&
isa<ExistentialMetatypeType>(inputSubstType)) {
return SGF.emitExistentialMetatypeToObject(Loc, v,
SGF.getLoweredLoadableType(outputSubstType));
}
// - existentials
if (outputSubstType->isAnyExistentialType()) {
// We have to re-abstract payload if its a metatype or a function
v = SGF.emitSubstToOrigValue(Loc, v, AbstractionPattern::getOpaque(),
inputSubstType);
return emitTransformExistential(SGF, Loc, v,
inputSubstType, outputSubstType,
ctxt);
}
// - upcasting class-constrained existentials or metatypes thereof
if (inputSubstType->isAnyExistentialType()) {
auto instanceType = inputSubstType;
while (auto metatypeType = dyn_cast<ExistentialMetatypeType>(instanceType))
instanceType = metatypeType.getInstanceType();
auto layout = instanceType.getExistentialLayout();
if (layout.superclass) {
CanType openedType = ArchetypeType::getAnyOpened(inputSubstType);
SILType loweredOpenedType = SGF.getLoweredType(openedType);
// Unwrap zero or more metatype levels
auto openedArchetype = getOpenedArchetype(openedType);
auto state = SGF.emitOpenExistential(Loc, v, openedArchetype,
loweredOpenedType,
AccessKind::Read);
auto payload = SGF.manageOpaqueValue(state, Loc, SGFContext());
return transform(payload,
AbstractionPattern::getOpaque(),
openedType,
outputOrigType,
outputSubstType,
ctxt);
}
}
// - T : Hashable to AnyHashable
if (isa<StructType>(outputSubstType) &&
outputSubstType->getAnyNominal() ==
SGF.getASTContext().getAnyHashableDecl()) {
auto *protocol = SGF.getASTContext().getProtocol(
KnownProtocolKind::Hashable);
auto conformance = SGF.SGM.M.getSwiftModule()->lookupConformance(
inputSubstType, protocol, nullptr);
auto result = SGF.emitAnyHashableErasure(Loc, v, inputSubstType,
*conformance, ctxt);
if (result.isInContext())
return ManagedValue::forInContext();
return std::move(result).getAsSingleValue(SGF, Loc);
}
// Should have handled the conversion in one of the cases above.
llvm_unreachable("Unhandled transform?");
}
ManagedValue Transform::transformMetatype(ManagedValue meta,
AbstractionPattern inputOrigType,
CanMetatypeType inputSubstType,
AbstractionPattern outputOrigType,
CanMetatypeType outputSubstType) {
assert(!meta.hasCleanup() && "metatype with cleanup?!");
auto expectedType = SGF.getTypeLowering(outputOrigType,
outputSubstType).getLoweredType();
auto wasRepr = meta.getType().castTo<MetatypeType>()->getRepresentation();
auto willBeRepr = expectedType.castTo<MetatypeType>()->getRepresentation();
SILValue result;
if ((wasRepr == MetatypeRepresentation::Thick &&
willBeRepr == MetatypeRepresentation::Thin) ||
(wasRepr == MetatypeRepresentation::Thin &&
willBeRepr == MetatypeRepresentation::Thick)) {
// If we have a thin-to-thick abstraction change, cook up new a metatype
// value out of nothing -- thin metatypes carry no runtime state.
result = SGF.B.createMetatype(Loc, expectedType);
} else {
// Otherwise, we have a metatype subtype conversion of thick metatypes.
assert(wasRepr == willBeRepr && "Unhandled metatype conversion");
result = SGF.B.createUpcast(Loc, meta.getUnmanagedValue(), expectedType);
}
return ManagedValue::forUnmanaged(result);
}
/// Explode a managed tuple into a bunch of managed elements.
///
/// If the tuple is in memory, the result elements will also be in
/// memory.
typedef std::pair<ManagedValue, const TypeLowering *> ManagedValueAndType;
static void explodeTuple(SILGenFunction &gen,
SILLocation loc,
ManagedValue managedTuple,
SmallVectorImpl<ManagedValueAndType> &out) {
// None of the operations we do here can fail, so we can atomically
// disable the tuple's cleanup and then create cleanups for all the
// elements.
SILValue tuple = managedTuple.forward(gen);
auto tupleSILType = tuple->getType();
auto tupleType = tupleSILType.castTo<TupleType>();
out.reserve(tupleType->getNumElements());
for (auto index : indices(tupleType.getElementTypes())) {
// We're starting with a SIL-lowered tuple type, so the elements
// must also all be SIL-lowered.
SILType eltType = tupleSILType.getTupleElementType(index);
auto &eltTL = gen.getTypeLowering(eltType);
ManagedValue elt;
if (tupleSILType.isAddress()) {
auto addr = gen.B.createTupleElementAddr(loc, tuple, index, eltType);
elt = gen.emitManagedBufferWithCleanup(addr, eltTL);
} else {
auto value = gen.B.createTupleExtract(loc, tuple, index, eltType);
elt = gen.emitManagedRValueWithCleanup(value, eltTL);
}
out.push_back(ManagedValueAndType(elt, &eltTL));
}
}
/// Apply this transformation to all the elements of a tuple value,
/// which just entails mapping over each of its component elements.
ManagedValue Transform::transformTuple(ManagedValue inputTuple,
AbstractionPattern inputOrigType,
CanTupleType inputSubstType,
AbstractionPattern outputOrigType,
CanTupleType outputSubstType,
SGFContext ctxt) {
const TypeLowering &outputTL =
SGF.getTypeLowering(outputOrigType, outputSubstType);
assert((outputTL.isAddressOnly() == inputTuple.getType().isAddress() ||
!SGF.silConv.useLoweredAddresses()) &&
"expected loadable inputs to have been loaded");
// If there's no representation difference, we're done.
if (outputTL.getLoweredType() == inputTuple.getType())
return inputTuple;
assert(inputOrigType.matchesTuple(outputSubstType));
assert(outputOrigType.matchesTuple(outputSubstType));
auto inputType = inputTuple.getType().castTo<TupleType>();
assert(outputSubstType->getNumElements() == inputType->getNumElements());
// If the tuple is address only, we need to do the operation in memory.
SILValue outputAddr;
if (outputTL.isAddressOnly() && SGF.silConv.useLoweredAddresses())
outputAddr = SGF.getBufferForExprResult(Loc, outputTL.getLoweredType(),
ctxt);
// Explode the tuple into individual managed values.
SmallVector<ManagedValueAndType, 4> inputElts;
explodeTuple(SGF, Loc, inputTuple, inputElts);
// Track all the managed elements whether or not we're actually
// emitting to an address, just so that we can disable them after.
SmallVector<ManagedValue, 4> outputElts;
for (auto index : indices(inputType->getElementTypes())) {
auto &inputEltTL = *inputElts[index].second;
ManagedValue inputElt = inputElts[index].first;
if (inputElt.getType().isAddress() && !inputEltTL.isAddressOnly()) {
inputElt = emitManagedLoad(SGF, Loc, inputElt, inputEltTL);
}
auto inputEltOrigType = inputOrigType.getTupleElementType(index);
auto inputEltSubstType = inputSubstType.getElementType(index);
auto outputEltOrigType = outputOrigType.getTupleElementType(index);
auto outputEltSubstType = outputSubstType.getElementType(index);
// If we're emitting to memory, project out this element in the
// destination buffer, then wrap that in an Initialization to
// track the cleanup.
Optional<TemporaryInitialization> outputEltTemp;
if (outputAddr) {
SILValue outputEltAddr =
SGF.B.createTupleElementAddr(Loc, outputAddr, index);
auto &outputEltTL = SGF.getTypeLowering(outputEltAddr->getType());
assert(outputEltTL.isAddressOnly() == inputEltTL.isAddressOnly());
auto cleanup =
SGF.enterDormantTemporaryCleanup(outputEltAddr, outputEltTL);
outputEltTemp.emplace(outputEltAddr, cleanup);
}
SGFContext eltCtxt =
(outputEltTemp ? SGFContext(&outputEltTemp.getValue()) : SGFContext());
auto outputElt = transform(inputElt,
inputEltOrigType, inputEltSubstType,
outputEltOrigType, outputEltSubstType,
eltCtxt);
// If we're not emitting to memory, remember this element for
// later assembly into a tuple.
if (!outputEltTemp) {
assert(outputElt);
assert(!inputEltTL.isAddressOnly() || !SGF.silConv.useLoweredAddresses());
outputElts.push_back(outputElt);
continue;
}
// Otherwise, make sure we emit into the slot.
auto &temp = outputEltTemp.getValue();
auto outputEltAddr = temp.getManagedAddress();
// That might involve storing directly.
if (!outputElt.isInContext()) {
outputElt.forwardInto(SGF, Loc, outputEltAddr.getValue());
temp.finishInitialization(SGF);
}
outputElts.push_back(outputEltAddr);
}
// Okay, disable all the individual element cleanups and collect
// the values for a potential tuple aggregate.
SmallVector<SILValue, 4> outputEltValues;
for (auto outputElt : outputElts) {
SILValue value = outputElt.forward(SGF);
if (!outputAddr) outputEltValues.push_back(value);
}
// If we're emitting to an address, just manage that.
if (outputAddr)
return SGF.manageBufferForExprResult(outputAddr, outputTL, ctxt);
// Otherwise, assemble the tuple value and manage that.
auto outputTuple =
SGF.B.createTuple(Loc, outputTL.getLoweredType(), outputEltValues);
return SGF.emitManagedRValueWithCleanup(outputTuple, outputTL);
}
static ManagedValue manageParam(SILGenFunction &gen,
SILLocation loc,
SILValue paramValue,
SILParameterInfo info,
bool allowPlusZero) {
switch (info.getConvention()) {
case ParameterConvention::Indirect_In_Guaranteed:
if (gen.silConv.useLoweredAddresses()) {
// FIXME: Avoid a behavior change while guaranteed self is disabled by
// default.
if (allowPlusZero) {
return ManagedValue::forUnmanaged(paramValue);
} else {
auto copy = gen.emitTemporaryAllocation(loc, paramValue->getType());
gen.B.createCopyAddr(loc, paramValue, copy, IsNotTake, IsInitialization);
return gen.emitManagedBufferWithCleanup(copy);
}
}
LLVM_FALLTHROUGH;
case ParameterConvention::Direct_Guaranteed:
if (allowPlusZero)
return gen.emitManagedBeginBorrow(loc, paramValue);
LLVM_FALLTHROUGH;
// Unowned parameters are only guaranteed at the instant of the call, so we
// must retain them even if we're in a context that can accept a +0 value.
case ParameterConvention::Direct_Unowned:
paramValue = gen.getTypeLowering(paramValue->getType())
.emitCopyValue(gen.B, loc, paramValue);
LLVM_FALLTHROUGH;
case ParameterConvention::Direct_Owned:
return gen.emitManagedRValueWithCleanup(paramValue);
case ParameterConvention::Indirect_In:
case ParameterConvention::Indirect_In_Constant:
if (gen.silConv.useLoweredAddresses())
return gen.emitManagedBufferWithCleanup(paramValue);
return gen.emitManagedRValueWithCleanup(paramValue);
case ParameterConvention::Indirect_Inout:
case ParameterConvention::Indirect_InoutAliasable:
return ManagedValue::forLValue(paramValue);
}
llvm_unreachable("bad parameter convention");
}
void SILGenFunction::collectThunkParams(SILLocation loc,
SmallVectorImpl<ManagedValue> ¶ms,
bool allowPlusZero) {
// Add the indirect results.
for (auto resultTy : F.getConventions().getIndirectSILResultTypes()) {
auto paramTy = F.mapTypeIntoContext(resultTy);
SILArgument *arg = F.begin()->createFunctionArgument(paramTy);
(void)arg;
}
// Add the parameters.
auto paramTypes = F.getLoweredFunctionType()->getParameters();
for (auto param : paramTypes) {
auto paramTy = F.mapTypeIntoContext(F.getConventions().getSILType(param));
auto paramValue = F.begin()->createFunctionArgument(paramTy);
auto paramMV = manageParam(*this, loc, paramValue, param, allowPlusZero);
params.push_back(paramMV);
}
}
/// Force a ManagedValue to be stored into a temporary initialization
/// if it wasn't emitted that way directly.
static void emitForceInto(SILGenFunction &SGF, SILLocation loc,
ManagedValue result, TemporaryInitialization &temp) {
if (result.isInContext()) return;
result.forwardInto(SGF, loc, temp.getAddress());
temp.finishInitialization(SGF);
}
/// If the type is a single-element tuple, return the element type.
static CanType getSingleTupleElement(CanType type) {
if (auto tupleType = dyn_cast<TupleType>(type)) {
if (tupleType->getNumElements() == 1)
return tupleType.getElementType(0);
}
return type;
}
namespace {
class TranslateArguments {
SILGenFunction &SGF;
SILLocation Loc;
ArrayRef<ManagedValue> Inputs;
SmallVectorImpl<ManagedValue> &Outputs;
ArrayRef<SILParameterInfo> OutputTypes;
public:
TranslateArguments(SILGenFunction &SGF, SILLocation loc,
ArrayRef<ManagedValue> inputs,
SmallVectorImpl<ManagedValue> &outputs,
ArrayRef<SILParameterInfo> outputTypes)
: SGF(SGF), Loc(loc), Inputs(inputs), Outputs(outputs),
OutputTypes(outputTypes) {}
void translate(AbstractionPattern inputOrigType,
CanType inputSubstType,
AbstractionPattern outputOrigType,
CanType outputSubstType) {
// Most of this function is about tuples: tuples can be represented
// as one or many values, with varying levels of indirection.
auto inputTupleType = dyn_cast<TupleType>(inputSubstType);
auto outputTupleType = dyn_cast<TupleType>(outputSubstType);
// Look inside one-element exploded tuples, but not if both input
// and output types are *both* one-element tuples.
if (!(inputTupleType && outputTupleType &&
inputTupleType.getElementTypes().size() == 1 &&
outputTupleType.getElementTypes().size() == 1)) {
if (inputOrigType.isTuple() &&
inputOrigType.getNumTupleElements() == 1) {
inputOrigType = inputOrigType.getTupleElementType(0);
inputSubstType = getSingleTupleElement(inputSubstType);
return translate(inputOrigType, inputSubstType,
outputOrigType, outputSubstType);
}
if (outputOrigType.isTuple() &&
outputOrigType.getNumTupleElements() == 1) {
outputOrigType = outputOrigType.getTupleElementType(0);
outputSubstType = getSingleTupleElement(outputSubstType);
return translate(inputOrigType, inputSubstType,
outputOrigType, outputSubstType);
}
}
// Special-case: tuples containing inouts.
if (inputTupleType && inputTupleType->hasInOutElement()) {
// Non-materializable tuple types cannot be bound as generic
// arguments, so none of the remaining transformations apply.
// Instead, the outermost tuple layer is exploded, even when
// they are being passed opaquely. See the comment in
// AbstractionPattern.h for a discussion.
return translateParallelExploded(inputOrigType,
inputTupleType,
outputOrigType,
outputTupleType);
}
// Case where the input type is an exploded tuple.
if (inputOrigType.isTuple()) {
if (outputOrigType.isTuple()) {
// Both input and output are exploded tuples, easy case.
return translateParallelExploded(inputOrigType,
inputTupleType,
outputOrigType,
outputTupleType);
}
// Tuple types are subtypes of their optionals
if (auto outputObjectType =
outputSubstType.getAnyOptionalObjectType()) {
auto outputOrigObjectType = outputOrigType.getAnyOptionalObjectType();
if (auto outputTupleType = dyn_cast<TupleType>(outputObjectType)) {
// The input is exploded and the output is an optional tuple.
// Translate values and collect them into a single optional
// payload.
auto result =
translateAndImplodeIntoOptional(inputOrigType,
inputTupleType,
outputOrigObjectType,
outputTupleType);
Outputs.push_back(result);
return;
}
// Tuple types are subtypes of optionals of Any, too.
assert(outputObjectType->isAny());
// First, construct the existential.
auto result =
translateAndImplodeIntoAny(inputOrigType,
inputTupleType,
outputOrigObjectType,
outputObjectType);
// Now, convert it to an optional.
translateSingle(outputOrigObjectType, outputObjectType,
outputOrigType, outputSubstType,
result, claimNextOutputType());
return;
}
if (outputSubstType->isAny()) {
claimNextOutputType();
auto result =
translateAndImplodeIntoAny(inputOrigType,
inputTupleType,
outputOrigType,
outputSubstType);
Outputs.push_back(result);
return;
}
if (outputTupleType) {
// The input is exploded and the output is not. Translate values
// and store them to a result tuple in memory.
assert(outputOrigType.isTypeParameter() &&
"Output is not a tuple and is not opaque?");
auto outputTy = SGF.getSILType(claimNextOutputType());
auto &outputTL = SGF.getTypeLowering(outputTy);
if (SGF.silConv.useLoweredAddresses()) {
auto temp = SGF.emitTemporary(Loc, outputTL);
translateAndImplodeInto(inputOrigType, inputTupleType,
outputOrigType, outputTupleType, *temp);
Outputs.push_back(temp->getManagedAddress());
} else {
auto result = translateAndImplodeIntoValue(
inputOrigType, inputTupleType, outputOrigType, outputTupleType,
outputTL.getLoweredType());
Outputs.push_back(result);
}
return;
}
llvm_unreachable("Unhandled conversion from exploded tuple");
}
// Handle output being an exploded tuple when the input is opaque.
if (outputOrigType.isTuple()) {
if (inputTupleType) {
// The input is exploded and the output is not. Translate values
// and store them to a result tuple in memory.
assert(inputOrigType.isTypeParameter() &&
"Input is not a tuple and is not opaque?");
return translateAndExplodeOutOf(inputOrigType,
inputTupleType,
outputOrigType,
outputTupleType,
claimNextInput());
}
// FIXME: IUO<Tuple> to Tuple
llvm_unreachable("Unhandled conversion to exploded tuple");
}
// Okay, we are now working with a single value turning into a
// single value.
auto inputElt = claimNextInput();
auto outputEltType = claimNextOutputType();
translateSingle(inputOrigType, inputSubstType,
outputOrigType, outputSubstType,
inputElt, outputEltType);
}
private:
/// Take a tuple that has been exploded in the input and turn it into
/// a tuple value in the output.
ManagedValue translateAndImplodeIntoValue(AbstractionPattern inputOrigType,
CanTupleType inputType,
AbstractionPattern outputOrigType,
CanTupleType outputType,
SILType loweredOutputTy) {
assert(loweredOutputTy.is<TupleType>());
SmallVector<ManagedValue, 4> elements;
assert(outputType->getNumElements() == inputType->getNumElements());
for (unsigned i : indices(outputType->getElementTypes())) {
auto inputOrigEltType = inputOrigType.getTupleElementType(i);
auto inputEltType = inputType.getElementType(i);
auto outputOrigEltType = outputOrigType.getTupleElementType(i);
auto outputEltType = outputType.getElementType(i);
SILType loweredOutputEltTy = loweredOutputTy.getTupleElementType(i);
ManagedValue elt;
if (auto inputEltTupleType = dyn_cast<TupleType>(inputEltType)) {
elt = translateAndImplodeIntoValue(inputOrigEltType,
inputEltTupleType,
outputOrigEltType,
cast<TupleType>(outputEltType),
loweredOutputEltTy);
} else {
elt = claimNextInput();
// Load if necessary.
if (elt.getType().isAddress()) {
elt = SGF.emitLoad(Loc, elt.forward(SGF),
SGF.getTypeLowering(elt.getType()),
SGFContext(), IsTake);
}
}
if (elt.getType() != loweredOutputEltTy)
elt = translatePrimitive(inputOrigEltType, inputEltType,
outputOrigEltType, outputEltType,
elt);
elements.push_back(elt);
}
SmallVector<SILValue, 4> forwarded;
for (auto &elt : elements)
forwarded.push_back(elt.forward(SGF));
auto tuple = SGF.B.createTuple(Loc, loweredOutputTy, forwarded);
return SGF.emitManagedRValueWithCleanup(tuple);
}
/// Handle a tuple that has been exploded in the input but wrapped in
/// an optional in the output.
ManagedValue
translateAndImplodeIntoOptional(AbstractionPattern inputOrigType,
CanTupleType inputTupleType,
AbstractionPattern outputOrigType,
CanTupleType outputTupleType) {
assert(!inputTupleType->hasInOutElement() &&
!outputTupleType->hasInOutElement());
assert(inputTupleType->getNumElements() ==
outputTupleType->getNumElements());
// Collect the tuple elements.
auto &loweredTL = SGF.getTypeLowering(outputOrigType, outputTupleType);
auto loweredTy = loweredTL.getLoweredType();
auto optionalTy = SGF.getSILType(claimNextOutputType());
auto someDecl = SGF.getASTContext().getOptionalSomeDecl();
if (loweredTL.isLoadable() || !SGF.silConv.useLoweredAddresses()) {
auto payload =
translateAndImplodeIntoValue(inputOrigType, inputTupleType,
outputOrigType, outputTupleType,
loweredTy);
auto optional = SGF.B.createEnum(Loc, payload.getValue(),
someDecl, optionalTy);
return ManagedValue(optional, payload.getCleanup());
} else {
auto optionalBuf = SGF.emitTemporaryAllocation(Loc, optionalTy);
auto tupleBuf = SGF.B.createInitEnumDataAddr(Loc, optionalBuf, someDecl,
loweredTy);
auto tupleTemp = SGF.useBufferAsTemporary(tupleBuf, loweredTL);
translateAndImplodeInto(inputOrigType, inputTupleType,
outputOrigType, outputTupleType,
*tupleTemp);
SGF.B.createInjectEnumAddr(Loc, optionalBuf, someDecl);
auto payload = tupleTemp->getManagedAddress();
return ManagedValue(optionalBuf, payload.getCleanup());
}
}
/// Handle a tuple that has been exploded in the input but wrapped
/// in an existential in the output.
ManagedValue
translateAndImplodeIntoAny(AbstractionPattern inputOrigType,
CanTupleType inputTupleType,
AbstractionPattern outputOrigType,
CanType outputSubstType) {
auto existentialTy = SGF.getLoweredType(outputOrigType, outputSubstType);
auto existentialBuf = SGF.emitTemporaryAllocation(Loc, existentialTy);
auto opaque = AbstractionPattern::getOpaque();
auto &concreteTL = SGF.getTypeLowering(opaque, inputTupleType);
auto tupleBuf =
SGF.B.createInitExistentialAddr(Loc, existentialBuf,
inputTupleType,
concreteTL.getLoweredType(),
/*conformances=*/{});
auto tupleTemp = SGF.useBufferAsTemporary(tupleBuf, concreteTL);
translateAndImplodeInto(inputOrigType, inputTupleType,
opaque, inputTupleType,
*tupleTemp);
auto payload = tupleTemp->getManagedAddress();
if (SGF.silConv.useLoweredAddresses()) {
return ManagedValue(existentialBuf, payload.getCleanup());
}
// We are under opaque value(s) mode - load the any and init an opaque
auto loadedPayload = SGF.emitManagedLoadCopy(Loc, payload.getValue());
auto &anyTL = SGF.getTypeLowering(opaque, outputSubstType);
SILValue loadedOpaque = SGF.B.createInitExistentialOpaque(
Loc, anyTL.getLoweredType(), inputTupleType, loadedPayload.getValue(),
/*Conformances=*/{});
return ManagedValue(loadedOpaque, loadedPayload.getCleanup());
}
/// Handle a tuple that has been exploded in both the input and
/// the output.
void translateParallelExploded(AbstractionPattern inputOrigType,
CanTupleType inputSubstType,
AbstractionPattern outputOrigType,
CanTupleType outputSubstType) {
assert(inputOrigType.matchesTuple(inputSubstType));
assert(outputOrigType.matchesTuple(outputSubstType));
// Non-materializable input and materializable output occurs
// when witness method thunks re-abstract a non-mutating
// witness for a mutating requirement. The inout self is just
// loaded to produce a value in this case.
assert(inputSubstType->hasInOutElement() ||
!outputSubstType->hasInOutElement());
assert(inputSubstType->getNumElements() ==
outputSubstType->getNumElements());
for (auto index : indices(outputSubstType.getElementTypes())) {
translate(inputOrigType.getTupleElementType(index),
inputSubstType.getElementType(index),
outputOrigType.getTupleElementType(index),
outputSubstType.getElementType(index));
}
}
/// Given that a tuple value is being passed indirectly in the
/// input, explode it and translate the elements.
void translateAndExplodeOutOf(AbstractionPattern inputOrigType,
CanTupleType inputSubstType,
AbstractionPattern outputOrigType,
CanTupleType outputSubstType,
ManagedValue inputTupleAddr) {
assert(inputOrigType.isTypeParameter());
assert(outputOrigType.matchesTuple(outputSubstType));
assert(!inputSubstType->hasInOutElement() &&
!outputSubstType->hasInOutElement());
assert(inputSubstType->getNumElements() ==
outputSubstType->getNumElements());
SmallVector<ManagedValueAndType, 4> inputEltAddrs;
explodeTuple(SGF, Loc, inputTupleAddr, inputEltAddrs);
assert(inputEltAddrs.size() == outputSubstType->getNumElements());
for (auto index : indices(outputSubstType.getElementTypes())) {
auto inputEltOrigType = inputOrigType.getTupleElementType(index);
auto inputEltSubstType = inputSubstType.getElementType(index);
auto outputEltOrigType = outputOrigType.getTupleElementType(index);
auto outputEltSubstType = outputSubstType.getElementType(index);
auto inputEltAddr = inputEltAddrs[index].first;
assert(inputEltAddr.getType().isAddress() ||
!SGF.silConv.useLoweredAddresses());
if (auto outputEltTupleType = dyn_cast<TupleType>(outputEltSubstType)) {
assert(outputEltOrigType.isTuple());
auto inputEltTupleType = cast<TupleType>(inputEltSubstType);
translateAndExplodeOutOf(inputEltOrigType,
inputEltTupleType,
outputEltOrigType,
outputEltTupleType,
inputEltAddr);
} else {
auto outputType = claimNextOutputType();
translateSingle(inputEltOrigType,
inputEltSubstType,
outputEltOrigType,
outputEltSubstType,
inputEltAddr,
outputType);
}
}
}
/// Given that a tuple value is being passed indirectly in the
/// output, translate the elements and implode it.
void translateAndImplodeInto(AbstractionPattern inputOrigType,
CanTupleType inputSubstType,
AbstractionPattern outputOrigType,
CanTupleType outputSubstType,
TemporaryInitialization &tupleInit) {
assert(inputOrigType.matchesTuple(inputSubstType));
assert(outputOrigType.matchesTuple(outputSubstType));
assert(!inputSubstType->hasInOutElement() &&
!outputSubstType->hasInOutElement());
assert(inputSubstType->getNumElements() ==
outputSubstType->getNumElements());
SmallVector<CleanupHandle, 4> cleanups;
for (auto index : indices(outputSubstType.getElementTypes())) {
auto inputEltOrigType = inputOrigType.getTupleElementType(index);
auto inputEltSubstType = inputSubstType.getElementType(index);
auto outputEltOrigType = outputOrigType.getTupleElementType(index);
auto outputEltSubstType = outputSubstType.getElementType(index);
auto eltAddr =
SGF.B.createTupleElementAddr(Loc, tupleInit.getAddress(), index);
auto &outputEltTL = SGF.getTypeLowering(eltAddr->getType());
CleanupHandle eltCleanup =
SGF.enterDormantTemporaryCleanup(eltAddr, outputEltTL);
if (eltCleanup.isValid()) cleanups.push_back(eltCleanup);
TemporaryInitialization eltInit(eltAddr, eltCleanup);
if (auto outputEltTupleType = dyn_cast<TupleType>(outputEltSubstType)) {
auto inputEltTupleType = cast<TupleType>(inputEltSubstType);
translateAndImplodeInto(inputEltOrigType, inputEltTupleType,
outputEltOrigType, outputEltTupleType,
eltInit);
} else {
// Otherwise, we come from a single value.
auto input = claimNextInput();
translateSingleInto(inputEltOrigType, inputEltSubstType,
outputEltOrigType, outputEltSubstType,
input, eltInit);
}
}
// Deactivate all the element cleanups and activate the tuple cleanup.
for (auto cleanup : cleanups)
SGF.Cleanups.forwardCleanup(cleanup);
tupleInit.finishInitialization(SGF);
}
/// Translate a single value and add it as an output.
void translateSingle(AbstractionPattern inputOrigType,
CanType inputSubstType,
AbstractionPattern outputOrigType,
CanType outputSubstType,
ManagedValue input,
SILParameterInfo result) {
// Easy case: we want to pass exactly this value.
if (input.getType() == SGF.getSILType(result)) {
Outputs.push_back(input);
return;
}
switch (result.getConvention()) {
// Direct translation is relatively easy.
case ParameterConvention::Direct_Owned:
case ParameterConvention::Direct_Unowned: {
auto output =
translatePrimitive(inputOrigType, inputSubstType, outputOrigType,
outputSubstType, input);
assert(output.getType() == SGF.getSILType(result));
// If our output is guaranteed, we need to create a copy here.
if (output.getOwnershipKind() == ValueOwnershipKind::Guaranteed)
output = output.copyUnmanaged(SGF, Loc);
Outputs.push_back(output);
return;
}
case ParameterConvention::Direct_Guaranteed: {
auto output = translatePrimitive(inputOrigType, inputSubstType,
outputOrigType, outputSubstType,
input);
assert(output.getType() == SGF.getSILType(result));
// If our output value is not guaranteed, we need to:
//
// 1. Unowned - Copy + Borrow.
// 2. Owned - Borrow.
// 3. Trivial - do nothing.
//
// This means we can first transition unowned => owned and then handle
// the new owned value using the same code path as values that are
// initially owned.
if (output.getOwnershipKind() == ValueOwnershipKind::Unowned) {
assert(!output.hasCleanup());
output = SGF.emitManagedRetain(Loc, output.getValue());
}
if (output.getOwnershipKind() == ValueOwnershipKind::Owned) {
output = SGF.emitManagedBeginBorrow(Loc, output.getValue());
}
Outputs.push_back(output);
return;
}
case ParameterConvention::Indirect_Inout: {
// If it's inout, we need writeback.
llvm::errs() << "inout writeback in abstraction difference thunk "
"not yet implemented\n";
llvm::errs() << "input value ";
input.getValue()->dump();
llvm::errs() << "output type " << SGF.getSILType(result) << "\n";
abort();
}
case ParameterConvention::Indirect_In:
case ParameterConvention::Indirect_In_Constant:
case ParameterConvention::Indirect_In_Guaranteed: {
if (SGF.silConv.useLoweredAddresses()) {
// We need to translate into a temporary.
auto &outputTL = SGF.getTypeLowering(SGF.getSILType(result));
auto temp = SGF.emitTemporary(Loc, outputTL);
translateSingleInto(inputOrigType, inputSubstType, outputOrigType,
outputSubstType, input, *temp);
Outputs.push_back(temp->getManagedAddress());
} else {
auto output =
translatePrimitive(inputOrigType, inputSubstType, outputOrigType,
outputSubstType, input);
assert(output.getType() == SGF.getSILType(result));
if (output.getOwnershipKind() == ValueOwnershipKind::Unowned) {
assert(!output.hasCleanup());
output = SGF.emitManagedRetain(Loc, output.getValue());
}
if (output.getOwnershipKind() == ValueOwnershipKind::Owned) {
output = SGF.emitManagedBeginBorrow(Loc, output.getValue());
}
Outputs.push_back(output);
}
return;
}
case ParameterConvention::Indirect_InoutAliasable: {
llvm_unreachable("abstraction difference in aliasable argument not "
"allowed");
}
}
llvm_unreachable("Covered switch isn't covered?!");
}
/// Translate a single value and initialize the given temporary with it.
void translateSingleInto(AbstractionPattern inputOrigType,
CanType inputSubstType,
AbstractionPattern outputOrigType,
CanType outputSubstType,
ManagedValue input,
TemporaryInitialization &temp) {
auto output = translatePrimitive(inputOrigType, inputSubstType,
outputOrigType, outputSubstType,
input, SGFContext(&temp));
forceInto(output, temp);
}
/// Apply primitive translation to the given value.
ManagedValue translatePrimitive(AbstractionPattern inputOrigType,
CanType inputSubstType,
AbstractionPattern outputOrigType,
CanType outputSubstType,
ManagedValue input,
SGFContext context = SGFContext()) {
return SGF.emitTransformedValue(Loc, input,
inputOrigType, inputSubstType,
outputOrigType, outputSubstType,
context);
}
/// Force the given result into the given initialization.
void forceInto(ManagedValue result, TemporaryInitialization &temp) {
emitForceInto(SGF, Loc, result, temp);
}
ManagedValue claimNextInput() {
return claimNext(Inputs);
}
SILParameterInfo claimNextOutputType() {
return claimNext(OutputTypes);
}
};
} // end anonymous namespace
/// Forward arguments according to a function type's ownership conventions.
static void forwardFunctionArguments(SILGenFunction &gen,
SILLocation loc,
CanSILFunctionType fTy,
ArrayRef<ManagedValue> managedArgs,
SmallVectorImpl<SILValue> &forwardedArgs) {
auto argTypes = fTy->getParameters();
for (auto index : indices(managedArgs)) {
auto &arg = managedArgs[index];
auto argTy = argTypes[index];
if (argTy.isConsumed()) {
forwardedArgs.push_back(arg.forward(gen));
continue;
}
if (argTy.getConvention() == ParameterConvention::Direct_Guaranteed) {
forwardedArgs.push_back(
gen.emitManagedBeginBorrow(loc, arg.getValue()).getValue());
continue;
}
forwardedArgs.push_back(arg.getValue());
}
}
namespace {
/// A helper class to translate the inner results to the outer results.
///
/// Creating a result-translation plan involves three basic things:
/// - building SILArguments for each of the outer indirect results
/// - building a list of SILValues for each of the inner indirect results
/// - building a list of Operations to perform which will reabstract
/// the inner results to match the outer.
class ResultPlanner {
SILGenFunction &Gen;
SILLocation Loc;
/// A single result-translation operation.
struct Operation {
enum Kind {
/// Take the last N direct outer results, tuple them, and make that a
/// new direct outer result.
///
/// Valid: NumElements, OuterResult
TupleDirect,
/// Take the last direct outer result, inject it into an optional
/// type, and make that a new direct outer result.
///
/// Valid: SomeDecl, OuterResult
InjectOptionalDirect,
/// Finish building an optional Some in the given address.
///
/// Valid: SomeDecl, OuterResultAddr
InjectOptionalIndirect,
/// Take the next direct inner result and just make it a direct
/// outer result.
///
/// Valid: InnerResult, OuterResult.
DirectToDirect,
/// Take the next direct inner result and store it into an
/// outer result address.
///
/// Valid: InnerDirect, OuterResultAddr.
DirectToIndirect,
/// Take from an indirect inner result and make it the next outer
/// direct result.
///
/// Valid: InnerResultAddr, OuterResult.
IndirectToDirect,
/// Take from an indirect inner result into an outer indirect result.
///
/// Valid: InnerResultAddr, OuterResultAddr.
IndirectToIndirect,
/// Take a value out of the source inner result address, reabstract
/// it, and initialize the destination outer result address.
///
/// Valid: reabstraction info, InnerAddress, OuterAddress.
ReabstractIndirectToIndirect,
/// Take a value out of the source inner result address, reabstract
/// it, and add it as the next direct outer result.
///
/// Valid: reabstraction info, InnerAddress, OuterResult.
ReabstractIndirectToDirect,
/// Take the next direct inner result, reabstract it, and initialize
/// the destination outer result address.
///
/// Valid: reabstraction info, InnerResult, OuterAddress.
ReabstractDirectToIndirect,
/// Take the next direct inner result, reabstract it, and add it as
/// the next direct outer result.
///
/// Valid: reabstraction info, InnerResult, OuterResult.
ReabstractDirectToDirect,
};
Operation(Kind kind) : TheKind(kind) {}
Kind TheKind;
// Reabstraction information. Only valid for reabstraction kinds.
AbstractionPattern InnerOrigType = AbstractionPattern::getInvalid();
AbstractionPattern OuterOrigType = AbstractionPattern::getInvalid();
CanType InnerSubstType, OuterSubstType;
union {
SILValue InnerResultAddr;
SILResultInfo InnerResult;
unsigned NumElements;
EnumElementDecl *SomeDecl;
};
union {
SILValue OuterResultAddr;
SILResultInfo OuterResult;
};
};
struct PlanData {
ArrayRef<SILResultInfo> OuterResults;
ArrayRef<SILResultInfo> InnerResults;
SmallVectorImpl<SILValue> &InnerIndirectResultAddrs;
size_t NextOuterIndirectResultIndex;
};
SmallVector<Operation, 8> Operations;
public:
ResultPlanner(SILGenFunction &gen, SILLocation loc) : Gen(gen), Loc(loc) {}
void plan(AbstractionPattern innerOrigType, CanType innerSubstType,
AbstractionPattern outerOrigType, CanType outerSubstType,
CanSILFunctionType innerFnType, CanSILFunctionType outerFnType,
SmallVectorImpl<SILValue> &innerIndirectResultAddrs) {
// Assert that the indirect results are set up like we expect.
assert(innerIndirectResultAddrs.empty());
assert(Gen.F.begin()->args_size()
>= SILFunctionConventions(outerFnType, Gen.SGM.M)
.getNumIndirectSILResults());
innerIndirectResultAddrs.reserve(
SILFunctionConventions(innerFnType, Gen.SGM.M)
.getNumIndirectSILResults());
PlanData data = {outerFnType->getResults(), innerFnType->getResults(),
innerIndirectResultAddrs, 0};
// Recursively walk the result types.
plan(innerOrigType, innerSubstType, outerOrigType, outerSubstType, data);
// Assert that we consumed and produced all the indirect result
// information we needed.
assert(data.OuterResults.empty());
assert(data.InnerResults.empty());
assert(data.InnerIndirectResultAddrs.size() ==
SILFunctionConventions(innerFnType, Gen.SGM.M)
.getNumIndirectSILResults());
assert(data.NextOuterIndirectResultIndex
== SILFunctionConventions(outerFnType, Gen.SGM.M)
.getNumIndirectSILResults());
}
SILValue execute(SILValue innerResult);
private:
void execute(ArrayRef<SILValue> innerDirectResults,
SmallVectorImpl<SILValue> &outerDirectResults);
void executeInnerTuple(SILValue innerElement,
SmallVector<SILValue, 4> &innerDirectResults);
void plan(AbstractionPattern innerOrigType, CanType innerSubstType,
AbstractionPattern outerOrigType, CanType outerSubstType,
PlanData &planData);
void planIntoIndirectResult(AbstractionPattern innerOrigType,
CanType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
PlanData &planData,
SILValue outerResultAddr);
void planTupleIntoIndirectResult(AbstractionPattern innerOrigType,
CanTupleType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
PlanData &planData,
SILValue outerResultAddr);
void planScalarIntoIndirectResult(AbstractionPattern innerOrigType,
CanType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
PlanData &planData,
SILResultInfo innerResult,
SILValue outerResultAddr);
void planIntoDirectResult(AbstractionPattern innerOrigType,
CanType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
PlanData &planData,
SILResultInfo outerResult);
void planScalarIntoDirectResult(AbstractionPattern innerOrigType,
CanType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
PlanData &planData,
SILResultInfo innerResult,
SILResultInfo outerResult);
void planTupleIntoDirectResult(AbstractionPattern innerOrigType,
CanTupleType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
PlanData &planData,
SILResultInfo outerResult);
void planFromIndirectResult(AbstractionPattern innerOrigType,
CanType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
PlanData &planData,
SILValue innerResultAddr);
void planTupleFromIndirectResult(AbstractionPattern innerOrigType,
CanTupleType innerSubstType,
AbstractionPattern outerOrigType,
CanTupleType outerSubstType,
PlanData &planData,
SILValue innerResultAddr);
void planTupleFromDirectResult(AbstractionPattern innerOrigType,
CanTupleType innerSubstType,
AbstractionPattern outerOrigType,
CanTupleType outerSubstType,
PlanData &planData, SILResultInfo innerResult);
void planScalarFromIndirectResult(AbstractionPattern innerOrigType,
CanType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
SILValue innerResultAddr,
SILResultInfo outerResult,
SILValue optOuterResultAddr);
/// Claim the next inner result from the plan data.
SILResultInfo claimNextInnerResult(PlanData &data) {
return claimNext(data.InnerResults);
}
/// Claim the next outer result from the plan data. If it's indirect,
/// grab its SILArgument.
std::pair<SILResultInfo, SILValue> claimNextOuterResult(PlanData &data) {
SILResultInfo result = claimNext(data.OuterResults);
SILValue resultAddr;
if (Gen.silConv.isSILIndirect(result)) {
resultAddr =
Gen.F.begin()->getArgument(data.NextOuterIndirectResultIndex++);
}
return { result, resultAddr };
}
/// Create a temporary address suitable for passing to the given inner
/// indirect result and add it as an inner indirect result.
SILValue addInnerIndirectResultTemporary(PlanData &data,
SILResultInfo innerResult) {
assert(Gen.silConv.isSILIndirect(innerResult) ||
!Gen.silConv.useLoweredAddresses());
auto temporary =
Gen.emitTemporaryAllocation(Loc, Gen.getSILType(innerResult));
data.InnerIndirectResultAddrs.push_back(temporary);
return temporary;
}
/// Cause the next inner indirect result to be emitted directly into
/// the given outer result address.
void addInPlace(PlanData &data, SILValue outerResultAddr) {
data.InnerIndirectResultAddrs.push_back(outerResultAddr);
// Does not require an Operation.
}
Operation &addOperation(Operation::Kind kind) {
Operations.emplace_back(kind);
return Operations.back();
}
void addDirectToDirect(SILResultInfo innerResult, SILResultInfo outerResult) {
auto &op = addOperation(Operation::DirectToDirect);
op.InnerResult = innerResult;
op.OuterResult = outerResult;
}
void addDirectToIndirect(SILResultInfo innerResult,
SILValue outerResultAddr) {
auto &op = addOperation(Operation::DirectToIndirect);
op.InnerResult = innerResult;
op.OuterResultAddr = outerResultAddr;
}
void addIndirectToDirect(SILValue innerResultAddr,
SILResultInfo outerResult) {
auto &op = addOperation(Operation::IndirectToDirect);
op.InnerResultAddr = innerResultAddr;
op.OuterResult = outerResult;
}
void addIndirectToIndirect(SILValue innerResultAddr,
SILValue outerResultAddr) {
auto &op = addOperation(Operation::IndirectToIndirect);
op.InnerResultAddr = innerResultAddr;
op.OuterResultAddr = outerResultAddr;
}
void addTupleDirect(unsigned numElements, SILResultInfo outerResult) {
auto &op = addOperation(Operation::TupleDirect);
op.NumElements = numElements;
op.OuterResult = outerResult;
}
void addInjectOptionalDirect(EnumElementDecl *someDecl,
SILResultInfo outerResult) {
auto &op = addOperation(Operation::InjectOptionalDirect);
op.SomeDecl = someDecl;
op.OuterResult = outerResult;
}
void addInjectOptionalIndirect(EnumElementDecl *someDecl,
SILValue outerResultAddr) {
auto &op = addOperation(Operation::InjectOptionalIndirect);
op.SomeDecl = someDecl;
op.OuterResultAddr = outerResultAddr;
}
void addReabstractDirectToDirect(AbstractionPattern innerOrigType,
CanType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
SILResultInfo innerResult,
SILResultInfo outerResult) {
auto &op = addOperation(Operation::ReabstractDirectToDirect);
op.InnerResult = innerResult;
op.OuterResult = outerResult;
op.InnerOrigType = innerOrigType;
op.InnerSubstType = innerSubstType;
op.OuterOrigType = outerOrigType;
op.OuterSubstType = outerSubstType;
}
void addReabstractDirectToIndirect(AbstractionPattern innerOrigType,
CanType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
SILResultInfo innerResult,
SILValue outerResultAddr) {
auto &op = addOperation(Operation::ReabstractDirectToIndirect);
op.InnerResult = innerResult;
op.OuterResultAddr = outerResultAddr;
op.InnerOrigType = innerOrigType;
op.InnerSubstType = innerSubstType;
op.OuterOrigType = outerOrigType;
op.OuterSubstType = outerSubstType;
}
void addReabstractIndirectToDirect(AbstractionPattern innerOrigType,
CanType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
SILValue innerResultAddr,
SILResultInfo outerResult) {
auto &op = addOperation(Operation::ReabstractIndirectToDirect);
op.InnerResultAddr = innerResultAddr;
op.OuterResult = outerResult;
op.InnerOrigType = innerOrigType;
op.InnerSubstType = innerSubstType;
op.OuterOrigType = outerOrigType;
op.OuterSubstType = outerSubstType;
}
void addReabstractIndirectToIndirect(AbstractionPattern innerOrigType,
CanType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
SILValue innerResultAddr,
SILValue outerResultAddr) {
auto &op = addOperation(Operation::ReabstractIndirectToIndirect);
op.InnerResultAddr = innerResultAddr;
op.OuterResultAddr = outerResultAddr;
op.InnerOrigType = innerOrigType;
op.InnerSubstType = innerSubstType;
op.OuterOrigType = outerOrigType;
op.OuterSubstType = outerSubstType;
}
};
} // end anonymous namespace
/// Plan the reabstraction of a call result.
void ResultPlanner::plan(AbstractionPattern innerOrigType,
CanType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
PlanData &planData) {
// The substituted types must match up in tuple-ness and arity.
assert(isa<TupleType>(innerSubstType) == isa<TupleType>(outerSubstType) ||
(isa<TupleType>(innerSubstType) &&
(outerSubstType->isAny() ||
outerSubstType->getAnyOptionalObjectType())));
assert(!isa<TupleType>(outerSubstType) ||
cast<TupleType>(innerSubstType)->getNumElements() ==
cast<TupleType>(outerSubstType)->getNumElements());
// If the inner abstraction pattern is a tuple, that result will be expanded.
if (innerOrigType.isTuple()) {
auto innerSubstTupleType = cast<TupleType>(innerSubstType);
// If the outer abstraction pattern is also a tuple, that result will also
// be expanded, in parallel with the inner pattern.
if (outerOrigType.isTuple()) {
auto outerSubstTupleType = cast<TupleType>(outerSubstType);
assert(innerSubstTupleType->getNumElements()
== outerSubstTupleType->getNumElements());
// Otherwise, recursively descend into the tuples.
for (auto eltIndex : indices(innerSubstTupleType.getElementTypes())) {
plan(innerOrigType.getTupleElementType(eltIndex),
innerSubstTupleType.getElementType(eltIndex),
outerOrigType.getTupleElementType(eltIndex),
outerSubstTupleType.getElementType(eltIndex),
planData);
}
return;
}
// Otherwise, the next outer result must be either opaque or optional.
// In either case, it corresponds to a single result.
auto outerResult = claimNextOuterResult(planData);
// Base the plan on whether the single result is direct or indirect.
if (Gen.silConv.isSILIndirect(outerResult.first)) {
assert(outerResult.second);
planTupleIntoIndirectResult(innerOrigType, innerSubstTupleType,
outerOrigType, outerSubstType,
planData, outerResult.second);
} else {
planTupleIntoDirectResult(innerOrigType, innerSubstTupleType,
outerOrigType, outerSubstType,
planData, outerResult.first);
}
return;
}
// Otherwise, the inner pattern is a scalar; claim the next inner result.
SILResultInfo innerResult = claimNextInnerResult(planData);
assert((!outerOrigType.isTuple() || innerResult.isFormalIndirect()) &&
"outer pattern is a tuple, inner pattern is not, but inner result is "
"not indirect?");
// If the inner result is a tuple, we need to expand from a temporary.
if (innerResult.isFormalIndirect() && outerOrigType.isTuple()) {
if (Gen.silConv.isSILIndirect(innerResult)) {
SILValue innerResultAddr =
addInnerIndirectResultTemporary(planData, innerResult);
planTupleFromIndirectResult(
innerOrigType, cast<TupleType>(innerSubstType), outerOrigType,
cast<TupleType>(outerSubstType), planData, innerResultAddr);
} else {
assert(!Gen.silConv.useLoweredAddresses() &&
"Formal Indirect Results that are not SIL Indirect are only "
"allowed in opaque values mode");
planTupleFromDirectResult(innerOrigType, cast<TupleType>(innerSubstType),
outerOrigType, cast<TupleType>(outerSubstType),
planData, innerResult);
}
return;
}
// Otherwise, the outer pattern is a scalar; claim the next outer result.
auto outerResult = claimNextOuterResult(planData);
// If the outer result is indirect, plan to emit into that.
if (Gen.silConv.isSILIndirect(outerResult.first)) {
assert(outerResult.second);
planScalarIntoIndirectResult(innerOrigType, innerSubstType,
outerOrigType, outerSubstType,
planData, innerResult, outerResult.second);
} else {
planScalarIntoDirectResult(innerOrigType, innerSubstType,
outerOrigType, outerSubstType,
planData, innerResult, outerResult.first);
}
}
/// Plan the emission of a call result into an outer result address.
void ResultPlanner::planIntoIndirectResult(AbstractionPattern innerOrigType,
CanType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
PlanData &planData,
SILValue outerResultAddr) {
// outerOrigType can be a tuple if we're also injecting into an optional.
// If the inner pattern is a tuple, expand it.
if (innerOrigType.isTuple()) {
planTupleIntoIndirectResult(innerOrigType, cast<TupleType>(innerSubstType),
outerOrigType, outerSubstType,
planData, outerResultAddr);
// Otherwise, it's scalar.
} else {
// Claim the next inner result.
SILResultInfo innerResult = claimNextInnerResult(planData);
planScalarIntoIndirectResult(innerOrigType, innerSubstType,
outerOrigType, outerSubstType,
planData, innerResult, outerResultAddr);
}
}
/// Plan the emission of a call result into an outer result address,
/// given that the inner abstraction pattern is a tuple.
void
ResultPlanner::planTupleIntoIndirectResult(AbstractionPattern innerOrigType,
CanTupleType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
PlanData &planData,
SILValue outerResultAddr) {
assert(innerOrigType.isTuple());
// outerOrigType can be a tuple if we're doing something like
// injecting into an optional tuple.
auto outerSubstTupleType = dyn_cast<TupleType>(outerSubstType);
// If the outer type is not a tuple, it must be optional.
if (!outerSubstTupleType) {
// Figure out what kind of optional it is.
CanType outerSubstObjectType =
outerSubstType.getAnyOptionalObjectType();
if (outerSubstObjectType) {
auto someDecl = Gen.getASTContext().getOptionalSomeDecl();
// Prepare the value slot in the optional value.
SILType outerObjectType =
outerResultAddr->getType().getAnyOptionalObjectType();
SILValue outerObjectResultAddr
= Gen.B.createInitEnumDataAddr(Loc, outerResultAddr, someDecl,
outerObjectType);
// Emit into that address.
planTupleIntoIndirectResult(innerOrigType, innerSubstType,
outerOrigType.getAnyOptionalObjectType(),
outerSubstObjectType,
planData, outerObjectResultAddr);
// Add an operation to finish the enum initialization.
addInjectOptionalIndirect(someDecl, outerResultAddr);
return;
}
assert(outerSubstType->isAny());
// Prepare the value slot in the existential.
auto opaque = AbstractionPattern::getOpaque();
SILValue outerConcreteResultAddr
= Gen.B.createInitExistentialAddr(Loc, outerResultAddr, innerSubstType,
Gen.getLoweredType(opaque, innerSubstType),
/*conformances=*/{});
// Emit into that address.
planTupleIntoIndirectResult(innerOrigType, innerSubstType,
innerOrigType, innerSubstType,
planData, outerConcreteResultAddr);
return;
}
assert(innerSubstType->getNumElements()
== outerSubstTupleType->getNumElements());
for (auto eltIndex : indices(innerSubstType.getElementTypes())) {
// Project the address of the element.
SILValue outerEltResultAddr =
Gen.B.createTupleElementAddr(Loc, outerResultAddr, eltIndex);
// Plan to emit into that location.
planIntoIndirectResult(innerOrigType.getTupleElementType(eltIndex),
innerSubstType.getElementType(eltIndex),
outerOrigType.getTupleElementType(eltIndex),
outerSubstTupleType.getElementType(eltIndex),
planData, outerEltResultAddr);
}
}
/// Plan the emission of a call result as a single outer direct result.
void
ResultPlanner::planIntoDirectResult(AbstractionPattern innerOrigType,
CanType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
PlanData &planData,
SILResultInfo outerResult) {
assert(!outerOrigType.isTuple() || !Gen.silConv.useLoweredAddresses());
// If the inner pattern is a tuple, expand it.
if (innerOrigType.isTuple()) {
planTupleIntoDirectResult(innerOrigType, cast<TupleType>(innerSubstType),
outerOrigType, outerSubstType,
planData, outerResult);
// Otherwise, it's scalar.
} else {
// Claim the next inner result.
SILResultInfo innerResult = claimNextInnerResult(planData);
planScalarIntoDirectResult(innerOrigType, innerSubstType,
outerOrigType, outerSubstType,
planData, innerResult, outerResult);
}
}
/// Plan the emission of a call result as a single outer direct result,
/// given that the inner abstraction pattern is a tuple.
void
ResultPlanner::planTupleIntoDirectResult(AbstractionPattern innerOrigType,
CanTupleType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
PlanData &planData,
SILResultInfo outerResult) {
assert(innerOrigType.isTuple());
auto outerSubstTupleType = dyn_cast<TupleType>(outerSubstType);
// If the outer type is not a tuple, it must be optional or we are under
// opaque value mode
if (!outerSubstTupleType) {
CanType outerSubstObjectType =
outerSubstType.getAnyOptionalObjectType();
if (outerSubstObjectType) {
auto someDecl = Gen.getASTContext().getOptionalSomeDecl();
SILType outerObjectType =
Gen.getSILType(outerResult).getAnyOptionalObjectType();
SILResultInfo outerObjectResult(outerObjectType.getSwiftRValueType(),
outerResult.getConvention());
// Plan to leave the tuple elements as a single direct outer result.
planTupleIntoDirectResult(innerOrigType, innerSubstType,
outerOrigType.getAnyOptionalObjectType(),
outerSubstObjectType, planData,
outerObjectResult);
// Take that result and inject it into an optional.
addInjectOptionalDirect(someDecl, outerResult);
return;
} else {
assert(!Gen.silConv.useLoweredAddresses() &&
"inner type was a tuple but outer type was neither a tuple nor "
"optional nor are we under opaque value mode");
assert(outerSubstType->isAny());
auto opaque = AbstractionPattern::getOpaque();
auto anyType = Gen.getLoweredType(opaque, outerSubstType);
auto outerResultAddr = Gen.emitTemporaryAllocation(Loc, anyType);
SILValue outerConcreteResultAddr = Gen.B.createInitExistentialAddr(
Loc, outerResultAddr, innerSubstType,
Gen.getLoweredType(opaque, innerSubstType), /*conformances=*/{});
planTupleIntoIndirectResult(innerOrigType, innerSubstType, innerOrigType,
innerSubstType, planData,
outerConcreteResultAddr);
addReabstractIndirectToDirect(innerOrigType, innerSubstType,
outerOrigType, outerSubstType,
outerConcreteResultAddr, outerResult);
return;
}
}
// Otherwise, the outer type is a tuple.
assert(innerSubstType->getNumElements()
== outerSubstTupleType->getNumElements());
// Create direct outer results for each of the elements.
for (auto eltIndex : indices(innerSubstType.getElementTypes())) {
auto outerEltType =
Gen.getSILType(outerResult).getTupleElementType(eltIndex);
SILResultInfo outerEltResult(outerEltType.getSwiftRValueType(),
outerResult.getConvention());
planIntoDirectResult(innerOrigType.getTupleElementType(eltIndex),
innerSubstType.getElementType(eltIndex),
outerOrigType.getTupleElementType(eltIndex),
outerSubstTupleType.getElementType(eltIndex),
planData, outerEltResult);
}
// Bind them together into a single tuple.
addTupleDirect(innerSubstType->getNumElements(), outerResult);
}
/// Plan the emission of a call result as a single outer direct result,
/// given that the inner abstraction pattern is not a tuple.
void ResultPlanner::planScalarIntoDirectResult(AbstractionPattern innerOrigType,
CanType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
PlanData &planData,
SILResultInfo innerResult,
SILResultInfo outerResult) {
assert(!innerOrigType.isTuple());
assert(!outerOrigType.isTuple());
// If the inner result is indirect, plan to emit from that.
if (Gen.silConv.isSILIndirect(innerResult)) {
SILValue innerResultAddr =
addInnerIndirectResultTemporary(planData, innerResult);
planScalarFromIndirectResult(innerOrigType, innerSubstType,
outerOrigType, outerSubstType,
innerResultAddr, outerResult, SILValue());
return;
}
// Otherwise, we have two direct results.
// If there's no abstraction difference, it's just returned directly.
if (Gen.getSILType(innerResult) == Gen.getSILType(outerResult)) {
addDirectToDirect(innerResult, outerResult);
// Otherwise, we need to reabstract.
} else {
addReabstractDirectToDirect(innerOrigType, innerSubstType,
outerOrigType, outerSubstType,
innerResult, outerResult);
}
}
/// Plan the emission of a call result into an outer result address,
/// given that the inner abstraction pattern is not a tuple.
void
ResultPlanner::planScalarIntoIndirectResult(AbstractionPattern innerOrigType,
CanType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
PlanData &planData,
SILResultInfo innerResult,
SILValue outerResultAddr) {
assert(!innerOrigType.isTuple());
assert(!outerOrigType.isTuple());
bool hasAbstractionDifference =
(innerResult.getType() != outerResultAddr->getType().getSwiftRValueType());
// If the inner result is indirect, we need some memory to emit it into.
if (Gen.silConv.isSILIndirect(innerResult)) {
// If there's no abstraction difference, that can just be
// in-place into the outer result address.
if (!hasAbstractionDifference) {
addInPlace(planData, outerResultAddr);
// Otherwise, we'll need a temporary.
} else {
SILValue innerResultAddr =
addInnerIndirectResultTemporary(planData, innerResult);
addReabstractIndirectToIndirect(innerOrigType, innerSubstType,
outerOrigType, outerSubstType,
innerResultAddr, outerResultAddr);
}
// Otherwise, the inner result is direct.
} else {
// If there's no abstraction difference, we just need to store.
if (!hasAbstractionDifference) {
addDirectToIndirect(innerResult, outerResultAddr);
// Otherwise, we need to reabstract and store.
} else {
addReabstractDirectToIndirect(innerOrigType, innerSubstType,
outerOrigType, outerSubstType,
innerResult, outerResultAddr);
}
}
}
/// Plan the emission of a call result from an inner result address.
void ResultPlanner::planFromIndirectResult(AbstractionPattern innerOrigType,
CanType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
PlanData &planData,
SILValue innerResultAddr) {
assert(!innerOrigType.isTuple());
if (outerOrigType.isTuple()) {
planTupleFromIndirectResult(innerOrigType, cast<TupleType>(innerSubstType),
outerOrigType, cast<TupleType>(outerSubstType),
planData, innerResultAddr);
} else {
auto outerResult = claimNextOuterResult(planData);
planScalarFromIndirectResult(innerOrigType, innerSubstType,
outerOrigType, outerSubstType,
innerResultAddr,
outerResult.first, outerResult.second);
}
}
/// Plan the emission of a call result from an inner result address, given
/// that the outer abstraction pattern is a tuple.
void
ResultPlanner::planTupleFromIndirectResult(AbstractionPattern innerOrigType,
CanTupleType innerSubstType,
AbstractionPattern outerOrigType,
CanTupleType outerSubstType,
PlanData &planData,
SILValue innerResultAddr) {
assert(!innerOrigType.isTuple());
assert(innerSubstType->getNumElements() == outerSubstType->getNumElements());
assert(outerOrigType.isTuple());
for (auto eltIndex : indices(innerSubstType.getElementTypes())) {
// Project the address of the element.
SILValue innerEltResultAddr =
Gen.B.createTupleElementAddr(Loc, innerResultAddr, eltIndex);
// Plan to expand from that location.
planFromIndirectResult(innerOrigType.getTupleElementType(eltIndex),
innerSubstType.getElementType(eltIndex),
outerOrigType.getTupleElementType(eltIndex),
outerSubstType.getElementType(eltIndex),
planData, innerEltResultAddr);
}
}
void ResultPlanner::planTupleFromDirectResult(AbstractionPattern innerOrigType,
CanTupleType innerSubstType,
AbstractionPattern outerOrigType,
CanTupleType outerSubstType,
PlanData &planData,
SILResultInfo innerResult) {
assert(!innerOrigType.isTuple());
auto outerSubstTupleType = dyn_cast<TupleType>(outerSubstType);
assert(outerSubstTupleType && "Outer type must be a tuple");
assert(innerSubstType->getNumElements() ==
outerSubstTupleType->getNumElements());
// Create direct outer results for each of the elements.
for (auto eltIndex : indices(innerSubstType.getElementTypes())) {
AbstractionPattern newOuterOrigType =
outerOrigType.getTupleElementType(eltIndex);
AbstractionPattern newInnerOrigType =
innerOrigType.getTupleElementType(eltIndex);
if (newOuterOrigType.isTuple()) {
planTupleFromDirectResult(
newInnerOrigType,
cast<TupleType>(innerSubstType.getElementType(eltIndex)),
newOuterOrigType,
cast<TupleType>(outerSubstTupleType.getElementType(eltIndex)),
planData, innerResult);
continue;
}
auto outerResult = claimNextOuterResult(planData);
auto elemType = outerSubstTupleType.getElementType(eltIndex);
SILResultInfo eltResult(elemType, outerResult.first.getConvention());
planScalarIntoDirectResult(
newInnerOrigType, innerSubstType.getElementType(eltIndex),
newOuterOrigType, outerSubstTupleType.getElementType(eltIndex),
planData, eltResult, outerResult.first);
}
}
/// Plan the emission of a call result from an inner result address,
/// given that the outer abstraction pattern is not a tuple.
void
ResultPlanner::planScalarFromIndirectResult(AbstractionPattern innerOrigType,
CanType innerSubstType,
AbstractionPattern outerOrigType,
CanType outerSubstType,
SILValue innerResultAddr,
SILResultInfo outerResult,
SILValue optOuterResultAddr) {
assert(!innerOrigType.isTuple());
assert(!outerOrigType.isTuple());
assert(Gen.silConv.isSILIndirect(outerResult) == bool(optOuterResultAddr));
bool hasAbstractionDifference =
(innerResultAddr->getType().getSwiftRValueType() != outerResult.getType());
// The outer result can be indirect, and it doesn't necessarily have an
// abstraction difference. Note that we should only end up in this path
// in cases where simply forwarding the outer result address wasn't possible.
if (Gen.silConv.isSILIndirect(outerResult)) {
assert(optOuterResultAddr);
if (!hasAbstractionDifference) {
addIndirectToIndirect(innerResultAddr, optOuterResultAddr);
} else {
addReabstractIndirectToIndirect(innerOrigType, innerSubstType,
outerOrigType, outerSubstType,
innerResultAddr, optOuterResultAddr);
}
} else {
if (!hasAbstractionDifference) {
addIndirectToDirect(innerResultAddr, outerResult);
} else {
addReabstractIndirectToDirect(innerOrigType, innerSubstType,
outerOrigType, outerSubstType,
innerResultAddr, outerResult);
}
}
}
void ResultPlanner::executeInnerTuple(
SILValue innerElement, SmallVector<SILValue, 4> &innerDirectResults) {
auto innerTupleType = innerElement->getType().getAs<TupleType>();
assert(innerTupleType && "Only supports tuple inner types");
ManagedValue ownedInnerResult =
Gen.emitManagedRValueWithCleanup(innerElement);
// Then borrow the managed direct result.
ManagedValue borrowedInnerResult = ownedInnerResult.borrow(Gen, Loc);
for (unsigned i : indices(innerTupleType.getElementTypes())) {
ManagedValue elt = Gen.B.createTupleExtract(Loc, borrowedInnerResult, i);
auto eltType = elt.getType();
if (eltType.is<TupleType>()) {
executeInnerTuple(elt.getValue(), innerDirectResults);
continue;
}
innerDirectResults.push_back(elt.copyUnmanaged(Gen, Loc).forward(Gen));
}
}
SILValue ResultPlanner::execute(SILValue innerResult) {
// The code emission here assumes that we don't need to have
// active cleanups for all the result values we're not actively
// transforming. In other words, it's not "exception-safe".
// Explode the inner direct results.
SmallVector<SILValue, 4> innerDirectResults;
auto innerResultTupleType = innerResult->getType().getAs<TupleType>();
if (!innerResultTupleType) {
innerDirectResults.push_back(innerResult);
} else {
{
Scope S(Gen.Cleanups, CleanupLocation::get(Loc));
// First create an rvalue cleanup for our direct result.
assert(innerResult.getOwnershipKind() == ValueOwnershipKind::Owned ||
innerResult.getOwnershipKind() == ValueOwnershipKind::Trivial);
executeInnerTuple(innerResult, innerDirectResults);
// Then allow the cleanups to be emitted in the proper reverse order.
}
}
// Translate the result values.
SmallVector<SILValue, 4> outerDirectResults;
execute(innerDirectResults, outerDirectResults);
// Implode the outer direct results.
SILValue outerResult;
if (outerDirectResults.size() == 1) {
outerResult = outerDirectResults[0];
} else {
outerResult = Gen.B.createTuple(Loc, outerDirectResults);
}
return outerResult;
}
void ResultPlanner::execute(ArrayRef<SILValue> innerDirectResults,
SmallVectorImpl<SILValue> &outerDirectResults) {
// A helper function to claim an inner direct result.
auto claimNextInnerDirectResult = [&](SILResultInfo result) -> ManagedValue {
auto resultValue = claimNext(innerDirectResults);
assert(resultValue->getType() == Gen.getSILType(result));
auto &resultTL = Gen.getTypeLowering(result.getType());
switch (result.getConvention()) {
case ResultConvention::Indirect:
assert(!Gen.silConv.isSILIndirect(result)
&& "claiming indirect result as direct!");
LLVM_FALLTHROUGH;
case ResultConvention::Owned:
case ResultConvention::Autoreleased:
return Gen.emitManagedRValueWithCleanup(resultValue, resultTL);
case ResultConvention::UnownedInnerPointer:
// FIXME: We can't reasonably lifetime-extend an inner-pointer result
// through a thunk. We don't know which parameter to the thunk was
// originally 'self'.
Gen.SGM.diagnose(Loc.getSourceLoc(), diag::not_implemented,
"reabstraction of returns_inner_pointer function");
LLVM_FALLTHROUGH;
case ResultConvention::Unowned:
return Gen.emitManagedRetain(Loc, resultValue, resultTL);
}
llvm_unreachable("bad result convention!");
};
// A helper function to add an outer direct result.
auto addOuterDirectResult = [&](ManagedValue resultValue,
SILResultInfo result) {
assert(resultValue.getType()
== Gen.F.mapTypeIntoContext(Gen.getSILType(result)));
outerDirectResults.push_back(resultValue.forward(Gen));
};
auto emitReabstract =
[&](Operation &op, bool innerIsIndirect, bool outerIsIndirect) {
// Set up the inner result.
ManagedValue innerResult;
if (innerIsIndirect) {
innerResult = Gen.emitManagedBufferWithCleanup(op.InnerResultAddr);
} else {
innerResult = claimNextInnerDirectResult(op.InnerResult);
}
// Set up the context into which to emit the outer result.
SGFContext outerResultCtxt;
Optional<TemporaryInitialization> outerResultInit;
if (outerIsIndirect) {
outerResultInit.emplace(op.OuterResultAddr, CleanupHandle::invalid());
outerResultCtxt = SGFContext(&*outerResultInit);
}
// Perform the translation.
auto translated =
Gen.emitTransformedValue(Loc, innerResult,
op.InnerOrigType, op.InnerSubstType,
op.OuterOrigType, op.OuterSubstType,
outerResultCtxt);
// If the outer is indirect, force it into the context.
if (outerIsIndirect) {
if (!translated.isInContext()) {
translated.forwardInto(Gen, Loc, op.OuterResultAddr);
}
// Otherwise, it's a direct result.
} else {
addOuterDirectResult(translated, op.OuterResult);
}
};
// Execute each operation.
for (auto &op : Operations) {
switch (op.TheKind) {
case Operation::DirectToDirect: {
auto result = claimNextInnerDirectResult(op.InnerResult);
addOuterDirectResult(result, op.OuterResult);
continue;
}
case Operation::DirectToIndirect: {
auto result = claimNextInnerDirectResult(op.InnerResult);
Gen.B.emitStoreValueOperation(Loc, result.forward(Gen),
op.OuterResultAddr,
StoreOwnershipQualifier::Init);
continue;
}
case Operation::IndirectToDirect: {
auto resultAddr = op.InnerResultAddr;
auto &resultTL = Gen.getTypeLowering(resultAddr->getType());
auto result = Gen.emitManagedRValueWithCleanup(
resultTL.emitLoad(Gen.B, Loc, resultAddr,
LoadOwnershipQualifier::Take),
resultTL);
addOuterDirectResult(result, op.OuterResult);
continue;
}
case Operation::IndirectToIndirect: {
// The type could be address-only; just take.
Gen.B.createCopyAddr(Loc, op.InnerResultAddr, op.OuterResultAddr,
IsTake, IsInitialization);
continue;
}
case Operation::ReabstractIndirectToIndirect:
emitReabstract(op, /*indirect source*/ true, /*indirect dest*/ true);
continue;
case Operation::ReabstractIndirectToDirect:
emitReabstract(op, /*indirect source*/ true, /*indirect dest*/ false);
continue;
case Operation::ReabstractDirectToIndirect:
emitReabstract(op, /*indirect source*/ false, /*indirect dest*/ true);
continue;
case Operation::ReabstractDirectToDirect:
emitReabstract(op, /*indirect source*/ false, /*indirect dest*/ false);
continue;
case Operation::TupleDirect: {
auto firstEltIndex = outerDirectResults.size() - op.NumElements;
auto elts = makeArrayRef(outerDirectResults).slice(firstEltIndex);
auto tupleType = Gen.F.mapTypeIntoContext(Gen.getSILType(op.OuterResult));
auto tuple = Gen.B.createTuple(Loc, tupleType, elts);
outerDirectResults.resize(firstEltIndex);
outerDirectResults.push_back(tuple);
continue;
}
case Operation::InjectOptionalDirect: {
SILValue value = outerDirectResults.pop_back_val();
auto tupleType = Gen.F.mapTypeIntoContext(Gen.getSILType(op.OuterResult));
SILValue optValue = Gen.B.createEnum(Loc, value, op.SomeDecl, tupleType);
outerDirectResults.push_back(optValue);
continue;
}
case Operation::InjectOptionalIndirect:
Gen.B.createInjectEnumAddr(Loc, op.OuterResultAddr, op.SomeDecl);
continue;
}
llvm_unreachable("bad operation kind");
}
assert(innerDirectResults.empty() && "didn't consume all inner results?");
}
/// Build the body of a transformation thunk.
///
/// \param inputOrigType Abstraction pattern of function value being thunked
/// \param inputSubstType Formal AST type of function value being thunked
/// \param outputOrigType Abstraction pattern of the thunk
/// \param outputSubstType Formal AST type of the thunk
static void buildThunkBody(SILGenFunction &gen, SILLocation loc,
AbstractionPattern inputOrigType,
CanAnyFunctionType inputSubstType,
AbstractionPattern outputOrigType,
CanAnyFunctionType outputSubstType) {
PrettyStackTraceSILFunction stackTrace("emitting reabstraction thunk in",
&gen.F);
auto thunkType = gen.F.getLoweredFunctionType();
FullExpr scope(gen.Cleanups, CleanupLocation::get(loc));
SmallVector<ManagedValue, 8> params;
// TODO: Could accept +0 arguments here when forwardFunctionArguments/
// emitApply can.
gen.collectThunkParams(loc, params, /*allowPlusZero*/ false);
ManagedValue fnValue = params.pop_back_val();
auto fnType = fnValue.getType().castTo<SILFunctionType>();
assert(!fnType->isPolymorphic());
auto argTypes = fnType->getParameters();
// Translate the argument values. Function parameters are
// contravariant: we want to switch the direction of transformation
// on them by flipping inputOrigType and outputOrigType.
//
// For example, a transformation of (Int,Int)->Int to (T,T)->T is
// one that should take an (Int,Int)->Int value and make it be
// abstracted like a (T,T)->T value. This must be done with a thunk.
// Within the thunk body, the result of calling the inner function
// needs to be translated from Int to T (we receive a normal Int
// and return it like a T), but the parameters are translated in the
// other direction (the thunk receives an Int like a T, and passes it
// like a normal Int when calling the inner function).
SmallVector<ManagedValue, 8> args;
TranslateArguments(gen, loc, params, args, argTypes)
.translate(outputOrigType.getFunctionInputType(),
outputSubstType.getInput(),
inputOrigType.getFunctionInputType(),
inputSubstType.getInput());
SmallVector<SILValue, 8> argValues;
// Plan the results. This builds argument values for all the
// inner indirect results.
ResultPlanner resultPlanner(gen, loc);
resultPlanner.plan(inputOrigType.getFunctionResultType(),
inputSubstType.getResult(),
outputOrigType.getFunctionResultType(),
outputSubstType.getResult(),
fnType, thunkType, argValues);
// Add the rest of the arguments.
forwardFunctionArguments(gen, loc, fnType, args, argValues);
SILValue innerResult =
gen.emitApplyWithRethrow(loc, fnValue.forward(gen),
/*substFnType*/ fnValue.getType(),
/*substitutions*/ {},
argValues);
// Reabstract the result.
SILValue outerResult = resultPlanner.execute(innerResult);
scope.pop();
gen.B.createReturn(loc, outerResult);
}
/// Build a generic signature and environment for a re-abstraction thunk.
///
/// Most thunks share the generic environment with their original function.
/// The one exception is if the thunk type involves an open existential,
/// in which case we "promote" the opened existential to a new generic parameter.
///
/// \param gen - the parent function
/// \param openedExistential - the opened existential to promote to a generic
// parameter, if any
/// \param inheritGenericSig - whether to inherit the generic signature from the
/// parent function.
/// \param genericEnv - the new generic environment
/// \param contextSubs - map old archetypes to new archetypes
/// \param interfaceSubs - map interface types to old archetypes
static CanGenericSignature
buildThunkSignature(SILGenFunction &gen,
bool inheritGenericSig,
ArchetypeType *openedExistential,
GenericEnvironment *&genericEnv,
SubstitutionMap &contextSubs,
SubstitutionMap &interfaceSubs,
ArchetypeType *&newArchetype) {
auto *mod = gen.F.getModule().getSwiftModule();
auto &ctx = mod->getASTContext();
// If there's no opened existential, we just inherit the generic environment
// from the parent function.
if (openedExistential == nullptr) {
auto genericSig = gen.F.getLoweredFunctionType()->getGenericSignature();
genericEnv = gen.F.getGenericEnvironment();
auto subsArray = gen.F.getForwardingSubstitutions();
interfaceSubs = genericSig->getSubstitutionMap(subsArray);
contextSubs = interfaceSubs;
return genericSig;
}
GenericSignatureBuilder builder(ctx, LookUpConformanceInModule(mod));
// Add the existing generic signature.
int depth = 0;
if (inheritGenericSig) {
if (auto genericSig = gen.F.getLoweredFunctionType()->getGenericSignature()) {
builder.addGenericSignature(genericSig);
depth = genericSig->getGenericParams().back()->getDepth() + 1;
}
}
// Add a new generic parameter to replace the opened existential.
auto *newGenericParam = GenericTypeParamType::get(depth, 0, ctx);
builder.addGenericParameter(newGenericParam);
Requirement newRequirement(RequirementKind::Conformance, newGenericParam,
openedExistential->getOpenedExistentialType());
auto source =
GenericSignatureBuilder::FloatingRequirementSource::forAbstract();
builder.addRequirement(newRequirement, source, nullptr);
GenericSignature *genericSig =
builder.computeGenericSignature(SourceLoc(),
/*allowConcreteGenericParams=*/true);
genericEnv = genericSig->createGenericEnvironment(*mod);
newArchetype = genericEnv->mapTypeIntoContext(newGenericParam)
->castTo<ArchetypeType>();
// Calculate substitutions to map the caller's archetypes to the thunk's
// archetypes.
if (auto calleeGenericSig = gen.F.getLoweredFunctionType()
->getGenericSignature()) {
contextSubs = calleeGenericSig->getSubstitutionMap(
[&](SubstitutableType *type) -> Type {
return genericEnv->mapTypeIntoContext(type);
},
MakeAbstractConformanceForGenericType());
}
// Calculate substitutions to map interface types to the caller's archetypes.
interfaceSubs = genericSig->getSubstitutionMap(
[&](SubstitutableType *type) -> Type {
if (type->isEqual(newGenericParam))
return openedExistential;
return gen.F.mapTypeIntoContext(type);
},
MakeAbstractConformanceForGenericType());
return genericSig->getCanonicalSignature();
}
/// Build the type of a function transformation thunk.
CanSILFunctionType SILGenFunction::buildThunkType(
CanSILFunctionType &sourceType,
CanSILFunctionType &expectedType,
CanType &inputSubstType,
CanType &outputSubstType,
GenericEnvironment *&genericEnv,
SubstitutionMap &interfaceSubs) {
assert(!expectedType->isPolymorphic());
assert(!sourceType->isPolymorphic());
// Can't build a thunk without context, so we require ownership semantics
// on the result type.
assert(expectedType->getExtInfo().hasContext());
auto extInfo = expectedType->getExtInfo()
.withRepresentation(SILFunctionType::Representation::Thin);
// Does the thunk type involve archetypes other than opened existentials?
bool hasArchetypes = false;
// Does the thunk type involve an open existential type?
CanArchetypeType openedExistential;
auto archetypeVisitor = [&](CanType t) {
if (auto archetypeTy = dyn_cast<ArchetypeType>(t)) {
if (archetypeTy->getOpenedExistentialType()) {
assert((openedExistential == CanArchetypeType() ||
openedExistential == archetypeTy) &&
"one too many open existentials");
openedExistential = archetypeTy;
} else
hasArchetypes = true;
}
};
// Use the generic signature from the context if the thunk involves
// generic parameters.
CanGenericSignature genericSig;
SubstitutionMap contextSubs;
ArchetypeType *newArchetype = nullptr;
if (expectedType->hasArchetype() || sourceType->hasArchetype()) {
expectedType.visit(archetypeVisitor);
sourceType.visit(archetypeVisitor);
genericSig = buildThunkSignature(*this,
hasArchetypes,
openedExistential,
genericEnv,
contextSubs,
interfaceSubs,
newArchetype);
}
// Utility function to apply contextSubs, and also replace the
// opened existential with the new archetype.
auto substIntoThunkContext = [&](CanType t) -> CanType {
return t.subst(
[&](SubstitutableType *type) -> Type {
if (CanType(type) == openedExistential)
return newArchetype;
return Type(type).subst(contextSubs);
},
LookUpConformanceInSubstitutionMap(contextSubs),
SubstFlags::AllowLoweredTypes)
->getCanonicalType();
};
sourceType = cast<SILFunctionType>(
substIntoThunkContext(sourceType));
expectedType = cast<SILFunctionType>(
substIntoThunkContext(expectedType));
if (inputSubstType) {
inputSubstType = cast<AnyFunctionType>(
substIntoThunkContext(inputSubstType));
}
if (outputSubstType) {
outputSubstType = cast<AnyFunctionType>(
substIntoThunkContext(outputSubstType));
}
// If our parent function was pseudogeneric, this thunk must also be
// pseudogeneric, since we have no way to pass generic parameters.
if (genericSig)
if (F.getLoweredFunctionType()->isPseudogeneric())
extInfo = extInfo.withIsPseudogeneric();
// Add the function type as the parameter.
SmallVector<SILParameterInfo, 4> params;
params.append(expectedType->getParameters().begin(),
expectedType->getParameters().end());
params.push_back({sourceType,
sourceType->getExtInfo().hasContext()
? DefaultThickCalleeConvention
: ParameterConvention::Direct_Unowned});
auto &mod = *F.getModule().getSwiftModule();
auto getCanonicalType = [&](Type t) -> CanType {
return t->getCanonicalType(genericSig, mod);
};
// Map the parameter and expected types out of context to get the interface
// type of the thunk.
SmallVector<SILParameterInfo, 4> interfaceParams;
interfaceParams.reserve(params.size());
for (auto ¶m : params) {
auto paramIfaceTy = GenericEnvironment::mapTypeOutOfContext(
genericEnv, param.getType());
interfaceParams.push_back(
SILParameterInfo(getCanonicalType(paramIfaceTy),
param.getConvention()));
}
SmallVector<SILResultInfo, 4> interfaceResults;
for (auto &result : expectedType->getResults()) {
auto resultIfaceTy = GenericEnvironment::mapTypeOutOfContext(
genericEnv, result.getType());
auto interfaceResult = result.getWithType(getCanonicalType(resultIfaceTy));
interfaceResults.push_back(interfaceResult);
}
Optional<SILResultInfo> interfaceErrorResult;
if (expectedType->hasErrorResult()) {
auto errorResult = expectedType->getErrorResult();
auto errorIfaceTy = GenericEnvironment::mapTypeOutOfContext(
genericEnv, errorResult.getType());
interfaceErrorResult = SILResultInfo(
getCanonicalType(errorIfaceTy),
expectedType->getErrorResult().getConvention());
}
// The type of the thunk function.
return SILFunctionType::get(genericSig, extInfo,
ParameterConvention::Direct_Unowned,
interfaceParams, interfaceResults,
interfaceErrorResult,
getASTContext());
}
/// Create a reabstraction thunk.
static ManagedValue createThunk(SILGenFunction &gen,
SILLocation loc,
ManagedValue fn,
AbstractionPattern inputOrigType,
CanAnyFunctionType inputSubstType,
AbstractionPattern outputOrigType,
CanAnyFunctionType outputSubstType,
const TypeLowering &expectedTL) {
auto sourceType = fn.getType().castTo<SILFunctionType>();
auto expectedType = expectedTL.getLoweredType().castTo<SILFunctionType>();
// We can't do bridging here.
assert(expectedType->getLanguage() ==
fn.getType().castTo<SILFunctionType>()->getLanguage() &&
"bridging in re-abstraction thunk?");
// Declare the thunk.
SubstitutionMap interfaceSubs;
GenericEnvironment *genericEnv = nullptr;
auto toType = expectedType;
auto thunkType = gen.buildThunkType(sourceType, toType,
inputSubstType,
outputSubstType,
genericEnv,
interfaceSubs);
auto thunk = gen.SGM.getOrCreateReabstractionThunk(
genericEnv,
thunkType,
sourceType,
toType,
gen.F.isSerialized());
// Build it if necessary.
if (thunk->empty()) {
thunk->setGenericEnvironment(genericEnv);
SILGenFunction thunkSGF(gen.SGM, *thunk);
auto loc = RegularLocation::getAutoGeneratedLocation();
buildThunkBody(thunkSGF, loc,
inputOrigType,
inputSubstType,
outputOrigType,
outputSubstType);
}
CanSILFunctionType substFnType = thunkType;
SmallVector<Substitution, 4> subs;
if (auto genericSig = thunkType->getGenericSignature()) {
genericSig->getSubstitutions(interfaceSubs, subs);
substFnType = thunkType->substGenericArgs(gen.F.getModule(),
interfaceSubs);
}
// Create it in our current function.
auto thunkValue = gen.B.createFunctionRef(loc, thunk);
auto thunkedFn = gen.B.createPartialApply(loc, thunkValue,
SILType::getPrimitiveObjectType(substFnType),
subs, fn.forward(gen),
SILType::getPrimitiveObjectType(expectedType));
return gen.emitManagedRValueWithCleanup(thunkedFn, expectedTL);
}
ManagedValue Transform::transformFunction(ManagedValue fn,
AbstractionPattern inputOrigType,
CanAnyFunctionType inputSubstType,
AbstractionPattern outputOrigType,
CanAnyFunctionType outputSubstType,
const TypeLowering &expectedTL) {
assert(fn.getType().isObject() &&
"expected input to emitTransformedFunctionValue to be loaded");
auto expectedFnType = expectedTL.getLoweredType().castTo<SILFunctionType>();
auto fnType = fn.getType().castTo<SILFunctionType>();
assert(expectedFnType->getExtInfo().hasContext()
|| !fnType->getExtInfo().hasContext());
// If there's no abstraction difference, we're done.
if (fnType == expectedFnType) {
return fn;
}
// Check if we require a re-abstraction thunk.
if (SGF.SGM.Types.checkForABIDifferences(
SILType::getPrimitiveObjectType(fnType),
SILType::getPrimitiveObjectType(expectedFnType))
== TypeConverter::ABIDifference::NeedsThunk) {
assert(expectedFnType->getExtInfo().hasContext()
&& "conversion thunk will not be thin!");
return createThunk(SGF, Loc, fn,
inputOrigType, inputSubstType,
outputOrigType, outputSubstType,
expectedTL);
}
// We do not, conversion is trivial.
auto expectedEI = expectedFnType->getExtInfo();
auto newEI = expectedEI.withRepresentation(fnType->getRepresentation());
auto newFnType = adjustFunctionType(expectedFnType, newEI,
fnType->getCalleeConvention());
// Apply any ABI-compatible conversions before doing thin-to-thick.
if (fnType != newFnType) {
SILType resTy = SILType::getPrimitiveObjectType(newFnType);
fn = ManagedValue(
SGF.B.createConvertFunction(Loc, fn.getValue(), resTy),
fn.getCleanup());
}
// Now do thin-to-thick if necessary.
if (newFnType != expectedFnType) {
assert(expectedEI.getRepresentation() ==
SILFunctionTypeRepresentation::Thick &&
"all other conversions should have been handled by "
"FunctionConversionExpr");
SILType resTy = SILType::getPrimitiveObjectType(expectedFnType);
fn = SGF.emitManagedRValueWithCleanup(
SGF.B.createThinToThickFunction(Loc, fn.forward(SGF), resTy));
}
return fn;
}
/// Given a value with the abstraction patterns of the original formal
/// type, give it the abstraction patterns of the substituted formal type.
ManagedValue
SILGenFunction::emitOrigToSubstValue(SILLocation loc, ManagedValue v,
AbstractionPattern origType,
CanType substType,
SGFContext ctxt) {
return emitTransformedValue(loc, v,
origType, substType,
AbstractionPattern(substType), substType,
ctxt);
}
/// Given a value with the abstraction patterns of the original formal
/// type, give it the abstraction patterns of the substituted formal type.
RValue SILGenFunction::emitOrigToSubstValue(SILLocation loc, RValue &&v,
AbstractionPattern origType,
CanType substType,
SGFContext ctxt) {
return emitTransformedValue(loc, std::move(v),
origType, substType,
AbstractionPattern(substType), substType,
ctxt);
}
/// Given a value with the abstraction patterns of the substituted
/// formal type, give it the abstraction patterns of the original
/// formal type.
ManagedValue
SILGenFunction::emitSubstToOrigValue(SILLocation loc, ManagedValue v,
AbstractionPattern origType,
CanType substType,
SGFContext ctxt) {
return emitTransformedValue(loc, v,
AbstractionPattern(substType), substType,
origType, substType,
ctxt);
}
/// Given a value with the abstraction patterns of the substituted
/// formal type, give it the abstraction patterns of the original
/// formal type.
RValue SILGenFunction::emitSubstToOrigValue(SILLocation loc, RValue &&v,
AbstractionPattern origType,
CanType substType,
SGFContext ctxt) {
return emitTransformedValue(loc, std::move(v),
AbstractionPattern(substType), substType,
origType, substType,
ctxt);
}
ManagedValue
SILGenFunction::emitMaterializedRValueAsOrig(Expr *expr,
AbstractionPattern origType) {
// Create a temporary.
auto &origTL = getTypeLowering(origType, expr->getType());
auto temporary = emitTemporary(expr, origTL);
// Emit the reabstracted r-value.
auto result =
emitRValueAsOrig(expr, origType, origTL, SGFContext(temporary.get()));
// Force the result into the temporary.
if (!result.isInContext()) {
temporary->copyOrInitValueInto(*this, expr, result, /*init*/ true);
temporary->finishInitialization(*this);
}
return temporary->getManagedAddress();
}
ManagedValue
SILGenFunction::emitRValueAsOrig(Expr *expr, AbstractionPattern origPattern,
const TypeLowering &origTL, SGFContext ctxt) {
auto outputSubstType = expr->getType()->getCanonicalType();
auto &substTL = getTypeLowering(outputSubstType);
if (substTL.getLoweredType() == origTL.getLoweredType())
return emitRValueAsSingleValue(expr, ctxt);
ManagedValue temp = emitRValueAsSingleValue(expr);
return emitSubstToOrigValue(expr, temp, origPattern,
outputSubstType, ctxt);
}
ManagedValue
SILGenFunction::emitTransformedValue(SILLocation loc, ManagedValue v,
CanType inputType,
CanType outputType,
SGFContext ctxt) {
return emitTransformedValue(loc, v,
AbstractionPattern(inputType), inputType,
AbstractionPattern(outputType), outputType);
}
ManagedValue
SILGenFunction::emitTransformedValue(SILLocation loc, ManagedValue v,
AbstractionPattern inputOrigType,
CanType inputSubstType,
AbstractionPattern outputOrigType,
CanType outputSubstType,
SGFContext ctxt) {
return Transform(*this, loc).transform(v,
inputOrigType,
inputSubstType,
outputOrigType,
outputSubstType, ctxt);
}
RValue
SILGenFunction::emitTransformedValue(SILLocation loc, RValue &&v,
AbstractionPattern inputOrigType,
CanType inputSubstType,
AbstractionPattern outputOrigType,
CanType outputSubstType,
SGFContext ctxt) {
return Transform(*this, loc).transform(std::move(v),
inputOrigType,
inputSubstType,
outputOrigType,
outputSubstType, ctxt);
}
//===----------------------------------------------------------------------===//
// vtable thunks
//===----------------------------------------------------------------------===//
void
SILGenFunction::emitVTableThunk(SILDeclRef derived,
SILFunction *implFn,
AbstractionPattern inputOrigType,
CanAnyFunctionType inputSubstType,
CanAnyFunctionType outputSubstType) {
auto fd = cast<AbstractFunctionDecl>(derived.getDecl());
SILLocation loc(fd);
loc.markAutoGenerated();
CleanupLocation cleanupLoc(fd);
cleanupLoc.markAutoGenerated();
Scope scope(Cleanups, cleanupLoc);
auto fTy = implFn->getLoweredFunctionType();
SubstitutionList subs;
if (auto *genericEnv = fd->getGenericEnvironment()) {
F.setGenericEnvironment(genericEnv);
subs = getForwardingSubstitutions();
fTy = fTy->substGenericArgs(SGM.M, subs);
inputSubstType = cast<FunctionType>(
cast<GenericFunctionType>(inputSubstType)
->substGenericArgs(subs)->getCanonicalType());
outputSubstType = cast<FunctionType>(
cast<GenericFunctionType>(outputSubstType)
->substGenericArgs(subs)->getCanonicalType());
}
// Emit the indirect return and arguments.
auto thunkTy = F.getLoweredFunctionType();
SmallVector<ManagedValue, 8> thunkArgs;
collectThunkParams(loc, thunkArgs, /*allowPlusZero*/ true);
SmallVector<ManagedValue, 8> substArgs;
AbstractionPattern outputOrigType(outputSubstType);
// Reabstract the arguments.
TranslateArguments(*this, loc, thunkArgs, substArgs, fTy->getParameters())
.translate(inputOrigType.getFunctionInputType(),
inputSubstType.getInput(),
outputOrigType.getFunctionInputType(),
outputSubstType.getInput());
// Collect the arguments to the implementation.
SmallVector<SILValue, 8> args;
// First, indirect results.
ResultPlanner resultPlanner(*this, loc);
resultPlanner.plan(outputOrigType.getFunctionResultType(),
outputSubstType.getResult(),
inputOrigType.getFunctionResultType(),
inputSubstType.getResult(),
fTy, thunkTy, args);
// Then, the arguments.
forwardFunctionArguments(*this, loc, fTy, substArgs, args);
// Create the call.
auto implRef = B.createFunctionRef(loc, implFn);
SILValue implResult = emitApplyWithRethrow(loc, implRef,
SILType::getPrimitiveObjectType(fTy),
subs, args);
// Reabstract the return.
SILValue result = resultPlanner.execute(implResult);
scope.pop();
B.createReturn(loc, result);
}
//===----------------------------------------------------------------------===//
// Protocol witnesses
//===----------------------------------------------------------------------===//
enum class WitnessDispatchKind {
Static,
Dynamic,
Class
};
static WitnessDispatchKind
getWitnessDispatchKind(Type selfType, SILDeclRef witness, bool isFree) {
// Free functions are always statically dispatched...
if (isFree)
return WitnessDispatchKind::Static;
// If we have a non-class, non-objc method or a class, objc method that is
// final, we do not dynamic dispatch.
ClassDecl *C = selfType->getClassOrBoundGenericClass();
if (!C)
return WitnessDispatchKind::Static;
auto *decl = witness.getDecl();
// If the witness is dynamic, go through dynamic dispatch.
if (decl->isDynamic())
return WitnessDispatchKind::Dynamic;
bool isFinal = (decl->isFinal() || C->isFinal());
if (auto fnDecl = dyn_cast<AbstractFunctionDecl>(witness.getDecl()))
isFinal |= fnDecl->hasForcedStaticDispatch();
bool isExtension = isa<ExtensionDecl>(decl->getDeclContext());
// If we have a final method or a method from an extension that is not
// Objective-C, emit a static reference.
// A natively ObjC method witness referenced this way will end up going
// through its native thunk, which will redispatch the method after doing
// bridging just like we want.
if (isFinal || isExtension || witness.isForeignToNativeThunk()
// Hack--We emit a static thunk for ObjC allocating constructors.
|| (decl->hasClangNode() && witness.kind == SILDeclRef::Kind::Allocator))
return WitnessDispatchKind::Static;
// Otherwise emit a class method.
return WitnessDispatchKind::Class;
}
static CanSILFunctionType
getWitnessFunctionType(SILGenModule &SGM,
SILDeclRef witness,
WitnessDispatchKind witnessKind) {
switch (witnessKind) {
case WitnessDispatchKind::Static:
case WitnessDispatchKind::Dynamic:
return SGM.Types.getConstantInfo(witness).SILFnType;
case WitnessDispatchKind::Class:
return SGM.Types.getConstantOverrideType(witness);
}
llvm_unreachable("Unhandled WitnessDispatchKind in switch.");
}
static SILValue
getWitnessFunctionRef(SILGenFunction &gen,
SILDeclRef witness,
WitnessDispatchKind witnessKind,
SmallVectorImpl<ManagedValue> &witnessParams,
SILLocation loc) {
SILGenModule &SGM = gen.SGM;
switch (witnessKind) {
case WitnessDispatchKind::Static:
return gen.emitGlobalFunctionRef(loc, witness);
case WitnessDispatchKind::Dynamic:
return gen.emitDynamicMethodRef(loc, witness,
SGM.Types.getConstantInfo(witness));
case WitnessDispatchKind::Class:
SILValue selfPtr = witnessParams.back().getValue();
return gen.B.createClassMethod(loc, selfPtr, witness);
}
llvm_unreachable("Unhandled WitnessDispatchKind in switch.");
}
static CanType dropLastElement(CanType type) {
auto elts = cast<TupleType>(type)->getElements().drop_back();
return TupleType::get(elts, type->getASTContext())->getCanonicalType();
}
void SILGenFunction::emitProtocolWitness(Type selfType,
AbstractionPattern reqtOrigTy,
CanAnyFunctionType reqtSubstTy,
SILDeclRef requirement,
SILDeclRef witness,
SubstitutionList witnessSubs,
IsFreeFunctionWitness_t isFree) {
// FIXME: Disable checks that the protocol witness carries debug info.
// Should we carry debug info for witnesses?
F.setBare(IsBare);
SILLocation loc(witness.getDecl());
FullExpr scope(Cleanups, CleanupLocation::get(loc));
FormalEvaluationScope formalEvalScope(*this);
auto witnessKind = getWitnessDispatchKind(selfType, witness, isFree);
auto thunkTy = F.getLoweredFunctionType();
SmallVector<ManagedValue, 8> origParams;
// TODO: Should be able to accept +0 values here, once
// forwardFunctionArguments/emitApply are able to.
collectThunkParams(loc, origParams, /*allowPlusZero*/ false);
// Handle special abstraction differences in "self".
// If the witness is a free function, drop it completely.
// WAY SPECULATIVE TODO: What if 'self' comprised multiple SIL-level params?
if (isFree)
origParams.pop_back();
// Get the type of the witness.
auto witnessInfo = getConstantInfo(witness);
CanAnyFunctionType witnessSubstTy = witnessInfo.LoweredInterfaceType;
if (!witnessSubs.empty()) {
witnessSubstTy = cast<FunctionType>(
cast<GenericFunctionType>(witnessSubstTy)
->substGenericArgs(witnessSubs)
->getCanonicalType());
}
CanType reqtSubstInputTy = F.mapTypeIntoContext(reqtSubstTy.getInput())
->getCanonicalType();
CanType reqtSubstResultTy = F.mapTypeIntoContext(reqtSubstTy.getResult())
->getCanonicalType();
AbstractionPattern reqtOrigInputTy = reqtOrigTy.getFunctionInputType();
// For a free function witness, discard the 'self' parameter of the
// requirement.
if (isFree) {
reqtOrigInputTy = reqtOrigInputTy.dropLastTupleElement();
reqtSubstInputTy = dropLastElement(reqtSubstInputTy);
}
// Translate the argument values from the requirement abstraction level to
// the substituted signature of the witness.
auto witnessFTy = getWitnessFunctionType(SGM, witness, witnessKind);
if (!witnessSubs.empty())
witnessFTy = witnessFTy->substGenericArgs(SGM.M, witnessSubs);
SmallVector<ManagedValue, 8> witnessParams;
if (!isFree) {
// If the requirement has a self parameter passed as an indirect +0 value,
// and the witness takes it as a non-inout value, we must load and retain
// the self pointer coming in. This happens when class witnesses implement
// non-mutating protocol requirements.
auto reqConvention = thunkTy->getSelfParameter().getConvention();
auto witnessConvention = witnessFTy->getSelfParameter().getConvention();
bool inoutDifference;
inoutDifference = reqConvention == ParameterConvention::Indirect_Inout &&
witnessConvention != ParameterConvention::Indirect_Inout;
if (inoutDifference) {
// If there is an inout difference in self, load the inout self parameter.
ManagedValue &selfParam = origParams.back();
SILValue selfAddr = selfParam.getUnmanagedValue();
selfParam = emitLoad(loc, selfAddr,
getTypeLowering(selfType),
SGFContext(),
IsNotTake);
}
}
AbstractionPattern witnessOrigTy(witnessInfo.LoweredInterfaceType);
TranslateArguments(*this, loc,
origParams, witnessParams,
witnessFTy->getParameters())
.translate(reqtOrigInputTy,
reqtSubstInputTy,
witnessOrigTy.getFunctionInputType(),
witnessSubstTy.getInput());
SILValue witnessFnRef = getWitnessFunctionRef(*this, witness, witnessKind,
witnessParams, loc);
// Collect the arguments.
SmallVector<SILValue, 8> args;
// - indirect results
ResultPlanner resultPlanner(*this, loc);
resultPlanner.plan(witnessOrigTy.getFunctionResultType(),
witnessSubstTy.getResult(),
reqtOrigTy.getFunctionResultType(),
reqtSubstResultTy,
witnessFTy, thunkTy, args);
// - the rest of the arguments
forwardFunctionArguments(*this, loc, witnessFTy, witnessParams, args);
// Perform the call.
SILType witnessSILTy = SILType::getPrimitiveObjectType(witnessFTy);
SILValue witnessResultValue =
emitApplyWithRethrow(loc, witnessFnRef, witnessSILTy, witnessSubs, args);
// Reabstract the result value.
SILValue reqtResultValue = resultPlanner.execute(witnessResultValue);
scope.pop();
B.createReturn(loc, reqtResultValue);
}
| calebd/swift | lib/SILGen/SILGenPoly.cpp | C++ | apache-2.0 | 141,662 |
#==========================================================================
#
# Copyright Insight Software Consortium
#
# Licensed 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.txt
#
# 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.
#
#==========================================================================*/
#
# Example on the use of the SmoothingRecursiveGaussianImageFilter
#
import itk
from sys import argv
itk.auto_progress(2)
dim = 2
IType = itk.Image[itk.F, dim]
OIType = itk.Image[itk.UC, dim]
reader = itk.ImageFileReader[IType].New( FileName=argv[1] )
filter = itk.SmoothingRecursiveGaussianImageFilter[IType, IType].New( reader,
Sigma=eval( argv[3] ) )
cast = itk.RescaleIntensityImageFilter[IType, OIType].New(filter,
OutputMinimum=0,
OutputMaximum=255)
writer = itk.ImageFileWriter[OIType].New( cast, FileName=argv[2] )
writer.Update()
| daviddoria/itkHoughTransform | Wrapping/WrapITK/Languages/Python/Tests/SmoothingRecursiveGaussianImageFilter.py | Python | apache-2.0 | 1,366 |
/*
* Minio Cloud Storage, (C) 2019 Minio, Inc.
*
* Licensed 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 parquet
import (
"encoding/binary"
)
func uint32ToBytes(v uint32) []byte {
buf := make([]byte, 4)
binary.LittleEndian.PutUint32(buf, v)
return buf
}
func bytesToUint32(buf []byte) uint32 {
return binary.LittleEndian.Uint32(buf)
}
func bytesToUint64(buf []byte) uint64 {
return binary.LittleEndian.Uint64(buf)
}
| aead/minio | pkg/s3select/internal/parquet-go/endian.go | GO | apache-2.0 | 940 |
var welcomeText = (
' ____ _ ____ \n'+
'| _ \\ __ __ | / ___| \n'+
'| |_) |\\ \\/ / | \\___ \\ \n'+
'| _ < > < |_| |___) | \n'+
'|_| \\_\\/_/\\_\\___/|____/ \n'+
'\n试试下面这段代码来开启 RxJS 之旅:\n'+
'\n var subscription = Rx.Observable.interval(500)'+
'.take(4).subscribe(function (x) { console.log(x) });\n'+
'\n还引入了 rxjs-spy 来帮助你调试 RxJS 代码,试试下面这段代码:\n'+
'\n rxSpy.spy();'+
'\n var subscription = Rx.Observable.interval(500)'+
'.tag("interval").subscribe();'+
'\n rxSpy.show();'+
'\n rxSpy.log("interval");\n'+
'\n 想了解更多 rxjs-spy 的用法,请查阅 https://zhuanlan.zhihu.com/p/30870431'
);
if (console.info) {
console.info(welcomeText);
} else {
console.log(welcomeText);
}
| SangKa/RxJS-Docs-CN | doc/asset/devtools-welcome.js | JavaScript | apache-2.0 | 826 |
/*
* Copyright (C) 2011 The Bible Assistant Open Source Project
*
* Licensed 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.heavenus.bible.generator;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import android.text.TextUtils;
/*
* Book content format:
* <section_name><TAB><section_content>
* <section_name><TAB><section_content>
* ...
*/
class Book {
public class Section {
public String name;
public String content;
}
private String mName;
private ArrayList<Section> mSections = new ArrayList<Section>();
public Book(File f) throws IOException {
mName = Path.getFileNameWithoutExtension(f.getAbsolutePath());
init(f);
}
public String getName() {
return mName;
}
public int getSectionCount() {
return mSections.size();
}
public Section getSection(int index) {
if(index >= 0 && index < mSections.size()) {
return mSections.get(index);
}
return null;
}
private void init(File book) throws IOException {
InputStream in = null;
try {
// Read all book content.
in = new BufferedInputStream(new FileInputStream(book));
byte[] data = new byte[in.available()];
in.read(data);
// Skip beginning encoding data.
String content = new String(data).substring(1);
// Parse every line.
String[] rows = content.split("\r\n");
for(String r : rows) {
// Parse every field.
if(!TextUtils.isEmpty(r)) {
String[] fields = r.split("\t");
int count = fields.length;
if(count > 0) {
// Add new section.
Section s = new Section();
s.name = fields[0].trim();
s.content = (count > 1 ? fields[1] : "");
mSections.add(s);
}
}
}
} finally {
if (in != null) {
in.close();
}
}
}
} | johnidelight/bible-assistant | platform/android/tool/BibleGenerator/src/org/heavenus/bible/generator/Book.java | Java | apache-2.0 | 2,467 |
// Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.
//
// Licensed 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 main
// typedef struct {
// char *value;
// int len;
// } buf;
//
// typedef struct path_t {
// buf nlri;
// buf** path_attributes;
// int path_attributes_len;
// int path_attributes_cap;
// } path;
// extern path* new_path();
// extern void free_path(path*);
// extern int append_path_attribute(path*, int, char*);
// extern buf* get_path_attribute(path*, int);
import "C"
import (
"encoding/json"
"strings"
"github.com/osrg/gobgp/gobgp/cmd"
"github.com/osrg/gobgp/packet/bgp"
)
//export get_route_family
func get_route_family(input *C.char) C.int {
rf, err := bgp.GetRouteFamily(C.GoString(input))
if err != nil {
return C.int(-1)
}
return C.int(rf)
}
//export serialize_path
func serialize_path(rf C.int, input *C.char) *C.path {
args := strings.Split(C.GoString(input), " ")
p, err := cmd.ParsePath(bgp.RouteFamily(rf), args)
if err != nil {
return nil
}
path := C.new_path()
if len(p.Nlri) > 0 {
path.nlri.len = C.int(len(p.Nlri))
path.nlri.value = C.CString(string(p.Nlri))
}
for _, attr := range p.Pattrs {
C.append_path_attribute(path, C.int(len(attr)), C.CString(string(attr)))
}
return path
}
//export decode_path
func decode_path(p *C.path) *C.char {
var buf []byte
var nlri bgp.AddrPrefixInterface
if p.nlri.len > 0 {
buf = []byte(C.GoStringN(p.nlri.value, p.nlri.len))
nlri = &bgp.IPAddrPrefix{}
err := nlri.DecodeFromBytes(buf)
if err != nil {
return nil
}
}
pattrs := make([]bgp.PathAttributeInterface, 0, int(p.path_attributes_len))
for i := 0; i < int(p.path_attributes_len); i++ {
b := C.get_path_attribute(p, C.int(i))
buf = []byte(C.GoStringN(b.value, b.len))
pattr, err := bgp.GetPathAttribute(buf)
if err != nil {
return nil
}
err = pattr.DecodeFromBytes(buf)
if err != nil {
return nil
}
switch pattr.GetType() {
case bgp.BGP_ATTR_TYPE_MP_REACH_NLRI:
mpreach := pattr.(*bgp.PathAttributeMpReachNLRI)
if len(mpreach.Value) != 1 {
return nil
}
nlri = mpreach.Value[0]
}
pattrs = append(pattrs, pattr)
}
j, _ := json.Marshal(struct {
Nlri bgp.AddrPrefixInterface `json:"nlri"`
PathAttrs []bgp.PathAttributeInterface `json:"attrs"`
}{
Nlri: nlri,
PathAttrs: pattrs,
})
return C.CString(string(j))
}
//export decode_capabilities
func decode_capabilities(p *C.buf) *C.char {
buf := []byte(C.GoStringN(p.value, p.len))
c, err := bgp.DecodeCapability(buf)
if err != nil {
return nil
}
j, _ := json.Marshal(c)
return C.CString(string(j))
}
func main() {
// We need the main function to make possible
// CGO compiler to compile the package as C shared library
}
| ramrunner/gobgp | gobgp/lib/path.go | GO | apache-2.0 | 3,283 |
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "prmem.h"
#include "gfxAlphaRecovery.h"
#include "gfxImageSurface.h"
#include "cairo.h"
#include "mozilla/gfx/2D.h"
#include "gfx2DGlue.h"
using namespace mozilla::gfx;
gfxImageSurface::gfxImageSurface()
: mSize(0, 0),
mOwnsData(false),
mFormat(ImageFormatUnknown),
mStride(0)
{
}
void
gfxImageSurface::InitFromSurface(cairo_surface_t *csurf)
{
mSize.width = cairo_image_surface_get_width(csurf);
mSize.height = cairo_image_surface_get_height(csurf);
mData = cairo_image_surface_get_data(csurf);
mFormat = (gfxImageFormat) cairo_image_surface_get_format(csurf);
mOwnsData = false;
mStride = cairo_image_surface_get_stride(csurf);
Init(csurf, true);
}
gfxImageSurface::gfxImageSurface(unsigned char *aData, const gfxIntSize& aSize,
long aStride, gfxImageFormat aFormat)
{
InitWithData(aData, aSize, aStride, aFormat);
}
void
gfxImageSurface::MakeInvalid()
{
mSize = gfxIntSize(-1, -1);
mData = NULL;
mStride = 0;
}
void
gfxImageSurface::InitWithData(unsigned char *aData, const gfxIntSize& aSize,
long aStride, gfxImageFormat aFormat)
{
mSize = aSize;
mOwnsData = false;
mData = aData;
mFormat = aFormat;
mStride = aStride;
if (!CheckSurfaceSize(aSize))
MakeInvalid();
cairo_surface_t *surface =
cairo_image_surface_create_for_data((unsigned char*)mData,
(cairo_format_t)mFormat,
mSize.width,
mSize.height,
mStride);
// cairo_image_surface_create_for_data can return a 'null' surface
// in out of memory conditions. The gfxASurface::Init call checks
// the surface it receives to see if there is an error with the
// surface and handles it appropriately. That is why there is
// no check here.
Init(surface);
}
static void*
TryAllocAlignedBytes(size_t aSize)
{
// Use fallible allocators here
#if defined(HAVE_POSIX_MEMALIGN)
void* ptr;
// Try to align for fast alpha recovery. This should only help
// cairo too, can't hurt.
return moz_posix_memalign(&ptr,
1 << gfxAlphaRecovery::GoodAlignmentLog2(),
aSize) ?
nullptr : ptr;
#else
// Oh well, hope that luck is with us in the allocator
return moz_malloc(aSize);
#endif
}
gfxImageSurface::gfxImageSurface(const gfxIntSize& size, gfxImageFormat format, bool aClear) :
mSize(size), mOwnsData(false), mData(nullptr), mFormat(format)
{
mStride = ComputeStride();
if (!CheckSurfaceSize(size))
MakeInvalid();
// if we have a zero-sized surface, just leave mData nullptr
if (mSize.height * mStride > 0) {
// This can fail to allocate memory aligned as we requested,
// or it can fail to allocate any memory at all.
mData = (unsigned char *) TryAllocAlignedBytes(mSize.height * mStride);
if (!mData)
return;
if (aClear)
memset(mData, 0, mSize.height * mStride);
}
mOwnsData = true;
cairo_surface_t *surface =
cairo_image_surface_create_for_data((unsigned char*)mData,
(cairo_format_t)format,
mSize.width,
mSize.height,
mStride);
Init(surface);
if (mSurfaceValid) {
RecordMemoryUsed(mSize.height * ComputeStride() +
sizeof(gfxImageSurface));
}
}
gfxImageSurface::gfxImageSurface(cairo_surface_t *csurf)
{
mSize.width = cairo_image_surface_get_width(csurf);
mSize.height = cairo_image_surface_get_height(csurf);
mData = cairo_image_surface_get_data(csurf);
mFormat = (gfxImageFormat) cairo_image_surface_get_format(csurf);
mOwnsData = false;
mStride = cairo_image_surface_get_stride(csurf);
Init(csurf, true);
}
gfxImageSurface::~gfxImageSurface()
{
if (mOwnsData)
free(mData);
}
/*static*/ long
gfxImageSurface::ComputeStride(const gfxIntSize& aSize, gfxImageFormat aFormat)
{
long stride;
if (aFormat == ImageFormatARGB32)
stride = aSize.width * 4;
else if (aFormat == ImageFormatRGB24)
stride = aSize.width * 4;
else if (aFormat == ImageFormatRGB16_565)
stride = aSize.width * 2;
else if (aFormat == ImageFormatA8)
stride = aSize.width;
else if (aFormat == ImageFormatA1) {
stride = (aSize.width + 7) / 8;
} else {
NS_WARNING("Unknown format specified to gfxImageSurface!");
stride = aSize.width * 4;
}
stride = ((stride + 3) / 4) * 4;
return stride;
}
// helper function for the CopyFrom methods
static void
CopyForStride(unsigned char* aDest, unsigned char* aSrc, const gfxIntSize& aSize, long aDestStride, long aSrcStride)
{
if (aDestStride == aSrcStride) {
memcpy (aDest, aSrc, aSrcStride * aSize.height);
} else {
int lineSize = NS_MIN(aDestStride, aSrcStride);
for (int i = 0; i < aSize.height; i++) {
unsigned char* src = aSrc + aSrcStride * i;
unsigned char* dst = aDest + aDestStride * i;
memcpy (dst, src, lineSize);
}
}
}
// helper function for the CopyFrom methods
static bool
FormatsAreCompatible(gfxASurface::gfxImageFormat a1, gfxASurface::gfxImageFormat a2)
{
if (a1 != a2 &&
!(a1 == gfxASurface::ImageFormatARGB32 &&
a2 == gfxASurface::ImageFormatRGB24) &&
!(a1 == gfxASurface::ImageFormatRGB24 &&
a2 == gfxASurface::ImageFormatARGB32)) {
return false;
}
return true;
}
bool
gfxImageSurface::CopyFrom (SourceSurface *aSurface)
{
mozilla::RefPtr<DataSourceSurface> data = aSurface->GetDataSurface();
if (!data) {
return false;
}
gfxIntSize size(data->GetSize().width, data->GetSize().height);
if (size != mSize) {
return false;
}
if (!FormatsAreCompatible(SurfaceFormatToImageFormat(aSurface->GetFormat()),
mFormat)) {
return false;
}
CopyForStride(mData, data->GetData(), size, mStride, data->Stride());
return true;
}
bool
gfxImageSurface::CopyFrom(gfxImageSurface *other)
{
if (other->mSize != mSize) {
return false;
}
if (!FormatsAreCompatible(other->mFormat, mFormat)) {
return false;
}
CopyForStride(mData, other->mData, mSize, mStride, other->mStride);
return true;
}
already_AddRefed<gfxSubimageSurface>
gfxImageSurface::GetSubimage(const gfxRect& aRect)
{
gfxRect r(aRect);
r.Round();
unsigned char* subData = Data() +
(Stride() * (int)r.Y()) +
(int)r.X() * gfxASurface::BytePerPixelFromFormat(Format());
nsRefPtr<gfxSubimageSurface> image =
new gfxSubimageSurface(this, subData,
gfxIntSize((int)r.Width(), (int)r.Height()));
return image.forget().get();
}
gfxSubimageSurface::gfxSubimageSurface(gfxImageSurface* aParent,
unsigned char* aData,
const gfxIntSize& aSize)
: gfxImageSurface(aData, aSize, aParent->Stride(), aParent->Format())
, mParent(aParent)
{
}
already_AddRefed<gfxImageSurface>
gfxImageSurface::GetAsImageSurface()
{
nsRefPtr<gfxImageSurface> surface = this;
return surface.forget();
}
void
gfxImageSurface::MovePixels(const nsIntRect& aSourceRect,
const nsIntPoint& aDestTopLeft)
{
const nsIntRect bounds(0, 0, mSize.width, mSize.height);
nsIntPoint offset = aDestTopLeft - aSourceRect.TopLeft();
nsIntRect clippedSource = aSourceRect;
clippedSource.IntersectRect(clippedSource, bounds);
nsIntRect clippedDest = clippedSource + offset;
clippedDest.IntersectRect(clippedDest, bounds);
const nsIntRect dest = clippedDest;
const nsIntRect source = dest - offset;
// NB: this relies on IntersectRect() and operator+/- preserving
// x/y for empty rectangles
NS_ABORT_IF_FALSE(bounds.Contains(dest) && bounds.Contains(source) &&
aSourceRect.Contains(source) &&
nsIntRect(aDestTopLeft, aSourceRect.Size()).Contains(dest) &&
source.Size() == dest.Size() &&
offset == (dest.TopLeft() - source.TopLeft()),
"Messed up clipping, crash or corruption will follow");
if (source.IsEmpty() || source.IsEqualInterior(dest)) {
return;
}
long naturalStride = ComputeStride(mSize, mFormat);
if (mStride == naturalStride && dest.width == bounds.width) {
// Fast path: this is a vertical shift of some rows in a
// "normal" image surface. We can directly memmove and
// hopefully stay in SIMD land.
unsigned char* dst = mData + dest.y * mStride;
const unsigned char* src = mData + source.y * mStride;
size_t nBytes = dest.height * mStride;
memmove(dst, src, nBytes);
return;
}
// Slow(er) path: have to move row-by-row.
const int32_t bpp = BytePerPixelFromFormat(mFormat);
const size_t nRowBytes = dest.width * bpp;
// dstRow points at the first pixel within the current destination
// row, and similarly for srcRow. endSrcRow is one row beyond the
// last row we need to copy. stride is either +mStride or
// -mStride, depending on which direction we're copying.
unsigned char* dstRow;
unsigned char* srcRow;
unsigned char* endSrcRow; // NB: this may point outside the image
long stride;
if (dest.y > source.y) {
// We're copying down from source to dest, so walk backwards
// starting from the last rows to avoid stomping pixels we
// need.
stride = -mStride;
dstRow = mData + dest.x * bpp + (dest.YMost() - 1) * mStride;
srcRow = mData + source.x * bpp + (source.YMost() - 1) * mStride;
endSrcRow = mData + source.x * bpp + (source.y - 1) * mStride;
} else {
stride = mStride;
dstRow = mData + dest.x * bpp + dest.y * mStride;
srcRow = mData + source.x * bpp + source.y * mStride;
endSrcRow = mData + source.x * bpp + source.YMost() * mStride;
}
for (; srcRow != endSrcRow; dstRow += stride, srcRow += stride) {
memmove(dstRow, srcRow, nRowBytes);
}
}
| sergecodd/FireFox-OS | B2G/gecko/gfx/thebes/gfxImageSurface.cpp | C++ | apache-2.0 | 10,870 |
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed 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.
==============================================================================*/
#include <cstddef>
#include <cstdint>
#include <string>
#include <utility>
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Debug.h"
#include "mlir/Pass/Pass.h" // from @llvm-project
#include "mlir/Pass/PassManager.h" // from @llvm-project
#include "mlir/Support/LLVM.h" // from @llvm-project
#include "mlir/Transforms/Passes.h" // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/analysis/resource_alias_analysis.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
namespace mlir {
namespace TF {
namespace {
// A pass that annotates each operation with a resource type result with the
// aliasing values for each such result. Each value is assigned a unique ID, and
// that ID is used to annotate the operations.
struct TestResourceAliasAnalysis
: public TF::PerFunctionAggregateAnalysisConsumerPass<
TestResourceAliasAnalysis, TF::ResourceAliasAnalysis> {
StringRef getArgument() const final {
return "tf-test-resource-alias-analysis";
}
StringRef getDescription() const final {
return "Add remarks based on resource alias analysis result, for testing "
"purpose.";
}
void runOnFunction(FuncOp func,
const TF::ResourceAliasAnalysis::Info& analysis) {
int64_t next_id = 0;
llvm::SmallDenseMap<Value, int64_t, 8> ids;
auto assign_id = [&](Value value) {
if (ids.find(value) == ids.end()) ids.insert({value, next_id++});
};
auto get_id = [&](Value value) -> int64_t {
auto it = ids.find(value);
assert(it != ids.end());
return it->second;
};
auto print_aliases = [&](InFlightDiagnostic& diag, Value value) {
diag << ", ID " << get_id(value) << " : ";
if (analysis.IsUnknownResource(value)) {
diag << "Unknown";
} else {
auto aliases = llvm::to_vector<4>(analysis.GetResourceAliases(value));
llvm::sort(aliases,
[&](Value v1, Value v2) { return get_id(v1) < get_id(v2); });
llvm::interleaveComma(aliases, diag,
[&](Value v) { diag << get_id(v); });
}
};
// Assign a unique ID to each value seen in this function.
func.walk([&](Operation* op) {
// For all attached regions, assign ID to the region arguments.
for (Region& region : op->getRegions()) {
for (auto region_arg : filter_resources(region.getArguments()))
assign_id(region_arg);
}
// Assign ID for all results.
for (auto result : filter_resources(op->getResults())) assign_id(result);
});
// Now walk each operation, and annotate it wil remarks for aliases for
// each resource type result
func.walk([&](Operation* op) {
// For all attached regions, assign ID to the region arguments.
for (Region& region : op->getRegions()) {
for (auto region_arg : filter_resources(region.getArguments())) {
InFlightDiagnostic diag = op->emitRemark("Region #")
<< region.getRegionNumber() << ", Arg #"
<< region_arg.getArgNumber();
print_aliases(diag, region_arg);
}
}
for (auto result : filter_resources(op->getResults())) {
InFlightDiagnostic diag = op->emitRemark("Result #")
<< result.getResultNumber();
print_aliases(diag, result);
}
});
}
};
static mlir::PassRegistration<TestResourceAliasAnalysis> pass;
} // anonymous namespace
} // namespace TF
} // namespace mlir
| frreiss/tensorflow-fred | tensorflow/compiler/mlir/tensorflow/transforms/test_resource_alias_analysis.cc | C++ | apache-2.0 | 4,295 |
// Copyright 2022 Google LLC
//
// Licensed 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
//
// https://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.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.CertificateManager.V1.Snippets
{
// [START certificatemanager_v1_generated_CertificateManager_GetCertificateMap_async_flattened_resourceNames]
using Google.Cloud.CertificateManager.V1;
using System.Threading.Tasks;
public sealed partial class GeneratedCertificateManagerClientSnippets
{
/// <summary>Snippet for GetCertificateMapAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task GetCertificateMapResourceNamesAsync()
{
// Create client
CertificateManagerClient certificateManagerClient = await CertificateManagerClient.CreateAsync();
// Initialize request argument(s)
CertificateMapName name = CertificateMapName.FromProjectLocationCertificateMap("[PROJECT]", "[LOCATION]", "[CERTIFICATE_MAP]");
// Make the request
CertificateMap response = await certificateManagerClient.GetCertificateMapAsync(name);
}
}
// [END certificatemanager_v1_generated_CertificateManager_GetCertificateMap_async_flattened_resourceNames]
}
| googleapis/google-cloud-dotnet | apis/Google.Cloud.CertificateManager.V1/Google.Cloud.CertificateManager.V1.GeneratedSnippets/CertificateManagerClient.GetCertificateMapResourceNamesAsyncSnippet.g.cs | C# | apache-2.0 | 1,884 |
/**
* 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.storm.scheduler.multitenant;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import org.apache.storm.scheduler.SchedulerAssignment;
import org.apache.storm.scheduler.TopologyDetails;
import org.apache.storm.scheduler.WorkerSlot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A pool of machines that anyone can use, but topologies are not isolated
*/
public class DefaultPool extends NodePool {
private static final Logger LOG = LoggerFactory.getLogger(DefaultPool.class);
private Set<Node> _nodes = new HashSet<>();
private HashMap<String, TopologyDetails> _tds = new HashMap<>();
@Override
public void addTopology(TopologyDetails td) {
String topId = td.getId();
LOG.debug("Adding in Topology {}", topId);
_tds.put(topId, td);
SchedulerAssignment assignment = _cluster.getAssignmentById(topId);
if (assignment != null) {
for (WorkerSlot ws : assignment.getSlots()) {
Node n = _nodeIdToNode.get(ws.getNodeId());
_nodes.add(n);
}
}
}
@Override
public boolean canAdd(TopologyDetails td) {
return true;
}
@Override
public Collection<Node> takeNodes(int nodesNeeded) {
HashSet<Node> ret = new HashSet<>();
LinkedList<Node> sortedNodes = new LinkedList<>(_nodes);
Collections.sort(sortedNodes, Node.FREE_NODE_COMPARATOR_DEC);
for (Node n : sortedNodes) {
if (nodesNeeded <= ret.size()) {
break;
}
if (n.isAlive()) {
n.freeAllSlots(_cluster);
_nodes.remove(n);
ret.add(n);
}
}
return ret;
}
@Override
public int nodesAvailable() {
int total = 0;
for (Node n : _nodes) {
if (n.isAlive()) total++;
}
return total;
}
@Override
public int slotsAvailable() {
return Node.countTotalSlotsAlive(_nodes);
}
@Override
public NodeAndSlotCounts getNodeAndSlotCountIfSlotsWereTaken(int slotsNeeded) {
int nodesFound = 0;
int slotsFound = 0;
LinkedList<Node> sortedNodes = new LinkedList<>(_nodes);
Collections.sort(sortedNodes, Node.FREE_NODE_COMPARATOR_DEC);
for (Node n : sortedNodes) {
if (slotsNeeded <= 0) {
break;
}
if (n.isAlive()) {
nodesFound++;
int totalSlotsFree = n.totalSlots();
slotsFound += totalSlotsFree;
slotsNeeded -= totalSlotsFree;
}
}
return new NodeAndSlotCounts(nodesFound, slotsFound);
}
@Override
public Collection<Node> takeNodesBySlots(int slotsNeeded) {
HashSet<Node> ret = new HashSet<>();
LinkedList<Node> sortedNodes = new LinkedList<>(_nodes);
Collections.sort(sortedNodes, Node.FREE_NODE_COMPARATOR_DEC);
for (Node n : sortedNodes) {
if (slotsNeeded <= 0) {
break;
}
if (n.isAlive()) {
n.freeAllSlots(_cluster);
_nodes.remove(n);
ret.add(n);
slotsNeeded -= n.totalSlotsFree();
}
}
return ret;
}
@Override
public void scheduleAsNeeded(NodePool... lesserPools) {
for (TopologyDetails td : _tds.values()) {
String topId = td.getId();
if (_cluster.needsScheduling(td)) {
LOG.debug("Scheduling topology {}", topId);
int totalTasks = td.getExecutors().size();
int origRequest = td.getNumWorkers();
int slotsRequested = Math.min(totalTasks, origRequest);
int slotsUsed = Node.countSlotsUsed(topId, _nodes);
int slotsFree = Node.countFreeSlotsAlive(_nodes);
//Check to see if we have enough slots before trying to get them
int slotsAvailable = 0;
if (slotsRequested > slotsFree) {
slotsAvailable = NodePool.slotsAvailable(lesserPools);
}
int slotsToUse = Math.min(slotsRequested - slotsUsed, slotsFree + slotsAvailable);
int executorsNotRunning = _cluster.getUnassignedExecutors(td).size();
LOG.debug("Slots... requested {} used {} free {} available {} to be used {}, executors not running {}",
slotsRequested, slotsUsed, slotsFree, slotsAvailable, slotsToUse, executorsNotRunning);
if (slotsToUse <= 0) {
if (executorsNotRunning > 0) {
_cluster.setStatus(topId, "Not fully scheduled (No free slots in default pool) " + executorsNotRunning +
" executors not scheduled");
} else {
if (slotsUsed < slotsRequested) {
_cluster.setStatus(topId, "Running with fewer slots than requested (" + slotsUsed + "/" + origRequest + ")");
} else { //slotsUsed < origRequest
_cluster.setStatus(topId,
"Fully Scheduled (requested " + origRequest + " slots, but could only use " + slotsUsed +
")");
}
}
continue;
}
int slotsNeeded = slotsToUse - slotsFree;
if (slotsNeeded > 0) {
_nodes.addAll(NodePool.takeNodesBySlot(slotsNeeded, lesserPools));
}
if (executorsNotRunning <= 0) {
//There are free slots that we can take advantage of now.
for (Node n : _nodes) {
n.freeTopology(topId, _cluster);
}
slotsFree = Node.countFreeSlotsAlive(_nodes);
slotsToUse = Math.min(slotsRequested, slotsFree);
}
RoundRobinSlotScheduler slotSched =
new RoundRobinSlotScheduler(td, slotsToUse, _cluster);
LinkedList<Node> nodes = new LinkedList<>(_nodes);
while (true) {
Node n;
do {
if (nodes.isEmpty()) {
throw new IllegalStateException("This should not happen, we" +
" messed up and did not get enough slots");
}
n = nodes.peekFirst();
if (n.totalSlotsFree() == 0) {
nodes.remove();
n = null;
}
} while (n == null);
if (!slotSched.assignSlotTo(n)) {
break;
}
}
int afterSchedSlotsUsed = Node.countSlotsUsed(topId, _nodes);
if (afterSchedSlotsUsed < slotsRequested) {
_cluster.setStatus(topId, "Running with fewer slots than requested (" + afterSchedSlotsUsed + "/" + origRequest + ")");
} else if (afterSchedSlotsUsed < origRequest) {
_cluster.setStatus(topId,
"Fully Scheduled (requested " + origRequest + " slots, but could only use " + afterSchedSlotsUsed +
")");
} else {
_cluster.setStatus(topId, "Fully Scheduled");
}
} else {
_cluster.setStatus(topId, "Fully Scheduled");
}
}
}
@Override
public String toString() {
return "DefaultPool " + _nodes.size() + " nodes " + _tds.size() + " topologies";
}
}
| srdo/storm | storm-server/src/main/java/org/apache/storm/scheduler/multitenant/DefaultPool.java | Java | apache-2.0 | 8,903 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Strings for component 'quizaccess_safebrowser', language 'zh_cn', branch 'MOODLE_22_STABLE'
*
* @package quizaccess_safebrowser
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['requiresafeexambrowser'] = '必须使用Safe Exam Browser';
| carnegiespeech/translations | zh_cn/quizaccess_safebrowser.php | PHP | apache-2.0 | 1,084 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-792
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2011.04.07 at 12:06:52 PM GMT+05:30
//
package com.ebay.marketplace.search.v1.services;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* This type defines a mapping between a Field and
* its value(s) in the search results.
*
*
* <p>Java class for FieldValuesPair complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="FieldValuesPair">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="field" type="{http://www.ebay.com/marketplace/search/v1/services}Field"/>
* <element name="fieldValue" type="{http://www.ebay.com/marketplace/search/v1/services}FieldValue" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "FieldValuesPair", propOrder = {
"field",
"fieldValue"
})
public class FieldValuesPair {
@XmlElement(required = true)
protected Field field;
@XmlElement(required = true)
protected List<FieldValue> fieldValue;
/**
* Gets the value of the field property.
*
* @return
* possible object is
* {@link Field }
*
*/
public Field getField() {
return field;
}
/**
* Sets the value of the field property.
*
* @param value
* allowed object is
* {@link Field }
*
*/
public void setField(Field value) {
this.field = value;
}
/**
* Gets the value of the fieldValue property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the fieldValue property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getFieldValue().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link FieldValue }
*
*
*/
public List<FieldValue> getFieldValue() {
if (fieldValue == null) {
fieldValue = new ArrayList<FieldValue>();
}
return this.fieldValue;
}
}
| vthangathurai/SOA-Runtime | integration-tests/ProtoBufFindItemService/src/main/java/com/ebay/marketplace/search/v1/services/FieldValuesPair.java | Java | apache-2.0 | 3,008 |
require 'pathname'
Puppet::Type.newtype(:dsc_xexcheventloglevel) do
require Pathname.new(__FILE__).dirname + '../../' + 'puppet/type/base_dsc'
require Pathname.new(__FILE__).dirname + '../../puppet_x/puppetlabs/dsc_type_helpers'
@doc = %q{
The DSC xExchEventLogLevel resource type.
Automatically generated from
'xExchange/DSCResources/MSFT_xExchEventLogLevel/MSFT_xExchEventLogLevel.schema.mof'
To learn more about PowerShell Desired State Configuration, please
visit https://technet.microsoft.com/en-us/library/dn249912.aspx.
For more information about built-in DSC Resources, please visit
https://technet.microsoft.com/en-us/library/dn249921.aspx.
For more information about xDsc Resources, please visit
https://github.com/PowerShell/DscResources.
}
validate do
fail('dsc_identity is a required attribute') if self[:dsc_identity].nil?
end
def dscmeta_resource_friendly_name; 'xExchEventLogLevel' end
def dscmeta_resource_name; 'MSFT_xExchEventLogLevel' end
def dscmeta_module_name; 'xExchange' end
def dscmeta_module_version; '1.11.0.0' end
newparam(:name, :namevar => true ) do
end
ensurable do
newvalue(:exists?) { provider.exists? }
newvalue(:present) { provider.create }
defaultto { :present }
end
# Name: PsDscRunAsCredential
# Type: MSFT_Credential
# IsMandatory: False
# Values: None
newparam(:dsc_psdscrunascredential) do
def mof_type; 'MSFT_Credential' end
def mof_is_embedded?; true end
desc "PsDscRunAsCredential"
validate do |value|
unless value.kind_of?(Hash)
fail("Invalid value '#{value}'. Should be a hash")
end
PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("Credential", value)
end
end
# Name: Identity
# Type: string
# IsMandatory: True
# Values: None
newparam(:dsc_identity) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "Identity - The Identity parameter specifies the name of the event logging category for which you want to set the event logging level."
isrequired
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
end
end
# Name: Credential
# Type: MSFT_Credential
# IsMandatory: False
# Values: None
newparam(:dsc_credential) do
def mof_type; 'MSFT_Credential' end
def mof_is_embedded?; true end
desc "Credential - Credentials used to establish a remote Powershell session to Exchange"
validate do |value|
unless value.kind_of?(Hash)
fail("Invalid value '#{value}'. Should be a hash")
end
PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("Credential", value)
end
end
# Name: Level
# Type: string
# IsMandatory: False
# Values: ["Lowest", "Low", "Medium", "High", "Expert"]
newparam(:dsc_level) do
def mof_type; 'string' end
def mof_is_embedded?; false end
desc "Level - The Level parameter specifies the log level for the specific event logging category. Valid values are Lowest, Low, Medium, High, Expert."
validate do |value|
unless value.kind_of?(String)
fail("Invalid value '#{value}'. Should be a string")
end
unless ['Lowest', 'lowest', 'Low', 'low', 'Medium', 'medium', 'High', 'high', 'Expert', 'expert'].include?(value)
fail("Invalid value '#{value}'. Valid values are Lowest, Low, Medium, High, Expert")
end
end
end
def builddepends
pending_relations = super()
PuppetX::Dsc::TypeHelpers.ensure_reboot_relationship(self, pending_relations)
end
end
Puppet::Type.type(:dsc_xexcheventloglevel).provide :powershell, :parent => Puppet::Type.type(:base_dsc).provider(:powershell) do
confine :true => (Gem::Version.new(Facter.value(:powershell_version)) >= Gem::Version.new('5.0.10240.16384'))
defaultfor :operatingsystem => :windows
mk_resource_methods
end
| ferventcoder/puppetlabs-dsc | lib/puppet/type/dsc_xexcheventloglevel.rb | Ruby | apache-2.0 | 4,027 |
/*
* 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.wicket.validation.validator;
import java.io.Serializable;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;
/**
* Base class for validators that check if a given value falls within [min,max] range.
*
* If either min or max are {@code null} they are not checked.
*
* <p>
* Resource keys:
* <ul>
* <li>{@code <class.simpleName>.exact} if min==max</li>
* <li>{@code <class.simpleName>.range} if both min and max are not {@code null}</li>
* <li>{@code <class.simpleName>.minimum} if max is {@code null}</li>
* <li>{@code <class.simpleName>.maximum} if min is {@code null}</li>
* </ul>
* </p>
*
* <p>
* Error Message Variables:
* <ul>
* <li>{@code name}: the id of {@code Component} that failed</li>
* <li>{@code label}: the label of the {@code Component} (either comes from
* {@code FormComponent.labelModel} or resource key {@code <form-id>.<form-component-id>}</li>
* <li>{@code input}: the input value</li>
* <li>{@code minimum}: the minimum allowed value</li>
* <li>{@code maximum}: the maximum allowed value</li>
* </ul>
* </p>
*
* @param <R>
* type of range value
* @param <V>
* type of validatable
*
* @author igor
*/
public abstract class AbstractRangeValidator<R extends Comparable<R> & Serializable, V extends Serializable>
extends Behavior implements IValidator<V>
{
private static final long serialVersionUID = 1L;
private R minimum;
private R maximum;
/**
* Constructor that sets the minimum and maximum values.
*
* @param minimum
* the minimum value
* @param maximum
* the maximum value
*/
public AbstractRangeValidator(R minimum, R maximum)
{
setRange(minimum, maximum);
}
/**
* Constructor used for subclasses who want to set the range using
* {@link #setRange(Comparable, Comparable)}
*/
protected AbstractRangeValidator()
{
}
/**
* Sets validator range
*
* @param minimum
* @param maximum
*/
protected final void setRange(R minimum, R maximum)
{
if (minimum == null && maximum == null)
{
throw new IllegalArgumentException("Both minimum and maximum values cannot be null");
}
this.minimum = minimum;
this.maximum = maximum;
}
@Override
public void validate(IValidatable<V> validatable)
{
R value = getValue(validatable);
final R min = getMinimum();
final R max = getMaximum();
if ((min != null && value.compareTo(min) < 0) || (max != null && value.compareTo(max) > 0))
{
Mode mode = getMode();
ValidationError error = new ValidationError(this, mode.getVariation());
if (min != null)
{
error.setVariable("minimum", min);
}
if (max != null)
{
error.setVariable("maximum", max);
}
if (mode == Mode.EXACT)
{
error.setVariable("exact", max);
}
validatable.error(decorate(error, validatable));
}
}
/**
* Gets the value that should be validated against the range
*
* @param validatable
* @return value to validate
*/
protected abstract R getValue(IValidatable<V> validatable);
/**
* Gets the minimum value.
*
* @return minimum value
*/
public R getMinimum()
{
return minimum;
}
/**
* Gets the maximum value.
*
* @return maximum value
*/
public R getMaximum()
{
return maximum;
}
/**
* Allows subclasses to decorate reported errors
*
* @param error
* @param validatable
* @return decorated error
*/
protected ValidationError decorate(ValidationError error, IValidatable<V> validatable)
{
return error;
}
/**
* Gets validation mode which is determined by whether min, max, or both values are provided
*
* @return validation mode
*/
public final Mode getMode()
{
final R min = getMinimum();
final R max = getMaximum();
if (min == null && max != null)
{
return Mode.MAXIMUM;
}
else if (max == null && min != null)
{
return Mode.MINIMUM;
}
else if ((min == null && max == null) || max.equals(min))
{
return Mode.EXACT;
}
else
{
return Mode.RANGE;
}
}
/**
* Validator mode
*
* @author igor
*/
public static enum Mode {
MINIMUM, MAXIMUM, RANGE, EXACT;
public String getVariation()
{
return name().toLowerCase();
}
}
} | mafulafunk/wicket | wicket-core/src/main/java/org/apache/wicket/validation/validator/AbstractRangeValidator.java | Java | apache-2.0 | 5,358 |
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 com.amazonaws.services.cloudsearchv2.model;
import java.io.Serializable;
import com.amazonaws.AmazonWebServiceRequest;
/**
* <p>
* Container for the parameters to the <code><a>BuildSuggester</a></code>
* operation. Specifies the name of the domain you want to update.
* </p>
*/
public class BuildSuggestersRequest extends AmazonWebServiceRequest implements
Serializable, Cloneable {
private String domainName;
/**
* @param domainName
*/
public void setDomainName(String domainName) {
this.domainName = domainName;
}
/**
* @return
*/
public String getDomainName() {
return this.domainName;
}
/**
* @param domainName
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public BuildSuggestersRequest withDomainName(String domainName) {
setDomainName(domainName);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getDomainName() != null)
sb.append("DomainName: " + getDomainName());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof BuildSuggestersRequest == false)
return false;
BuildSuggestersRequest other = (BuildSuggestersRequest) obj;
if (other.getDomainName() == null ^ this.getDomainName() == null)
return false;
if (other.getDomainName() != null
&& other.getDomainName().equals(this.getDomainName()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getDomainName() == null) ? 0 : getDomainName().hashCode());
return hashCode;
}
@Override
public BuildSuggestersRequest clone() {
return (BuildSuggestersRequest) super.clone();
}
} | flofreud/aws-sdk-java | aws-java-sdk-cloudsearch/src/main/java/com/amazonaws/services/cloudsearchv2/model/BuildSuggestersRequest.java | Java | apache-2.0 | 3,006 |
/*
* Copyright 2012-2014 the original author or authors.
*
* Licensed 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.springframework.boot.configurationprocessor;
import java.io.IOException;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.springframework.boot.configurationprocessor.metadata.ConfigurationMetadata;
import org.springframework.boot.configurationsample.lombok.LombokExplicitProperties;
import org.springframework.boot.configurationsample.lombok.LombokSimpleDataProperties;
import org.springframework.boot.configurationsample.lombok.LombokSimpleProperties;
import org.springframework.boot.configurationsample.method.EmptyTypeMethodConfig;
import org.springframework.boot.configurationsample.method.InvalidMethodConfig;
import org.springframework.boot.configurationsample.method.MethodAndClassConfig;
import org.springframework.boot.configurationsample.method.SimpleMethodConfig;
import org.springframework.boot.configurationsample.simple.HierarchicalProperties;
import org.springframework.boot.configurationsample.simple.NotAnnotated;
import org.springframework.boot.configurationsample.simple.SimpleCollectionProperties;
import org.springframework.boot.configurationsample.simple.SimplePrefixValueProperties;
import org.springframework.boot.configurationsample.simple.SimpleProperties;
import org.springframework.boot.configurationsample.simple.SimpleTypeProperties;
import org.springframework.boot.configurationsample.specific.BuilderPojo;
import org.springframework.boot.configurationsample.specific.ExcludedTypesPojo;
import org.springframework.boot.configurationsample.specific.InnerClassAnnotatedGetterConfig;
import org.springframework.boot.configurationsample.specific.InnerClassProperties;
import org.springframework.boot.configurationsample.specific.InnerClassRootConfig;
import org.springframework.boot.configurationsample.specific.SimplePojo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsGroup;
import static org.springframework.boot.configurationprocessor.ConfigurationMetadataMatchers.containsProperty;
/**
* Tests for {@link ConfigurationMetadataAnnotationProcessor}.
*
* @author Stephane Nicoll
* @author Phillip Webb
*/
public class ConfigurationMetadataAnnotationProcessorTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void notAnnotated() throws Exception {
ConfigurationMetadata metadata = compile(NotAnnotated.class);
assertThat("No config metadata file should have been generated when "
+ "no metadata is discovered", metadata.getItems(), empty());
}
@Test
public void simpleProperties() throws Exception {
ConfigurationMetadata metadata = compile(SimpleProperties.class);
assertThat(metadata, containsGroup("simple").fromSource(SimpleProperties.class));
assertThat(
metadata,
containsProperty("simple.the-name", String.class)
.fromSource(SimpleProperties.class)
.withDescription("The name of this simple properties.")
.withDefaultValue(is("boot")).withDeprecated());
assertThat(
metadata,
containsProperty("simple.flag", Boolean.class)
.fromSource(SimpleProperties.class)
.withDescription("A simple flag.").withDeprecated());
assertThat(metadata, containsProperty("simple.comparator"));
assertThat(metadata, not(containsProperty("simple.counter")));
assertThat(metadata, not(containsProperty("simple.size")));
}
@Test
public void simplePrefixValueProperties() throws Exception {
ConfigurationMetadata metadata = compile(SimplePrefixValueProperties.class);
assertThat(metadata,
containsGroup("simple").fromSource(SimplePrefixValueProperties.class));
assertThat(
metadata,
containsProperty("simple.name", String.class).fromSource(
SimplePrefixValueProperties.class));
}
@Test
public void simpleTypeProperties() throws Exception {
ConfigurationMetadata metadata = compile(SimpleTypeProperties.class);
assertThat(metadata,
containsGroup("simple.type").fromSource(SimpleTypeProperties.class));
assertThat(metadata, containsProperty("simple.type.my-string", String.class));
assertThat(metadata, containsProperty("simple.type.my-byte", Byte.class));
assertThat(metadata,
containsProperty("simple.type.my-primitive-byte", Byte.class));
assertThat(metadata, containsProperty("simple.type.my-char", Character.class));
assertThat(metadata,
containsProperty("simple.type.my-primitive-char", Character.class));
assertThat(metadata, containsProperty("simple.type.my-boolean", Boolean.class));
assertThat(metadata,
containsProperty("simple.type.my-primitive-boolean", Boolean.class));
assertThat(metadata, containsProperty("simple.type.my-short", Short.class));
assertThat(metadata,
containsProperty("simple.type.my-primitive-short", Short.class));
assertThat(metadata, containsProperty("simple.type.my-integer", Integer.class));
assertThat(metadata,
containsProperty("simple.type.my-primitive-integer", Integer.class));
assertThat(metadata, containsProperty("simple.type.my-long", Long.class));
assertThat(metadata,
containsProperty("simple.type.my-primitive-long", Long.class));
assertThat(metadata, containsProperty("simple.type.my-double", Double.class));
assertThat(metadata,
containsProperty("simple.type.my-primitive-double", Double.class));
assertThat(metadata, containsProperty("simple.type.my-float", Float.class));
assertThat(metadata,
containsProperty("simple.type.my-primitive-float", Float.class));
assertThat(metadata.getItems().size(), equalTo(18));
}
@Test
public void hierarchicalProperties() throws Exception {
ConfigurationMetadata metadata = compile(HierarchicalProperties.class);
assertThat(metadata,
containsGroup("hierarchical").fromSource(HierarchicalProperties.class));
assertThat(metadata, containsProperty("hierarchical.first", String.class)
.fromSource(HierarchicalProperties.class));
assertThat(metadata, containsProperty("hierarchical.second", String.class)
.fromSource(HierarchicalProperties.class));
assertThat(metadata, containsProperty("hierarchical.third", String.class)
.fromSource(HierarchicalProperties.class));
}
@Test
@SuppressWarnings("deprecation")
public void deprecatedProperties() throws Exception {
Class<?> type = org.springframework.boot.configurationsample.simple.DeprecatedProperties.class;
ConfigurationMetadata metadata = compile(type);
assertThat(metadata, containsGroup("deprecated").fromSource(type));
assertThat(metadata, containsProperty("deprecated.name", String.class)
.fromSource(type).withDeprecated());
assertThat(metadata, containsProperty("deprecated.description", String.class)
.fromSource(type).withDeprecated());
}
@Test
public void parseCollectionConfig() throws Exception {
ConfigurationMetadata metadata = compile(SimpleCollectionProperties.class);
// getter and setter
assertThat(
metadata,
containsProperty("collection.integers-to-names",
"java.util.Map<java.lang.Integer,java.lang.String>"));
assertThat(
metadata,
containsProperty("collection.longs",
"java.util.Collection<java.lang.Long>"));
assertThat(metadata,
containsProperty("collection.floats", "java.util.List<java.lang.Float>"));
// getter only
assertThat(
metadata,
containsProperty("collection.names-to-integers",
"java.util.Map<java.lang.String,java.lang.Integer>"));
assertThat(
metadata,
containsProperty("collection.bytes",
"java.util.Collection<java.lang.Byte>"));
assertThat(
metadata,
containsProperty("collection.doubles", "java.util.List<java.lang.Double>"));
}
@Test
public void simpleMethodConfig() throws Exception {
ConfigurationMetadata metadata = compile(SimpleMethodConfig.class);
assertThat(metadata, containsGroup("foo").fromSource(SimpleMethodConfig.class));
assertThat(
metadata,
containsProperty("foo.name", String.class).fromSource(
SimpleMethodConfig.Foo.class));
assertThat(
metadata,
containsProperty("foo.flag", Boolean.class).fromSource(
SimpleMethodConfig.Foo.class));
}
@Test
public void invalidMethodConfig() throws Exception {
ConfigurationMetadata metadata = compile(InvalidMethodConfig.class);
assertThat(
metadata,
containsProperty("something.name", String.class).fromSource(
InvalidMethodConfig.class));
assertThat(metadata, not(containsProperty("invalid.name")));
}
@Test
public void methodAndClassConfig() throws Exception {
ConfigurationMetadata metadata = compile(MethodAndClassConfig.class);
assertThat(
metadata,
containsProperty("conflict.name", String.class).fromSource(
MethodAndClassConfig.Foo.class));
assertThat(
metadata,
containsProperty("conflict.flag", Boolean.class).fromSource(
MethodAndClassConfig.Foo.class));
assertThat(
metadata,
containsProperty("conflict.value", String.class).fromSource(
MethodAndClassConfig.class));
}
@Test
public void emptyTypeMethodConfig() throws Exception {
ConfigurationMetadata metadata = compile(EmptyTypeMethodConfig.class);
assertThat(metadata, not(containsProperty("something.foo")));
}
@Test
public void innerClassRootConfig() throws Exception {
ConfigurationMetadata metadata = compile(InnerClassRootConfig.class);
assertThat(metadata, containsProperty("config.name"));
}
@Test
public void innerClassProperties() throws Exception {
ConfigurationMetadata metadata = compile(InnerClassProperties.class);
assertThat(metadata,
containsGroup("config").fromSource(InnerClassProperties.class));
assertThat(metadata,
containsGroup("config.first").ofType(InnerClassProperties.Foo.class)
.fromSource(InnerClassProperties.class));
assertThat(metadata, containsProperty("config.first.name"));
assertThat(metadata, containsProperty("config.first.bar.name"));
assertThat(metadata,
containsGroup("config.the-second", InnerClassProperties.Foo.class)
.fromSource(InnerClassProperties.class));
assertThat(metadata, containsProperty("config.the-second.name"));
assertThat(metadata, containsProperty("config.the-second.bar.name"));
assertThat(metadata, containsGroup("config.third").ofType(SimplePojo.class)
.fromSource(InnerClassProperties.class));
assertThat(metadata, containsProperty("config.third.value"));
assertThat(metadata, containsProperty("config.fourth"));
assertThat(metadata, not(containsGroup("config.fourth")));
}
@Test
public void innerClassAnnotatedGetterConfig() throws Exception {
ConfigurationMetadata metadata = compile(InnerClassAnnotatedGetterConfig.class);
assertThat(metadata, containsProperty("specific.value"));
assertThat(metadata, containsProperty("foo.name"));
assertThat(metadata, not(containsProperty("specific.foo")));
}
@Test
public void builderPojo() throws IOException {
ConfigurationMetadata metadata = compile(BuilderPojo.class);
assertThat(metadata, containsProperty("builder.name"));
}
@Test
public void excludedTypesPojo() throws IOException {
ConfigurationMetadata metadata = compile(ExcludedTypesPojo.class);
assertThat(metadata, containsProperty("excluded.name"));
assertThat(metadata, not(containsProperty("excluded.class-loader")));
assertThat(metadata, not(containsProperty("excluded.data-source")));
assertThat(metadata, not(containsProperty("excluded.print-writer")));
assertThat(metadata, not(containsProperty("excluded.writer")));
assertThat(metadata, not(containsProperty("excluded.writer-array")));
}
@Test
public void lombokDataProperties() throws Exception {
ConfigurationMetadata metadata = compile(LombokSimpleDataProperties.class);
assertSimpleLombokProperties(metadata, LombokSimpleDataProperties.class, "data");
}
@Test
public void lombokSimpleProperties() throws Exception {
ConfigurationMetadata metadata = compile(LombokSimpleProperties.class);
assertSimpleLombokProperties(metadata, LombokSimpleProperties.class, "simple");
}
@Test
public void lombokExplicitProperties() throws Exception {
ConfigurationMetadata metadata = compile(LombokExplicitProperties.class);
assertSimpleLombokProperties(metadata, LombokExplicitProperties.class, "explicit");
}
private void assertSimpleLombokProperties(ConfigurationMetadata metadata,
Class<?> source, String prefix) {
assertThat(metadata, containsGroup(prefix).fromSource(source));
assertThat(metadata, not(containsProperty(prefix + ".id")));
assertThat(metadata,
containsProperty(prefix + ".name", String.class).fromSource(source)
.withDescription("Name description."));
assertThat(metadata, containsProperty(prefix + ".description"));
assertThat(metadata, containsProperty(prefix + ".counter"));
assertThat(metadata, containsProperty(prefix + ".number").fromSource(source)
.withDefaultValue(is(0)).withDeprecated());
assertThat(metadata, containsProperty(prefix + ".items"));
assertThat(metadata, not(containsProperty(prefix + ".ignored")));
}
private ConfigurationMetadata compile(Class<?>... types) throws IOException {
TestConfigurationMetadataAnnotationProcessor processor = new TestConfigurationMetadataAnnotationProcessor();
new TestCompiler(this.temporaryFolder).getTask(types).call(processor);
return processor.getMetadata();
}
@SupportedAnnotationTypes({ "*" })
@SupportedSourceVersion(SourceVersion.RELEASE_6)
private static class TestConfigurationMetadataAnnotationProcessor extends
ConfigurationMetadataAnnotationProcessor {
static final String CONFIGURATION_PROPERTIES_ANNOTATION = "org.springframework.boot.configurationsample.ConfigurationProperties";
static final String NESTED_CONFIGURATION_PROPERTY_ANNOTATION = "org.springframework.boot.configurationsample.NestedConfigurationProperty";
private ConfigurationMetadata metadata;
@Override
protected String configurationPropertiesAnnotation() {
return CONFIGURATION_PROPERTIES_ANNOTATION;
}
@Override
protected String nestedConfigurationPropertyAnnotation() {
return NESTED_CONFIGURATION_PROPERTY_ANNOTATION;
}
@Override
protected void writeMetaData(ConfigurationMetadata metadata) {
this.metadata = metadata;
}
public ConfigurationMetadata getMetadata() {
return this.metadata;
}
}
}
| snicoll/spring-boot | spring-boot-tools/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationprocessor/ConfigurationMetadataAnnotationProcessorTests.java | Java | apache-2.0 | 15,218 |
/*
Copyright 2015 The Kubernetes Authors.
Licensed 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 storage
import (
"fmt"
"net/http"
"net/url"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/generic"
genericregistry "k8s.io/apiserver/pkg/registry/generic/registry"
"k8s.io/apiserver/pkg/registry/rest"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/v1"
"k8s.io/kubernetes/pkg/kubelet/client"
"k8s.io/kubernetes/pkg/registry/cachesize"
"k8s.io/kubernetes/pkg/registry/core/node"
noderest "k8s.io/kubernetes/pkg/registry/core/node/rest"
)
// NodeStorage includes storage for nodes and all sub resources
type NodeStorage struct {
Node *REST
Status *StatusREST
Proxy *noderest.ProxyREST
KubeletConnectionInfo client.ConnectionInfoGetter
}
type REST struct {
*genericregistry.Store
connection client.ConnectionInfoGetter
proxyTransport http.RoundTripper
}
// StatusREST implements the REST endpoint for changing the status of a pod.
type StatusREST struct {
store *genericregistry.Store
}
func (r *StatusREST) New() runtime.Object {
return &api.Node{}
}
// Get retrieves the object from the storage. It is required to support Patch.
func (r *StatusREST) Get(ctx genericapirequest.Context, name string, options *metav1.GetOptions) (runtime.Object, error) {
return r.store.Get(ctx, name, options)
}
// Update alters the status subset of an object.
func (r *StatusREST) Update(ctx genericapirequest.Context, name string, objInfo rest.UpdatedObjectInfo) (runtime.Object, bool, error) {
return r.store.Update(ctx, name, objInfo)
}
// NewStorage returns a NodeStorage object that will work against nodes.
func NewStorage(optsGetter generic.RESTOptionsGetter, kubeletClientConfig client.KubeletClientConfig, proxyTransport http.RoundTripper) (*NodeStorage, error) {
store := &genericregistry.Store{
Copier: api.Scheme,
NewFunc: func() runtime.Object { return &api.Node{} },
NewListFunc: func() runtime.Object { return &api.NodeList{} },
ObjectNameFunc: func(obj runtime.Object) (string, error) {
return obj.(*api.Node).Name, nil
},
PredicateFunc: node.MatchNode,
QualifiedResource: api.Resource("nodes"),
WatchCacheSize: cachesize.GetWatchCacheSizeByResource("nodes"),
CreateStrategy: node.Strategy,
UpdateStrategy: node.Strategy,
DeleteStrategy: node.Strategy,
ExportStrategy: node.Strategy,
}
options := &generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: node.GetAttrs, TriggerFunc: node.NodeNameTriggerFunc}
if err := store.CompleteWithOptions(options); err != nil {
return nil, err
}
statusStore := *store
statusStore.UpdateStrategy = node.StatusStrategy
// Set up REST handlers
nodeREST := &REST{Store: store, proxyTransport: proxyTransport}
statusREST := &StatusREST{store: &statusStore}
proxyREST := &noderest.ProxyREST{Store: store, ProxyTransport: proxyTransport}
// Build a NodeGetter that looks up nodes using the REST handler
nodeGetter := client.NodeGetterFunc(func(nodeName string, options metav1.GetOptions) (*v1.Node, error) {
obj, err := nodeREST.Get(genericapirequest.NewContext(), nodeName, &options)
if err != nil {
return nil, err
}
node, ok := obj.(*api.Node)
if !ok {
return nil, fmt.Errorf("unexpected type %T", obj)
}
// TODO: Remove the conversion. Consider only return the NodeAddresses
externalNode := &v1.Node{}
err = v1.Convert_api_Node_To_v1_Node(node, externalNode, nil)
if err != nil {
return nil, fmt.Errorf("failed to convert to v1.Node: %v", err)
}
return externalNode, nil
})
connectionInfoGetter, err := client.NewNodeConnectionInfoGetter(nodeGetter, kubeletClientConfig)
if err != nil {
return nil, err
}
nodeREST.connection = connectionInfoGetter
proxyREST.Connection = connectionInfoGetter
return &NodeStorage{
Node: nodeREST,
Status: statusREST,
Proxy: proxyREST,
KubeletConnectionInfo: connectionInfoGetter,
}, nil
}
// Implement Redirector.
var _ = rest.Redirector(&REST{})
// ResourceLocation returns a URL to which one can send traffic for the specified node.
func (r *REST) ResourceLocation(ctx genericapirequest.Context, id string) (*url.URL, http.RoundTripper, error) {
return node.ResourceLocation(r, r.connection, r.proxyTransport, ctx, id)
}
| ahakanbaba/kubernetes | pkg/registry/core/node/storage/storage.go | GO | apache-2.0 | 4,861 |
/*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed 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 com.thoughtworks.go.server.cache;
import com.thoughtworks.go.server.transaction.TransactionSynchronizationManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import java.util.function.Supplier;
public class LazyCache {
private final Ehcache ehcache;
private final TransactionSynchronizationManager transactionSynchronizationManager;
public LazyCache(Ehcache ehcache, TransactionSynchronizationManager transactionSynchronizationManager) {
this.ehcache = ehcache;
this.transactionSynchronizationManager = transactionSynchronizationManager;
}
public <T> T get(String key, Supplier<T> compute) {
Element element = ehcache.get(key);
if (element != null) {
return (T) element.getObjectValue();
}
synchronized (key.intern()) {
element = ehcache.get(key);
if (element != null) {
return (T) element.getObjectValue();
}
T object = compute.get();
ehcache.put(new Element(key, object));
return object;
}
}
public void flushOnCommit() {
transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() {
ehcache.flush();
}
});
}
}
| gocd/gocd | server/src/main/java/com/thoughtworks/go/server/cache/LazyCache.java | Java | apache-2.0 | 2,065 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.