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 |
|---|---|---|---|---|---|
<?php
namespace WiderFunnel\OptimizelyX\Items;
/**
* Class Experiment
* @package WiderFunnel\Items;
*/
class Experiment extends ItemAbstract
{
//
} | WiderFunnel/Optimizely-X-SDK | src/OptimizelyX/Items/Experiment.php | PHP | mit | 156 |
using System.Text;
namespace GuruComponents.Netrix.Events
{
/// <summary>
/// SaveEventArgs provides information about the current save process.
/// </summary>
public class SaveEventArgs : LoadEventArgs
{
/// <summary>
/// Constructor. It's build by Save event handler and not intendet to being called from user's code.
/// </summary>
/// <param name="encoding"></param>
/// <param name="url"></param>
public SaveEventArgs(Encoding encoding, string url) : base(encoding, url)
{
}
/// <summary>
/// Set another encoding temporarily, if used within the <see cref="IHtmlEditor.Saving">Saving</see> event.
/// </summary>
/// <param name="encoding"></param>
public void SetEncoding(Encoding encoding)
{
_encoding = encoding;
}
}
}
| joergkrause/netrix | NetrixPackage/Core/Events/SaveEventArgs.cs | C# | mit | 820 |
YUI.add("yuidoc-meta", function(Y) {
Y.YUIDoc = { meta: {
"classes": [
"Audio"
],
"modules": [
"gallery-audio"
],
"allModules": [
{
"displayName": "gallery-audio",
"name": "gallery-audio"
}
]
} };
}); | inikoo/fact | libs/yui/yui3-gallery/src/gallery-audio/api/api.js | JavaScript | mit | 283 |
// angular
import { HttpClient } from '@angular/common/http';
import { Routes } from '@angular/router';
// libs
import * as _ from 'lodash';
import { I18NRouterLoader, I18NRouterSettings } from '@ngx-i18n-router/core';
export class I18NRouterHttpLoader implements I18NRouterLoader {
private _translations: any;
get routes(): Routes {
return _.map(this.providedSettings.routes, _.cloneDeep);
}
get translations(): any {
return this._translations;
}
constructor(private readonly http: HttpClient,
private readonly path: string = '/routes.json',
private readonly providedSettings: I18NRouterSettings = {}) {
}
loadTranslations(): any {
return new Promise((resolve, reject) => {
this.http.get(this.path)
.subscribe(res => {
this._translations = res;
return resolve(res);
}, () => reject('Endpoint unreachable!'));
});
}
}
| fulls1z3/ngx-i18n-router | packages/@ngx-i18n-router/http-loader/src/i18n-router.http-loader.ts | TypeScript | mit | 929 |
'use strict';
var fs = require('fs'),
util = require('util'),
Duplexify = require('duplexify'),
_ = require('lodash'),
su = require('bindings')('serialutil.node'),
fsu = require('./fsutil'),
pins = require('./pins'),
Dto = require('./dto'),
dto = new Dto(__dirname + '/../templates/uart.dts');
var DEFAULT_OPTIONS;
function onopen(uart, options) {
if (uart._rxfd !== -1 && uart._txfd !== -1) {
su.setRawMode(uart._rxfd);
uart.baudRate(options.baudRate);
uart.characterSize(options.characterSize);
uart.parity(options.parity);
uart.stopBits(options.stopBits);
setImmediate(function () {
uart.emit('open');
uart.emit('ready');
});
}
}
function onclose(uart) {
if (uart._rxfd === -1 && uart._txfd === -1) {
setImmediate(function () {
uart.emit('close');
});
}
}
function createStreams(uart, options) {
uart._rxfd = -1;
uart._txfd = -1;
uart._rxstream = fs.createReadStream(uart.devPath, {
highWaterMark: options.highWaterMark,
encoding: options.encoding
});
uart._txstream = fs.createWriteStream(uart.devPath, {
highWaterMark: options.highWaterMark,
encoding: options.encoding,
flags: 'r+'
});
uart._rxstream.once('open', function (rxfd) {
uart._rxfd = rxfd;
onopen(uart, options);
});
uart._txstream.once('open', function (txfd) {
uart._txfd = txfd;
onopen(uart, options);
});
uart._rxstream.once('close', function () {
uart._rxfd = -1;
onclose(uart);
});
uart._txstream.once('close', function () {
uart._txfd = -1;
onclose(uart);
});
// TODO - test error handling
uart.setReadable(uart._rxstream);
uart.setWritable(uart._txstream);
}
function waitForUart(uart, options) {
fsu.waitForFile(uart.devPath, function (err, devPath) {
if (err) {
return uart.emit('error', err);
}
createStreams(uart, options);
});
}
function Uart(uartDef, options) {
var badPin,
config;
if (!(this instanceof Uart)) {
return new Uart(uartDef);
}
options = options ? _.defaults(options, DEFAULT_OPTIONS) : DEFAULT_OPTIONS;
// Consider calling Duplexify with the allowHalfOpen option set to false.
// It's super-class (Duplex) will then ensure that this.end is called when
// the read stream fires the 'end' event. (see:
// https://github.com/joyent/node/blob/v0.10.25/lib/_stream_duplex.js)
Duplexify.call(this, null, null);
if (typeof uartDef === 'string') {
this.uartDef = null;
this.devPath = uartDef;
this.name = null;
waitForUart(this, options);
} else {
if (uartDef.txPin.uart === undefined) {
badPin = new Error(uartDef.txPin + ' doesn\'t support uarts');
} else if (uartDef.rxPin.uart === undefined) {
badPin = new Error(uartDef.rxPin + ' doesn\'t support uarts');
}
if (badPin) {
setImmediate(function () {
this.emit('error', badPin);
}.bind(this));
return;
}
this.uartDef = uartDef;
this.devPath = '/dev/ttyO' + uartDef.id;
this.name = 'bot_uart' + uartDef.id;
config = {
txHeader: this.uartDef.txPin.name.toUpperCase().replace('_', '.'),
rxHeader: this.uartDef.rxPin.name.toUpperCase().replace('_', '.'),
hardwareIp: 'uart' + this.uartDef.id,
name: this.name,
rxMuxOffset: '0x' + this.uartDef.rxPin.muxOffset.toString(16),
rxMuxValue: '0x' + this.uartDef.rxPin.uart.muxValue.toString(16),
txMuxOffset: '0x' + this.uartDef.txPin.muxOffset.toString(16),
txMuxValue: '0x' + this.uartDef.txPin.uart.muxValue.toString(16),
targetUart: 'uart' + (this.uartDef.id + 1),
partNumber: this.name
};
dto.install(config, function (err) {
if (err) {
return this.emit('error', err);
}
waitForUart(this, options);
}.bind(this));
}
}
module.exports = Uart;
util.inherits(Uart, Duplexify);
Uart.B0 = su.B0;
Uart.B50 = su.B50;
Uart.B75 = su.B75;
Uart.B110 = su.B110;
Uart.B134 = su.B134;
Uart.B150 = su.B150;
Uart.B200 = su.B200;
Uart.B300 = su.B300;
Uart.B600 = su.B600;
Uart.B1200 = su.B1200;
Uart.B1800 = su.B1800;
Uart.B2400 = su.B2400;
Uart.B4800 = su.B4800;
Uart.B9600 = su.B9600;
Uart.B19200 = su.B19200;
Uart.B38400 = su.B38400;
Uart.B57600 = su.B57600;
Uart.B115200 = su.B115200;
Uart.B230400 = su.B230400;
Uart.B460800 = su.B460800;
Uart.B500000 = su.B500000;
Uart.B576000 = su.B576000;
Uart.B921600 = su.B921600;
Uart.B1000000 = su.B1000000;
Uart.B1152000 = su.B1152000;
Uart.B1500000 = su.B1500000;
Uart.B2000000 = su.B2000000;
Uart.B2500000 = su.B2500000;
Uart.B3000000 = su.B3000000;
Uart.B3500000 = su.B3500000;
Uart.B4000000 = su.B4000000;
Uart.PARITY_NONE = su.PARITY_NONE;
Uart.PARITY_ODD = su.PARITY_ODD;
Uart.PARITY_EVEN = su.PARITY_EVEN;
Uart.UART1 = {
id: 1,
txPin: pins.p9_24,
rxPin: pins.p9_26
};
Uart.UART2 = {
id: 2,
txPin: pins.p9_21,
rxPin: pins.p9_22
};
Uart.UART4 = {
id: 4,
txPin: pins.p9_13,
rxPin: pins.p9_11
};
DEFAULT_OPTIONS = {
baudRate: Uart.B38400,
characterSize: 8,
parity: Uart.PARITY_NONE,
stopBits: 1,
highWaterMark: 512,
encoding: null
};
Object.freeze(DEFAULT_OPTIONS);
Uart.prototype.baudRate = function (rate) {
if (rate === undefined) {
return su.getBaudRate(this._rxfd);
}
su.setBaudRate(this._rxfd, rate);
};
Uart.prototype.characterSize = function (size) {
if (size === undefined) {
return su.getCharacterSize(this._rxfd);
}
su.setCharacterSize(this._rxfd, size);
};
Uart.prototype.parity = function (type) {
if (type === undefined) {
return su.getParity(this._rxfd);
}
su.setParity(this._rxfd, type);
};
Uart.prototype.stopBits = function (count) {
if (count === undefined) {
return su.getStopBits(this._rxfd);
}
su.setStopBits(this._rxfd, count);
};
Uart.prototype.close = function () {
this.removeAllListeners('data'); // Is this a good idea? Should the user be doing this?
// TODO: the following is a bit of a hack.
// Here \n EOF is faked for this._rxfd inorder to close the read stream.
// It's faked three times as the uart may receive a character between
// \n and EOF and the stream will not be closed. Faking three times
// increases the chances of it working!
su.setCanonical(this._rxfd, true);
su.fakeInput(this._rxfd, '\n'.charCodeAt(0));
su.fakeInput(this._rxfd, 4); // fake eof
su.fakeInput(this._rxfd, '\n'.charCodeAt(0));
su.fakeInput(this._rxfd, 4); // fake eof
su.fakeInput(this._rxfd, '\n'.charCodeAt(0));
su.fakeInput(this._rxfd, 4); // fake eof
};
| fivdi/brkontru | lib/uart.js | JavaScript | mit | 6,528 |
package de.andreasgiemza.mangadownloader.gui.chapter;
import de.andreasgiemza.mangadownloader.MangaDownloader;
import de.andreasgiemza.mangadownloader.helpers.RegexHelper;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableRowSorter;
/**
*
* @author Andreas Giemza <andreas@giemza.net>
*/
public class ChapterListSearchDocumentListener implements DocumentListener {
private final MangaDownloader mangaDownloader;
private final JTextField chapterListSearchTextField;
private final TableRowSorter<ChapterTableModel> chapterTableRowSorter;
@SuppressWarnings("unchecked")
public ChapterListSearchDocumentListener(MangaDownloader mangaDownloader,
JTextField chapterListSearchTextField, JTable chapterListTable) {
this.mangaDownloader = mangaDownloader;
this.chapterListSearchTextField = chapterListSearchTextField;
chapterTableRowSorter = (TableRowSorter<ChapterTableModel>) chapterListTable
.getRowSorter();
}
@Override
public void insertUpdate(DocumentEvent e) {
changed();
}
@Override
public void removeUpdate(DocumentEvent e) {
changed();
}
@Override
public void changedUpdate(DocumentEvent e) {
changed();
}
private void changed() {
mangaDownloader.chapterSearchChanged();
final String searchText = chapterListSearchTextField.getText();
if (searchText.length() == 0) {
chapterTableRowSorter.setRowFilter(null);
} else if (searchText.length() > 0) {
chapterTableRowSorter.setRowFilter(RowFilter
.regexFilter(RegexHelper.build(searchText)));
}
}
}
| hurik/MangaDownloader | src/main/java/de/andreasgiemza/mangadownloader/gui/chapter/ChapterListSearchDocumentListener.java | Java | mit | 1,897 |
package nxt.http;
import nxt.Account;
import nxt.Attachment;
import nxt.Constants;
import nxt.NxtException;
import nxt.util.Convert;
import org.json.simple.JSONStreamAware;
import javax.servlet.http.HttpServletRequest;
import static nxt.http.JSONResponses.INCORRECT_ASSET;
import static nxt.http.JSONResponses.INCORRECT_PRICE;
import static nxt.http.JSONResponses.INCORRECT_QUANTITY;
import static nxt.http.JSONResponses.MISSING_ASSET;
import static nxt.http.JSONResponses.MISSING_PRICE;
import static nxt.http.JSONResponses.MISSING_QUANTITY;
import static nxt.http.JSONResponses.NOT_ENOUGH_ASSETS;
import static nxt.http.JSONResponses.UNKNOWN_ACCOUNT;
public final class PlaceAskOrder extends CreateTransaction {
static final PlaceAskOrder instance = new PlaceAskOrder();
private PlaceAskOrder() {
super("asset", "quantity", "price");
}
@Override
JSONStreamAware processRequest(HttpServletRequest req) throws NxtException.ValidationException {
String assetValue = req.getParameter("asset");
String quantityValue = req.getParameter("quantity");
String priceValue = req.getParameter("price");
if (assetValue == null) {
return MISSING_ASSET;
} else if (quantityValue == null) {
return MISSING_QUANTITY;
} else if (priceValue == null) {
return MISSING_PRICE;
}
long price;
try {
price = Long.parseLong(priceValue);
if (price <= 0 || price > Constants.MAX_BALANCE * 100L) {
return INCORRECT_PRICE;
}
} catch (NumberFormatException e) {
return INCORRECT_PRICE;
}
Long asset;
try {
asset = Convert.parseUnsignedLong(assetValue);
} catch (RuntimeException e) {
return INCORRECT_ASSET;
}
int quantity;
try {
quantity = Integer.parseInt(quantityValue);
if (quantity <= 0 || quantity > Constants.MAX_ASSET_QUANTITY) {
return INCORRECT_QUANTITY;
}
} catch (NumberFormatException e) {
return INCORRECT_QUANTITY;
}
Account account = getAccount(req);
if (account == null) {
return UNKNOWN_ACCOUNT;
}
Integer assetBalance = account.getUnconfirmedAssetBalance(asset);
if (assetBalance == null || quantity > assetBalance) {
return NOT_ENOUGH_ASSETS;
}
Attachment attachment = new Attachment.ColoredCoinsAskOrderPlacement(asset, quantity, price);
return createTransaction(req, account, attachment);
}
}
| aspnmy/NasCoin | src/java/nxt/http/PlaceAskOrder.java | Java | mit | 2,662 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var FaHouzz = function FaHouzz(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm19.9 26.6l11.5-6.6v13.2l-11.5 6.6v-13.2z m-11.4-6.6v13.2l11.4-6.6z m11.4-19.8v13.2l-11.4 6.6v-13.2z m0 13.2l11.5-6.6v13.2z' })
)
);
};
exports.default = FaHouzz;
module.exports = exports['default']; | bengimbel/Solstice-React-Contacts-Project | node_modules/react-icons/lib/fa/houzz.js | JavaScript | mit | 1,139 |
//===--- JumpDiagnostics.cpp - Protected scope jump analysis ------*- C++ -*-=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the JumpScopeChecker class, which is used to diagnose
// jumps that enter a protected scope in an invalid way.
//
//===----------------------------------------------------------------------===//
#include "clang/Sema/SemaInternal.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/StmtObjC.h"
#include "llvm/ADT/BitVector.h"
using namespace clang;
namespace {
/// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps
/// into VLA and other protected scopes. For example, this rejects:
/// goto L;
/// int a[n];
/// L:
///
class JumpScopeChecker {
Sema &S;
/// Permissive - True when recovering from errors, in which case precautions
/// are taken to handle incomplete scope information.
const bool Permissive;
/// GotoScope - This is a record that we use to keep track of all of the
/// scopes that are introduced by VLAs and other things that scope jumps like
/// gotos. This scope tree has nothing to do with the source scope tree,
/// because you can have multiple VLA scopes per compound statement, and most
/// compound statements don't introduce any scopes.
struct GotoScope {
/// ParentScope - The index in ScopeMap of the parent scope. This is 0 for
/// the parent scope is the function body.
unsigned ParentScope;
/// InDiag - The note to emit if there is a jump into this scope.
unsigned InDiag;
/// OutDiag - The note to emit if there is an indirect jump out
/// of this scope. Direct jumps always clean up their current scope
/// in an orderly way.
unsigned OutDiag;
/// Loc - Location to emit the diagnostic.
SourceLocation Loc;
GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag,
SourceLocation L)
: ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {}
};
SmallVector<GotoScope, 48> Scopes;
llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
SmallVector<Stmt*, 16> Jumps;
SmallVector<IndirectGotoStmt*, 4> IndirectJumps;
SmallVector<LabelDecl*, 4> IndirectJumpTargets;
public:
JumpScopeChecker(Stmt *Body, Sema &S);
private:
void BuildScopeInformation(Decl *D, unsigned &ParentScope);
void BuildScopeInformation(VarDecl *D, const BlockDecl *BDecl,
unsigned &ParentScope);
void BuildScopeInformation(Stmt *S, unsigned &origParentScope);
void VerifyJumps();
void VerifyIndirectJumps();
void NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes);
void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope,
LabelDecl *Target, unsigned TargetScope);
void CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
unsigned JumpDiag, unsigned JumpDiagWarning,
unsigned JumpDiagCXX98Compat);
void CheckGotoStmt(GotoStmt *GS);
unsigned GetDeepestCommonScope(unsigned A, unsigned B);
};
} // end anonymous namespace
#define CHECK_PERMISSIVE(x) (assert(Permissive || !(x)), (Permissive && (x)))
JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s)
: S(s), Permissive(s.hasAnyUnrecoverableErrorsInThisFunction()) {
// Add a scope entry for function scope.
Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
// Build information for the top level compound statement, so that we have a
// defined scope record for every "goto" and label.
unsigned BodyParentScope = 0;
BuildScopeInformation(Body, BodyParentScope);
// Check that all jumps we saw are kosher.
VerifyJumps();
VerifyIndirectJumps();
}
/// GetDeepestCommonScope - Finds the innermost scope enclosing the
/// two scopes.
unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
while (A != B) {
// Inner scopes are created after outer scopes and therefore have
// higher indices.
if (A < B) {
assert(Scopes[B].ParentScope < B);
B = Scopes[B].ParentScope;
} else {
assert(Scopes[A].ParentScope < A);
A = Scopes[A].ParentScope;
}
}
return A;
}
typedef std::pair<unsigned,unsigned> ScopePair;
/// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
/// diagnostic that should be emitted if control goes over it. If not, return 0.
static ScopePair GetDiagForGotoScopeDecl(Sema &S, const Decl *D) {
if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
unsigned InDiag = 0;
unsigned OutDiag = 0;
if (VD->getType()->isVariablyModifiedType())
InDiag = diag::note_protected_by_vla;
if (VD->hasAttr<BlocksAttr>())
return ScopePair(diag::note_protected_by___block,
diag::note_exits___block);
if (VD->hasAttr<CleanupAttr>())
return ScopePair(diag::note_protected_by_cleanup,
diag::note_exits_cleanup);
if (VD->hasLocalStorage()) {
switch (VD->getType().isDestructedType()) {
case QualType::DK_objc_strong_lifetime:
return ScopePair(diag::note_protected_by_objc_strong_init,
diag::note_exits_objc_strong);
case QualType::DK_objc_weak_lifetime:
return ScopePair(diag::note_protected_by_objc_weak_init,
diag::note_exits_objc_weak);
case QualType::DK_cxx_destructor:
OutDiag = diag::note_exits_dtor;
break;
case QualType::DK_none:
break;
}
}
const Expr *Init = VD->getInit();
if (S.Context.getLangOpts().CPlusPlus && VD->hasLocalStorage() && Init) {
// C++11 [stmt.dcl]p3:
// A program that jumps from a point where a variable with automatic
// storage duration is not in scope to a point where it is in scope
// is ill-formed unless the variable has scalar type, class type with
// a trivial default constructor and a trivial destructor, a
// cv-qualified version of one of these types, or an array of one of
// the preceding types and is declared without an initializer.
// C++03 [stmt.dcl.p3:
// A program that jumps from a point where a local variable
// with automatic storage duration is not in scope to a point
// where it is in scope is ill-formed unless the variable has
// POD type and is declared without an initializer.
InDiag = diag::note_protected_by_variable_init;
// For a variable of (array of) class type declared without an
// initializer, we will have call-style initialization and the initializer
// will be the CXXConstructExpr with no intervening nodes.
if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
const CXXConstructorDecl *Ctor = CCE->getConstructor();
if (Ctor->isTrivial() && Ctor->isDefaultConstructor() &&
VD->getInitStyle() == VarDecl::CallInit) {
if (OutDiag)
InDiag = diag::note_protected_by_variable_nontriv_destructor;
else if (!Ctor->getParent()->isPOD())
InDiag = diag::note_protected_by_variable_non_pod;
else
InDiag = 0;
}
}
}
return ScopePair(InDiag, OutDiag);
}
if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
if (TD->getUnderlyingType()->isVariablyModifiedType())
return ScopePair(isa<TypedefDecl>(TD)
? diag::note_protected_by_vla_typedef
: diag::note_protected_by_vla_type_alias,
0);
}
return ScopePair(0U, 0U);
}
/// \brief Build scope information for a declaration that is part of a DeclStmt.
void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
// If this decl causes a new scope, push and switch to it.
std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S, D);
if (Diags.first || Diags.second) {
Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
D->getLocation()));
ParentScope = Scopes.size()-1;
}
// If the decl has an initializer, walk it with the potentially new
// scope we just installed.
if (VarDecl *VD = dyn_cast<VarDecl>(D))
if (Expr *Init = VD->getInit())
BuildScopeInformation(Init, ParentScope);
}
/// \brief Build scope information for a captured block literal variables.
void JumpScopeChecker::BuildScopeInformation(VarDecl *D,
const BlockDecl *BDecl,
unsigned &ParentScope) {
// exclude captured __block variables; there's no destructor
// associated with the block literal for them.
if (D->hasAttr<BlocksAttr>())
return;
QualType T = D->getType();
QualType::DestructionKind destructKind = T.isDestructedType();
if (destructKind != QualType::DK_none) {
std::pair<unsigned,unsigned> Diags;
switch (destructKind) {
case QualType::DK_cxx_destructor:
Diags = ScopePair(diag::note_enters_block_captures_cxx_obj,
diag::note_exits_block_captures_cxx_obj);
break;
case QualType::DK_objc_strong_lifetime:
Diags = ScopePair(diag::note_enters_block_captures_strong,
diag::note_exits_block_captures_strong);
break;
case QualType::DK_objc_weak_lifetime:
Diags = ScopePair(diag::note_enters_block_captures_weak,
diag::note_exits_block_captures_weak);
break;
case QualType::DK_none:
llvm_unreachable("non-lifetime captured variable");
}
SourceLocation Loc = D->getLocation();
if (Loc.isInvalid())
Loc = BDecl->getLocation();
Scopes.push_back(GotoScope(ParentScope,
Diags.first, Diags.second, Loc));
ParentScope = Scopes.size()-1;
}
}
/// BuildScopeInformation - The statements from CI to CE are known to form a
/// coherent VLA scope with a specified parent node. Walk through the
/// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
/// walking the AST as needed.
void JumpScopeChecker::BuildScopeInformation(Stmt *S,
unsigned &origParentScope) {
// If this is a statement, rather than an expression, scopes within it don't
// propagate out into the enclosing scope. Otherwise we have to worry
// about block literals, which have the lifetime of their enclosing statement.
unsigned independentParentScope = origParentScope;
unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S))
? origParentScope : independentParentScope);
unsigned StmtsToSkip = 0u;
// If we found a label, remember that it is in ParentScope scope.
switch (S->getStmtClass()) {
case Stmt::AddrLabelExprClass:
IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
break;
case Stmt::IndirectGotoStmtClass:
// "goto *&&lbl;" is a special case which we treat as equivalent
// to a normal goto. In addition, we don't calculate scope in the
// operand (to avoid recording the address-of-label use), which
// works only because of the restricted set of expressions which
// we detect as constant targets.
if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
LabelAndGotoScopes[S] = ParentScope;
Jumps.push_back(S);
return;
}
LabelAndGotoScopes[S] = ParentScope;
IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
break;
case Stmt::SwitchStmtClass:
// Evaluate the C++17 init stmt and condition variable
// before entering the scope of the switch statement.
if (Stmt *Init = cast<SwitchStmt>(S)->getInit()) {
BuildScopeInformation(Init, ParentScope);
++StmtsToSkip;
}
if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
BuildScopeInformation(Var, ParentScope);
++StmtsToSkip;
}
// Fall through
case Stmt::GotoStmtClass:
// Remember both what scope a goto is in as well as the fact that we have
// it. This makes the second scan not have to walk the AST again.
LabelAndGotoScopes[S] = ParentScope;
Jumps.push_back(S);
break;
case Stmt::IfStmtClass: {
IfStmt *IS = cast<IfStmt>(S);
if (!(IS->isConstexpr() || IS->isObjCAvailabilityCheck()))
break;
unsigned Diag = IS->isConstexpr() ? diag::note_protected_by_constexpr_if
: diag::note_protected_by_if_available;
if (VarDecl *Var = IS->getConditionVariable())
BuildScopeInformation(Var, ParentScope);
// Cannot jump into the middle of the condition.
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getLocStart()));
BuildScopeInformation(IS->getCond(), NewParentScope);
// Jumps into either arm of an 'if constexpr' are not allowed.
NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getLocStart()));
BuildScopeInformation(IS->getThen(), NewParentScope);
if (Stmt *Else = IS->getElse()) {
NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getLocStart()));
BuildScopeInformation(Else, NewParentScope);
}
return;
}
case Stmt::CXXTryStmtClass: {
CXXTryStmt *TS = cast<CXXTryStmt>(S);
{
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_cxx_try,
diag::note_exits_cxx_try,
TS->getSourceRange().getBegin()));
if (Stmt *TryBlock = TS->getTryBlock())
BuildScopeInformation(TryBlock, NewParentScope);
}
// Jump from the catch into the try is not allowed either.
for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
CXXCatchStmt *CS = TS->getHandler(I);
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_cxx_catch,
diag::note_exits_cxx_catch,
CS->getSourceRange().getBegin()));
BuildScopeInformation(CS->getHandlerBlock(), NewParentScope);
}
return;
}
case Stmt::SEHTryStmtClass: {
SEHTryStmt *TS = cast<SEHTryStmt>(S);
{
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_seh_try,
diag::note_exits_seh_try,
TS->getSourceRange().getBegin()));
if (Stmt *TryBlock = TS->getTryBlock())
BuildScopeInformation(TryBlock, NewParentScope);
}
// Jump from __except or __finally into the __try are not allowed either.
if (SEHExceptStmt *Except = TS->getExceptHandler()) {
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_seh_except,
diag::note_exits_seh_except,
Except->getSourceRange().getBegin()));
BuildScopeInformation(Except->getBlock(), NewParentScope);
} else if (SEHFinallyStmt *Finally = TS->getFinallyHandler()) {
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_seh_finally,
diag::note_exits_seh_finally,
Finally->getSourceRange().getBegin()));
BuildScopeInformation(Finally->getBlock(), NewParentScope);
}
return;
}
case Stmt::DeclStmtClass: {
// If this is a declstmt with a VLA definition, it defines a scope from here
// to the end of the containing context.
DeclStmt *DS = cast<DeclStmt>(S);
// The decl statement creates a scope if any of the decls in it are VLAs
// or have the cleanup attribute.
for (auto *I : DS->decls())
BuildScopeInformation(I, origParentScope);
return;
}
case Stmt::ObjCAtTryStmtClass: {
// Disallow jumps into any part of an @try statement by pushing a scope and
// walking all sub-stmts in that scope.
ObjCAtTryStmt *AT = cast<ObjCAtTryStmt>(S);
// Recursively walk the AST for the @try part.
{
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_objc_try,
diag::note_exits_objc_try,
AT->getAtTryLoc()));
if (Stmt *TryPart = AT->getTryBody())
BuildScopeInformation(TryPart, NewParentScope);
}
// Jump from the catch to the finally or try is not valid.
for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_objc_catch,
diag::note_exits_objc_catch,
AC->getAtCatchLoc()));
// @catches are nested and it isn't
BuildScopeInformation(AC->getCatchBody(), NewParentScope);
}
// Jump from the finally to the try or catch is not valid.
if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_objc_finally,
diag::note_exits_objc_finally,
AF->getAtFinallyLoc()));
BuildScopeInformation(AF, NewParentScope);
}
return;
}
case Stmt::ObjCAtSynchronizedStmtClass: {
// Disallow jumps into the protected statement of an @synchronized, but
// allow jumps into the object expression it protects.
ObjCAtSynchronizedStmt *AS = cast<ObjCAtSynchronizedStmt>(S);
// Recursively walk the AST for the @synchronized object expr, it is
// evaluated in the normal scope.
BuildScopeInformation(AS->getSynchExpr(), ParentScope);
// Recursively walk the AST for the @synchronized part, protected by a new
// scope.
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_objc_synchronized,
diag::note_exits_objc_synchronized,
AS->getAtSynchronizedLoc()));
BuildScopeInformation(AS->getSynchBody(), NewParentScope);
return;
}
case Stmt::ObjCAutoreleasePoolStmtClass: {
// Disallow jumps into the protected statement of an @autoreleasepool.
ObjCAutoreleasePoolStmt *AS = cast<ObjCAutoreleasePoolStmt>(S);
// Recursively walk the AST for the @autoreleasepool part, protected by a
// new scope.
unsigned NewParentScope = Scopes.size();
Scopes.push_back(GotoScope(ParentScope,
diag::note_protected_by_objc_autoreleasepool,
diag::note_exits_objc_autoreleasepool,
AS->getAtLoc()));
BuildScopeInformation(AS->getSubStmt(), NewParentScope);
return;
}
case Stmt::ExprWithCleanupsClass: {
// Disallow jumps past full-expressions that use blocks with
// non-trivial cleanups of their captures. This is theoretically
// implementable but a lot of work which we haven't felt up to doing.
ExprWithCleanups *EWC = cast<ExprWithCleanups>(S);
for (unsigned i = 0, e = EWC->getNumObjects(); i != e; ++i) {
const BlockDecl *BDecl = EWC->getObject(i);
for (const auto &CI : BDecl->captures()) {
VarDecl *variable = CI.getVariable();
BuildScopeInformation(variable, BDecl, origParentScope);
}
}
break;
}
case Stmt::MaterializeTemporaryExprClass: {
// Disallow jumps out of scopes containing temporaries lifetime-extended to
// automatic storage duration.
MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
if (MTE->getStorageDuration() == SD_Automatic) {
SmallVector<const Expr *, 4> CommaLHS;
SmallVector<SubobjectAdjustment, 4> Adjustments;
const Expr *ExtendedObject =
MTE->GetTemporaryExpr()->skipRValueSubobjectAdjustments(
CommaLHS, Adjustments);
if (ExtendedObject->getType().isDestructedType()) {
Scopes.push_back(GotoScope(ParentScope, 0,
diag::note_exits_temporary_dtor,
ExtendedObject->getExprLoc()));
origParentScope = Scopes.size()-1;
}
}
break;
}
case Stmt::CaseStmtClass:
case Stmt::DefaultStmtClass:
case Stmt::LabelStmtClass:
LabelAndGotoScopes[S] = ParentScope;
break;
default:
break;
}
for (Stmt *SubStmt : S->children()) {
if (!SubStmt)
continue;
if (StmtsToSkip) {
--StmtsToSkip;
continue;
}
// Cases, labels, and defaults aren't "scope parents". It's also
// important to handle these iteratively instead of recursively in
// order to avoid blowing out the stack.
while (true) {
Stmt *Next;
if (SwitchCase *SC = dyn_cast<SwitchCase>(SubStmt))
Next = SC->getSubStmt();
else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
Next = LS->getSubStmt();
else
break;
LabelAndGotoScopes[SubStmt] = ParentScope;
SubStmt = Next;
}
// Recursively walk the AST.
BuildScopeInformation(SubStmt, ParentScope);
}
}
/// VerifyJumps - Verify each element of the Jumps array to see if they are
/// valid, emitting diagnostics if not.
void JumpScopeChecker::VerifyJumps() {
while (!Jumps.empty()) {
Stmt *Jump = Jumps.pop_back_val();
// With a goto,
if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
// The label may not have a statement if it's coming from inline MS ASM.
if (GS->getLabel()->getStmt()) {
CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
diag::err_goto_into_protected_scope,
diag::ext_goto_into_protected_scope,
diag::warn_cxx98_compat_goto_into_protected_scope);
}
CheckGotoStmt(GS);
continue;
}
// We only get indirect gotos here when they have a constant target.
if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
LabelDecl *Target = IGS->getConstantTarget();
CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
diag::err_goto_into_protected_scope,
diag::ext_goto_into_protected_scope,
diag::warn_cxx98_compat_goto_into_protected_scope);
continue;
}
SwitchStmt *SS = cast<SwitchStmt>(Jump);
for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
SC = SC->getNextSwitchCase()) {
if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(SC)))
continue;
SourceLocation Loc;
if (CaseStmt *CS = dyn_cast<CaseStmt>(SC))
Loc = CS->getLocStart();
else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC))
Loc = DS->getLocStart();
else
Loc = SC->getLocStart();
CheckJump(SS, SC, Loc, diag::err_switch_into_protected_scope, 0,
diag::warn_cxx98_compat_switch_into_protected_scope);
}
}
}
/// VerifyIndirectJumps - Verify whether any possible indirect jump
/// might cross a protection boundary. Unlike direct jumps, indirect
/// jumps count cleanups as protection boundaries: since there's no
/// way to know where the jump is going, we can't implicitly run the
/// right cleanups the way we can with direct jumps.
///
/// Thus, an indirect jump is "trivial" if it bypasses no
/// initializations and no teardowns. More formally, an indirect jump
/// from A to B is trivial if the path out from A to DCA(A,B) is
/// trivial and the path in from DCA(A,B) to B is trivial, where
/// DCA(A,B) is the deepest common ancestor of A and B.
/// Jump-triviality is transitive but asymmetric.
///
/// A path in is trivial if none of the entered scopes have an InDiag.
/// A path out is trivial is none of the exited scopes have an OutDiag.
///
/// Under these definitions, this function checks that the indirect
/// jump between A and B is trivial for every indirect goto statement A
/// and every label B whose address was taken in the function.
void JumpScopeChecker::VerifyIndirectJumps() {
if (IndirectJumps.empty()) return;
// If there aren't any address-of-label expressions in this function,
// complain about the first indirect goto.
if (IndirectJumpTargets.empty()) {
S.Diag(IndirectJumps[0]->getGotoLoc(),
diag::err_indirect_goto_without_addrlabel);
return;
}
// Collect a single representative of every scope containing an
// indirect goto. For most code bases, this substantially cuts
// down on the number of jump sites we'll have to consider later.
typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
SmallVector<JumpScope, 32> JumpScopes;
{
llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
for (SmallVectorImpl<IndirectGotoStmt*>::iterator
I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
IndirectGotoStmt *IG = *I;
if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(IG)))
continue;
unsigned IGScope = LabelAndGotoScopes[IG];
IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
if (!Entry) Entry = IG;
}
JumpScopes.reserve(JumpScopesMap.size());
for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
JumpScopes.push_back(*I);
}
// Collect a single representative of every scope containing a
// label whose address was taken somewhere in the function.
// For most code bases, there will be only one such scope.
llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
for (SmallVectorImpl<LabelDecl*>::iterator
I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
I != E; ++I) {
LabelDecl *TheLabel = *I;
if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(TheLabel->getStmt())))
continue;
unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
LabelDecl *&Target = TargetScopes[LabelScope];
if (!Target) Target = TheLabel;
}
// For each target scope, make sure it's trivially reachable from
// every scope containing a jump site.
//
// A path between scopes always consists of exitting zero or more
// scopes, then entering zero or more scopes. We build a set of
// of scopes S from which the target scope can be trivially
// entered, then verify that every jump scope can be trivially
// exitted to reach a scope in S.
llvm::BitVector Reachable(Scopes.size(), false);
for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
unsigned TargetScope = TI->first;
LabelDecl *TargetLabel = TI->second;
Reachable.reset();
// Mark all the enclosing scopes from which you can safely jump
// into the target scope. 'Min' will end up being the index of
// the shallowest such scope.
unsigned Min = TargetScope;
while (true) {
Reachable.set(Min);
// Don't go beyond the outermost scope.
if (Min == 0) break;
// Stop if we can't trivially enter the current scope.
if (Scopes[Min].InDiag) break;
Min = Scopes[Min].ParentScope;
}
// Walk through all the jump sites, checking that they can trivially
// reach this label scope.
for (SmallVectorImpl<JumpScope>::iterator
I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
unsigned Scope = I->first;
// Walk out the "scope chain" for this scope, looking for a scope
// we've marked reachable. For well-formed code this amortizes
// to O(JumpScopes.size() / Scopes.size()): we only iterate
// when we see something unmarked, and in well-formed code we
// mark everything we iterate past.
bool IsReachable = false;
while (true) {
if (Reachable.test(Scope)) {
// If we find something reachable, mark all the scopes we just
// walked through as reachable.
for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
Reachable.set(S);
IsReachable = true;
break;
}
// Don't walk out if we've reached the top-level scope or we've
// gotten shallower than the shallowest reachable scope.
if (Scope == 0 || Scope < Min) break;
// Don't walk out through an out-diagnostic.
if (Scopes[Scope].OutDiag) break;
Scope = Scopes[Scope].ParentScope;
}
// Only diagnose if we didn't find something.
if (IsReachable) continue;
DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
}
}
}
/// Return true if a particular error+note combination must be downgraded to a
/// warning in Microsoft mode.
static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) {
return (JumpDiag == diag::err_goto_into_protected_scope &&
(InDiagNote == diag::note_protected_by_variable_init ||
InDiagNote == diag::note_protected_by_variable_nontriv_destructor));
}
/// Return true if a particular note should be downgraded to a compatibility
/// warning in C++11 mode.
static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) {
return S.getLangOpts().CPlusPlus11 &&
InDiagNote == diag::note_protected_by_variable_non_pod;
}
/// Produce primary diagnostic for an indirect jump statement.
static void DiagnoseIndirectJumpStmt(Sema &S, IndirectGotoStmt *Jump,
LabelDecl *Target, bool &Diagnosed) {
if (Diagnosed)
return;
S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
Diagnosed = true;
}
/// Produce note diagnostics for a jump into a protected scope.
void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) {
if (CHECK_PERMISSIVE(ToScopes.empty()))
return;
for (unsigned I = 0, E = ToScopes.size(); I != E; ++I)
if (Scopes[ToScopes[I]].InDiag)
S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag);
}
/// Diagnose an indirect jump which is known to cross scopes.
void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
unsigned JumpScope,
LabelDecl *Target,
unsigned TargetScope) {
if (CHECK_PERMISSIVE(JumpScope == TargetScope))
return;
unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
bool Diagnosed = false;
// Walk out the scope chain until we reach the common ancestor.
for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
if (Scopes[I].OutDiag) {
DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
}
SmallVector<unsigned, 10> ToScopesCXX98Compat;
// Now walk into the scopes containing the label whose address was taken.
for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
ToScopesCXX98Compat.push_back(I);
else if (Scopes[I].InDiag) {
DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
}
// Diagnose this jump if it would be ill-formed in C++98.
if (!Diagnosed && !ToScopesCXX98Compat.empty()) {
S.Diag(Jump->getGotoLoc(),
diag::warn_cxx98_compat_indirect_goto_in_protected_scope);
S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
NoteJumpIntoScopes(ToScopesCXX98Compat);
}
}
/// CheckJump - Validate that the specified jump statement is valid: that it is
/// jumping within or out of its current scope, not into a deeper one.
void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
unsigned JumpDiagError, unsigned JumpDiagWarning,
unsigned JumpDiagCXX98Compat) {
if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(From)))
return;
if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(To)))
return;
unsigned FromScope = LabelAndGotoScopes[From];
unsigned ToScope = LabelAndGotoScopes[To];
// Common case: exactly the same scope, which is fine.
if (FromScope == ToScope) return;
// Warn on gotos out of __finally blocks.
if (isa<GotoStmt>(From) || isa<IndirectGotoStmt>(From)) {
// If FromScope > ToScope, FromScope is more nested and the jump goes to a
// less nested scope. Check if it crosses a __finally along the way.
for (unsigned I = FromScope; I > ToScope; I = Scopes[I].ParentScope) {
if (Scopes[I].InDiag == diag::note_protected_by_seh_finally) {
S.Diag(From->getLocStart(), diag::warn_jump_out_of_seh_finally);
break;
}
}
}
unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
// It's okay to jump out from a nested scope.
if (CommonScope == ToScope) return;
// Pull out (and reverse) any scopes we might need to diagnose skipping.
SmallVector<unsigned, 10> ToScopesCXX98Compat;
SmallVector<unsigned, 10> ToScopesError;
SmallVector<unsigned, 10> ToScopesWarning;
for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) {
if (S.getLangOpts().MSVCCompat && JumpDiagWarning != 0 &&
IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag))
ToScopesWarning.push_back(I);
else if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
ToScopesCXX98Compat.push_back(I);
else if (Scopes[I].InDiag)
ToScopesError.push_back(I);
}
// Handle warnings.
if (!ToScopesWarning.empty()) {
S.Diag(DiagLoc, JumpDiagWarning);
NoteJumpIntoScopes(ToScopesWarning);
}
// Handle errors.
if (!ToScopesError.empty()) {
S.Diag(DiagLoc, JumpDiagError);
NoteJumpIntoScopes(ToScopesError);
}
// Handle -Wc++98-compat warnings if the jump is well-formed.
if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) {
S.Diag(DiagLoc, JumpDiagCXX98Compat);
NoteJumpIntoScopes(ToScopesCXX98Compat);
}
}
void JumpScopeChecker::CheckGotoStmt(GotoStmt *GS) {
if (GS->getLabel()->isMSAsmLabel()) {
S.Diag(GS->getGotoLoc(), diag::err_goto_ms_asm_label)
<< GS->getLabel()->getIdentifier();
S.Diag(GS->getLabel()->getLocation(), diag::note_goto_ms_asm_label)
<< GS->getLabel()->getIdentifier();
}
}
void Sema::DiagnoseInvalidJumps(Stmt *Body) {
(void)JumpScopeChecker(Body, *this);
}
| ensemblr/llvm-project-boilerplate | include/llvm/tools/clang/lib/Sema/JumpDiagnostics.cpp | C++ | mit | 35,368 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ==++==
//
//
// ==--==
// ****************************************************************************
// File: controller.cpp
//
//
// controller.cpp: Debugger execution control routines
//
// ****************************************************************************
// Putting code & #includes, #defines, etc, before the stdafx.h will
// cause the code,etc, to be silently ignored
#include "stdafx.h"
#include "openum.h"
#include "../inc/common.h"
#include "eeconfig.h"
#include "../../vm/methoditer.h"
const char *GetTType( TraceType tt);
#define IsSingleStep(exception) (exception == EXCEPTION_SINGLE_STEP)
// -------------------------------------------------------------------------
// DebuggerController routines
// -------------------------------------------------------------------------
SPTR_IMPL_INIT(DebuggerPatchTable, DebuggerController, g_patches, NULL);
SVAL_IMPL_INIT(BOOL, DebuggerController, g_patchTableValid, FALSE);
#if !defined(DACCESS_COMPILE)
DebuggerController *DebuggerController::g_controllers = NULL;
DebuggerControllerPage *DebuggerController::g_protections = NULL;
CrstStatic DebuggerController::g_criticalSection;
int DebuggerController::g_cTotalMethodEnter = 0;
// Is this patch at a position at which it's safe to take a stack?
bool DebuggerControllerPatch::IsSafeForStackTrace()
{
LIMITED_METHOD_CONTRACT;
TraceType tt = this->trace.GetTraceType();
Module *module = this->key.module;
BOOL managed = this->IsManagedPatch();
// Patches placed by MgrPush can come at lots of illegal spots. Can't take a stack trace here.
if ((module == NULL) && managed && (tt == TRACE_MGR_PUSH))
{
return false;
}
// Consider everything else legal.
// This is a little shady for TRACE_FRAME_PUSH. But TraceFrame() needs a stackInfo
// to get a RegDisplay (though almost nobody uses it, so perhaps it could be removed).
return true;
}
#ifndef _TARGET_ARM_
// returns a pointer to the shared buffer. each call will AddRef() the object
// before returning it so callers only need to Release() when they're finished with it.
SharedPatchBypassBuffer* DebuggerControllerPatch::GetOrCreateSharedPatchBypassBuffer()
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
}
CONTRACTL_END;
if (m_pSharedPatchBypassBuffer == NULL)
{
m_pSharedPatchBypassBuffer = new (interopsafeEXEC) SharedPatchBypassBuffer();
_ASSERTE(m_pSharedPatchBypassBuffer);
TRACE_ALLOC(m_pSharedPatchBypassBuffer);
}
m_pSharedPatchBypassBuffer->AddRef();
return m_pSharedPatchBypassBuffer;
}
#endif // _TARGET_ARM_
// @todo - remove all this splicing trash
// This Sort/Splice stuff just reorders the patches within a particular chain such
// that when we iterate through by calling GetPatch() and GetNextPatch(DebuggerControllerPatch),
// we'll get patches in increasing order of DebuggerControllerTypes.
// Practically, this means that calling GetPatch() will return EnC patches before stepping patches.
//
#if 1
void DebuggerPatchTable::SortPatchIntoPatchList(DebuggerControllerPatch **ppPatch)
{
LOG((LF_CORDB, LL_EVERYTHING, "DPT::SPIPL called.\n"));
#ifdef _DEBUG
DebuggerControllerPatch *patchFirst
= (DebuggerControllerPatch *) Find(Hash((*ppPatch)), Key((*ppPatch)));
_ASSERTE(patchFirst == (*ppPatch));
_ASSERTE((*ppPatch)->controller->GetDCType() != DEBUGGER_CONTROLLER_STATIC);
#endif //_DEBUG
DebuggerControllerPatch *patchNext = GetNextPatch((*ppPatch));
LOG((LF_CORDB, LL_EVERYTHING, "DPT::SPIPL GetNextPatch passed\n"));
//List contains one, (sorted) element
if (patchNext == NULL)
{
LOG((LF_CORDB, LL_INFO10000,
"DPT::SPIPL: Patch 0x%x is a sorted singleton\n", (*ppPatch)));
return;
}
// If we decide to reorder the list, we'll need to keep the element
// indexed by the hash function as the (sorted)first item. Everything else
// chains off this element, can can thus stay put.
// Thus, either the element we just added is already sorted, or else we'll
// have to move it elsewhere in the list, meaning that we'll have to swap
// the second item & the new item, so that the index points to the proper
// first item in the list.
//use Cur ptr for case where patch gets appended to list
DebuggerControllerPatch *patchCur = patchNext;
while (patchNext != NULL &&
((*ppPatch)->controller->GetDCType() >
patchNext->controller->GetDCType()) )
{
patchCur = patchNext;
patchNext = GetNextPatch(patchNext);
}
if (patchNext == GetNextPatch((*ppPatch)))
{
LOG((LF_CORDB, LL_INFO10000,
"DPT::SPIPL: Patch 0x%x is already sorted\n", (*ppPatch)));
return; //already sorted
}
LOG((LF_CORDB, LL_INFO10000,
"DPT::SPIPL: Patch 0x%x will be moved \n", (*ppPatch)));
//remove it from the list
SpliceOutOfList((*ppPatch));
// the kinda neat thing is: since we put it originally at the front of the list,
// and it's not in order, then it must be behind another element of this list,
// so we don't have to write any 'SpliceInFrontOf' code.
_ASSERTE(patchCur != NULL);
SpliceInBackOf((*ppPatch), patchCur);
LOG((LF_CORDB, LL_INFO10000,
"DPT::SPIPL: Patch 0x%x is now sorted\n", (*ppPatch)));
}
// This can leave the list empty, so don't do this unless you put
// the patch back somewhere else.
void DebuggerPatchTable::SpliceOutOfList(DebuggerControllerPatch *patch)
{
// We need to get iHash, the index of the ptr within
// m_piBuckets, ie it's entry in the hashtable.
ULONG iHash = Hash(patch) % m_iBuckets;
ULONG iElement = m_piBuckets[iHash];
DebuggerControllerPatch *patchFirst
= (DebuggerControllerPatch *) EntryPtr(iElement);
// Fix up pointers to chain
if (patchFirst == patch)
{
// The first patch shouldn't have anything behind it.
_ASSERTE(patch->entry.iPrev == DPT_INVALID_SLOT);
if (patch->entry.iNext != DPT_INVALID_SLOT)
{
m_piBuckets[iHash] = patch->entry.iNext;
}
else
{
m_piBuckets[iHash] = DPT_INVALID_SLOT;
}
}
if (patch->entry.iNext != DPT_INVALID_SLOT)
{
EntryPtr(patch->entry.iNext)->iPrev = patch->entry.iPrev;
}
if (patch->entry.iPrev != DPT_INVALID_SLOT)
{
EntryPtr(patch->entry.iNext)->iNext = patch->entry.iNext;
}
patch->entry.iNext = DPT_INVALID_SLOT;
patch->entry.iPrev = DPT_INVALID_SLOT;
}
void DebuggerPatchTable::SpliceInBackOf(DebuggerControllerPatch *patchAppend,
DebuggerControllerPatch *patchEnd)
{
ULONG iAppend = ItemIndex((HASHENTRY*)patchAppend);
ULONG iEnd = ItemIndex((HASHENTRY*)patchEnd);
patchAppend->entry.iPrev = iEnd;
patchAppend->entry.iNext = patchEnd->entry.iNext;
if (patchAppend->entry.iNext != DPT_INVALID_SLOT)
EntryPtr(patchAppend->entry.iNext)->iPrev = iAppend;
patchEnd->entry.iNext = iAppend;
}
#endif
//-----------------------------------------------------------------------------
// Stack safety rules.
// In general, we're safe to crawl whenever we're in preemptive mode.
// We're also must be safe at any spot the thread could get synchronized,
// because that means that the thread will be stopped to let the debugger shell
// inspect it and that can definitely take stack traces.
// Basically the only unsafe spot is in the middle of goofy stub with some
// partially constructed frame while in coop mode.
//-----------------------------------------------------------------------------
// Safe if we're at certain types of patches.
// See Patch::IsSafeForStackTrace for details.
StackTraceTicket::StackTraceTicket(DebuggerControllerPatch * patch)
{
_ASSERTE(patch != NULL);
_ASSERTE(patch->IsSafeForStackTrace());
}
// Safe if there was already another stack trace at this spot. (Grandfather clause)
// This is commonly used for StepOut, which takes runs stacktraces to crawl up
// the stack to find a place to patch.
StackTraceTicket::StackTraceTicket(ControllerStackInfo * info)
{
_ASSERTE(info != NULL);
// Ensure that the other stack info object actually executed (and thus was
// actually valid).
_ASSERTE(info->m_dbgExecuted);
}
// Safe b/c the context shows we're in native managed code.
// This must be safe because we could always set a managed breakpoint by native
// offset and thus synchronize the shell at this spot. So this is
// a specific example of the Synchronized case. The fact that we don't actually
// synchronize doesn't make us any less safe.
StackTraceTicket::StackTraceTicket(const BYTE * ip)
{
_ASSERTE(g_pEEInterface->IsManagedNativeCode(ip));
}
// Safe it we're at a Synchronized point point.
StackTraceTicket::StackTraceTicket(Thread * pThread)
{
_ASSERTE(pThread != NULL);
// If we're synchronized, the debugger should be stopped.
// That means all threads are synced and must be safe to take a stacktrace.
// Thus we don't even need to do a thread-specific check.
_ASSERTE(g_pDebugger->IsStopped());
}
// DebuggerUserBreakpoint has a special case of safety. See that ctor for details.
StackTraceTicket::StackTraceTicket(DebuggerUserBreakpoint * p)
{
_ASSERTE(p != NULL);
}
//void ControllerStackInfo::GetStackInfo(): GetStackInfo
// is invoked by the user to trigger the stack walk. This will
// cause the stack walk detailed in the class description to happen.
// Thread* thread: The thread to do the stack walk on.
// void* targetFP: Can be either NULL (meaning that the bottommost
// frame is the target), or an frame pointer, meaning that the
// caller wants information about a specific frame.
// CONTEXT* pContext: A pointer to a CONTEXT structure. Can be null,
// we use our temp context.
// bool suppressUMChainFromComPlusMethodFrameGeneric - A ridiculous flag that is trying to narrowly
// target a fix for issue 650903.
// StackTraceTicket - ticket to ensure that we actually have permission for this stacktrace
void ControllerStackInfo::GetStackInfo(
StackTraceTicket ticket,
Thread *thread,
FramePointer targetFP,
CONTEXT *pContext,
bool suppressUMChainFromComPlusMethodFrameGeneric
)
{
_ASSERTE(thread != NULL);
BOOL contextValid = (pContext != NULL);
if (!contextValid)
{
// We're assuming the thread is protected w/ a frame (which includes the redirection
// case). The stackwalker will use that protection to prime the context.
pContext = &this->m_tempContext;
}
else
{
// If we provided an explicit context for this thread, it better not be redirected.
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
}
// Mark this stackwalk as valid so that it can in turn be used to grandfather
// in other stackwalks.
INDEBUG(m_dbgExecuted = true);
m_activeFound = false;
m_returnFound = false;
m_bottomFP = LEAF_MOST_FRAME;
m_targetFP = targetFP;
m_targetFrameFound = (m_targetFP == LEAF_MOST_FRAME);
m_specialChainReason = CHAIN_NONE;
m_suppressUMChainFromComPlusMethodFrameGeneric = suppressUMChainFromComPlusMethodFrameGeneric;
int result = DebuggerWalkStack(thread,
LEAF_MOST_FRAME,
pContext,
contextValid,
WalkStack,
(void *) this,
FALSE);
_ASSERTE(m_activeFound); // All threads have at least one unmanaged frame
if (result == SWA_DONE)
{
_ASSERTE(!m_returnFound);
m_returnFrame = m_activeFrame;
}
}
//---------------------------------------------------------------------------------------
//
// This function "undoes" an unwind, i.e. it takes the active frame (the current frame)
// and sets it to be the return frame (the caller frame). Currently it is only used by
// the stepper to step out of an LCG method. See DebuggerStepper::DetectHandleLCGMethods()
// for more information.
//
// Assumptions:
// The current frame is valid on entry.
//
// Notes:
// After this function returns, the active frame on this instance of ControllerStackInfo will no longer be valid.
//
// This function is specifically for DebuggerStepper::DetectHandleLCGMethods(). Using it in other scencarios may
// require additional changes.
//
void ControllerStackInfo::SetReturnFrameWithActiveFrame()
{
// Copy the active frame into the return frame.
m_returnFound = true;
m_returnFrame = m_activeFrame;
// Invalidate the active frame.
m_activeFound = false;
memset(&(m_activeFrame), 0, sizeof(m_activeFrame));
m_activeFrame.fp = LEAF_MOST_FRAME;
}
// Fill in a controller-stack info.
StackWalkAction ControllerStackInfo::WalkStack(FrameInfo *pInfo, void *data)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(!pInfo->HasStubFrame()); // we didn't ask for stub frames.
ControllerStackInfo *i = (ControllerStackInfo *) data;
//save this info away for later use
if (i->m_bottomFP == LEAF_MOST_FRAME)
i->m_bottomFP = pInfo->fp;
// This is part of the targetted fix for issue 650903. (See the other
// parts in in code:TrackUMChain and code:DebuggerStepper::TrapStepOut.)
// pInfo->fIgnoreThisFrameIfSuppressingUMChainFromComPlusMethodFrameGeneric has been
// set by TrackUMChain to help us remember that the current frame we're looking at is
// ComPlusMethodFrameGeneric (we can't rely on looking at pInfo->frame to check
// this), and i->m_suppressUMChainFromComPlusMethodFrameGeneric has been set by the
// dude initiating this walk to remind us that our goal in life is to do a Step Out
// during managed-only debugging. These two things together tell us we should ignore
// this frame, rather than erroneously identifying it as the target frame.
#ifdef FEATURE_COMINTEROP
if(i->m_suppressUMChainFromComPlusMethodFrameGeneric &&
(pInfo->chainReason == CHAIN_ENTER_UNMANAGED) &&
(pInfo->fIgnoreThisFrameIfSuppressingUMChainFromComPlusMethodFrameGeneric))
{
return SWA_CONTINUE;
}
#endif // FEATURE_COMINTEROP
//have we reached the correct frame yet?
if (!i->m_targetFrameFound &&
IsEqualOrCloserToLeaf(i->m_targetFP, pInfo->fp))
{
i->m_targetFrameFound = true;
}
if (i->m_targetFrameFound )
{
// Ignore Enter-managed chains.
if (pInfo->chainReason == CHAIN_ENTER_MANAGED)
{
return SWA_CONTINUE;
}
if (i->m_activeFound )
{
// We care if the current frame is unmanaged (in case a managed stepper is initiated
// on a thread currently in unmanaged code). But since we can't step-out to UM frames,
// we can just skip them in the stack walk.
if (!pInfo->managed)
{
return SWA_CONTINUE;
}
if (pInfo->chainReason == CHAIN_CLASS_INIT)
i->m_specialChainReason = pInfo->chainReason;
if (pInfo->fp != i->m_activeFrame.fp) // avoid dups
{
i->m_returnFrame = *pInfo;
#if defined(WIN64EXCEPTIONS)
CopyREGDISPLAY(&(i->m_returnFrame.registers), &(pInfo->registers));
#endif // WIN64EXCEPTIONS
i->m_returnFound = true;
return SWA_ABORT;
}
}
else
{
i->m_activeFrame = *pInfo;
#if defined(WIN64EXCEPTIONS)
CopyREGDISPLAY(&(i->m_activeFrame.registers), &(pInfo->registers));
#endif // WIN64EXCEPTIONS
i->m_activeFound = true;
return SWA_CONTINUE;
}
}
return SWA_CONTINUE;
}
//
// Note that patches may be reallocated - do not keep a pointer to a patch.
//
DebuggerControllerPatch *DebuggerPatchTable::AddPatchForMethodDef(DebuggerController *controller,
Module *module,
mdMethodDef md,
size_t offset,
DebuggerPatchKind kind,
FramePointer fp,
AppDomain *pAppDomain,
SIZE_T masterEnCVersion,
DebuggerJitInfo *dji)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
LOG( (LF_CORDB,LL_INFO10000,"DCP:AddPatchForMethodDef unbound "
"relative in methodDef 0x%x with dji 0x%x "
"controller:0x%x AD:0x%x\n", md,
dji, controller, pAppDomain));
DebuggerFunctionKey key;
key.module = module;
key.md = md;
// Get a new uninitialized patch object
DebuggerControllerPatch *patch =
(DebuggerControllerPatch *) Add(HashKey(&key));
if (patch == NULL)
{
ThrowOutOfMemory();
}
#ifndef _TARGET_ARM_
patch->Initialize();
#endif
//initialize the patch data structure.
InitializePRD(&(patch->opcode));
patch->controller = controller;
patch->key.module = module;
patch->key.md = md;
patch->offset = offset;
patch->offsetIsIL = (kind == PATCH_KIND_IL_MASTER);
patch->address = NULL;
patch->fp = fp;
patch->trace.Bad_SetTraceType(DPT_DEFAULT_TRACE_TYPE); // TRACE_OTHER
patch->refCount = 1; // AddRef()
patch->fSaveOpcode = false;
patch->pAppDomain = pAppDomain;
patch->pid = m_pid++;
if (kind == PATCH_KIND_IL_MASTER)
{
_ASSERTE(dji == NULL);
patch->encVersion = masterEnCVersion;
}
else
{
patch->dji = dji;
}
patch->kind = kind;
if (dji)
LOG((LF_CORDB,LL_INFO10000,"AddPatchForMethodDef w/ version 0x%04x, "
"pid:0x%x\n", dji->m_encVersion, patch->pid));
else if (kind == PATCH_KIND_IL_MASTER)
LOG((LF_CORDB,LL_INFO10000,"AddPatchForMethodDef w/ version 0x%04x, "
"pid:0x%x\n", masterEnCVersion,patch->pid));
else
LOG((LF_CORDB,LL_INFO10000,"AddPatchForMethodDef w/ no dji or dmi, pid:0x%x\n",patch->pid));
// This patch is not yet bound or activated
_ASSERTE( !patch->IsBound() );
_ASSERTE( !patch->IsActivated() );
// The only kind of patch with IL offset is the IL master patch.
_ASSERTE(patch->IsILMasterPatch() || patch->offsetIsIL == FALSE);
return patch;
}
// Create and bind a patch to the specified address
// The caller should immediately activate the patch since we typically expect bound patches
// will always be activated.
DebuggerControllerPatch *DebuggerPatchTable::AddPatchForAddress(DebuggerController *controller,
MethodDesc *fd,
size_t offset,
DebuggerPatchKind kind,
CORDB_ADDRESS_TYPE *address,
FramePointer fp,
AppDomain *pAppDomain,
DebuggerJitInfo *dji,
SIZE_T pid,
TraceType traceType)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(kind == PATCH_KIND_NATIVE_MANAGED || kind == PATCH_KIND_NATIVE_UNMANAGED);
LOG((LF_CORDB,LL_INFO10000,"DCP:AddPatchForAddress bound "
"absolute to 0x%x with dji 0x%x (mdDef:0x%x) "
"controller:0x%x AD:0x%x\n",
address, dji, (fd!=NULL?fd->GetMemberDef():0), controller,
pAppDomain));
// get new uninitialized patch object
DebuggerControllerPatch *patch =
(DebuggerControllerPatch *) Add(HashAddress(address));
if (patch == NULL)
{
ThrowOutOfMemory();
}
#ifndef _TARGET_ARM_
patch->Initialize();
#endif
// initialize the patch data structure
InitializePRD(&(patch->opcode));
patch->controller = controller;
if (fd == NULL)
{
patch->key.module = NULL;
patch->key.md = mdTokenNil;
}
else
{
patch->key.module = g_pEEInterface->MethodDescGetModule(fd);
patch->key.md = fd->GetMemberDef();
}
patch->offset = offset;
patch->offsetIsIL = FALSE;
patch->address = address;
patch->fp = fp;
patch->trace.Bad_SetTraceType(traceType);
patch->refCount = 1; // AddRef()
patch->fSaveOpcode = false;
patch->pAppDomain = pAppDomain;
if (pid == DCP_PID_INVALID)
patch->pid = m_pid++;
else
patch->pid = pid;
patch->dji = dji;
patch->kind = kind;
if (dji == NULL)
LOG((LF_CORDB,LL_INFO10000,"AddPatchForAddress w/ version with no dji, pid:0x%x\n", patch->pid));
else
{
LOG((LF_CORDB,LL_INFO10000,"AddPatchForAddress w/ version 0x%04x, "
"pid:0x%x\n", dji->m_methodInfo->GetCurrentEnCVersion(), patch->pid));
_ASSERTE( fd==NULL || fd == dji->m_fd );
}
SortPatchIntoPatchList(&patch);
// This patch is bound but not yet activated
_ASSERTE( patch->IsBound() );
_ASSERTE( !patch->IsActivated() );
// The only kind of patch with IL offset is the IL master patch.
_ASSERTE(patch->IsILMasterPatch() || patch->offsetIsIL == FALSE);
return patch;
}
// Set the native address for this patch.
void DebuggerPatchTable::BindPatch(DebuggerControllerPatch *patch, CORDB_ADDRESS_TYPE *address)
{
_ASSERTE(patch != NULL);
_ASSERTE(address != NULL);
_ASSERTE( !patch->IsILMasterPatch() );
_ASSERTE(!patch->IsBound() );
//Since the actual patch doesn't move, we don't have to worry about
//zeroing out the opcode field (see lenghty comment above)
// Since the patch is double-hashed based off Address, if we change the address,
// we must remove and reinsert the patch.
CHashTable::Delete(HashKey(&patch->key), ItemIndex((HASHENTRY*)patch));
patch->address = address;
CHashTable::Add(HashAddress(address), ItemIndex((HASHENTRY*)patch));
SortPatchIntoPatchList(&patch);
_ASSERTE(patch->IsBound() );
_ASSERTE(!patch->IsActivated() );
}
// Disassociate a patch from a specific code address.
void DebuggerPatchTable::UnbindPatch(DebuggerControllerPatch *patch)
{
_ASSERTE(patch != NULL);
_ASSERTE(patch->kind != PATCH_KIND_IL_MASTER);
_ASSERTE(patch->IsBound() );
_ASSERTE(!patch->IsActivated() );
//<REVISIT_TODO>@todo We're hosed if the patch hasn't been primed with
// this info & we can't get it...</REVISIT_TODO>
if (patch->key.module == NULL ||
patch->key.md == mdTokenNil)
{
MethodDesc *fd = g_pEEInterface->GetNativeCodeMethodDesc(
dac_cast<PCODE>(patch->address));
_ASSERTE( fd != NULL );
patch->key.module = g_pEEInterface->MethodDescGetModule(fd);
patch->key.md = fd->GetMemberDef();
}
// Update it's index entry in the table to use it's unbound key
// Since the patch is double-hashed based off Address, if we change the address,
// we must remove and reinsert the patch.
CHashTable::Delete( HashAddress(patch->address),
ItemIndex((HASHENTRY*)patch));
patch->address = NULL; // we're no longer bound to this address
CHashTable::Add( HashKey(&patch->key),
ItemIndex((HASHENTRY*)patch));
_ASSERTE(!patch->IsBound() );
}
void DebuggerPatchTable::RemovePatch(DebuggerControllerPatch *patch)
{
// Since we're deleting this patch, it must not be activated (i.e. it must not have a stored opcode)
_ASSERTE( !patch->IsActivated() );
#ifndef _TARGET_ARM_
patch->DoCleanup();
#endif
//
// Because of the implementation of CHashTable, we can safely
// delete elements while iterating through the table. This
// behavior is relied upon - do not change to a different
// implementation without considering this fact.
//
Delete(Hash(patch), (HASHENTRY *) patch);
}
DebuggerControllerPatch *DebuggerPatchTable::GetNextPatch(DebuggerControllerPatch *prev)
{
ULONG iNext;
HASHENTRY *psEntry;
// Start at the next entry in the chain.
// @todo - note that: EntryPtr(ItemIndex(x)) == x
iNext = EntryPtr(ItemIndex((HASHENTRY*)prev))->iNext;
// Search until we hit the end.
while (iNext != UINT32_MAX)
{
// Compare the keys.
psEntry = EntryPtr(iNext);
// Careful here... we can hash the entries in this table
// by two types of keys. In this type of search, the type
// of the second key (psEntry) does not necessarily
// indicate the type of the first key (prev), so we have
// to check for sure.
DebuggerControllerPatch *pc2 = (DebuggerControllerPatch*)psEntry;
if (((pc2->address == NULL) && (prev->address == NULL)) ||
((pc2->address != NULL) && (prev->address != NULL)))
if (!Cmp(Key(prev), psEntry))
return pc2;
// Advance to the next item in the chain.
iNext = psEntry->iNext;
}
return NULL;
}
#ifdef _DEBUG_PATCH_TABLE
// DEBUG An internal debugging routine, it iterates
// through the hashtable, stopping at every
// single entry, no matter what it's state. For this to
// compile, you're going to have to add friend status
// of this class to CHashTableAndData in
// to $\Com99\Src\inc\UtilCode.h
void DebuggerPatchTable::CheckPatchTable()
{
if (NULL != m_pcEntries)
{
DebuggerControllerPatch *dcp;
int i = 0;
while (i++ <m_iEntries)
{
dcp = (DebuggerControllerPatch*)&(((DebuggerControllerPatch *)m_pcEntries)[i]);
if (dcp->opcode != 0 )
{
LOG((LF_CORDB,LL_INFO1000, "dcp->addr:0x%8x "
"mdMD:0x%8x, offset:0x%x, native:%d\n",
dcp->address, dcp->key.md, dcp->offset,
dcp->IsNativePatch()));
}
}
}
}
#endif // _DEBUG_PATCH_TABLE
// Count how many patches are in the table.
// Use for asserts
int DebuggerPatchTable::GetNumberOfPatches()
{
int total = 0;
if (NULL != m_pcEntries)
{
DebuggerControllerPatch *dcp;
ULONG i = 0;
while (i++ <m_iEntries)
{
dcp = (DebuggerControllerPatch*)&(((DebuggerControllerPatch *)m_pcEntries)[i]);
if (dcp->IsActivated() || !dcp->IsFree())
total++;
}
}
return total;
}
#if defined(_DEBUG)
//-----------------------------------------------------------------------------
// Debug check that we only have 1 thread-starter per thread.
// pNew - the new DTS. We'll make sure there's not already a DTS on this thread.
//-----------------------------------------------------------------------------
void DebuggerController::EnsureUniqueThreadStarter(DebuggerThreadStarter * pNew)
{
// This lock should be safe to take since our base class ctor takes it.
ControllerLockHolder lockController;
DebuggerController * pExisting = g_controllers;
while(pExisting != NULL)
{
if (pExisting->GetDCType() == DEBUGGER_CONTROLLER_THREAD_STARTER)
{
if (pExisting != pNew)
{
// If we have 2 thread starters, they'd better be on different threads.
_ASSERTE((pExisting->GetThread() != pNew->GetThread()));
}
}
pExisting = pExisting->m_next;
}
}
#endif
//-----------------------------------------------------------------------------
// If we have a thread-starter on the given EE thread, make sure it's cancel.
// Thread-Starters normally delete themselves when they fire. But if the EE
// destroys the thread before it fires, then we'd still have an active DTS.
//-----------------------------------------------------------------------------
void DebuggerController::CancelOutstandingThreadStarter(Thread * pThread)
{
_ASSERTE(pThread != NULL);
LOG((LF_CORDB, LL_EVERYTHING, "DC:CancelOutstandingThreadStarter - checking on thread =0x%p\n", pThread));
ControllerLockHolder lockController;
DebuggerController * p = g_controllers;
while(p != NULL)
{
if (p->GetDCType() == DEBUGGER_CONTROLLER_THREAD_STARTER)
{
if (p->GetThread() == pThread)
{
LOG((LF_CORDB, LL_EVERYTHING, "DC:CancelOutstandingThreadStarter, pThread=0x%p, Found=0x%p\n", p));
// There's only 1 DTS per thread, so once we find it, we can quit.
p->Delete();
p = NULL;
break;
}
}
p = p->m_next;
}
// The common case is that our DTS hit its patch and did a SendEvent (and
// deleted itself). So usually we'll get through the whole list w/o deleting anything.
}
//void DebuggerController::Initialize() Sets up the static
// variables for the static DebuggerController class.
// How: Sets g_runningOnWin95, initializes the critical section
HRESULT DebuggerController::Initialize()
{
CONTRACT(HRESULT)
{
THROWS;
GC_NOTRIGGER;
// This can be called in an "early attach" case, so DebuggerIsInvolved()
// will be b/c we don't realize the debugger's attaching to us.
//PRECONDITION(DebuggerIsInvolved());
POSTCONDITION(CheckPointer(g_patches));
POSTCONDITION(RETVAL == S_OK);
}
CONTRACT_END;
if (g_patches == NULL)
{
ZeroMemory(&g_criticalSection, sizeof(g_criticalSection)); // Init() expects zero-init memory.
// NOTE: CRST_UNSAFE_ANYMODE prevents a GC mode switch when entering this crst.
// If you remove this flag, we will switch to preemptive mode when entering
// g_criticalSection, which means all functions that enter it will become
// GC_TRIGGERS. (This includes all uses of ControllerLockHolder.) So be sure
// to update the contracts if you remove this flag.
g_criticalSection.Init(CrstDebuggerController,
(CrstFlags)(CRST_UNSAFE_ANYMODE | CRST_REENTRANCY | CRST_DEBUGGER_THREAD));
g_patches = new (interopsafe) DebuggerPatchTable();
_ASSERTE(g_patches != NULL); // throws on oom
HRESULT hr = g_patches->Init();
if (FAILED(hr))
{
DeleteInteropSafe(g_patches);
ThrowHR(hr);
}
g_patchTableValid = TRUE;
TRACE_ALLOC(g_patches);
}
_ASSERTE(g_patches != NULL);
RETURN (S_OK);
}
//---------------------------------------------------------------------------------------
//
// Constructor for a controller
//
// Arguments:
// pThread - thread that controller has affinity to. NULL if no thread - affinity.
// pAppdomain - appdomain that controller has affinity to. NULL if no AD affinity.
//
//
// Notes:
// "Affinity" is per-controller specific. Affinity is generally passed on to
// any patches the controller creates. So if a controller has affinity to Thread X,
// then any patches it creates will only fire on Thread-X.
//
//---------------------------------------------------------------------------------------
DebuggerController::DebuggerController(Thread * pThread, AppDomain * pAppDomain)
: m_pAppDomain(pAppDomain),
m_thread(pThread),
m_singleStep(false),
m_exceptionHook(false),
m_traceCall(0),
m_traceCallFP(ROOT_MOST_FRAME),
m_unwindFP(LEAF_MOST_FRAME),
m_eventQueuedCount(0),
m_deleted(false),
m_fEnableMethodEnter(false)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
CONSTRUCTOR_CHECK;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO10000, "DC: 0x%x m_eventQueuedCount to 0 - DC::DC\n", this));
ControllerLockHolder lockController;
{
m_next = g_controllers;
g_controllers = this;
}
}
//---------------------------------------------------------------------------------------
//
// Debugger::Controller::DeleteAllControlers - deletes all debugger contollers
//
// Arguments:
// None
//
// Return Value:
// None
//
// Notes:
// This is used at detach time to remove all DebuggerControllers. This will remove all
// patches and do whatever other cleanup individual DebuggerControllers consider
// necessary to allow the debugger to detach and the process to run normally.
//
void DebuggerController::DeleteAllControllers()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ControllerLockHolder lockController;
DebuggerController * pDebuggerController = g_controllers;
DebuggerController * pNextDebuggerController = NULL;
while (pDebuggerController != NULL)
{
pNextDebuggerController = pDebuggerController->m_next;
pDebuggerController->DebuggerDetachClean();
pDebuggerController->Delete();
pDebuggerController = pNextDebuggerController;
}
}
DebuggerController::~DebuggerController()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
DESTRUCTOR_CHECK;
}
CONTRACTL_END;
ControllerLockHolder lockController;
_ASSERTE(m_eventQueuedCount == 0);
DisableAll();
//
// Remove controller from list
//
DebuggerController **c;
c = &g_controllers;
while (*c != this)
c = &(*c)->m_next;
*c = m_next;
}
// void DebuggerController::Delete()
// What: Marks an instance as deletable. If it's ref count
// (see Enqueue, Dequeue) is currently zero, it actually gets deleted
// How: Set m_deleted to true. If m_eventQueuedCount==0, delete this
void DebuggerController::Delete()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
if (m_eventQueuedCount == 0)
{
LOG((LF_CORDB|LF_ENC, LL_INFO100000, "DC::Delete: actual delete of this:0x%x!\n", this));
TRACE_FREE(this);
DeleteInteropSafe(this);
}
else
{
LOG((LF_CORDB|LF_ENC, LL_INFO100000, "DC::Delete: marked for "
"future delete of this:0x%x!\n", this));
LOG((LF_CORDB|LF_ENC, LL_INFO10000, "DC:0x%x m_eventQueuedCount at 0x%x\n",
this, m_eventQueuedCount));
m_deleted = true;
}
}
void DebuggerController::DebuggerDetachClean()
{
//do nothing here
}
//static
void DebuggerController::AddRef(DebuggerControllerPatch *patch)
{
patch->refCount++;
}
//static
void DebuggerController::Release(DebuggerControllerPatch *patch)
{
patch->refCount--;
if (patch->refCount == 0)
{
LOG((LF_CORDB, LL_INFO10000, "DCP::R: patch deleted, deactivating\n"));
DeactivatePatch(patch);
GetPatchTable()->RemovePatch(patch);
}
}
// void DebuggerController::DisableAll() DisableAll removes
// all control from the controller. This includes all patches & page
// protection. This will invoke Disable* for unwind,singlestep,
// exceptionHook, and tracecall. It will also go through the patch table &
// attempt to remove any and all patches that belong to this controller.
// If the patch is currently triggering, then a Dispatch* method expects the
// patch to be there after we return, so we instead simply mark the patch
// itself as deleted.
void DebuggerController::DisableAll()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
LOG((LF_CORDB,LL_INFO1000, "DC::DisableAll\n"));
_ASSERTE(g_patches != NULL);
ControllerLockHolder ch;
{
//
// Remove controller's patches from list.
// Don't do this on shutdown because the shutdown thread may have killed another thread asynchronously
// thus leaving the patchtable in an inconsistent state such that we may fail trying to walk it.
// Since we're exiting anyways, leaving int3 in the code can't harm anybody.
//
if (!g_fProcessDetach)
{
HASHFIND f;
for (DebuggerControllerPatch *patch = g_patches->GetFirstPatch(&f);
patch != NULL;
patch = g_patches->GetNextPatch(&f))
{
if (patch->controller == this)
{
Release(patch);
}
}
}
if (m_singleStep)
DisableSingleStep();
if (m_exceptionHook)
DisableExceptionHook();
if (m_unwindFP != LEAF_MOST_FRAME)
DisableUnwind();
if (m_traceCall)
DisableTraceCall();
if (m_fEnableMethodEnter)
DisableMethodEnter();
}
}
// void DebuggerController::Enqueue() What: Does
// reference counting so we don't toast a
// DebuggerController while it's in a Dispatch queue.
// Why: In DispatchPatchOrSingleStep, we can't hold locks when going
// into PreEmptiveGC mode b/c we'll create a deadlock.
// So we have to UnLock() prior to
// EnablePreEmptiveGC(). But somebody else can show up and delete the
// DebuggerControllers since we no longer have the lock. So we have to
// do this reference counting thing to make sure that the controllers
// don't get toasted as we're trying to invoke SendEvent on them. We have to
// reaquire the lock before invoking Dequeue because Dequeue may
// result in the controller being deleted, which would change the global
// controller list.
// How: InterlockIncrement( m_eventQueuedCount )
void DebuggerController::Enqueue()
{
LIMITED_METHOD_CONTRACT;
m_eventQueuedCount++;
LOG((LF_CORDB, LL_INFO10000, "DC::Enq DC:0x%x m_eventQueuedCount at 0x%x\n",
this, m_eventQueuedCount));
}
// void DebuggerController::Dequeue() What: Does
// reference counting so we don't toast a
// DebuggerController while it's in a Dispatch queue.
// How: InterlockDecrement( m_eventQueuedCount ), delete this if
// m_eventQueuedCount == 0 AND m_deleted has been set to true
void DebuggerController::Dequeue()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO10000, "DC::Deq DC:0x%x m_eventQueuedCount at 0x%x\n",
this, m_eventQueuedCount));
if (--m_eventQueuedCount == 0)
{
if (m_deleted)
{
TRACE_FREE(this);
DeleteInteropSafe(this);
}
}
}
// bool DebuggerController::BindPatch() If the method has
// been JITted and isn't hashed by address already, then hash
// it into the hashtable by address and not DebuggerFunctionKey.
// If the patch->address field is nonzero, we're done.
// Otherwise ask g_pEEInterface to FindLoadedMethodRefOrDef, then
// GetFunctionAddress of the method, if the method is in IL,
// MapILOffsetToNative. If everything else went Ok, we can now invoke
// g_patches->BindPatch.
// Returns: false if we know that we can't bind the patch immediately.
// true if we either can bind the patch right now, or can't right now,
// but might be able to in the future (eg, the method hasn't been JITted)
// Have following outcomes:
// 1) Succeeded in binding the patch to a raw address. patch->address is set.
// (Note we still must apply the patch to put the int 3 in.)
// returns true, *pFail = false
//
// 2) Fails to bind, but a future attempt may succeed. Obvious ex, for an IL-only
// patch on an unjitted method.
// returns false, *pFail = false
//
// 3) Fails to bind because something's wrong. Ex: bad IL offset, no DJI to do a
// mapping with. Future calls will fail too.
// returns false, *pFail = true
bool DebuggerController::BindPatch(DebuggerControllerPatch *patch,
MethodDesc *fd,
CORDB_ADDRESS_TYPE *startAddr)
{
CONTRACTL
{
SO_NOT_MAINLINE;
THROWS; // from GetJitInfo
GC_NOTRIGGER;
MODE_ANY; // don't really care what mode we're in.
PRECONDITION(ThisMaybeHelperThread());
}
CONTRACTL_END;
_ASSERTE(patch != NULL);
_ASSERTE(!patch->IsILMasterPatch());
_ASSERTE(fd != NULL);
//
// Translate patch to address, if it hasn't been already.
//
if (patch->address != NULL)
{
return true;
}
if (startAddr == NULL)
{
if (patch->HasDJI() && patch->GetDJI()->m_jitComplete)
{
startAddr = (CORDB_ADDRESS_TYPE *) CORDB_ADDRESS_TO_PTR(patch->GetDJI()->m_addrOfCode);
_ASSERTE(startAddr != NULL);
}
if (startAddr == NULL)
{
// Should not be trying to place patches on MethodDecs's for stubs.
// These stubs will never get jitted.
CONSISTENCY_CHECK_MSGF(!fd->IsWrapperStub(), ("Can't place patch at stub md %p, %s::%s",
fd, fd->m_pszDebugClassName, fd->m_pszDebugMethodName));
startAddr = (CORDB_ADDRESS_TYPE *)g_pEEInterface->GetFunctionAddress(fd);
//
// Code is not available yet to patch. The prestub should
// notify us when it is executed.
//
if (startAddr == NULL)
{
LOG((LF_CORDB, LL_INFO10000,
"DC::BP:Patch at 0x%x not bindable yet.\n", patch->offset));
return false;
}
}
}
_ASSERTE(!g_pEEInterface->IsStub((const BYTE *)startAddr));
// If we've jitted, map to a native offset.
DebuggerJitInfo *info = g_pDebugger->GetJitInfo(fd, (const BYTE *)startAddr);
#ifdef LOGGING
if (info == NULL)
{
LOG((LF_CORDB,LL_INFO10000, "DC::BindPa: For startAddr 0x%x, didn't find a DJI\n", startAddr));
}
#endif //LOGGING
if (info != NULL)
{
// There is a strange case with prejitted code and unjitted trace patches. We can enter this function
// with no DebuggerJitInfo created, then have the call just above this actually create the
// DebuggerJitInfo, which causes JitComplete to be called, which causes all patches to be bound! If this
// happens, then we don't need to continue here (its already been done recursivley) and we don't need to
// re-active the patch, so we return false from right here. We can check this by seeing if we suddently
// have the address in the patch set.
if (patch->address != NULL)
{
LOG((LF_CORDB,LL_INFO10000, "DC::BindPa: patch bound recursivley by GetJitInfo, bailing...\n"));
return false;
}
LOG((LF_CORDB,LL_INFO10000, "DC::BindPa: For startAddr 0x%x, got DJI "
"0x%x, from 0x%x size: 0x%x\n", startAddr, info, info->m_addrOfCode, info->m_sizeOfCode));
}
LOG((LF_CORDB, LL_INFO10000, "DC::BP:Trying to bind patch in %s::%s version %d\n",
fd->m_pszDebugClassName, fd->m_pszDebugMethodName, info ? info->m_encVersion : (SIZE_T)-1));
_ASSERTE(g_patches != NULL);
CORDB_ADDRESS_TYPE *addr = (CORDB_ADDRESS_TYPE *)
CodeRegionInfo::GetCodeRegionInfo(NULL, NULL, startAddr).OffsetToAddress(patch->offset);
g_patches->BindPatch(patch, addr);
LOG((LF_CORDB, LL_INFO10000, "DC::BP:Binding patch at 0x%x(off:%x)\n", addr, patch->offset));
return true;
}
// bool DebuggerController::ApplyPatch() applies
// the patch described to the code, and
// remembers the replaced opcode. Note that the same address
// cannot be patched twice at the same time.
// Grabs the opcode & stores in patch, then sets a break
// instruction for either native or IL.
// VirtualProtect & some macros. Returns false if anything
// went bad.
// DebuggerControllerPatch *patch: The patch, indicates where
// to set the INT3 instruction
// Returns: true if the user break instruction was successfully
// placed into the code-stream, false otherwise
bool DebuggerController::ApplyPatch(DebuggerControllerPatch *patch)
{
LOG((LF_CORDB, LL_INFO10000, "DC::ApplyPatch at addr 0x%p\n",
patch->address));
// If we try to apply an already applied patch, we'll overide our saved opcode
// with the break opcode and end up getting a break in out patch bypass buffer.
_ASSERTE(!patch->IsActivated() );
_ASSERTE(patch->IsBound());
// Note we may be patching at certain "blessed" points in mscorwks.
// This is very dangerous b/c we can't be sure patch->Address is blessed or not.
//
// Apply the patch.
//
_ASSERTE(!(g_pConfig->GetGCStressLevel() & (EEConfig::GCSTRESS_INSTR_JIT|EEConfig::GCSTRESS_INSTR_NGEN))
&& "Debugger does not work with GCSTRESS 4");
if (patch->IsNativePatch())
{
if (patch->fSaveOpcode)
{
// We only used SaveOpcode for when we've moved code, so
// the patch should already be there.
patch->opcode = patch->opcodeSaved;
_ASSERTE( AddressIsBreakpoint(patch->address) );
return true;
}
#if _DEBUG
VerifyExecutableAddress((BYTE*)patch->address);
#endif
LPVOID baseAddress = (LPVOID)(patch->address);
DWORD oldProt;
if (!VirtualProtect(baseAddress,
CORDbg_BREAK_INSTRUCTION_SIZE,
PAGE_EXECUTE_READWRITE, &oldProt))
{
_ASSERTE(!"VirtualProtect of code page failed");
return false;
}
patch->opcode = CORDbgGetInstruction(patch->address);
CORDbgInsertBreakpoint((CORDB_ADDRESS_TYPE *)patch->address);
LOG((LF_CORDB, LL_EVERYTHING, "Breakpoint was inserted at %p for opcode %x\n", patch->address, patch->opcode));
if (!VirtualProtect(baseAddress,
CORDbg_BREAK_INSTRUCTION_SIZE,
oldProt, &oldProt))
{
_ASSERTE(!"VirtualProtect of code page failed");
return false;
}
}
// TODO: : determine if this is needed for AMD64
#if defined(_TARGET_X86_) //REVISIT_TODO what is this?!
else
{
DWORD oldProt;
//
// !!! IL patch logic assumes reference insruction encoding
//
if (!VirtualProtect((void *) patch->address, 2,
PAGE_EXECUTE_READWRITE, &oldProt))
{
_ASSERTE(!"VirtualProtect of code page failed");
return false;
}
patch->opcode =
(unsigned int) *(unsigned short*)(patch->address+1);
_ASSERTE(patch->opcode != CEE_BREAK);
*(unsigned short *) (patch->address+1) = CEE_BREAK;
if (!VirtualProtect((void *) patch->address, 2, oldProt, &oldProt))
{
_ASSERTE(!"VirtualProtect of code page failed");
return false;
}
}
#endif //_TARGET_X86_
return true;
}
// bool DebuggerController::UnapplyPatch()
// UnapplyPatch removes the patch described by the patch.
// (CopyOpcodeFromAddrToPatch, in reverse.)
// Looks a lot like CopyOpcodeFromAddrToPatch, except that we use a macro to
// copy the instruction back to the code-stream & immediately set the
// opcode field to 0 so ReadMemory,WriteMemory will work right.
// Note that it's very important to zero out the opcode field, as it
// is used by the right side to determine if a patch is
// valid or not.
// NO LOCKING
// DebuggerControllerPatch * patch: Patch to remove
// Returns: true if the patch was unapplied, false otherwise
bool DebuggerController::UnapplyPatch(DebuggerControllerPatch *patch)
{
_ASSERTE(patch->address != NULL);
_ASSERTE(patch->IsActivated() );
LOG((LF_CORDB,LL_INFO1000, "DC::UP unapply patch at addr 0x%p\n",
patch->address));
if (patch->IsNativePatch())
{
if (patch->fSaveOpcode)
{
// We're doing this for MoveCode, and we don't want to
// overwrite something if we don't get moved far enough.
patch->opcodeSaved = patch->opcode;
InitializePRD(&(patch->opcode));
_ASSERTE( !patch->IsActivated() );
return true;
}
LPVOID baseAddress = (LPVOID)(patch->address);
DWORD oldProt;
if (!VirtualProtect(baseAddress,
CORDbg_BREAK_INSTRUCTION_SIZE,
PAGE_EXECUTE_READWRITE, &oldProt))
{
//
// We may be trying to remove a patch from memory
// which has been unmapped. We can ignore the
// error in this case.
//
InitializePRD(&(patch->opcode));
return false;
}
CORDbgSetInstruction((CORDB_ADDRESS_TYPE *)patch->address, patch->opcode);
//VERY IMPORTANT to zero out opcode, else we might mistake
//this patch for an active on on ReadMem/WriteMem (see
//header file comment)
InitializePRD(&(patch->opcode));
if (!VirtualProtect(baseAddress,
CORDbg_BREAK_INSTRUCTION_SIZE,
oldProt, &oldProt))
{
_ASSERTE(!"VirtualProtect of code page failed");
return false;
}
}
else
{
DWORD oldProt;
if (!VirtualProtect((void *) patch->address, 2,
PAGE_EXECUTE_READWRITE, &oldProt))
{
//
// We may be trying to remove a patch from memory
// which has been unmapped. We can ignore the
// error in this case.
//
InitializePRD(&(patch->opcode));
return false;
}
//
// !!! IL patch logic assumes reference encoding
//
// TODO: : determine if this is needed for AMD64
#if defined(_TARGET_X86_)
_ASSERTE(*(unsigned short*)(patch->address+1) == CEE_BREAK);
*(unsigned short *) (patch->address+1)
= (unsigned short) patch->opcode;
#endif //this makes no sense on anything but X86
//VERY IMPORTANT to zero out opcode, else we might mistake
//this patch for an active on on ReadMem/WriteMem (see
//header file comment
InitializePRD(&(patch->opcode));
if (!VirtualProtect((void *) patch->address, 2, oldProt, &oldProt))
{
_ASSERTE(!"VirtualProtect of code page failed");
return false;
}
}
_ASSERTE( !patch->IsActivated() );
_ASSERTE( patch->IsBound() );
return true;
}
// void DebuggerController::UnapplyPatchAt()
// NO LOCKING
// UnapplyPatchAt removes the patch from a copy of the patched code.
// Like UnapplyPatch, except that we don't bother checking
// memory permissions, but instead replace the breakpoint instruction
// with the opcode at an arbitrary memory address.
void DebuggerController::UnapplyPatchAt(DebuggerControllerPatch *patch,
CORDB_ADDRESS_TYPE *address)
{
_ASSERTE(patch->IsBound() );
if (patch->IsNativePatch())
{
CORDbgSetInstruction((CORDB_ADDRESS_TYPE *)address, patch->opcode);
//note that we don't have to zero out opcode field
//since we're unapplying at something other than
//the original spot. We assert this is true:
_ASSERTE( patch->address != address );
}
else
{
//
// !!! IL patch logic assumes reference encoding
//
// TODO: : determine if this is needed for AMD64
#ifdef _TARGET_X86_
_ASSERTE(*(unsigned short*)(address+1) == CEE_BREAK);
*(unsigned short *) (address+1)
= (unsigned short) patch->opcode;
_ASSERTE( patch->address != address );
#endif // this makes no sense on anything but X86
}
}
// bool DebuggerController::IsPatched() Is there a patch at addr?
// How: if fNative && the instruction at addr is the break
// instruction for this platform.
bool DebuggerController::IsPatched(CORDB_ADDRESS_TYPE *address, BOOL native)
{
LIMITED_METHOD_CONTRACT;
if (native)
{
return AddressIsBreakpoint(address);
}
else
return false;
}
// DWORD DebuggerController::GetPatchedOpcode() Gets the opcode
// at addr, 'looking underneath' any patches if needed.
// GetPatchedInstruction is a function for the EE to call to "see through"
// a patch to the opcodes which was patched.
// How: Lock() grab opcode directly unless there's a patch, in
// which case grab it out of the patch table.
// BYTE * address: The address that we want to 'see through'
// Returns: DWORD value, that is the opcode that should really be there,
// if we hadn't placed a patch there. If we haven't placed a patch
// there, then we'll see the actual opcode at that address.
PRD_TYPE DebuggerController::GetPatchedOpcode(CORDB_ADDRESS_TYPE *address)
{
_ASSERTE(g_patches != NULL);
PRD_TYPE opcode;
ZeroMemory(&opcode, sizeof(opcode));
ControllerLockHolder lockController;
//
// Look for a patch at the address
//
DebuggerControllerPatch *patch = g_patches->GetPatch((CORDB_ADDRESS_TYPE *)address);
if (patch != NULL)
{
// Since we got the patch at this address, is must by definition be bound to that address
_ASSERTE( patch->IsBound() );
_ASSERTE( patch->address == address );
// If we're going to be returning it's opcode, then the patch must also be activated
_ASSERTE( patch->IsActivated() );
opcode = patch->opcode;
}
else
{
//
// Patch was not found - it either is not our patch, or it has
// just been removed. In either case, just return the current
// opcode.
//
if (g_pEEInterface->IsManagedNativeCode((const BYTE *)address))
{
opcode = CORDbgGetInstruction((CORDB_ADDRESS_TYPE *)address);
}
// <REVISIT_TODO>
// TODO: : determine if this is needed for AMD64
// </REVISIT_TODO>
#ifdef _TARGET_X86_ //what is this?!
else
{
//
// !!! IL patch logic assumes reference encoding
//
opcode = *(unsigned short*)(address+1);
}
#endif //_TARGET_X86_
}
return opcode;
}
// Holding the controller lock, this will check if an address is patched,
// and if so will then set the PRT_TYPE out parameter to the unpatched value.
BOOL DebuggerController::CheckGetPatchedOpcode(CORDB_ADDRESS_TYPE *address,
/*OUT*/ PRD_TYPE *pOpcode)
{
CONTRACTL
{
SO_NOT_MAINLINE; // take Controller lock.
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(g_patches != NULL);
BOOL res;
ControllerLockHolder lockController;
//
// Look for a patch at the address
//
if (IsAddressPatched(address))
{
*pOpcode = GetPatchedOpcode(address);
res = TRUE;
}
else
{
InitializePRD(pOpcode);
res = FALSE;
}
return res;
}
// void DebuggerController::ActivatePatch() Place a breakpoint
// so that threads will trip over this patch.
// If there any patches at the address already, then copy
// their opcode into this one & return. Otherwise,
// call ApplyPatch(patch). There is an implicit list of patches at this
// address by virtue of the fact that we can iterate through all the
// patches in the patch with the same address.
// DebuggerControllerPatch *patch: The patch to activate
/* static */ void DebuggerController::ActivatePatch(DebuggerControllerPatch *patch)
{
_ASSERTE(g_patches != NULL);
_ASSERTE(patch != NULL);
_ASSERTE(patch->IsBound() );
_ASSERTE(!patch->IsActivated() );
bool fApply = true;
//
// See if we already have an active patch at this address.
//
for (DebuggerControllerPatch *p = g_patches->GetPatch(patch->address);
p != NULL;
p = g_patches->GetNextPatch(p))
{
if (p != patch)
{
// If we're going to skip activating 'patch' because 'p' already exists at the same address
// then 'p' must be activated. We expect that all bound patches are activated.
_ASSERTE( p->IsActivated() );
patch->opcode = p->opcode;
fApply = false;
break;
}
}
//
// This is the only patch at this address - apply the patch
// to the code.
//
if (fApply)
{
ApplyPatch(patch);
}
_ASSERTE(patch->IsActivated() );
}
// void DebuggerController::DeactivatePatch() Make sure that a
// patch won't be hit.
// How: If this patch is the last one at this address, then
// UnapplyPatch. The caller should then invoke RemovePatch to remove the
// patch from the patch table.
// DebuggerControllerPatch *patch: Patch to deactivate
void DebuggerController::DeactivatePatch(DebuggerControllerPatch *patch)
{
_ASSERTE(g_patches != NULL);
if( !patch->IsBound() ) {
// patch is not bound, nothing to do
return;
}
// We expect that all bound patches are also activated.
// One exception to this is if the shutdown thread killed another thread right after
// if deactivated a patch but before it got to remove it.
_ASSERTE(patch->IsActivated() );
bool fUnapply = true;
//
// See if we already have an active patch at this address.
//
for (DebuggerControllerPatch *p = g_patches->GetPatch(patch->address);
p != NULL;
p = g_patches->GetNextPatch(p))
{
if (p != patch)
{
// There is another patch at this address, so don't remove it
// However, clear the patch data so that we no longer consider this particular patch activated
fUnapply = false;
InitializePRD(&(patch->opcode));
break;
}
}
if (fUnapply)
{
UnapplyPatch(patch);
}
_ASSERTE(!patch->IsActivated() );
//
// Patch must now be removed from the table.
//
}
// AddILMasterPatch: record a patch on IL code but do not bind it or activate it. The master b.p.
// is associated with a module/token pair. It is used later
// (e.g. in MapAndBindFunctionPatches) to create one or more "slave"
// breakpoints which are associated with particular MethodDescs/JitInfos.
//
// Rationale: For generic code a single IL patch (e.g a breakpoint)
// may give rise to several patches, one for each JITting of
// the IL (i.e. generic code may be JITted multiple times for
// different instantiations).
//
// So we keep one patch which describes
// the breakpoint but which is never actually bound or activated.
// This is then used to apply new "slave" patches to all copies of
// JITted code associated with the method.
//
// <REVISIT_TODO>In theory we could bind and apply the master patch when the
// code is known not to be generic (as used to happen to all breakpoint
// patches in V1). However this seems like a premature
// optimization.</REVISIT_TODO>
DebuggerControllerPatch *DebuggerController::AddILMasterPatch(Module *module,
mdMethodDef md,
SIZE_T offset,
SIZE_T encVersion)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(g_patches != NULL);
ControllerLockHolder ch;
DebuggerControllerPatch *patch = g_patches->AddPatchForMethodDef(this,
module,
md,
offset,
PATCH_KIND_IL_MASTER,
LEAF_MOST_FRAME,
NULL,
encVersion,
NULL);
LOG((LF_CORDB, LL_INFO10000,
"DC::AP: Added IL master patch 0x%x for md 0x%x at offset %d encVersion %d\n", patch, md, offset, encVersion));
return patch;
}
// See notes above on AddILMasterPatch
BOOL DebuggerController::AddBindAndActivateILSlavePatch(DebuggerControllerPatch *master,
DebuggerJitInfo *dji)
{
_ASSERTE(g_patches != NULL);
_ASSERTE(master->IsILMasterPatch());
_ASSERTE(dji != NULL);
// Do not dereference the "master" pointer in the loop! The loop may add more patches,
// causing the patch table to grow and move.
BOOL result = FALSE;
SIZE_T masterILOffset = master->offset;
// Loop through all the native offsets mapped to the given IL offset. On x86 the mapping
// should be 1:1. On WIN64, because there are funclets, we have have an 1:N mapping.
DebuggerJitInfo::ILToNativeOffsetIterator it;
for (dji->InitILToNativeOffsetIterator(it, masterILOffset); !it.IsAtEnd(); it.Next())
{
BOOL fExact;
SIZE_T offsetNative = it.Current(&fExact);
// We special case offset 0, which is when a breakpoint is set
// at the beginning of a method that hasn't been jitted yet. In
// that case it's possible that offset 0 has been optimized out,
// but we still want to set the closest breakpoint to that.
if (!fExact && (masterILOffset != 0))
{
LOG((LF_CORDB, LL_INFO10000, "DC::BP:Failed to bind patch at IL offset 0x%p in %s::%s\n",
masterILOffset, dji->m_fd->m_pszDebugClassName, dji->m_fd->m_pszDebugMethodName));
continue;
}
else
{
result = TRUE;
}
INDEBUG(BOOL fOk = )
AddBindAndActivatePatchForMethodDesc(dji->m_fd, dji,
offsetNative, PATCH_KIND_IL_SLAVE,
LEAF_MOST_FRAME, m_pAppDomain);
_ASSERTE(fOk);
}
// As long as we have successfully bound at least one patch, we consider the operation successful.
return result;
}
// This routine places a patch that is conceptually a patch on the IL code.
// The IL code may be jitted multiple times, e.g. due to generics.
// This routine ensures that both present and subsequent JITtings of code will
// also be patched.
//
// This routine will return FALSE only if we will _never_ be able to
// place the patch in any native code corresponding to the given offset.
// Otherwise it will:
// (a) record a "master" patch
// (b) apply as many slave patches as it can to existing copies of code
// that have debugging information
BOOL DebuggerController::AddILPatch(AppDomain * pAppDomain, Module *module,
mdMethodDef md,
SIZE_T encVersion, // what encVersion does this apply to?
SIZE_T offset)
{
_ASSERTE(g_patches != NULL);
_ASSERTE(md != NULL);
_ASSERTE(module != NULL);
BOOL fOk = FALSE;
DebuggerMethodInfo *dmi = g_pDebugger->GetOrCreateMethodInfo(module, md); // throws
if (dmi == NULL)
{
return false;
}
EX_TRY
{
// OK, we either have (a) no code at all or (b) we have both JIT information and code
//.
// Either way, lay down the MasterPatch.
//
// MapAndBindFunctionPatches will take care of any instantiations that haven't
// finished JITting, by making a copy of the master breakpoint.
DebuggerControllerPatch *master = AddILMasterPatch(module, md, offset, encVersion);
// We have to keep the index here instead of the pointer. The loop below adds more patches,
// which may cause the patch table to grow and move.
ULONG masterIndex = g_patches->GetItemIndex((HASHENTRY*)master);
// Iterate through every existing NativeCodeBlob (with the same EnC version).
// This includes generics + prejitted code.
DebuggerMethodInfo::DJIIterator it;
dmi->IterateAllDJIs(pAppDomain, NULL /* module filter */, &it);
if (it.IsAtEnd())
{
// It is okay if we don't have any DJIs yet. It just means that the method hasn't been jitted.
fOk = TRUE;
}
else
{
// On the other hand, if the method has been jitted, then we expect to be able to bind at least
// one breakpoint. The exception is when we have multiple EnC versions of the method, in which
// case it is ok if we don't bind any breakpoint. One scenario is when a method has been updated
// via EnC but it's not yet jitted. We need to allow a debugger to put a breakpoint on the new
// version of the method, but the new version won't have a DJI yet.
BOOL fVersionMatch = FALSE;
while(!it.IsAtEnd())
{
DebuggerJitInfo *dji = it.Current();
_ASSERTE(dji->m_jitComplete);
if (dji->m_encVersion == encVersion)
{
fVersionMatch = TRUE;
master = (DebuggerControllerPatch *)g_patches->GetEntryPtr(masterIndex);
// <REVISIT_TODO> If we're missing JIT info for any then
// we won't have applied the bp to every instantiation. That should probably be reported
// as a new kind of condition to the debugger, i.e. report "bp only partially applied". It would be
// a shame to completely fail just because on instantiation is missing debug info: e.g. just because
// one component hasn't been prejitted with debugging information.</REVISIT_TODO>
fOk = (AddBindAndActivateILSlavePatch(master, dji) || fOk);
}
it.Next();
}
// This is the exceptional case referred to in the comment above. If we fail to put a breakpoint
// because we don't have a matching version of the method, we need to return TRUE.
if (fVersionMatch == FALSE)
{
fOk = TRUE;
}
}
}
EX_CATCH
{
fOk = FALSE;
}
EX_END_CATCH(SwallowAllExceptions)
return fOk;
}
// Add a patch at native-offset 0 in the latest version of the method.
// This is used by step-in.
// Calls to new methods always go to the latest version, so EnC is not an issue here.
// The method may be not yet jitted. Or it may be prejitted.
void DebuggerController::AddPatchToStartOfLatestMethod(MethodDesc * fd)
{
CONTRACTL
{
SO_NOT_MAINLINE;
THROWS; // from GetJitInfo
GC_NOTRIGGER;
MODE_ANY; // don't really care what mode we're in.
PRECONDITION(ThisMaybeHelperThread());
PRECONDITION(CheckPointer(fd));
}
CONTRACTL_END;
_ASSERTE(g_patches != NULL);
DebuggerController::AddBindAndActivatePatchForMethodDesc(fd, NULL, 0, PATCH_KIND_NATIVE_MANAGED, LEAF_MOST_FRAME, NULL);
return;
}
// Place patch in method at native offset.
BOOL DebuggerController::AddBindAndActivateNativeManagedPatch(MethodDesc * fd,
DebuggerJitInfo *dji,
SIZE_T offsetNative,
FramePointer fp,
AppDomain *pAppDomain)
{
CONTRACTL
{
SO_NOT_MAINLINE;
THROWS; // from GetJitInfo
GC_NOTRIGGER;
MODE_ANY; // don't really care what mode we're in.
PRECONDITION(ThisMaybeHelperThread());
PRECONDITION(CheckPointer(fd));
PRECONDITION(fd->IsDynamicMethod() || (dji != NULL));
}
CONTRACTL_END;
// For non-dynamic methods, we always expect to have a DJI, but just in case, we don't want the assert to AV.
_ASSERTE((dji == NULL) || (fd == dji->m_fd));
_ASSERTE(g_patches != NULL);
return DebuggerController::AddBindAndActivatePatchForMethodDesc(fd, dji, offsetNative, PATCH_KIND_NATIVE_MANAGED, fp, pAppDomain);
}
BOOL DebuggerController::AddBindAndActivatePatchForMethodDesc(MethodDesc *fd,
DebuggerJitInfo *dji,
SIZE_T offset,
DebuggerPatchKind kind,
FramePointer fp,
AppDomain *pAppDomain)
{
CONTRACTL
{
SO_NOT_MAINLINE;
THROWS;
GC_NOTRIGGER;
MODE_ANY; // don't really care what mode we're in.
PRECONDITION(ThisMaybeHelperThread());
}
CONTRACTL_END;
BOOL ok = FALSE;
ControllerLockHolder ch;
LOG((LF_CORDB|LF_ENC,LL_INFO10000,"DC::AP: Add to %s::%s, at offs 0x%x "
"fp:0x%x AD:0x%x\n", fd->m_pszDebugClassName,
fd->m_pszDebugMethodName,
offset, fp.GetSPValue(), pAppDomain));
DebuggerControllerPatch *patch = g_patches->AddPatchForMethodDef(
this,
g_pEEInterface->MethodDescGetModule(fd),
fd->GetMemberDef(),
offset,
kind,
fp,
pAppDomain,
NULL,
dji);
if (DebuggerController::BindPatch(patch, fd, NULL))
{
LOG((LF_CORDB|LF_ENC,LL_INFO1000,"BindPatch went fine, doing ActivatePatch\n"));
DebuggerController::ActivatePatch(patch);
ok = TRUE;
}
return ok;
}
// This version is particularly useful b/c it doesn't assume that the
// patch is inside a managed method.
DebuggerControllerPatch *DebuggerController::AddAndActivateNativePatchForAddress(CORDB_ADDRESS_TYPE *address,
FramePointer fp,
bool managed,
TraceType traceType)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
PRECONDITION(g_patches != NULL);
}
CONTRACTL_END;
ControllerLockHolder ch;
DebuggerControllerPatch *patch
= g_patches->AddPatchForAddress(this,
NULL,
0,
(managed? PATCH_KIND_NATIVE_MANAGED : PATCH_KIND_NATIVE_UNMANAGED),
address,
fp,
NULL,
NULL,
DebuggerPatchTable::DCP_PID_INVALID,
traceType);
ActivatePatch(patch);
return patch;
}
void DebuggerController::RemovePatchesFromModule(Module *pModule, AppDomain *pAppDomain )
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO100000, "DPT::CPFM mod:0x%p (%S)\n",
pModule, pModule->GetDebugName()));
// First find all patches of interest
DebuggerController::ControllerLockHolder ch;
HASHFIND f;
for (DebuggerControllerPatch *patch = g_patches->GetFirstPatch(&f);
patch != NULL;
patch = g_patches->GetNextPatch(&f))
{
// Skip patches not in the specified domain
if ((pAppDomain != NULL) && (patch->pAppDomain != pAppDomain))
continue;
BOOL fRemovePatch = FALSE;
// Remove both native and IL patches the belong to this module
if (patch->HasDJI())
{
DebuggerJitInfo * dji = patch->GetDJI();
_ASSERTE(patch->key.module == dji->m_fd->GetModule());
// It is not necessary to check for m_fd->GetModule() here. It will
// be covered by other module unload notifications issued for the appdomain.
if ( dji->m_pLoaderModule == pModule )
fRemovePatch = TRUE;
}
else
if (patch->key.module == pModule)
{
fRemovePatch = TRUE;
}
if (fRemovePatch)
{
LOG((LF_CORDB, LL_EVERYTHING, "Removing patch 0x%p\n",
patch));
// we shouldn't be both hitting this patch AND
// unloading the module it belongs to.
_ASSERTE(!patch->IsTriggering());
Release( patch );
}
}
}
#ifdef _DEBUG
bool DebuggerController::ModuleHasPatches( Module* pModule )
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
if( g_patches == NULL )
{
// Patch table hasn't been initialized
return false;
}
// First find all patches of interest
HASHFIND f;
for (DebuggerControllerPatch *patch = g_patches->GetFirstPatch(&f);
patch != NULL;
patch = g_patches->GetNextPatch(&f))
{
//
// This mirrors logic in code:DebuggerController::RemovePatchesFromModule
//
if (patch->HasDJI())
{
DebuggerJitInfo * dji = patch->GetDJI();
_ASSERTE(patch->key.module == dji->m_fd->GetModule());
// It may be sufficient to just check m_pLoaderModule here. Since this is used for debug-only
// check, we will check for m_fd->GetModule() as well to catch more potential problems.
if ( (dji->m_pLoaderModule == pModule) || (dji->m_fd->GetModule() == pModule) )
{
return true;
}
}
if (patch->key.module == pModule)
{
return true;
}
}
return false;
}
#endif // _DEBUG
//
// Returns true if the given address is in an internal helper
// function, false if its not.
//
// This is a temporary workaround function to avoid having us stop in
// unmanaged code belonging to the Runtime during a StepIn operation.
//
static bool _AddrIsJITHelper(PCODE addr)
{
#if !defined(_WIN64) && !defined(FEATURE_PAL)
// Is the address in the runtime dll (clr.dll or coreclr.dll) at all? (All helpers are in
// that dll)
if (g_runtimeLoadedBaseAddress <= addr &&
addr < g_runtimeLoadedBaseAddress + g_runtimeVirtualSize)
{
for (int i = 0; i < CORINFO_HELP_COUNT; i++)
{
if (hlpFuncTable[i].pfnHelper == (void*)addr)
{
LOG((LF_CORDB, LL_INFO10000,
"_ANIM: address of helper function found: 0x%08x\n",
addr));
return true;
}
}
for (unsigned d = 0; d < DYNAMIC_CORINFO_HELP_COUNT; d++)
{
if (hlpDynamicFuncTable[d].pfnHelper == (void*)addr)
{
LOG((LF_CORDB, LL_INFO10000,
"_ANIM: address of helper function found: 0x%08x\n",
addr));
return true;
}
}
LOG((LF_CORDB, LL_INFO10000,
"_ANIM: address within runtime dll, but not a helper function "
"0x%08x\n", addr));
}
#else // !defined(_WIN64) && !defined(FEATURE_PAL)
// TODO: Figure out what we want to do here
#endif // !defined(_WIN64) && !defined(FEATURE_PAL)
return false;
}
// bool DebuggerController::PatchTrace() What: Invoke
// AddPatch depending on the type of the given TraceDestination.
// How: Invokes AddPatch based on the trace type: TRACE_OTHER will
// return false, the others will obtain args for a call to an AddPatch
// method & return true.
//
// Return true if we set a patch, else false
bool DebuggerController::PatchTrace(TraceDestination *trace,
FramePointer fp,
bool fStopInUnmanaged)
{
CONTRACTL
{
THROWS; // Because AddPatch may throw on oom. We may want to convert this to nothrow and return false.
MODE_ANY;
DISABLED(GC_TRIGGERS); // @todo - what should this be?
PRECONDITION(ThisMaybeHelperThread());
}
CONTRACTL_END;
DebuggerControllerPatch *dcp = NULL;
switch (trace->GetTraceType())
{
case TRACE_ENTRY_STUB: // fall through
case TRACE_UNMANAGED:
LOG((LF_CORDB, LL_INFO10000,
"DC::PT: Setting unmanaged trace patch at 0x%p(%p)\n",
trace->GetAddress(), fp.GetSPValue()));
if (fStopInUnmanaged && !_AddrIsJITHelper(trace->GetAddress()))
{
AddAndActivateNativePatchForAddress((CORDB_ADDRESS_TYPE *)trace->GetAddress(),
fp,
FALSE,
trace->GetTraceType());
return true;
}
else
{
LOG((LF_CORDB, LL_INFO10000, "DC::PT: decided to NOT "
"place a patch in unmanaged code\n"));
return false;
}
case TRACE_MANAGED:
LOG((LF_CORDB, LL_INFO10000,
"Setting managed trace patch at 0x%p(%p)\n", trace->GetAddress(), fp.GetSPValue()));
MethodDesc *fd;
fd = g_pEEInterface->GetNativeCodeMethodDesc(trace->GetAddress());
_ASSERTE(fd);
DebuggerJitInfo *dji;
dji = g_pDebugger->GetJitInfoFromAddr(trace->GetAddress());
//_ASSERTE(dji); //we'd like to assert this, but attach won't work
AddBindAndActivateNativeManagedPatch(fd,
dji,
CodeRegionInfo::GetCodeRegionInfo(dji, fd).AddressToOffset((const BYTE *)trace->GetAddress()),
fp,
NULL);
return true;
case TRACE_UNJITTED_METHOD:
// trace->address is actually a MethodDesc* of the method that we'll
// soon JIT, so put a relative bp at offset zero in.
LOG((LF_CORDB, LL_INFO10000,
"Setting unjitted method patch in MethodDesc 0x%p %s\n", trace->GetMethodDesc(), trace->GetMethodDesc() ? trace->GetMethodDesc()->m_pszDebugMethodName : ""));
// Note: we have to make sure to bind here. If this function is prejitted, this may be our only chance to get a
// DebuggerJITInfo and thereby cause a JITComplete callback.
AddPatchToStartOfLatestMethod(trace->GetMethodDesc());
return true;
case TRACE_FRAME_PUSH:
LOG((LF_CORDB, LL_INFO10000,
"Setting frame patch at 0x%p(%p)\n", trace->GetAddress(), fp.GetSPValue()));
AddAndActivateNativePatchForAddress((CORDB_ADDRESS_TYPE *)trace->GetAddress(),
fp,
TRUE,
TRACE_FRAME_PUSH);
return true;
case TRACE_MGR_PUSH:
LOG((LF_CORDB, LL_INFO10000,
"Setting frame patch (TRACE_MGR_PUSH) at 0x%p(%p)\n",
trace->GetAddress(), fp.GetSPValue()));
dcp = AddAndActivateNativePatchForAddress((CORDB_ADDRESS_TYPE *)trace->GetAddress(),
LEAF_MOST_FRAME, // But Mgr_push can't have fp affinity!
TRUE,
DPT_DEFAULT_TRACE_TYPE); // TRACE_OTHER
// Now copy over the trace field since TriggerPatch will expect this
// to be set for this case.
if (dcp != NULL)
{
dcp->trace = *trace;
}
return true;
case TRACE_OTHER:
LOG((LF_CORDB, LL_INFO10000,
"Can't set a trace patch for TRACE_OTHER...\n"));
return false;
default:
_ASSERTE(0);
return false;
}
}
//-----------------------------------------------------------------------------
// Checks if the patch matches the context + thread.
// Multiple patches can exist at a single address, so given a patch at the
// Context's current address, this does additional patch-affinity checks like
// thread, AppDomain, and frame-pointer.
// thread - thread executing the given context that hit the patch
// context - context of the thread that hit the patch
// patch - candidate patch that we're looking for a match.
// Returns:
// True if the patch matches.
// False
//-----------------------------------------------------------------------------
bool DebuggerController::MatchPatch(Thread *thread,
CONTEXT *context,
DebuggerControllerPatch *patch)
{
LOG((LF_CORDB, LL_INFO100000, "DC::MP: EIP:0x%p\n", GetIP(context)));
// Caller should have already matched our addresses.
if (patch->address != dac_cast<PTR_CORDB_ADDRESS_TYPE>(GetIP(context)))
{
return false;
}
// <BUGNUM>RAID 67173 -</BUGNUM> we'll make sure that intermediate patches have NULL
// pAppDomain so that we don't end up running to completion when
// the appdomain switches halfway through a step.
if (patch->pAppDomain != NULL)
{
AppDomain *pAppDomainCur = thread->GetDomain();
if (pAppDomainCur != patch->pAppDomain)
{
LOG((LF_CORDB, LL_INFO10000, "DC::MP: patches didn't match b/c of "
"appdomains!\n"));
return false;
}
}
if (patch->controller->m_thread != NULL && patch->controller->m_thread != thread)
{
LOG((LF_CORDB, LL_INFO10000, "DC::MP: patches didn't match b/c threads\n"));
return false;
}
if (patch->fp != LEAF_MOST_FRAME)
{
// If we specified a Frame-pointer, than it should have been safe to take a stack trace.
ControllerStackInfo info;
StackTraceTicket ticket(patch);
info.GetStackInfo(ticket, thread, LEAF_MOST_FRAME, context);
// !!! This check should really be != , but there is some ambiguity about which frame is the parent frame
// in the destination returned from Frame::TraceFrame, so this allows some slop there.
if (info.HasReturnFrame() && IsCloserToLeaf(info.m_returnFrame.fp, patch->fp))
{
LOG((LF_CORDB, LL_INFO10000, "Patch hit but frame not matched at %p (current=%p, patch=%p)\n",
patch->address, info.m_returnFrame.fp.GetSPValue(), patch->fp.GetSPValue()));
return false;
}
}
LOG((LF_CORDB, LL_INFO100000, "DC::MP: Returning true"));
return true;
}
DebuggerPatchSkip *DebuggerController::ActivatePatchSkip(Thread *thread,
const BYTE *PC,
BOOL fForEnC)
{
#ifdef _DEBUG
BOOL shouldBreak = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ActivatePatchSkip);
if (shouldBreak > 0) {
_ASSERTE(!"ActivatePatchSkip");
}
#endif
LOG((LF_CORDB,LL_INFO10000, "DC::APS thread=0x%p pc=0x%p fForEnc=%d\n",
thread, PC, fForEnC));
_ASSERTE(g_patches != NULL);
// Previously, we assumed that if we got to this point & the patch
// was still there that we'd have to skip the patch. SetIP changes
// this like so:
// A breakpoint is set, and hit (but not removed), and all the
// EE threads come to a skreeching halt. The Debugger RC thread
// continues along, and is told to SetIP of the thread that hit
// the BP to whatever. Eventually the RC thread is told to continue,
// and at that point the EE thread is released, finishes DispatchPatchOrSingleStep,
// and shows up here.
// At that point, if the thread's current PC is
// different from the patch PC, then SetIP must have moved it elsewhere
// & we shouldn't do this patch skip (which will put us back to where
// we were, which is clearly wrong). If the PC _is_ the same, then
// the thread hasn't been moved, the patch is still in the code stream,
// and we want to do the patch skip thing in order to execute this
// instruction w/o removing it from the code stream.
DebuggerControllerPatch *patch = g_patches->GetPatch((CORDB_ADDRESS_TYPE *)PC);
DebuggerPatchSkip *skip = NULL;
if (patch != NULL && patch->IsNativePatch())
{
//
// We adjust the thread's PC to someplace where we write
// the next instruction, then
// we single step over that, then we set the PC back here so
// we don't let other threads race past here while we're stepping
// this one.
//
// !!! check result
LOG((LF_CORDB,LL_INFO10000, "DC::APS: About to skip from PC=0x%p\n", PC));
skip = new (interopsafe) DebuggerPatchSkip(thread, patch, thread->GetDomain());
TRACE_ALLOC(skip);
}
return skip;
}
DPOSS_ACTION DebuggerController::ScanForTriggers(CORDB_ADDRESS_TYPE *address,
Thread *thread,
CONTEXT *context,
DebuggerControllerQueue *pDcq,
SCAN_TRIGGER stWhat,
TP_RESULT *pTpr)
{
CONTRACTL
{
SO_NOT_MAINLINE;
// @todo - should this throw or not?
NOTHROW;
// call Triggers which may invoke GC stuff... See comment in DispatchNativeException for why it's disabled.
DISABLED(GC_TRIGGERS);
PRECONDITION(!ThisIsHelperThreadWorker());
PRECONDITION(CheckPointer(address));
PRECONDITION(CheckPointer(thread));
PRECONDITION(CheckPointer(context));
PRECONDITION(CheckPointer(pDcq));
PRECONDITION(CheckPointer(pTpr));
}
CONTRACTL_END;
_ASSERTE(HasLock());
CONTRACT_VIOLATION(ThrowsViolation);
LOG((LF_CORDB, LL_INFO10000, "DC::SFT: starting scan for addr:0x%p"
" thread:0x%x\n", address, thread));
_ASSERTE( pTpr != NULL );
DebuggerControllerPatch *patch = NULL;
if (g_patches != NULL)
patch = g_patches->GetPatch(address);
ULONG iEvent = UINT32_MAX;
ULONG iEventNext = UINT32_MAX;
BOOL fDone = FALSE;
// This is a debugger exception if there's a patch here, or
// we're here for something like a single step.
DPOSS_ACTION used = DPOSS_INVALID;
if ((patch != NULL) || !IsPatched(address, TRUE))
{
// we are sure that we care for this exception but not sure
// if we will send event to the RS
used = DPOSS_USED_WITH_NO_EVENT;
}
else
{
// initialize it to don't care for now
used = DPOSS_DONT_CARE;
}
TP_RESULT tpr = TPR_IGNORE;
while (stWhat & ST_PATCH &&
patch != NULL &&
!fDone)
{
_ASSERTE(IsInUsedAction(used) == true);
DebuggerControllerPatch *patchNext
= g_patches->GetNextPatch(patch);
LOG((LF_CORDB, LL_INFO10000, "DC::SFT: patch 0x%x, patchNext 0x%x\n", patch, patchNext));
// Annoyingly, TriggerPatch may add patches, which may cause
// the patch table to move, which may, in turn, invalidate
// the patch (and patchNext) pointers. Store indeces, instead.
iEvent = g_patches->GetItemIndex( (HASHENTRY *)patch );
if (patchNext != NULL)
{
iEventNext = g_patches->GetItemIndex((HASHENTRY *)patchNext);
}
if (MatchPatch(thread, context, patch))
{
LOG((LF_CORDB, LL_INFO10000, "DC::SFT: patch matched\n"));
AddRef(patch);
// We are hitting a patch at a virtual trace call target, so let's trigger trace call here.
if (patch->trace.GetTraceType() == TRACE_ENTRY_STUB)
{
patch->controller->TriggerTraceCall(thread, dac_cast<PTR_CBYTE>(::GetIP(context)));
tpr = TPR_IGNORE;
}
else
{
// Mark if we're at an unsafe place.
AtSafePlaceHolder unsafePlaceHolder(thread);
tpr = patch->controller->TriggerPatch(patch,
thread,
TY_NORMAL);
}
// Any patch may potentially send an event.
// (Whereas some single-steps are "internal-only" and can
// never send an event- such as a single step over an exception that
// lands us in la-la land.)
used = DPOSS_USED_WITH_EVENT;
if (tpr == TPR_TRIGGER ||
tpr == TPR_TRIGGER_ONLY_THIS ||
tpr == TPR_TRIGGER_ONLY_THIS_AND_LOOP)
{
// Make sure we've still got a valid pointer.
patch = (DebuggerControllerPatch *)
DebuggerController::g_patches->GetEntryPtr( iEvent );
pDcq->dcqEnqueue(patch->controller, TRUE); // <REVISIT_TODO>@todo Return value</REVISIT_TODO>
}
// Make sure we've got a valid pointer in case TriggerPatch
// returned false but still caused the table to move.
patch = (DebuggerControllerPatch *)
g_patches->GetEntryPtr( iEvent );
// A patch can be deleted as a result of it's being triggered.
// The actual deletion of the patch is delayed until after the
// the end of the trigger.
// Moreover, "patchNext" could have been deleted as a result of DisableAll()
// being called in TriggerPatch(). Thus, we should update our patchNext
// pointer now. We were just lucky before, because the now-deprecated
// "deleted" flag didn't get set when we iterate the patches in DisableAll().
patchNext = g_patches->GetNextPatch(patch);
if (patchNext != NULL)
iEventNext = g_patches->GetItemIndex((HASHENTRY *)patchNext);
// Note that Release() actually removes the patch if its ref count
// reaches 0 after the release.
Release(patch);
}
if (tpr == TPR_IGNORE_AND_STOP ||
tpr == TPR_TRIGGER_ONLY_THIS ||
tpr == TPR_TRIGGER_ONLY_THIS_AND_LOOP)
{
#ifdef _DEBUG
if (tpr == TPR_TRIGGER_ONLY_THIS ||
tpr == TPR_TRIGGER_ONLY_THIS_AND_LOOP)
_ASSERTE(pDcq->dcqGetCount() == 1);
#endif //_DEBUG
fDone = TRUE;
}
else if (patchNext != NULL)
{
patch = (DebuggerControllerPatch *)
g_patches->GetEntryPtr(iEventNext);
}
else
{
patch = NULL;
}
}
if (stWhat & ST_SINGLE_STEP &&
tpr != TPR_TRIGGER_ONLY_THIS)
{
LOG((LF_CORDB, LL_INFO10000, "DC::SFT: Trigger controllers with single step\n"));
//
// Now, go ahead & trigger all controllers with
// single step events
//
DebuggerController *p;
p = g_controllers;
while (p != NULL)
{
DebuggerController *pNext = p->m_next;
if (p->m_thread == thread && p->m_singleStep)
{
if (used == DPOSS_DONT_CARE)
{
// Debugger does care for this exception.
used = DPOSS_USED_WITH_NO_EVENT;
}
if (p->TriggerSingleStep(thread, (const BYTE *)address))
{
// by now, we should already know that we care for this exception.
_ASSERTE(IsInUsedAction(used) == true);
// now we are sure that we will send event to the RS
used = DPOSS_USED_WITH_EVENT;
pDcq->dcqEnqueue(p, FALSE); // <REVISIT_TODO>@todo Return value</REVISIT_TODO>
}
}
p = pNext;
}
UnapplyTraceFlag(thread);
//
// See if we have any steppers still active for this thread, if so
// re-apply the trace flag.
//
p = g_controllers;
while (p != NULL)
{
if (p->m_thread == thread && p->m_singleStep)
{
ApplyTraceFlag(thread);
break;
}
p = p->m_next;
}
}
// Significant speed increase from single dereference, I bet :)
(*pTpr) = tpr;
LOG((LF_CORDB, LL_INFO10000, "DC::SFT returning 0x%x as used\n",used));
return used;
}
#ifdef EnC_SUPPORTED
DebuggerControllerPatch *DebuggerController::IsXXXPatched(const BYTE *PC,
DEBUGGER_CONTROLLER_TYPE dct)
{
_ASSERTE(g_patches != NULL);
DebuggerControllerPatch *patch = g_patches->GetPatch((CORDB_ADDRESS_TYPE *)PC);
while(patch != NULL &&
(int)patch->controller->GetDCType() <= (int)dct)
{
if (patch->IsNativePatch() &&
patch->controller->GetDCType()==dct)
{
return patch;
}
patch = g_patches->GetNextPatch(patch);
}
return NULL;
}
// This function will check for an EnC patch at the given address and return
// it if one is there, otherwise it will return NULL.
DebuggerControllerPatch *DebuggerController::GetEnCPatch(const BYTE *address)
{
_ASSERTE(address);
if( g_pEEInterface->IsManagedNativeCode(address) )
{
DebuggerJitInfo *dji = g_pDebugger->GetJitInfoFromAddr((TADDR) address);
if (dji == NULL)
return NULL;
// we can have two types of patches - one in code where the IL has been updated to trigger
// the switch and the other in the code we've switched to in order to trigger FunctionRemapComplete
// callback. If version == default then can't be the latter, but otherwise if haven't handled the
// remap for this function yet is certainly the latter.
if (! dji->m_encBreakpointsApplied &&
(dji->m_encVersion == CorDB_DEFAULT_ENC_FUNCTION_VERSION))
{
return NULL;
}
}
return IsXXXPatched(address, DEBUGGER_CONTROLLER_ENC);
}
#endif //EnC_SUPPORTED
// DebuggerController::DispatchPatchOrSingleStep - Ask any patches that are active at a given
// address if they want to do anything about the exception that's occurred there. How: For the given
// address, go through the list of patches & see if any of them are interested (by invoking their
// DebuggerController's TriggerPatch). Put any DCs that are interested into a queue and then calls
// SendEvent on each.
// Note that control will not return from this function in the case of EnC remap
DPOSS_ACTION DebuggerController::DispatchPatchOrSingleStep(Thread *thread, CONTEXT *context, CORDB_ADDRESS_TYPE *address, SCAN_TRIGGER which)
{
CONTRACT(DPOSS_ACTION)
{
// @todo - should this throw or not?
NOTHROW;
DISABLED(GC_TRIGGERS); // Only GC triggers if we send an event. See Comment in DispatchNativeException
PRECONDITION(!ThisIsHelperThreadWorker());
PRECONDITION(CheckPointer(thread));
PRECONDITION(CheckPointer(context));
PRECONDITION(CheckPointer(address));
PRECONDITION(!HasLock());
POSTCONDITION(!HasLock()); // make sure we're not leaking the controller lock
}
CONTRACT_END;
CONTRACT_VIOLATION(ThrowsViolation);
LOG((LF_CORDB|LF_ENC,LL_INFO1000,"DC:DPOSS at 0x%x trigger:0x%x\n", address, which));
// We should only have an exception if some managed thread was running.
// Thus we should never be here when we're stopped.
// @todo - this assert fires! Is that an issue, or is it invalid?
//_ASSERTE(!g_pDebugger->IsStopped());
DPOSS_ACTION used = DPOSS_DONT_CARE;
DebuggerControllerQueue dcq;
if (!g_patchTableValid)
{
LOG((LF_CORDB|LF_ENC, LL_INFO1000, "DC::DPOSS returning, no patch table.\n"));
RETURN (used);
}
_ASSERTE(g_patches != NULL);
CrstHolderWithState lockController(&g_criticalSection);
TADDR originalAddress = 0;
#ifdef EnC_SUPPORTED
DebuggerControllerPatch *dcpEnCOriginal = NULL;
// If this sequence point has an EnC patch, we want to process it ahead of any others. If the
// debugger wants to remap the function at this point, then we'll call ResumeInUpdatedFunction and
// not return, otherwise we will just continue with regular patch-handling logic
dcpEnCOriginal = GetEnCPatch(dac_cast<PTR_CBYTE>(GetIP(context)));
if (dcpEnCOriginal)
{
LOG((LF_CORDB|LF_ENC,LL_INFO10000, "DC::DPOSS EnC short-circuit\n"));
TP_RESULT tpres =
dcpEnCOriginal->controller->TriggerPatch(dcpEnCOriginal,
thread,
TY_SHORT_CIRCUIT);
// We will only come back here on a RemapOppporunity that wasn't taken, or on a RemapComplete.
// If we processed a RemapComplete (which returns TPR_IGNORE_AND_STOP), then don't want to handle
// additional breakpoints on the current line because we've already effectively executed to that point
// and would have hit them already. If they are new, we also don't want to hit them because eg. if are
// sitting on line 10 and add a breakpoint at line 10 and step,
// don't expect to stop at line 10, expect to go to line 11.
//
// Special case is if an EnC remap breakpoint exists in the function. This could only happen if the function was
// updated between the RemapOpportunity and the RemapComplete. In that case we want to not skip the patches
// and fall through to handle the remap breakpoint.
if (tpres == TPR_IGNORE_AND_STOP)
{
// It was a RemapComplete, so fall through. Set dcpEnCOriginal to NULL to indicate that any
// EnC patch still there should be treated as a new patch. Any RemapComplete patch will have been
// already removed by patch processing.
dcpEnCOriginal = NULL;
LOG((LF_CORDB|LF_ENC,LL_INFO10000, "DC::DPOSS done EnC short-circuit, exiting\n"));
used = DPOSS_USED_WITH_EVENT; // indicate that we handled a patch
goto Exit;
}
_ASSERTE(tpres==TPR_IGNORE);
LOG((LF_CORDB|LF_ENC,LL_INFO10000, "DC::DPOSS done EnC short-circuit, ignoring\n"));
// if we got here, then the EnC remap opportunity was not taken, so just continue on.
}
#endif // EnC_SUPPORTED
TP_RESULT tpr;
used = ScanForTriggers((CORDB_ADDRESS_TYPE *)address, thread, context, &dcq, which, &tpr);
LOG((LF_CORDB|LF_ENC, LL_EVERYTHING, "DC::DPOSS ScanForTriggers called and returned.\n"));
// If we setip, then that will change the address in the context.
// Remeber the old address so that we can compare it to the context's ip and see if it changed.
// If it did change, then don't dispatch our current event.
originalAddress = (TADDR) address;
#ifdef _DEBUG
// If we do a SetIP after this point, the value of address will be garbage. Set it to a distictive pattern now, so
// we don't accidentally use what will (98% of the time) appear to be a valid value.
address = (CORDB_ADDRESS_TYPE *)(UINT_PTR)0xAABBCCFF;
#endif //_DEBUG
if (dcq.dcqGetCount()> 0)
{
lockController.Release();
// Mark if we're at an unsafe place.
bool atSafePlace = g_pDebugger->IsThreadAtSafePlace(thread);
if (!atSafePlace)
g_pDebugger->IncThreadsAtUnsafePlaces();
DWORD dwEvent = 0xFFFFFFFF;
DWORD dwNumberEvents = 0;
BOOL reabort = FALSE;
SENDIPCEVENT_BEGIN(g_pDebugger, thread);
// Now that we've resumed from blocking, check if somebody did a SetIp on us.
bool fIpChanged = (originalAddress != GetIP(context));
// Send the events outside of the controller lock
bool anyEventsSent = false;
dwNumberEvents = dcq.dcqGetCount();
dwEvent = 0;
while (dwEvent < dwNumberEvents)
{
DebuggerController *event = dcq.dcqGetElement(dwEvent);
if (!event->m_deleted)
{
#ifdef DEBUGGING_SUPPORTED
if (thread->GetDomain()->IsDebuggerAttached())
{
if (event->SendEvent(thread, fIpChanged))
{
anyEventsSent = true;
}
}
#endif //DEBUGGING_SUPPORTED
}
dwEvent++;
}
// Trap all threads if necessary, but only if we actually sent a event up (i.e., all the queued events weren't
// deleted before we got a chance to get the EventSending lock.)
if (anyEventsSent)
{
LOG((LF_CORDB|LF_ENC, LL_EVERYTHING, "DC::DPOSS We sent an event\n"));
g_pDebugger->SyncAllThreads(SENDIPCEVENT_PtrDbgLockHolder);
LOG((LF_CORDB,LL_INFO1000, "SAT called!\n"));
}
// If we need to to a re-abort (see below), then save the current IP in the thread's context before we block and
// possibly let another func eval get setup.
reabort = thread->m_StateNC & Thread::TSNC_DebuggerReAbort;
SENDIPCEVENT_END;
if (!atSafePlace)
g_pDebugger->DecThreadsAtUnsafePlaces();
lockController.Acquire();
// Dequeue the events while we have the controller lock.
dwEvent = 0;
while (dwEvent < dwNumberEvents)
{
dcq.dcqDequeue();
dwEvent++;
}
// If a func eval completed with a ThreadAbortException, go ahead and setup the thread to re-abort itself now
// that we're continuing the thread. Note: we make sure that the thread's IP hasn't changed between now and when
// we blocked above. While blocked above, the debugger has a chance to setup another func eval on this
// thread. If that happens, we don't want to setup the reabort just yet.
if (reabort)
{
if ((UINT_PTR)GetEEFuncEntryPoint(::FuncEvalHijack) != (UINT_PTR)GetIP(context))
{
HRESULT hr;
hr = g_pDebugger->FuncEvalSetupReAbort(thread, Thread::TAR_Thread);
_ASSERTE(SUCCEEDED(hr));
}
}
}
#if defined EnC_SUPPORTED
Exit:
#endif
// Note: if the thread filter context is NULL, then SetIP would have failed & thus we should do the
// patch skip thing.
// @todo - do we need to get the context again here?
CONTEXT *pCtx = GetManagedLiveCtx(thread);
#ifdef EnC_SUPPORTED
DebuggerControllerPatch *dcpEnCCurrent = GetEnCPatch(dac_cast<PTR_CBYTE>((GetIP(context))));
// we have a new patch if the original was null and the current is non-null. Otherwise we have an old
// patch. We want to skip old patches, but handle new patches.
if (dcpEnCOriginal == NULL && dcpEnCCurrent != NULL)
{
LOG((LF_CORDB|LF_ENC,LL_INFO10000, "DC::DPOSS EnC post-processing\n"));
dcpEnCCurrent->controller->TriggerPatch( dcpEnCCurrent,
thread,
TY_SHORT_CIRCUIT);
used = DPOSS_USED_WITH_EVENT; // indicate that we handled a patch
}
#endif
ActivatePatchSkip(thread, dac_cast<PTR_CBYTE>(GetIP(pCtx)), FALSE);
lockController.Release();
// We pulse the GC mode here too cooperate w/ a thread trying to suspend the runtime. If we didn't pulse
// the GC, the odds of catching this thread in interuptable code may be very small (since this filter
// could be very large compared to the managed code this thread is running).
// Only do this if the exception was actually for the debugger. (We don't want to toggle the GC mode on every
// random exception). We can't do this while holding any debugger locks.
if (used == DPOSS_USED_WITH_EVENT)
{
bool atSafePlace = g_pDebugger->IsThreadAtSafePlace(thread);
if (!atSafePlace)
{
g_pDebugger->IncThreadsAtUnsafePlaces();
}
// Always pulse the GC mode. This will allow an async break to complete even if we have a patch
// at an unsafe place.
// If we are at an unsafe place, then we can't do a GC.
thread->PulseGCMode();
if (!atSafePlace)
{
g_pDebugger->DecThreadsAtUnsafePlaces();
}
}
RETURN used;
}
bool DebuggerController::IsSingleStepEnabled()
{
LIMITED_METHOD_CONTRACT;
return m_singleStep;
}
void DebuggerController::EnableSingleStep()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
#ifdef _DEBUG
// Some controllers don't need to set the SS to do their job, and if they are setting it, it's likely an issue.
// So we assert here to catch them red-handed. This assert can always be updated to accomodate changes
// in a controller's behavior.
switch(GetDCType())
{
case DEBUGGER_CONTROLLER_THREAD_STARTER:
case DEBUGGER_CONTROLLER_BREAKPOINT:
case DEBUGGER_CONTROLLER_USER_BREAKPOINT:
case DEBUGGER_CONTROLLER_FUNC_EVAL_COMPLETE:
CONSISTENCY_CHECK_MSGF(false, ("Controller pThis=%p shouldn't be setting ss flag.", this));
break;
default: // MingW compilers require all enum cases to be handled in switch statement.
break;
}
#endif
EnableSingleStep(m_thread);
m_singleStep = true;
}
#ifdef EnC_SUPPORTED
// Note that this doesn't tell us if Single Stepping is currently enabled
// at the hardware level (ie, for x86, if (context->EFlags & 0x100), but
// rather, if we WANT single stepping enabled (pThread->m_State &Thread::TS_DebuggerIsStepping)
// This gets called from exactly one place - ActivatePatchSkipForEnC
BOOL DebuggerController::IsSingleStepEnabled(Thread *pThread)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
// This should be an atomic operation, do we
// don't need to lock it.
if(pThread->m_StateNC & Thread::TSNC_DebuggerIsStepping)
{
_ASSERTE(pThread->m_StateNC & Thread::TSNC_DebuggerIsStepping);
return TRUE;
}
else
return FALSE;
}
#endif //EnC_SUPPORTED
void DebuggerController::EnableSingleStep(Thread *pThread)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
LOG((LF_CORDB,LL_INFO1000, "DC::EnableSingleStep\n"));
_ASSERTE(pThread != NULL);
ControllerLockHolder lockController;
ApplyTraceFlag(pThread);
}
// Disable Single stepping for this controller.
// If none of the controllers on this thread want single-stepping, then also
// ensure that it's disabled on the hardware level.
void DebuggerController::DisableSingleStep()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(m_thread != NULL);
LOG((LF_CORDB,LL_INFO1000, "DC::DisableSingleStep\n"));
ControllerLockHolder lockController;
{
DebuggerController *p = g_controllers;
m_singleStep = false;
while (p != NULL)
{
if (p->m_thread == m_thread
&& p->m_singleStep)
break;
p = p->m_next;
}
if (p == NULL)
{
UnapplyTraceFlag(m_thread);
}
}
}
//
// ApplyTraceFlag sets the trace flag (i.e., turns on single-stepping)
// for a thread.
//
void DebuggerController::ApplyTraceFlag(Thread *thread)
{
LOG((LF_CORDB,LL_INFO1000, "DC::ApplyTraceFlag thread:0x%x [0x%0x]\n", thread, Debugger::GetThreadIdHelper(thread)));
CONTEXT *context;
if(thread->GetInteropDebuggingHijacked())
{
context = GetManagedLiveCtx(thread);
}
else
{
context = GetManagedStoppedCtx(thread);
}
CONSISTENCY_CHECK_MSGF(context != NULL, ("Can't apply ss flag to thread 0x%p b/c it's not in a safe place.\n", thread));
PREFIX_ASSUME(context != NULL);
g_pEEInterface->MarkThreadForDebugStepping(thread, true);
LOG((LF_CORDB,LL_INFO1000, "DC::ApplyTraceFlag marked thread for debug stepping\n"));
SetSSFlag(reinterpret_cast<DT_CONTEXT *>(context) ARM_ARG(thread));
LOG((LF_CORDB,LL_INFO1000, "DC::ApplyTraceFlag Leaving, baby!\n"));
}
//
// UnapplyTraceFlag sets the trace flag for a thread.
// Removes the hardware trace flag on this thread.
//
void DebuggerController::UnapplyTraceFlag(Thread *thread)
{
LOG((LF_CORDB,LL_INFO1000, "DC::UnapplyTraceFlag thread:0x%x\n", thread));
// Either this is the helper thread, or we're manipulating our own context.
_ASSERTE(
ThisIsHelperThreadWorker() ||
(thread == ::GetThread())
);
CONTEXT *context = GetManagedStoppedCtx(thread);
// If there's no context available, then the thread shouldn't have the single-step flag
// enabled and there's nothing for us to do.
if (context == NULL)
{
// In theory, I wouldn't expect us to ever get here.
// Even if we are here, our single-step flag should already be deactivated,
// so there should be nothing to do. However, we still assert b/c we want to know how
// we'd actually hit this.
// @todo - is there a path if TriggerUnwind() calls DisableAll(). But why would
CONSISTENCY_CHECK_MSGF(false, ("How did we get here?. thread=%p\n", thread));
LOG((LF_CORDB,LL_INFO1000, "DC::UnapplyTraceFlag couldn't get context.\n"));
return;
}
// Always need to unmark for stepping
g_pEEInterface->MarkThreadForDebugStepping(thread, false);
UnsetSSFlag(reinterpret_cast<DT_CONTEXT *>(context) ARM_ARG(thread));
}
void DebuggerController::EnableExceptionHook()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(m_thread != NULL);
ControllerLockHolder lockController;
m_exceptionHook = true;
}
void DebuggerController::DisableExceptionHook()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(m_thread != NULL);
ControllerLockHolder lockController;
m_exceptionHook = false;
}
// void DebuggerController::DispatchExceptionHook() Called before
// the switch statement in DispatchNativeException (therefore
// when any exception occurs), this allows patches to do something before the
// regular DispatchX methods.
// How: Iterate through list of controllers. If m_exceptionHook
// is set & m_thread is either thread or NULL, then invoke TriggerExceptionHook()
BOOL DebuggerController::DispatchExceptionHook(Thread *thread,
CONTEXT *context,
EXCEPTION_RECORD *pException)
{
// ExceptionHook has restrictive contract b/c it could come from anywhere.
// This can only modify controller's internal state. Can't send managed debug events.
CONTRACTL
{
SO_NOT_MAINLINE;
GC_NOTRIGGER;
NOTHROW;
MODE_ANY;
// Filter context not set yet b/c we can only set it in COOP, and this may be in preemptive.
PRECONDITION(thread == ::GetThread());
PRECONDITION((g_pEEInterface->GetThreadFilterContext(thread) == NULL));
PRECONDITION(CheckPointer(pException));
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO1000, "DC:: DispatchExceptionHook\n"));
if (!g_patchTableValid)
{
LOG((LF_CORDB, LL_INFO1000, "DC::DEH returning, no patch table.\n"));
return (TRUE);
}
_ASSERTE(g_patches != NULL);
ControllerLockHolder lockController;
TP_RESULT tpr = TPR_IGNORE;
DebuggerController *p;
p = g_controllers;
while (p != NULL)
{
DebuggerController *pNext = p->m_next;
if (p->m_exceptionHook
&& (p->m_thread == NULL || p->m_thread == thread) &&
tpr != TPR_IGNORE_AND_STOP)
{
LOG((LF_CORDB, LL_INFO1000, "DC::DEH calling TEH...\n"));
tpr = p->TriggerExceptionHook(thread, context , pException);
LOG((LF_CORDB, LL_INFO1000, "DC::DEH ... returned.\n"));
if (tpr == TPR_IGNORE_AND_STOP)
{
LOG((LF_CORDB, LL_INFO1000, "DC:: DEH: leaving early!\n"));
break;
}
}
p = pNext;
}
LOG((LF_CORDB, LL_INFO1000, "DC:: DEH: returning 0x%x!\n", tpr));
return (tpr != TPR_IGNORE_AND_STOP);
}
//
// EnableUnwind enables an unwind event to be called when the stack is unwound
// (via an exception) to or past the given pointer.
//
void DebuggerController::EnableUnwind(FramePointer fp)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ASSERT(m_thread != NULL);
LOG((LF_CORDB,LL_EVERYTHING,"DC:EU EnableUnwind at 0x%x\n", fp.GetSPValue()));
ControllerLockHolder lockController;
m_unwindFP = fp;
}
FramePointer DebuggerController::GetUnwind()
{
LIMITED_METHOD_CONTRACT;
return m_unwindFP;
}
//
// DisableUnwind disables the unwind event for the controller.
//
void DebuggerController::DisableUnwind()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
CAN_TAKE_LOCK;
}
CONTRACTL_END;
ASSERT(m_thread != NULL);
LOG((LF_CORDB,LL_INFO1000, "DC::DU\n"));
ControllerLockHolder lockController;
m_unwindFP = LEAF_MOST_FRAME;
}
//
// DispatchUnwind is called when an unwind happens.
// the event to the appropriate controllers.
// - handlerFP is the frame pointer that the handler will be invoked at.
// - DJI is EnC-aware method that the handler is in.
// - newOffset is the
//
bool DebuggerController::DispatchUnwind(Thread *thread,
MethodDesc *fd, DebuggerJitInfo * pDJI,
SIZE_T newOffset,
FramePointer handlerFP,
CorDebugStepReason unwindReason)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER; // don't send IPC events
MODE_COOPERATIVE; // TriggerUnwind always is coop
PRECONDITION(!IsDbgHelperSpecialThread());
}
CONTRACTL_END;
CONTRACT_VIOLATION(ThrowsViolation); // trigger unwind throws
_ASSERTE(unwindReason == STEP_EXCEPTION_FILTER || unwindReason == STEP_EXCEPTION_HANDLER);
bool used = false;
LOG((LF_CORDB, LL_INFO10000, "DC: Dispatch Unwind\n"));
ControllerLockHolder lockController;
{
DebuggerController *p;
p = g_controllers;
while (p != NULL)
{
DebuggerController *pNext = p->m_next;
if (p->m_thread == thread && p->m_unwindFP != LEAF_MOST_FRAME)
{
LOG((LF_CORDB, LL_INFO10000, "Dispatch Unwind: Found candidate\n"));
// Assumptions here:
// Function with handlers are -ALWAYS- EBP-frame based (JIT assumption)
//
// newFrame is the EBP for the handler
// p->m_unwindFP points to the stack slot with the return address of the function.
//
// For the interesting case: stepover, we want to know if the handler is in the same function
// as the stepper, if its above it (caller) o under it (callee) in order to know if we want
// to patch the handler or not.
//
// 3 cases:
//
// a) Handler is in a function under the function where the step happened. It therefore is
// a stepover. We don't want to patch this handler. The handler will have an EBP frame.
// So it will be at least be 2 DWORDs away from the m_unwindFP of the controller (
// 1 DWORD from the pushed return address and 1 DWORD for the push EBP).
//
// b) Handler is in the same function as the stepper. We want to patch the handler. In this
// case handlerFP will be the same as p->m_unwindFP-sizeof(void*). Why? p->m_unwindFP
// stores a pointer to the return address of the function. As a function with a handler
// is always EBP frame based it will have the following code in the prolog:
//
// push ebp <- ( sub esp, 4 ; mov [esp], ebp )
// mov esp, ebp
//
// Therefore EBP will be equal to &CallerReturnAddress-4.
//
// c) Handler is above the function where the stepper is. We want to patch the handler. handlerFP
// will be always greater than the pointer to the return address of the function where the
// stepper is.
//
//
//
if (IsEqualOrCloserToRoot(handlerFP, p->m_unwindFP))
{
used = true;
//
// Assume that this isn't going to block us at all --
// other threads may be waiting to patch or unpatch something,
// or to dispatch.
//
LOG((LF_CORDB, LL_INFO10000,
"Unwind trigger at offset 0x%p; handlerFP: 0x%p unwindReason: 0x%x.\n",
newOffset, handlerFP.GetSPValue(), unwindReason));
p->TriggerUnwind(thread,
fd, pDJI,
newOffset,
handlerFP,
unwindReason);
}
else
{
LOG((LF_CORDB, LL_INFO10000,
"Unwind trigger at offset 0x%p; handlerFP: 0x%p unwindReason: 0x%x.\n",
newOffset, handlerFP.GetSPValue(), unwindReason));
}
}
p = pNext;
}
}
return used;
}
//
// EnableTraceCall enables a call event on the controller
// maxFrame is the leaf-most frame that we want notifications for.
// For step-in stuff, this will always be LEAF_MOST_FRAME.
// for step-out, this will be the current frame because we don't
// care if the current frame calls back into managed code when we're
// only interested in our parent frames.
//
void DebuggerController::EnableTraceCall(FramePointer maxFrame)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ASSERT(m_thread != NULL);
LOG((LF_CORDB,LL_INFO1000, "DC::ETC maxFrame=0x%x, thread=0x%x\n",
maxFrame.GetSPValue(), Debugger::GetThreadIdHelper(m_thread)));
// JMC stepper should never enabled this. (They should enable ME instead).
_ASSERTE((DEBUGGER_CONTROLLER_JMC_STEPPER != this->GetDCType()) || !"JMC stepper shouldn't enable trace-call");
ControllerLockHolder lockController;
{
if (!m_traceCall)
{
m_traceCall = true;
g_pEEInterface->EnableTraceCall(m_thread);
}
if (IsCloserToLeaf(maxFrame, m_traceCallFP))
m_traceCallFP = maxFrame;
}
}
struct PatchTargetVisitorData
{
DebuggerController* controller;
FramePointer maxFrame;
};
VOID DebuggerController::PatchTargetVisitor(TADDR pVirtualTraceCallTarget, VOID* pUserData)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
DebuggerController* controller = ((PatchTargetVisitorData*) pUserData)->controller;
FramePointer maxFrame = ((PatchTargetVisitorData*) pUserData)->maxFrame;
EX_TRY
{
CONTRACT_VIOLATION(GCViolation); // PatchTrace throws, which implies GC-triggers
TraceDestination trace;
trace.InitForUnmanagedStub(pVirtualTraceCallTarget);
controller->PatchTrace(&trace, maxFrame, true);
}
EX_CATCH
{
// not much we can do here
}
EX_END_CATCH(SwallowAllExceptions)
}
//
// DisableTraceCall disables call events on the controller
//
void DebuggerController::DisableTraceCall()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ASSERT(m_thread != NULL);
ControllerLockHolder lockController;
{
if (m_traceCall)
{
LOG((LF_CORDB,LL_INFO1000, "DC::DTC thread=0x%x\n",
Debugger::GetThreadIdHelper(m_thread)));
g_pEEInterface->DisableTraceCall(m_thread);
m_traceCall = false;
m_traceCallFP = ROOT_MOST_FRAME;
}
}
}
// Get a FramePointer for the leafmost frame on this thread's stacktrace.
// It's tempting to create this off the head of the Frame chain, but that may
// include internal EE Frames (like GCRoot frames) which a FrameInfo-stackwalk may skip over.
// Thus using the Frame chain would err on the side of returning a FramePointer that
// closer to the leaf.
FramePointer GetCurrentFramePointerFromStackTraceForTraceCall(Thread * thread)
{
_ASSERTE(thread != NULL);
// Ensure this is really the same as CSI.
ControllerStackInfo info;
// It's possible this stackwalk may be done at an unsafe time.
// this method may trigger a GC, for example, in
// FramedMethodFrame::AskStubForUnmanagedCallSite
// which will trash the incoming argument array
// which is not gc-protected.
// We could probably imagine a more specialized stackwalk that
// avoids these calls and is thus GC_NOTRIGGER.
CONTRACT_VIOLATION(GCViolation);
// This is being run live, so there's no filter available.
CONTEXT *context;
context = g_pEEInterface->GetThreadFilterContext(thread);
_ASSERTE(context == NULL);
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
// This is actually safe because we're coming from a TraceCall, which
// means we're not in the middle of a stub. We don't have some partially
// constructed frame, so we can safely traverse the stack.
// However, we may still have a problem w/ the GC-violation.
StackTraceTicket ticket(StackTraceTicket::SPECIAL_CASE_TICKET);
info.GetStackInfo(ticket, thread, LEAF_MOST_FRAME, NULL);
FramePointer fp = info.m_activeFrame.fp;
return fp;
}
//
// DispatchTraceCall is called when a call is traced in the EE
// It dispatches the event to the appropriate controllers.
//
bool DebuggerController::DispatchTraceCall(Thread *thread,
const BYTE *ip)
{
CONTRACTL
{
GC_NOTRIGGER;
THROWS;
}
CONTRACTL_END;
bool used = false;
LOG((LF_CORDB, LL_INFO10000,
"DC::DTC: TraceCall at 0x%x\n", ip));
ControllerLockHolder lockController;
{
DebuggerController *p;
p = g_controllers;
while (p != NULL)
{
DebuggerController *pNext = p->m_next;
if (p->m_thread == thread && p->m_traceCall)
{
bool trigger;
if (p->m_traceCallFP == LEAF_MOST_FRAME)
trigger = true;
else
{
// We know we don't have a filter context, so get a frame pointer from our frame chain.
FramePointer fpToCheck = GetCurrentFramePointerFromStackTraceForTraceCall(thread);
// <REVISIT_TODO>
//
// Currently, we never ever put a patch in an IL stub, and as such, if the IL stub
// throws an exception after returning from unmanaged code, we would not trigger
// a trace call when we call the constructor of the exception. The following is
// kind of a workaround to make that working. If we ever make the change to stop in
// IL stubs (for example, if we start to share security IL stub), then this can be
// removed.
//
// </REVISIT_TODO>
// It's possible this stackwalk may be done at an unsafe time.
// this method may trigger a GC, for example, in
// FramedMethodFrame::AskStubForUnmanagedCallSite
// which will trash the incoming argument array
// which is not gc-protected.
ControllerStackInfo info;
{
CONTRACT_VIOLATION(GCViolation);
#ifdef _DEBUG
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
#endif // _DEBUG
_ASSERTE(context == NULL);
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
// See explanation in GetCurrentFramePointerFromStackTraceForTraceCall.
StackTraceTicket ticket(StackTraceTicket::SPECIAL_CASE_TICKET);
info.GetStackInfo(ticket, thread, LEAF_MOST_FRAME, NULL);
}
if (info.m_activeFrame.chainReason == CHAIN_ENTER_UNMANAGED)
{
_ASSERTE(info.HasReturnFrame());
// This check makes sure that we don't do this logic for inlined frames.
if (info.m_returnFrame.md->IsILStub())
{
// Make sure that the frame pointer of the active frame is actually
// the address of an exit frame.
_ASSERTE( (static_cast<Frame*>(info.m_activeFrame.fp.GetSPValue()))->GetFrameType()
== Frame::TYPE_EXIT );
_ASSERTE(!info.m_returnFrame.HasChainMarker());
fpToCheck = info.m_returnFrame.fp;
}
}
// @todo - This comparison seems somewhat nonsensical. We don't have a filter context
// in place, so what frame pointer is fpToCheck actually for?
trigger = IsEqualOrCloserToRoot(fpToCheck, p->m_traceCallFP);
}
if (trigger)
{
used = true;
// This can only update controller's state, can't actually send IPC events.
p->TriggerTraceCall(thread, ip);
}
}
p = pNext;
}
}
return used;
}
bool DebuggerController::IsMethodEnterEnabled()
{
LIMITED_METHOD_CONTRACT;
return m_fEnableMethodEnter;
}
// Notify dispatching logic that this controller wants to get TriggerMethodEnter
// We keep a count of total controllers waiting for MethodEnter (in g_cTotalMethodEnter).
// That way we know if any controllers want MethodEnter callbacks. If none do,
// then we can set the JMC probe flag to false for all modules.
void DebuggerController::EnableMethodEnter()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ControllerLockHolder chController;
Debugger::DebuggerDataLockHolder chInfo(g_pDebugger);
// Both JMC + Traditional steppers may use MethodEnter.
// For JMC, it's a core part of functionality. For Traditional steppers, we use it as a backstop
// in case the stub-managers fail.
_ASSERTE(g_cTotalMethodEnter >= 0);
if (!m_fEnableMethodEnter)
{
LOG((LF_CORDB, LL_INFO1000000, "DC::EnableME, this=%p, previously disabled\n", this));
m_fEnableMethodEnter = true;
g_cTotalMethodEnter++;
}
else
{
LOG((LF_CORDB, LL_INFO1000000, "DC::EnableME, this=%p, already set\n", this));
}
g_pDebugger->UpdateAllModuleJMCFlag(g_cTotalMethodEnter != 0); // Needs JitInfo lock
}
// Notify dispatching logic that this controller doesn't want to get
// TriggerMethodEnter
void DebuggerController::DisableMethodEnter()
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ControllerLockHolder chController;
Debugger::DebuggerDataLockHolder chInfo(g_pDebugger);
if (m_fEnableMethodEnter)
{
LOG((LF_CORDB, LL_INFO1000000, "DC::DisableME, this=%p, previously set\n", this));
m_fEnableMethodEnter = false;
g_cTotalMethodEnter--;
_ASSERTE(g_cTotalMethodEnter >= 0);
}
else
{
LOG((LF_CORDB, LL_INFO1000000, "DC::DisableME, this=%p, already disabled\n", this));
}
g_pDebugger->UpdateAllModuleJMCFlag(g_cTotalMethodEnter != 0); // Needs JitInfo lock
}
// Loop through controllers and dispatch TriggerMethodEnter
void DebuggerController::DispatchMethodEnter(void * pIP, FramePointer fp)
{
_ASSERTE(pIP != NULL);
Thread * pThread = g_pEEInterface->GetThread();
_ASSERTE(pThread != NULL);
// Lookup the DJI for this method & ip.
// Since we create DJIs when we jit the code, and this code has been jitted
// (that's where the probe's coming from!), we will have a DJI.
DebuggerJitInfo * dji = g_pDebugger->GetJitInfoFromAddr((TADDR) pIP);
// This includes the case where we have a LightWeight codegen method.
if (dji == NULL)
{
return;
}
LOG((LF_CORDB, LL_INFO100000, "DC::DispatchMethodEnter for '%s::%s'\n",
dji->m_fd->m_pszDebugClassName,
dji->m_fd->m_pszDebugMethodName));
ControllerLockHolder lockController;
// For debug check, keep a count to make sure that g_cTotalMethodEnter
// is actually the number of controllers w/ MethodEnter enabled.
int count = 0;
DebuggerController *p = g_controllers;
while (p != NULL)
{
if (p->m_fEnableMethodEnter)
{
if ((p->GetThread() == NULL) || (p->GetThread() == pThread))
{
++count;
p->TriggerMethodEnter(pThread, dji, (const BYTE *) pIP, fp);
}
}
p = p->m_next;
}
_ASSERTE(g_cTotalMethodEnter == count);
}
//
// AddProtection adds page protection to (at least) the given range of
// addresses
//
void DebuggerController::AddProtection(const BYTE *start, const BYTE *end,
bool readable)
{
// !!!
_ASSERTE(!"Not implemented yet");
}
//
// RemoveProtection removes page protection from the given
// addresses. The parameters should match an earlier call to
// AddProtection
//
void DebuggerController::RemoveProtection(const BYTE *start, const BYTE *end,
bool readable)
{
// !!!
_ASSERTE(!"Not implemented yet");
}
// Default implementations for FuncEvalEnter & Exit notifications.
void DebuggerController::TriggerFuncEvalEnter(Thread * thread)
{
LOG((LF_CORDB, LL_INFO100000, "DC::TFEEnter, thead=%p, this=%p\n", thread, this));
}
void DebuggerController::TriggerFuncEvalExit(Thread * thread)
{
LOG((LF_CORDB, LL_INFO100000, "DC::TFEExit, thead=%p, this=%p\n", thread, this));
}
// bool DebuggerController::TriggerPatch() What: Tells the
// static DC whether this patch should be activated now.
// Returns true if it should be, false otherwise.
// How: Base class implementation returns false. Others may
// return true.
TP_RESULT DebuggerController::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
LOG((LF_CORDB, LL_INFO10000, "DC::TP: in default TriggerPatch\n"));
return TPR_IGNORE;
}
bool DebuggerController::TriggerSingleStep(Thread *thread,
const BYTE *ip)
{
LOG((LF_CORDB, LL_INFO10000, "DC::TP: in default TriggerSingleStep\n"));
return false;
}
void DebuggerController::TriggerUnwind(Thread *thread,
MethodDesc *fd, DebuggerJitInfo * pDJI, SIZE_T offset,
FramePointer fp,
CorDebugStepReason unwindReason)
{
LOG((LF_CORDB, LL_INFO10000, "DC::TP: in default TriggerUnwind\n"));
}
void DebuggerController::TriggerTraceCall(Thread *thread,
const BYTE *ip)
{
LOG((LF_CORDB, LL_INFO10000, "DC::TP: in default TriggerTraceCall\n"));
}
TP_RESULT DebuggerController::TriggerExceptionHook(Thread *thread, CONTEXT * pContext,
EXCEPTION_RECORD *exception)
{
LOG((LF_CORDB, LL_INFO10000, "DC::TP: in default TriggerExceptionHook\n"));
return TPR_IGNORE;
}
void DebuggerController::TriggerMethodEnter(Thread * thread,
DebuggerJitInfo * dji,
const BYTE * ip,
FramePointer fp)
{
LOG((LF_CORDB, LL_INFO10000, "DC::TME in default impl. dji=%p, addr=%p, fp=%p\n",
dji, ip, fp.GetSPValue()));
}
bool DebuggerController::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO10000, "DC::TP: in default SendEvent\n"));
// If any derived class trigger SendEvent, it should also implement SendEvent.
_ASSERTE(false || !"Base DebuggerController sending an event?");
return false;
}
// Dispacth Func-Eval Enter & Exit notifications.
void DebuggerController::DispatchFuncEvalEnter(Thread * thread)
{
LOG((LF_CORDB, LL_INFO100000, "DC::DispatchFuncEvalEnter for thread 0x%p\n", thread));
ControllerLockHolder lockController;
DebuggerController *p = g_controllers;
while (p != NULL)
{
if ((p->GetThread() == NULL) || (p->GetThread() == thread))
{
p->TriggerFuncEvalEnter(thread);
}
p = p->m_next;
}
}
void DebuggerController::DispatchFuncEvalExit(Thread * thread)
{
LOG((LF_CORDB, LL_INFO100000, "DC::DispatchFuncEvalExit for thread 0x%p\n", thread));
ControllerLockHolder lockController;
DebuggerController *p = g_controllers;
while (p != NULL)
{
if ((p->GetThread() == NULL) || (p->GetThread() == thread))
{
p->TriggerFuncEvalExit(thread);
}
p = p->m_next;
}
}
#ifdef _DEBUG
// See comment in DispatchNativeException
void ThisFunctionMayHaveTriggerAGC()
{
CONTRACTL
{
SO_NOT_MAINLINE;
GC_TRIGGERS;
NOTHROW;
}
CONTRACTL_END;
}
#endif
// bool DebuggerController::DispatchNativeException() Figures out
// if any debugger controllers will handle the exception.
// DispatchNativeException should be called by the EE when a native exception
// occurs. If it returns true, the exception was generated by a Controller and
// should be ignored.
// How: Calls DispatchExceptionHook to see if anything is
// interested in ExceptionHook, then does a switch on dwCode:
// EXCEPTION_BREAKPOINT means invoke DispatchPatchOrSingleStep(ST_PATCH).
// EXCEPTION_SINGLE_STEP means DispatchPatchOrSingleStep(ST_SINGLE_STEP).
// EXCEPTION_ACCESS_VIOLATION means invoke DispatchAccessViolation.
// Returns true if the exception was actually meant for the debugger,
// returns false otherwise.
bool DebuggerController::DispatchNativeException(EXCEPTION_RECORD *pException,
CONTEXT *pContext,
DWORD dwCode,
Thread *pCurThread)
{
CONTRACTL
{
SO_INTOLERANT;
NOTHROW;
// If this exception is for the debugger, then we may trigger a GC.
// But we'll be called on _any_ exception, including ones in a GC-no-triggers region.
// Our current contract system doesn't let us specify such conditions on GC_TRIGGERS.
// So we disable it now, and if we find out the exception is meant for the debugger,
// we'll call ThisFunctionMayHaveTriggerAGC() to ping that we're really a GC_TRIGGERS.
DISABLED(GC_TRIGGERS); // Only GC triggers if we send an event,
PRECONDITION(!IsDbgHelperSpecialThread());
// If we're called from preemptive mode, than our caller has protected the stack.
// If we're in cooperative mode, then we need to protect the stack before toggling GC modes
// (by setting the filter-context)
MODE_ANY;
PRECONDITION(CheckPointer(pException));
PRECONDITION(CheckPointer(pContext));
PRECONDITION(CheckPointer(pCurThread));
}
CONTRACTL_END;
LOG((LF_CORDB, LL_EVERYTHING, "DispatchNativeException was called\n"));
LOG((LF_CORDB, LL_INFO10000, "Native exception at 0x%p, code=0x%8x, context=0x%p, er=0x%p\n",
pException->ExceptionAddress, dwCode, pContext, pException));
bool fDebuggers;
BOOL fDispatch;
DPOSS_ACTION result = DPOSS_DONT_CARE;
// We have a potentially ugly locking problem here. This notification is called on any exception,
// but we have no idea what our locking context is at the time. Thus we may hold locks smaller
// than the controller lock.
// The debugger logic really only cares about exceptions directly in managed code (eg, hardware exceptions)
// or in patch-skippers (since that's a copy of managed code running in a look-aside buffer).
// That should exclude all C++ exceptions, which are the common case if Runtime code throws an internal ex.
// So we ignore those to avoid the lock violation.
if (pException->ExceptionCode == EXCEPTION_MSVC)
{
LOG((LF_CORDB, LL_INFO1000, "Debugger skipping for C++ exception.\n"));
return FALSE;
}
// The debugger really only cares about exceptions in managed code. Any exception that occurs
// while the thread is redirected (such as EXCEPTION_HIJACK) is not of interest to the debugger.
// Allowing this would be problematic because when an exception occurs while the thread is
// redirected, we don't know which context (saved redirection context or filter context)
// we should be operating on (see code:GetManagedStoppedCtx).
if( ISREDIRECTEDTHREAD(pCurThread) )
{
LOG((LF_CORDB, LL_INFO1000, "Debugger ignoring exception 0x%x on redirected thread.\n", dwCode));
// We shouldn't be seeing debugging exceptions on a redirected thread. While a thread is
// redirected we only call a few internal things (see code:Thread.RedirectedHandledJITCase),
// and may call into the host. We can't call normal managed code or anything we'd want to debug.
_ASSERTE(dwCode != EXCEPTION_BREAKPOINT);
_ASSERTE(dwCode != EXCEPTION_SINGLE_STEP);
return FALSE;
}
// It's possible we're here without a debugger (since we have to call the
// patch skippers). The Debugger may detach anytime,
// so remember the attach state now.
#ifdef _DEBUG
bool fWasAttached = false;
#ifdef DEBUGGING_SUPPORTED
fWasAttached = (CORDebuggerAttached() != 0);
#endif //DEBUGGING_SUPPORTED
#endif //_DEBUG
{
// If we're in cooperative mode, it's unsafe to do a GC until we've put a filter context in place.
GCX_NOTRIGGER();
// If we know the debugger doesn't care about this exception, bail now.
// Usually this is just if there's a debugger attached.
// However, if a debugger detached but left outstanding controllers (like patch-skippers),
// we still may care.
// The only way a controller would get created outside of the helper thread is from
// a patch skipper, so we always handle breakpoints.
if (!CORDebuggerAttached() && (g_controllers == NULL) && (dwCode != EXCEPTION_BREAKPOINT))
{
return false;
}
FireEtwDebugExceptionProcessingStart();
// We should never be here if the debugger was never involved.
CONTEXT * pOldContext;
pOldContext = pCurThread->GetFilterContext();
// In most cases it is an error to nest, however in the patch-skipping logic we must
// copy an unknown amount of code into another buffer and it occasionally triggers
// an AV. This heuristic should filter that case out. See DDB 198093.
// Ensure we perform this exception nesting filtering even before the call to
// DebuggerController::DispatchExceptionHook, otherwise the nesting will continue when
// a contract check is triggered in DispatchExceptionHook and another BP exception is
// raised. See Dev11 66058.
if ((pOldContext != NULL) && pCurThread->AVInRuntimeImplOkay() &&
pException->ExceptionCode == STATUS_ACCESS_VIOLATION)
{
STRESS_LOG1(LF_CORDB, LL_INFO100, "DC::DNE Nested Access Violation at 0x%p is being ignored\n",
pException->ExceptionAddress);
return false;
}
// Otherwise it is an error to nest at all
_ASSERTE(pOldContext == NULL);
fDispatch = DebuggerController::DispatchExceptionHook(pCurThread,
pContext,
pException);
{
// Must be in cooperative mode to set the filter context. We know there are times we'll be in preemptive mode,
// (such as M2U handoff, or potentially patches in the middle of a stub, or various random exceptions)
// @todo - We need to worry about GC-protecting our stack. If we're in preemptive mode, the caller did it for us.
// If we're in cooperative, then we need to set the FilterContext *before* we toggle GC mode (since
// the FC protects the stack).
// If we're in preemptive, then we need to set the FilterContext *after* we toggle ourselves to Cooperative.
// Also note it may not be possible to toggle GC mode at these times (such as in the middle of the stub).
//
// Part of the problem is that the Filter Context is serving 2 purposes here:
// - GC protect the stack. (essential if we're in coop mode).
// - provide info to controllers (such as current IP, and a place to set the Single-Step flag).
//
// This contract violation is mitigated in that we must have had the debugger involved to get to this point.
CONTRACT_VIOLATION(ModeViolation);
g_pEEInterface->SetThreadFilterContext(pCurThread, pContext);
}
// Now that we've set the filter context, we can let the GCX_NOTRIGGER expire.
// It's still possible that we may be called from a No-trigger region.
}
if (fDispatch)
{
// Disable SingleStep for all controllers on this thread. This requires the filter context set.
// This is what would disable the ss-flag when single-stepping over an AV.
if (g_patchTableValid && (dwCode != EXCEPTION_SINGLE_STEP))
{
LOG((LF_CORDB, LL_INFO1000, "DC::DNE non-single-step exception; check if any controller has ss turned on\n"));
ControllerLockHolder lockController;
for (DebuggerController* p = g_controllers; p != NULL; p = p->m_next)
{
if (p->m_singleStep && (p->m_thread == pCurThread))
{
LOG((LF_CORDB, LL_INFO1000, "DC::DNE turn off ss for controller 0x%p\n", p));
p->DisableSingleStep();
}
}
// implicit controller lock release
}
CORDB_ADDRESS_TYPE * ip = dac_cast<PTR_CORDB_ADDRESS_TYPE>(GetIP(pContext));
switch (dwCode)
{
case EXCEPTION_BREAKPOINT:
// EIP should be properly set up at this point.
result = DebuggerController::DispatchPatchOrSingleStep(pCurThread,
pContext,
ip,
ST_PATCH);
LOG((LF_CORDB, LL_EVERYTHING, "DC::DNE DispatchPatch call returned\n"));
// If we detached, we should remove all our breakpoints. So if we try
// to handle this breakpoint, make sure that we're attached.
if (IsInUsedAction(result) == true)
{
_ASSERTE(fWasAttached);
}
break;
case EXCEPTION_SINGLE_STEP:
LOG((LF_CORDB, LL_EVERYTHING, "DC::DNE SINGLE_STEP Exception\n"));
result = DebuggerController::DispatchPatchOrSingleStep(pCurThread,
pContext,
ip,
(SCAN_TRIGGER)(ST_PATCH|ST_SINGLE_STEP));
// We pass patch | single step since single steps actually
// do both (eg, you SS onto a breakpoint).
break;
default:
break;
} // end switch
}
#ifdef _DEBUG
else
{
LOG((LF_CORDB, LL_INFO1000, "DC:: DNE step-around fDispatch:0x%x!\n", fDispatch));
}
#endif //_DEBUG
fDebuggers = (fDispatch?(IsInUsedAction(result)?true:false):true);
LOG((LF_CORDB, LL_INFO10000, "DC::DNE, returning 0x%x.\n", fDebuggers));
#ifdef _DEBUG
if (fDebuggers && (result == DPOSS_USED_WITH_EVENT))
{
// If the exception belongs to the debugger, then we may have sent an event,
// and thus we may have triggered a GC.
ThisFunctionMayHaveTriggerAGC();
}
#endif
// Must restore the filter context. After the filter context is gone, we're
// unprotected again and unsafe for a GC.
{
CONTRACT_VIOLATION(ModeViolation);
g_pEEInterface->SetThreadFilterContext(pCurThread, NULL);
}
#ifdef _TARGET_ARM_
if (pCurThread->IsSingleStepEnabled())
pCurThread->ApplySingleStep(pContext);
#endif
FireEtwDebugExceptionProcessingEnd();
return fDebuggers;
}
// * -------------------------------------------------------------------------
// * DebuggerPatchSkip routines
// * -------------------------------------------------------------------------
DebuggerPatchSkip::DebuggerPatchSkip(Thread *thread,
DebuggerControllerPatch *patch,
AppDomain *pAppDomain)
: DebuggerController(thread, pAppDomain),
m_address(patch->address)
{
LOG((LF_CORDB, LL_INFO10000,
"DPS::DPS: Patch skip 0x%p\n", patch->address));
// On ARM the single-step emulation already utilizes a per-thread execution buffer similar to the scheme
// below. As a result we can skip most of the instruction parsing logic that's instead internalized into
// the single-step emulation itself.
#ifndef _TARGET_ARM_
// NOTE: in order to correctly single-step RIP-relative writes on multiple threads we need to set up
// a shared buffer with the instruction and a buffer for the RIP-relative value so that all threads
// are working on the same copy. as the single-steps complete the modified data in the buffer is
// copied back to the real address to ensure proper execution of the program.
//
// Create the shared instruction block. this will also create the shared RIP-relative buffer
//
m_pSharedPatchBypassBuffer = patch->GetOrCreateSharedPatchBypassBuffer();
BYTE* patchBypass = m_pSharedPatchBypassBuffer->PatchBypass;
// Copy the instruction block over to the patch skip
// WARNING: there used to be an issue here because CopyInstructionBlock copied the breakpoint from the
// jitted code stream into the patch buffer. Further below CORDbgSetInstruction would correct the
// first instruction. This buffer is shared by all threads so if another thread executed the buffer
// between this thread's execution of CopyInstructionBlock and CORDbgSetInstruction the wrong
// code would be executed. The bug has been fixed by changing CopyInstructionBlock to only copy
// the code bytes after the breakpoint.
// You might be tempted to stop copying the code at all, however that wouldn't work well with rejit.
// If we skip a breakpoint that is sitting at the beginning of a method, then the profiler rejits that
// method causing a jump-stamp to be placed, then we skip the breakpoint again, we need to make sure
// the 2nd skip executes the new jump-stamp code and not the original method prologue code. Copying
// the code every time ensures that we have the most up-to-date version of the code in the buffer.
_ASSERTE( patch->IsBound() );
CopyInstructionBlock(patchBypass, (const BYTE *)patch->address);
// Technically, we could create a patch skipper for an inactive patch, but we rely on the opcode being
// set here.
_ASSERTE( patch->IsActivated() );
CORDbgSetInstruction((CORDB_ADDRESS_TYPE *)patchBypass, patch->opcode);
LOG((LF_CORDB, LL_EVERYTHING, "SetInstruction was called\n"));
//
// Look at instruction to get some attributes
//
NativeWalker::DecodeInstructionForPatchSkip(patchBypass, &(m_instrAttrib));
#if defined(_TARGET_AMD64_)
// The code below handles RIP-relative addressing on AMD64. the original implementation made the assumption that
// we are only using RIP-relative addressing to access read-only data (see VSW 246145 for more information). this
// has since been expanded to handle RIP-relative writes as well.
if (m_instrAttrib.m_dwOffsetToDisp != 0)
{
_ASSERTE(m_instrAttrib.m_cbInstr != 0);
//
// Populate the RIP-relative buffer with the current value if needed
//
BYTE* bufferBypass = m_pSharedPatchBypassBuffer->BypassBuffer;
// Overwrite the *signed* displacement.
int dwOldDisp = *(int*)(&patchBypass[m_instrAttrib.m_dwOffsetToDisp]);
int dwNewDisp = offsetof(SharedPatchBypassBuffer, BypassBuffer) -
(offsetof(SharedPatchBypassBuffer, PatchBypass) + m_instrAttrib.m_cbInstr);
*(int*)(&patchBypass[m_instrAttrib.m_dwOffsetToDisp]) = dwNewDisp;
// This could be an LEA, which we'll just have to change into a MOV
// and copy the original address
if (((patchBypass[0] == 0x4C) || (patchBypass[0] == 0x48)) && (patchBypass[1] == 0x8d))
{
patchBypass[1] = 0x8b; // MOV reg, mem
_ASSERTE((int)sizeof(void*) <= SharedPatchBypassBuffer::cbBufferBypass);
*(void**)bufferBypass = (void*)(patch->address + m_instrAttrib.m_cbInstr + dwOldDisp);
}
else
{
// Copy the data into our buffer.
memcpy(bufferBypass, patch->address + m_instrAttrib.m_cbInstr + dwOldDisp, SharedPatchBypassBuffer::cbBufferBypass);
if (m_instrAttrib.m_fIsWrite)
{
// save the actual destination address and size so when we TriggerSingleStep() we can update the value
m_pSharedPatchBypassBuffer->RipTargetFixup = (UINT_PTR)(patch->address + m_instrAttrib.m_cbInstr + dwOldDisp);
m_pSharedPatchBypassBuffer->RipTargetFixupSize = m_instrAttrib.m_cOperandSize;
}
}
}
#endif // _TARGET_AMD64_
#endif // !_TARGET_ARM_
// Signals our thread that the debugger will be manipulating the context
// during the patch skip operation. This effectively prevents other threads
// from suspending us until we have completed skiping the patch and restored
// a good context (See DDB 188816)
thread->BeginDebuggerPatchSkip(this);
//
// Set IP of context to point to patch bypass buffer
//
T_CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
CONTEXT c;
if (context == NULL)
{
// We can't play with our own context!
#if _DEBUG
if (g_pEEInterface->GetThread())
{
// current thread is mamaged thread
_ASSERTE(Debugger::GetThreadIdHelper(thread) != Debugger::GetThreadIdHelper(g_pEEInterface->GetThread()));
}
#endif // _DEBUG
c.ContextFlags = CONTEXT_CONTROL;
thread->GetThreadContext(&c);
context =(T_CONTEXT *) &c;
ARM_ONLY(_ASSERTE(!"We should always have a filter context in DebuggerPatchSkip."));
}
#ifdef _TARGET_ARM_
// Since we emulate all single-stepping on ARM using an instruction buffer and a breakpoint all we have to
// do here is initiate a normal single-step except that we pass the instruction to be stepped explicitly
// (calling EnableSingleStep() would infer this by looking at the PC in the context, which would pick up
// the patch we're trying to skip).
//
// Ideally we'd refactor the EnableSingleStep to support this alternative calling sequence but since this
// involves three levels of methods and is only applicable to ARM we've chosen to replicate the relevant
// implementation here instead.
{
ControllerLockHolder lockController;
g_pEEInterface->MarkThreadForDebugStepping(thread, true);
WORD opcode2 = 0;
if (Is32BitInstruction(patch->opcode))
{
opcode2 = CORDbgGetInstruction((CORDB_ADDRESS_TYPE *)(((DWORD)patch->address) + 2));
}
thread->BypassWithSingleStep((DWORD)patch->address, patch->opcode, opcode2);
m_singleStep = true;
}
#else // _TARGET_ARM_
#ifdef _TARGET_ARM64_
patchBypass = NativeWalker::SetupOrSimulateInstructionForPatchSkip(context, m_pSharedPatchBypassBuffer, (const BYTE *)patch->address, patch->opcode);
#endif //_TARGET_ARM64_
//set eip to point to buffer...
SetIP(context, (PCODE)patchBypass);
if (context ==(T_CONTEXT*) &c)
thread->SetThreadContext(&c);
LOG((LF_CORDB, LL_INFO10000, "DPS::DPS Bypass at 0x%p for opcode %p \n", patchBypass, patch->opcode));
//
// Turn on single step (if the platform supports it) so we can
// fix up state after the instruction is executed.
// Also turn on exception hook so we can adjust IP in exceptions
//
EnableSingleStep();
#endif // _TARGET_ARM_
EnableExceptionHook();
}
DebuggerPatchSkip::~DebuggerPatchSkip()
{
#ifndef _TARGET_ARM_
_ASSERTE(m_pSharedPatchBypassBuffer);
m_pSharedPatchBypassBuffer->Release();
#endif
}
void DebuggerPatchSkip::DebuggerDetachClean()
{
// Since for ARM SharedPatchBypassBuffer isn't existed, we don't have to anything here.
#ifndef _TARGET_ARM_
// Fix for Bug 1176448
// When a debugger is detaching from the debuggee, we need to move the IP if it is pointing
// somewhere in PatchBypassBuffer.All managed threads are suspended during detach, so changing
// the context without notifications is safe.
// Notice:
// THIS FIX IS INCOMPLETE!It attempts to update the IP in the cases we can easily detect.However,
// if a thread is in pre - emptive mode, and its filter context has been propagated to a VEH
// context, then the filter context we get will be NULL and this fix will not work.Our belief is
// that this scenario is rare enough that it doesnt justify the cost and risk associated with a
// complete fix, in which we would have to either :
// 1. Change the reference counting for DebuggerController and then change the exception handling
// logic in the debuggee so that we can handle the debugger event after detach.
// 2. Create a "stack walking" implementation for native code and use it to get the current IP and
// set the IP to the right place.
Thread *thread = GetThread();
if (thread != NULL)
{
BYTE *patchBypass = m_pSharedPatchBypassBuffer->PatchBypass;
CONTEXT *context = thread->GetFilterContext();
if (patchBypass != NULL &&
context != NULL &&
(size_t)GetIP(context) >= (size_t)patchBypass &&
(size_t)GetIP(context) <= (size_t)(patchBypass + MAX_INSTRUCTION_LENGTH + 1))
{
SetIP(context, (PCODE)((BYTE *)GetIP(context) - (patchBypass - (BYTE *)m_address)));
}
}
#endif
}
//
// We have to have a whole seperate function for this because you
// can't use __try in a function that requires object unwinding...
//
LONG FilterAccessViolation2(LPEXCEPTION_POINTERS ep, PVOID pv)
{
LIMITED_METHOD_CONTRACT;
return (ep->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;
}
// This helper is required because the AVInRuntimeImplOkayHolder can not
// be directly placed inside the scope of a PAL_TRY
void _CopyInstructionBlockHelper(BYTE* to, const BYTE* from)
{
AVInRuntimeImplOkayHolder AVOkay;
// This function only copies the portion of the instruction that follows the
// breakpoint opcode, not the breakpoint itself
to += CORDbg_BREAK_INSTRUCTION_SIZE;
from += CORDbg_BREAK_INSTRUCTION_SIZE;
// If an AV occurs because we walked off a valid page then we need
// to be certain that all bytes on the previous page were copied.
// We are certain that we copied enough bytes to contain the instruction
// because it must have fit within the valid page.
for (int i = 0; i < MAX_INSTRUCTION_LENGTH - CORDbg_BREAK_INSTRUCTION_SIZE; i++)
{
*to++ = *from++;
}
}
// WARNING: this function skips copying the first CORDbg_BREAK_INSTRUCTION_SIZE bytes by design
// See the comment at the callsite in DebuggerPatchSkip::DebuggerPatchSkip for more details on
// this
void DebuggerPatchSkip::CopyInstructionBlock(BYTE *to, const BYTE* from)
{
// We wrap the memcpy in an exception handler to handle the
// extremely rare case where we're copying an instruction off the
// end of a method that is also at the end of a page, and the next
// page is unmapped.
struct Param
{
BYTE *to;
const BYTE* from;
} param;
param.to = to;
param.from = from;
PAL_TRY(Param *, pParam, ¶m)
{
_CopyInstructionBlockHelper(pParam->to, pParam->from);
}
PAL_EXCEPT_FILTER(FilterAccessViolation2)
{
// The whole point is that if we copy up the the AV, then
// that's enough to execute, otherwise we would not have been
// able to execute the code anyway. So we just ignore the
// exception.
LOG((LF_CORDB, LL_INFO10000,
"DPS::DPS: AV copying instruction block ignored.\n"));
}
PAL_ENDTRY
// We just created a new buffer of code, but the CPU caches code and may
// not be aware of our changes. This should force the CPU to dump any cached
// instructions it has in this region and load the new ones from memory
FlushInstructionCache(GetCurrentProcess(), to + CORDbg_BREAK_INSTRUCTION_SIZE,
MAX_INSTRUCTION_LENGTH - CORDbg_BREAK_INSTRUCTION_SIZE);
}
TP_RESULT DebuggerPatchSkip::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
ARM_ONLY(_ASSERTE(!"Should not have called DebuggerPatchSkip::TriggerPatch."));
LOG((LF_CORDB, LL_EVERYTHING, "DPS::TP called\n"));
#if defined(_DEBUG) && !defined(_TARGET_ARM_)
CONTEXT *context = GetManagedLiveCtx(thread);
LOG((LF_CORDB, LL_INFO1000, "DPS::TP: We've patched 0x%x (byPass:0x%x) "
"for a skip after an EnC update!\n", GetIP(context),
GetBypassAddress()));
_ASSERTE(g_patches != NULL);
// We shouldn't have mucked with EIP, yet.
_ASSERTE(dac_cast<PTR_CORDB_ADDRESS_TYPE>(GetIP(context)) == GetBypassAddress());
//We should be the _only_ patch here
MethodDesc *md2 = dac_cast<PTR_MethodDesc>(GetIP(context));
DebuggerControllerPatch *patchCheck = g_patches->GetPatch(g_pEEInterface->MethodDescGetModule(md2),md2->GetMemberDef());
_ASSERTE(patchCheck == patch);
_ASSERTE(patchCheck->controller == patch->controller);
patchCheck = g_patches->GetNextPatch(patchCheck);
_ASSERTE(patchCheck == NULL);
#endif // _DEBUG
DisableAll();
EnableExceptionHook();
EnableSingleStep(); //gets us back to where we want.
return TPR_IGNORE; // don't actually want to stop here....
}
TP_RESULT DebuggerPatchSkip::TriggerExceptionHook(Thread *thread, CONTEXT * context,
EXCEPTION_RECORD *exception)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
GC_NOTRIGGER;
// Patch skippers only operate on patches set in managed code. But the infrastructure may have
// toggled the GC mode underneath us.
MODE_ANY;
PRECONDITION(GetThread() == thread);
PRECONDITION(thread != NULL);
PRECONDITION(CheckPointer(context));
}
CONTRACTL_END;
if (m_pAppDomain != NULL)
{
AppDomain *pAppDomainCur = thread->GetDomain();
if (pAppDomainCur != m_pAppDomain)
{
LOG((LF_CORDB,LL_INFO10000, "DPS::TEH: Appdomain mismatch - not skiiping!\n"));
return TPR_IGNORE;
}
}
LOG((LF_CORDB,LL_INFO10000, "DPS::TEH: doing the patch-skip thing\n"));
#if defined(_TARGET_ARM64_)
if (!IsSingleStep(exception->ExceptionCode))
{
LOG((LF_CORDB, LL_INFO10000, "Exception in patched Bypass instruction .\n"));
return (TPR_IGNORE_AND_STOP);
}
_ASSERTE(m_pSharedPatchBypassBuffer);
BYTE* patchBypass = m_pSharedPatchBypassBuffer->PatchBypass;
PCODE targetIp;
if (m_pSharedPatchBypassBuffer->RipTargetFixup)
{
targetIp = m_pSharedPatchBypassBuffer->RipTargetFixup;
}
else
{
targetIp = (PCODE)((BYTE *)GetIP(context) - (patchBypass - (BYTE *)m_address));
}
SetIP(context, targetIp);
LOG((LF_CORDB, LL_ALWAYS, "Redirecting after Patch to 0x%p\n", GetIP(context)));
#elif defined (_TARGET_ARM_)
//Do nothing
#else
_ASSERTE(m_pSharedPatchBypassBuffer);
BYTE* patchBypass = m_pSharedPatchBypassBuffer->PatchBypass;
if (m_instrAttrib.m_fIsCall && IsSingleStep(exception->ExceptionCode))
{
// Fixup return address on stack
#if defined(_TARGET_X86_) || defined(_TARGET_AMD64_)
SIZE_T *sp = (SIZE_T *) GetSP(context);
LOG((LF_CORDB, LL_INFO10000,
"Bypass call return address redirected from 0x%p\n", *sp));
*sp -= patchBypass - (BYTE*)m_address;
LOG((LF_CORDB, LL_INFO10000, "to 0x%p\n", *sp));
#else
PORTABILITY_ASSERT("DebuggerPatchSkip::TriggerExceptionHook -- return address fixup NYI");
#endif
}
if (!m_instrAttrib.m_fIsAbsBranch || !IsSingleStep(exception->ExceptionCode))
{
// Fixup IP
LOG((LF_CORDB, LL_INFO10000, "Bypass instruction redirected from 0x%p\n", GetIP(context)));
if (IsSingleStep(exception->ExceptionCode))
{
#ifndef FEATURE_PAL
// Check if the current IP is anywhere near the exception dispatcher logic.
// If it is, ignore the exception, as the real exception is coming next.
static FARPROC pExcepDispProc = NULL;
if (!pExcepDispProc)
{
HMODULE hNtDll = WszGetModuleHandle(W("ntdll.dll"));
if (hNtDll != NULL)
{
pExcepDispProc = GetProcAddress(hNtDll, "KiUserExceptionDispatcher");
if (!pExcepDispProc)
pExcepDispProc = (FARPROC)(size_t)(-1);
}
else
pExcepDispProc = (FARPROC)(size_t)(-1);
}
_ASSERTE(pExcepDispProc != NULL);
if ((size_t)pExcepDispProc != (size_t)(-1))
{
LPVOID pExcepDispEntryPoint = pExcepDispProc;
if ((size_t)GetIP(context) > (size_t)pExcepDispEntryPoint &&
(size_t)GetIP(context) <= ((size_t)pExcepDispEntryPoint + MAX_INSTRUCTION_LENGTH * 2 + 1))
{
LOG((LF_CORDB, LL_INFO10000,
"Bypass instruction not redirected. Landed in exception dispatcher.\n"));
return (TPR_IGNORE_AND_STOP);
}
}
#endif // FEATURE_PAL
// If the IP is close to the skip patch start, or if we were skipping over a call, then assume the IP needs
// adjusting.
if (m_instrAttrib.m_fIsCall ||
((size_t)GetIP(context) > (size_t)patchBypass &&
(size_t)GetIP(context) <= (size_t)(patchBypass + MAX_INSTRUCTION_LENGTH + 1)))
{
LOG((LF_CORDB, LL_INFO10000, "Bypass instruction redirected because still in skip area.\n"));
LOG((LF_CORDB, LL_INFO10000, "m_fIsCall = %d, patchBypass = 0x%x, m_address = 0x%x\n",
m_instrAttrib.m_fIsCall, patchBypass, m_address));
SetIP(context, (PCODE)((BYTE *)GetIP(context) - (patchBypass - (BYTE *)m_address)));
}
else
{
// Otherwise, need to see if the IP is something we recognize (either managed code
// or stub code) - if not, we ignore the exception
PCODE newIP = GetIP(context);
newIP -= PCODE(patchBypass - (BYTE *)m_address);
TraceDestination trace;
if (g_pEEInterface->IsManagedNativeCode(dac_cast<PTR_CBYTE>(newIP)) ||
(g_pEEInterface->TraceStub(LPBYTE(newIP), &trace)))
{
LOG((LF_CORDB, LL_INFO10000, "Bypass instruction redirected because we landed in managed or stub code\n"));
SetIP(context, newIP);
}
// If we have no idea where things have gone, then we assume that the IP needs no adjusting (which
// could happen if the instruction we were trying to patch skip caused an AV). In this case we want
// to claim it as ours but ignore it and continue execution.
else
{
LOG((LF_CORDB, LL_INFO10000, "Bypass instruction not redirected because we're not in managed or stub code.\n"));
return (TPR_IGNORE_AND_STOP);
}
}
}
else
{
LOG((LF_CORDB, LL_INFO10000, "Bypass instruction redirected because it wasn't a single step exception.\n"));
SetIP(context, (PCODE)((BYTE *)GetIP(context) - (patchBypass - (BYTE *)m_address)));
}
LOG((LF_CORDB, LL_ALWAYS, "to 0x%x\n", GetIP(context)));
}
#endif
// Signals our thread that the debugger is done manipulating the context
// during the patch skip operation. This effectively prevented other threads
// from suspending us until we completed skiping the patch and restored
// a good context (See DDB 188816)
m_thread->EndDebuggerPatchSkip();
// Don't delete the controller yet if this is a single step exception, as the code will still want to dispatch to
// our single step method, and if it doesn't find something to dispatch to we won't continue from the exception.
//
// (This is kind of broken behavior but is easily worked around here
// by this test)
if (!IsSingleStep(exception->ExceptionCode))
{
Delete();
}
DisableExceptionHook();
return TPR_TRIGGER;
}
bool DebuggerPatchSkip::TriggerSingleStep(Thread *thread, const BYTE *ip)
{
LOG((LF_CORDB,LL_INFO10000, "DPS::TSS: basically a no-op\n"));
if (m_pAppDomain != NULL)
{
AppDomain *pAppDomainCur = thread->GetDomain();
if (pAppDomainCur != m_pAppDomain)
{
LOG((LF_CORDB,LL_INFO10000, "DPS::TSS: Appdomain mismatch - "
"not SingSteping!!\n"));
return false;
}
}
#if defined(_TARGET_AMD64_)
// Dev11 91932: for RIP-relative writes we need to copy the value that was written in our buffer to the actual address
_ASSERTE(m_pSharedPatchBypassBuffer);
if (m_pSharedPatchBypassBuffer->RipTargetFixup)
{
_ASSERTE(m_pSharedPatchBypassBuffer->RipTargetFixupSize);
BYTE* bufferBypass = m_pSharedPatchBypassBuffer->BypassBuffer;
BYTE fixupSize = m_pSharedPatchBypassBuffer->RipTargetFixupSize;
UINT_PTR targetFixup = m_pSharedPatchBypassBuffer->RipTargetFixup;
switch (fixupSize)
{
case 1:
*(reinterpret_cast<BYTE*>(targetFixup)) = *(reinterpret_cast<BYTE*>(bufferBypass));
break;
case 2:
*(reinterpret_cast<WORD*>(targetFixup)) = *(reinterpret_cast<WORD*>(bufferBypass));
break;
case 4:
*(reinterpret_cast<DWORD*>(targetFixup)) = *(reinterpret_cast<DWORD*>(bufferBypass));
break;
case 8:
*(reinterpret_cast<ULONGLONG*>(targetFixup)) = *(reinterpret_cast<ULONGLONG*>(bufferBypass));
break;
case 16:
memcpy(reinterpret_cast<void*>(targetFixup), bufferBypass, 16);
break;
default:
_ASSERTE(!"bad operand size");
}
}
#endif
LOG((LF_CORDB,LL_INFO10000, "DPS::TSS: triggered, about to delete\n"));
TRACE_FREE(this);
Delete();
return false;
}
// * -------------------------------------------------------------------------
// * DebuggerBreakpoint routines
// * -------------------------------------------------------------------------
// DebuggerBreakpoint::DebuggerBreakpoint() The constructor
// invokes AddBindAndActivatePatch to set the breakpoint
DebuggerBreakpoint::DebuggerBreakpoint(Module *module,
mdMethodDef md,
AppDomain *pAppDomain,
SIZE_T offset,
bool native,
SIZE_T ilEnCVersion, // must give the EnC version for non-native bps
MethodDesc *nativeMethodDesc, // use only when m_native
DebuggerJitInfo *nativeJITInfo, // optional when m_native, null otherwise
BOOL *pSucceed
)
: DebuggerController(NULL, pAppDomain)
{
_ASSERTE(pSucceed != NULL);
_ASSERTE(native == (nativeMethodDesc != NULL));
_ASSERTE(native || nativeJITInfo == NULL);
_ASSERTE(!nativeJITInfo || nativeJITInfo->m_jitComplete); // this is sent by the left-side, and it couldn't have got the code if the JIT wasn't complete
if (native)
{
(*pSucceed) = AddBindAndActivateNativeManagedPatch(nativeMethodDesc, nativeJITInfo, offset, LEAF_MOST_FRAME, pAppDomain);
return;
}
else
{
(*pSucceed) = AddILPatch(pAppDomain, module, md, ilEnCVersion, offset);
}
}
// TP_RESULT DebuggerBreakpoint::TriggerPatch()
// What: This patch will always be activated.
// How: return true.
TP_RESULT DebuggerBreakpoint::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
LOG((LF_CORDB, LL_INFO10000, "DB::TP\n"));
return TPR_TRIGGER;
}
// void DebuggerBreakpoint::SendEvent() What: Inform
// the right side that the breakpoint was reached.
// How: g_pDebugger->SendBreakpoint()
bool DebuggerBreakpoint::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO10000, "DB::SE: in DebuggerBreakpoint's SendEvent\n"));
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
// If we got interupted by SetIp, we just don't send the IPC event. Our triggers are still
// active so no harm done.
if (!fIpChanged)
{
g_pDebugger->SendBreakpoint(thread, context, this);
return true;
}
// Controller is still alive, will fire if we hit the breakpoint again.
return false;
}
//* -------------------------------------------------------------------------
// * DebuggerStepper routines
// * -------------------------------------------------------------------------
DebuggerStepper::DebuggerStepper(Thread *thread,
CorDebugUnmappedStop rgfMappingStop,
CorDebugIntercept interceptStop,
AppDomain *appDomain)
: DebuggerController(thread, appDomain),
m_stepIn(false),
m_reason(STEP_NORMAL),
m_fpStepInto(LEAF_MOST_FRAME),
m_rgfInterceptStop(interceptStop),
m_rgfMappingStop(rgfMappingStop),
m_range(NULL),
m_rangeCount(0),
m_realRangeCount(0),
m_fp(LEAF_MOST_FRAME),
#if defined(WIN64EXCEPTIONS)
m_fpParentMethod(LEAF_MOST_FRAME),
#endif // WIN64EXCEPTIONS
m_fpException(LEAF_MOST_FRAME),
m_fdException(0),
m_cFuncEvalNesting(0)
{
#ifdef _DEBUG
m_fReadyToSend = false;
#endif
}
DebuggerStepper::~DebuggerStepper()
{
if (m_range != NULL)
{
TRACE_FREE(m_range);
DeleteInteropSafe(m_range);
}
}
// bool DebuggerStepper::ShouldContinueStep() Return true if
// the stepper should not stop at this address. The stepper should not
// stop here if: here is in the {prolog,epilog,etc};
// and the stepper is not interested in stopping here.
// We assume that this is being called in the frame which the stepper steps
// through. Unless, of course, we're returning from a call, in which
// case we want to stop in the epilog even if the user didn't say so,
// to prevent stepping out of multiple frames at once.
// <REVISIT_TODO>Possible optimization: GetJitInfo, then AddPatch @ end of prolog?</REVISIT_TODO>
bool DebuggerStepper::ShouldContinueStep( ControllerStackInfo *info,
SIZE_T nativeOffset)
{
LOG((LF_CORDB,LL_INFO10000, "DeSt::ShContSt: nativeOffset:0x%p \n", nativeOffset));
if (m_rgfMappingStop != STOP_ALL && (m_reason != STEP_EXIT) )
{
DebuggerJitInfo *ji = info->m_activeFrame.GetJitInfoFromFrame();
if ( ji != NULL )
{
LOG((LF_CORDB,LL_INFO10000,"DeSt::ShContSt: For code 0x%p, got "
"DJI 0x%p, from 0x%p to 0x%p\n",
(const BYTE*)GetControlPC(&(info->m_activeFrame.registers)),
ji, ji->m_addrOfCode, ji->m_addrOfCode+ji->m_sizeOfCode));
}
else
{
LOG((LF_CORDB,LL_INFO10000,"DeSt::ShCoSt: For code 0x%p, didn't "
"get DJI\n",(const BYTE*)GetControlPC(&(info->m_activeFrame.registers))));
return false; // Haven't a clue if we should continue, so
// don't
}
CorDebugMappingResult map = MAPPING_UNMAPPED_ADDRESS;
DWORD whichIDontCare;
ji->MapNativeOffsetToIL( nativeOffset, &map, &whichIDontCare);
unsigned int interestingMappings =
(map & ~(MAPPING_APPROXIMATE | MAPPING_EXACT));
LOG((LF_CORDB,LL_INFO10000,
"DeSt::ShContSt: interestingMappings:0x%x m_rgfMappingStop:%x\n",
interestingMappings,m_rgfMappingStop));
// If we're in a prolog,epilog, then we may want to skip
// over it or stop
if ( interestingMappings )
{
if ( interestingMappings & m_rgfMappingStop )
return false;
else
return true;
}
}
return false;
}
bool DebuggerStepper::IsRangeAppropriate(ControllerStackInfo *info)
{
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: info:0x%x \n", info));
if (m_range == NULL)
{
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: m_range == NULL, returning FALSE\n"));
return false;
}
FrameInfo *realFrame;
#if defined(WIN64EXCEPTIONS)
bool fActiveFrameIsFunclet = info->m_activeFrame.IsNonFilterFuncletFrame();
if (fActiveFrameIsFunclet)
{
realFrame = &(info->m_returnFrame);
}
else
#endif // WIN64EXCEPTIONS
{
realFrame = &(info->m_activeFrame);
}
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: info->m_activeFrame.fp:0x%x m_fp:0x%x\n", info->m_activeFrame.fp, m_fp));
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: m_fdException:0x%x realFrame->md:0x%x realFrame->fp:0x%x m_fpException:0x%x\n",
m_fdException, realFrame->md, realFrame->fp, m_fpException));
if ( (info->m_activeFrame.fp == m_fp) ||
( (m_fdException != NULL) && (realFrame->md == m_fdException) &&
IsEqualOrCloserToRoot(realFrame->fp, m_fpException) ) )
{
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: returning TRUE\n"));
return true;
}
#if defined(WIN64EXCEPTIONS)
// There are two scenarios which make this function more complicated on WIN64.
// 1) We initiate a step in the parent method or a funclet but end up stepping into another funclet closer to the leaf.
// a) start in the parent method
// b) start in a funclet
// 2) We initiate a step in a funclet but end up stepping out to the parent method or a funclet closer to the root.
// a) end up in the parent method
// b) end up in a funclet
// In both cases the range of the stepper should still be appropriate.
bool fValidParentMethodFP = (m_fpParentMethod != LEAF_MOST_FRAME);
if (fActiveFrameIsFunclet)
{
// Scenario 1a
if (m_fp == info->m_returnFrame.fp)
{
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: returning TRUE\n"));
return true;
}
// Scenario 1b & 2b have the same condition
else if (fValidParentMethodFP && (m_fpParentMethod == info->m_returnFrame.fp))
{
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: returning TRUE\n"));
return true;
}
}
else
{
// Scenario 2a
if (fValidParentMethodFP && (m_fpParentMethod == info->m_activeFrame.fp))
{
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: returning TRUE\n"));
return true;
}
}
#endif // WIN64EXCEPTIONS
LOG((LF_CORDB,LL_INFO10000, "DS::IRA: returning FALSE\n"));
return false;
}
// bool DebuggerStepper::IsInRange() Given the native offset ip,
// returns true if ip falls within any of the native offset ranges specified
// by the array of COR_DEBUG_STEP_RANGEs.
// Returns true if ip falls within any of the ranges. Returns false
// if ip doesn't, or if there are no ranges (rangeCount==0). Note that a
// COR_DEBUG_STEP_RANGE with an endOffset of zero is interpreted as extending
// from startOffset to the end of the method.
// SIZE_T ip: Native offset, relative to the beginning of the method.
// COR_DEBUG_STEP_RANGE *range: An array of ranges, which are themselves
// native offsets, to compare against ip.
// SIZE_T rangeCount: Number of elements in range
bool DebuggerStepper::IsInRange(SIZE_T ip, COR_DEBUG_STEP_RANGE *range, SIZE_T rangeCount,
ControllerStackInfo *pInfo)
{
LOG((LF_CORDB,LL_INFO10000,"DS::IIR: off=0x%x\n", ip));
if (range == NULL)
{
LOG((LF_CORDB,LL_INFO10000,"DS::IIR: range == NULL -> not in range\n"));
return false;
}
if (pInfo && !IsRangeAppropriate(pInfo))
{
LOG((LF_CORDB,LL_INFO10000,"DS::IIR: no pInfo or range not appropriate -> not in range\n"));
return false;
}
COR_DEBUG_STEP_RANGE *r = range;
COR_DEBUG_STEP_RANGE *rEnd = r + rangeCount;
while (r < rEnd)
{
SIZE_T endOffset = r->endOffset ? r->endOffset : ~0;
LOG((LF_CORDB,LL_INFO100000,"DS::IIR: so=0x%x, eo=0x%x\n",
r->startOffset, endOffset));
if (ip >= r->startOffset && ip < endOffset)
{
LOG((LF_CORDB,LL_INFO1000,"DS::IIR:this:0x%x Found native offset "
"0x%x to be in the range"
"[0x%x, 0x%x), index 0x%x\n\n", this, ip, r->startOffset,
endOffset, ((r-range)/sizeof(COR_DEBUG_STEP_RANGE *)) ));
return true;
}
r++;
}
LOG((LF_CORDB,LL_INFO10000,"DS::IIR: not in range\n"));
return false;
}
// bool DebuggerStepper::DetectHandleInterceptors() Return true if
// the current execution takes place within an interceptor (that is, either
// the current frame, or the parent frame is a framed frame whose
// GetInterception method returns something other than INTERCEPTION_NONE),
// and this stepper doesn't want to stop in an interceptor, and we successfully
// set a breakpoint after the top-most interceptor in the stack.
bool DebuggerStepper::DetectHandleInterceptors(ControllerStackInfo *info)
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI: Start DetectHandleInterceptors\n"));
LOG((LF_CORDB,LL_INFO10000,"DS::DHI: active frame=0x%08x, has return frame=%d, return frame=0x%08x m_reason:%d\n",
info->m_activeFrame.frame, info->HasReturnFrame(), info->m_returnFrame.frame, m_reason));
// If this is a normal step, then we want to continue stepping, even if we
// are in an interceptor.
if (m_reason == STEP_NORMAL || m_reason == STEP_RETURN || m_reason == STEP_EXCEPTION_HANDLER)
{
LOG((LF_CORDB,LL_INFO1000,"DS::DHI: Returning false while stepping within function, finally!\n"));
return false;
}
bool fAttemptStepOut = false;
if (m_rgfInterceptStop != INTERCEPT_ALL) // we may have to skip out of one
{
if (info->m_activeFrame.frame != NULL &&
info->m_activeFrame.frame != FRAME_TOP &&
info->m_activeFrame.frame->GetInterception() != Frame::INTERCEPTION_NONE)
{
if (!((CorDebugIntercept)info->m_activeFrame.frame->GetInterception() & Frame::Interception(m_rgfInterceptStop)))
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI: Stepping out b/c of excluded frame type:0x%x\n",
info->m_returnFrame. frame->GetInterception()));
fAttemptStepOut = true;
}
else
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI: 0x%x set to STEP_INTERCEPT\n", this));
m_reason = STEP_INTERCEPT; //remember why we've stopped
}
}
if ((m_reason == STEP_EXCEPTION_FILTER) ||
(info->HasReturnFrame() &&
info->m_returnFrame.frame != NULL &&
info->m_returnFrame.frame != FRAME_TOP &&
info->m_returnFrame.frame->GetInterception() != Frame::INTERCEPTION_NONE))
{
if (m_reason == STEP_EXCEPTION_FILTER)
{
// Exceptions raised inside of the EE by COMPlusThrow, FCThrow, etc will not
// insert an ExceptionFrame, and hence info->m_returnFrame.frame->GetInterception()
// will not be accurate. Hence we use m_reason instead
if (!(Frame::INTERCEPTION_EXCEPTION & Frame::Interception(m_rgfInterceptStop)))
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI: Stepping out b/c of excluded INTERCEPTION_EXCEPTION\n"));
fAttemptStepOut = true;
}
}
else if (!(info->m_returnFrame.frame->GetInterception() & Frame::Interception(m_rgfInterceptStop)))
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI: Stepping out b/c of excluded return frame type:0x%x\n",
info->m_returnFrame.frame->GetInterception()));
fAttemptStepOut = true;
}
if (!fAttemptStepOut)
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI 0x%x set to STEP_INTERCEPT\n", this));
m_reason = STEP_INTERCEPT; //remember why we've stopped
}
}
else if (info->m_specialChainReason != CHAIN_NONE)
{
if(!(info->m_specialChainReason & CorDebugChainReason(m_rgfInterceptStop)) )
{
LOG((LF_CORDB,LL_INFO10000, "DS::DHI: (special) Stepping out b/c of excluded return frame type:0x%x\n",
info->m_specialChainReason));
fAttemptStepOut = true;
}
else
{
LOG((LF_CORDB,LL_INFO10000,"DS::DHI 0x%x set to STEP_INTERCEPT\n", this));
m_reason = STEP_INTERCEPT; //remember why we've stopped
}
}
else if (info->m_activeFrame.frame == NULL)
{
// Make sure we are not dealing with a chain here.
if (info->m_activeFrame.HasMethodFrame())
{
// Check whether we are executing in a class constructor.
_ASSERTE(info->m_activeFrame.md != NULL);
if (info->m_activeFrame.md->IsClassConstructor())
{
// We are in a class constructor. Check whether we want to stop in it.
if (!(CHAIN_CLASS_INIT & CorDebugChainReason(m_rgfInterceptStop)))
{
LOG((LF_CORDB, LL_INFO10000, "DS::DHI: Stepping out b/c of excluded cctor:0x%x\n",
CHAIN_CLASS_INIT));
fAttemptStepOut = true;
}
else
{
LOG((LF_CORDB, LL_INFO10000,"DS::DHI 0x%x set to STEP_INTERCEPT\n", this));
m_reason = STEP_INTERCEPT; //remember why we've stopped
}
}
}
}
}
if (fAttemptStepOut)
{
LOG((LF_CORDB,LL_INFO1000,"DS::DHI: Doing TSO!\n"));
// TrapStepOut could alter the step reason if we're stepping out of an inteceptor and it looks like we're
// running off the top of the program. So hold onto it here, and if our step reason becomes STEP_EXIT, then
// reset it to what it was.
CorDebugStepReason holdReason = m_reason;
// @todo - should this be TrapStepNext??? But that may stop in a child...
TrapStepOut(info);
EnableUnwind(m_fp);
if (m_reason == STEP_EXIT)
{
m_reason = holdReason;
}
return true;
}
// We're not in a special area of code, so we don't want to continue unless some other part of the code decides that
// we should.
LOG((LF_CORDB,LL_INFO1000,"DS::DHI: Returning false, finally!\n"));
return false;
}
//---------------------------------------------------------------------------------------
//
// This function checks whether the given IP is in an LCG method. If so, it enables
// JMC and does a step out. This effectively makes sure that we never stop in an LCG method.
//
// There are two common scnearios here:
// 1) We single-step into an LCG method from a managed method.
// 2) We single-step off the end of a method called by an LCG method and end up in the calling LCG method.
//
// In both cases, we don't want to stop in the LCG method. If the LCG method directly or indirectly calls
// another user method, we want to stop there. Otherwise, we just want to step out back to the caller of
// LCG method. In other words, what we want is exactly the JMC behaviour.
//
// Arguments:
// ip - the current IP where the thread is stopped at
// pMD - This is the MethodDesc for the specified ip. This can be NULL, but if it's not,
// then it has to match the specified IP.
// pInfo - the ControllerStackInfo taken at the specified IP (see Notes below)
//
// Return Value:
// Returns TRUE if the specified IP is indeed in an LCG method, in which case this function has already
// enabled all the traps to catch the thread, including turning on JMC, enabling unwind callback, and
// putting a patch in the caller.
//
// Notes:
// LCG methods don't show up in stackwalks done by the ControllerStackInfo. So even if the specified IP
// is in an LCG method, the LCG method won't show up in the call strack. That's why we need to call
// ControllerStackInfo::SetReturnFrameWithActiveFrame() in this function before calling TrapStepOut().
// Otherwise TrapStepOut() will put a patch in the caller's caller (if there is one).
//
BOOL DebuggerStepper::DetectHandleLCGMethods(const PCODE ip, MethodDesc * pMD, ControllerStackInfo * pInfo)
{
// Look up the MethodDesc for the given IP.
if (pMD == NULL)
{
if (g_pEEInterface->IsManagedNativeCode((const BYTE *)ip))
{
pMD = g_pEEInterface->GetNativeCodeMethodDesc(ip);
_ASSERTE(pMD != NULL);
}
}
#if defined(_DEBUG)
else
{
// If a MethodDesc is specified, it has to match the given IP.
_ASSERTE(pMD == g_pEEInterface->GetNativeCodeMethodDesc(ip));
}
#endif // _DEBUG
// If the given IP is in unmanaged code, then we won't have a MethodDesc by this point.
if (pMD != NULL)
{
if (pMD->IsLCGMethod())
{
// Enable all the traps to catch the thread.
EnableUnwind(m_fp);
EnableJMCBackStop(pMD);
pInfo->SetReturnFrameWithActiveFrame();
TrapStepOut(pInfo);
return TRUE;
}
}
return FALSE;
}
// Steppers override these so that they can skip func-evals. Note that steppers can
// be created & used inside of func-evals (nested-break states).
// On enter, we check for freezing the stepper.
void DebuggerStepper::TriggerFuncEvalEnter(Thread * thread)
{
LOG((LF_CORDB, LL_INFO10000, "DS::TFEEnter, this=0x%p, old nest=%d\n", this, m_cFuncEvalNesting));
// Since this is always called on the hijacking thread, we should be thread-safe
_ASSERTE(thread == this->GetThread());
if (IsDead())
return;
m_cFuncEvalNesting++;
if (m_cFuncEvalNesting == 1)
{
// We're entering our 1st funceval, so freeze us.
LOG((LF_CORDB, LL_INFO100000, "DS::TFEEnter - freezing stepper\n"));
// Freeze the stepper by disabling all triggers
m_bvFrozenTriggers = 0;
//
// We dont explicitly disable single-stepping because the OS
// gives us a new thread context during an exception. Since
// all func-evals are done inside exceptions, we should never
// have this problem.
//
// Note: however, that if func-evals were no longer done in
// exceptions, this would have to change.
//
if (IsMethodEnterEnabled())
{
m_bvFrozenTriggers |= kMethodEnter;
DisableMethodEnter();
}
}
else
{
LOG((LF_CORDB, LL_INFO100000, "DS::TFEEnter - new nest=%d\n", m_cFuncEvalNesting));
}
}
// On Func-EvalExit, we check if the stepper is trying to step-out of a func-eval
// (in which case we kill it)
// or if we previously entered this func-eval and should thaw it now.
void DebuggerStepper::TriggerFuncEvalExit(Thread * thread)
{
LOG((LF_CORDB, LL_INFO10000, "DS::TFEExit, this=0x%p, old nest=%d\n", this, m_cFuncEvalNesting));
// Since this is always called on the hijacking thread, we should be thread-safe
_ASSERTE(thread == this->GetThread());
if (IsDead())
return;
m_cFuncEvalNesting--;
if (m_cFuncEvalNesting == -1)
{
LOG((LF_CORDB, LL_INFO100000, "DS::TFEExit - disabling stepper\n"));
// we're exiting the func-eval session we were created in. So we just completely
// disable ourselves so that we don't fire anything anymore.
// The RS still has to free the stepper though.
// This prevents us from stepping-out of a func-eval. For traditional steppers,
// this is overkill since it won't have any outstanding triggers. (trap-step-out
// won't patch if it crosses a func-eval frame).
// But JMC-steppers have Method-Enter; and so this is the only place we have to
// disable that.
DisableAll();
}
else if (m_cFuncEvalNesting == 0)
{
// We're back to our starting Func-eval session, we should have been frozen,
// so now we thaw.
LOG((LF_CORDB, LL_INFO100000, "DS::TFEExit - thawing stepper\n"));
// Thaw the stepper (reenable triggers)
if ((m_bvFrozenTriggers & kMethodEnter) != 0)
{
EnableMethodEnter();
}
m_bvFrozenTriggers = 0;
}
else
{
LOG((LF_CORDB, LL_INFO100000, "DS::TFEExit - new nest=%d\n", m_cFuncEvalNesting));
}
}
// Return true iff we set a patch (which implies to caller that we should
// let controller run free and hit that patch)
bool DebuggerStepper::TrapStepInto(ControllerStackInfo *info,
const BYTE *ip,
TraceDestination *pTD)
{
_ASSERTE( pTD != NULL );
_ASSERTE(this->GetDCType() == DEBUGGER_CONTROLLER_STEPPER);
EnableTraceCall(LEAF_MOST_FRAME);
if (IsCloserToRoot(info->m_activeFrame.fp, m_fpStepInto))
m_fpStepInto = info->m_activeFrame.fp;
LOG((LF_CORDB, LL_INFO1000, "Ds::TSI this:0x%x m_fpStepInto:0x%x\n",
this, m_fpStepInto.GetSPValue()));
TraceDestination trace;
// Trace through the stubs.
// If we're calling from managed code, this should either succeed
// or become an ecall into mscorwks.
// @Todo - what about stubs in mscorwks.
// @todo - if this fails, we want to provde as much info as possible.
if (!g_pEEInterface->TraceStub(ip, &trace)
|| !g_pEEInterface->FollowTrace(&trace))
{
return false;
}
(*pTD) = trace; //bitwise copy
// Step-in always operates at the leaf-most frame. Thus the frame pointer for any
// patch for step-in should be LEAF_MOST_FRAME, regardless of whatever our current fp
// is before the step-in.
// Note that step-in may skip 'internal' frames (FrameInfo w/ internal=true) since
// such frames may really just be a marker for an internal EE Frame on the stack.
// However, step-out uses these frames b/c it may call frame->TraceFrame() on them.
return PatchTrace(&trace,
LEAF_MOST_FRAME, // step-in is always leaf-most frame.
(m_rgfMappingStop&STOP_UNMANAGED)?(true):(false));
}
// Enable the JMC backstop for stepping on Step-In.
// This activate the JMC probes, which will provide a safety net
// to stop a stepper if the StubManagers don't predict the call properly.
// Ideally, this should never be necessary (because the SMs would do their job).
void DebuggerStepper::EnableJMCBackStop(MethodDesc * pStartMethod)
{
// JMC steppers should not need the JMC backstop unless a thread inadvertently stops in an LCG method.
//_ASSERTE(DEBUGGER_CONTROLLER_JMC_STEPPER != this->GetDCType());
// Since we should never hit the JMC backstop (since it's really a SM issue), we'll assert if we actually do.
// However, there's 1 corner case here. If we trace calls at the start of the method before the JMC-probe,
// then we'll still hit the JMC backstop in our own method.
// Record that starting method. That way, if we end up hitting our JMC backstop in our own method,
// we don't over aggressively fire the assert. (This won't work for recursive cases, but since this is just
// changing an assert, we don't care).
#ifdef _DEBUG
// May be NULL if we didn't start in a method.
m_StepInStartMethod = pStartMethod;
#endif
// We don't want traditional steppers to rely on MethodEnter (b/c it's not guaranteed to be correct),
// but it may be a useful last resort.
this->EnableMethodEnter();
}
// Return true if the stepper can run free.
bool DebuggerStepper::TrapStepInHelper(
ControllerStackInfo * pInfo,
const BYTE * ipCallTarget,
const BYTE * ipNext,
bool fCallingIntoFunclet)
{
TraceDestination td;
#ifdef _DEBUG
// Begin logging the step-in activity in debug builds.
StubManager::DbgBeginLog((TADDR) ipNext, (TADDR) ipCallTarget);
#endif
if (TrapStepInto(pInfo, ipCallTarget, &td))
{
// If we placed a patch, see if we need to update our step-reason
if (td.GetTraceType() == TRACE_MANAGED )
{
// Possible optimization: Roll all of g_pEEInterface calls into
// one function so we don't repeatedly get the CodeMan,etc
MethodDesc *md = NULL;
_ASSERTE( g_pEEInterface->IsManagedNativeCode((const BYTE *)td.GetAddress()) );
md = g_pEEInterface->GetNativeCodeMethodDesc(td.GetAddress());
DebuggerJitInfo* pDJI = g_pDebugger->GetJitInfoFromAddr(td.GetAddress());
CodeRegionInfo code = CodeRegionInfo::GetCodeRegionInfo(pDJI, md);
if (code.AddressToOffset((const BYTE *)td.GetAddress()) == 0)
{
LOG((LF_CORDB,LL_INFO1000,"\tDS::TS 0x%x m_reason = STEP_CALL"
"@ip0x%x\n", this, (BYTE*)GetControlPC(&(pInfo->m_activeFrame.registers))));
m_reason = STEP_CALL;
}
else
{
LOG((LF_CORDB, LL_INFO1000, "Didn't step: md:0x%x"
"td.type:%s td.address:0x%x, gfa:0x%x\n",
md, GetTType(td.GetTraceType()), td.GetAddress(),
g_pEEInterface->GetFunctionAddress(md)));
}
}
else
{
LOG((LF_CORDB,LL_INFO10000,"DS::TS else 0x%x m_reason = STEP_CALL\n",
this));
m_reason = STEP_CALL;
}
return true;
} // end TrapStepIn
else
{
// If we can't figure out where the stepper should call into (likely because we can't find a stub-manager),
// then enable the JMC backstop.
EnableJMCBackStop(pInfo->m_activeFrame.md);
}
// We ignore ipNext here. Instead we'll return false and let the caller (TrapStep)
// set the patch for us.
return false;
}
FORCEINLINE bool IsTailCall(const BYTE * pTargetIP)
{
return TailCallStubManager::IsTailCallStubHelper(reinterpret_cast<PCODE>(pTargetIP));
}
// bool DebuggerStepper::TrapStep() TrapStep attepts to set a
// patch at the next IL instruction to be executed. If we're stepping in &
// the next IL instruction is a call, then this'll set a breakpoint inside
// the code that will be called.
// How: There are a number of cases, depending on where the IP
// currently is:
// Unmanaged code: EnableTraceCall() & return false - try and get
// it when it returns.
// In a frame: if the <p in> param is true, then do an
// EnableTraceCall(). If the frame isn't the top frame, also do
// g_pEEInterface->TraceFrame(), g_pEEInterface->FollowTrace, and
// PatchTrace.
// Normal managed frame: create a Walker and walk the instructions until either
// leave the provided range (AddPatch there, return true), or we don't know what the
// next instruction is (say, after a call, or return, or branch - return false).
// Returns a boolean indicating if we were able to set a patch successfully
// in either this method, or (if in == true & the next instruction is a call)
// inside a callee method.
// true: Patch successfully placed either in this method or a callee,
// so the stepping is taken care of.
// false: Unable to place patch in either this method or any
// applicable callee methods, so the only option the caller has to put
// patch to control flow is to call TrapStepOut & try and place a patch
// on the method that called the current frame's method.
bool DebuggerStepper::TrapStep(ControllerStackInfo *info, bool in)
{
LOG((LF_CORDB,LL_INFO10000,"DS::TS: this:0x%x\n", this));
if (!info->m_activeFrame.managed)
{
//
// We're not in managed code. Patch up all paths back in.
//
LOG((LF_CORDB,LL_INFO10000, "DS::TS: not in managed code\n"));
if (in)
{
EnablePolyTraceCall();
}
return false;
}
if (info->m_activeFrame.frame != NULL)
{
//
// We're in some kind of weird frame. Patch further entry to the frame.
// or if we can't, patch return from the frame
//
LOG((LF_CORDB,LL_INFO10000, "DS::TS: in a weird frame\n"));
if (in)
{
EnablePolyTraceCall();
// Only traditional steppers should patch a frame. JMC steppers will
// just rely on TriggerMethodEnter.
if (DEBUGGER_CONTROLLER_STEPPER == this->GetDCType())
{
if (info->m_activeFrame.frame != FRAME_TOP)
{
TraceDestination trace;
CONTRACT_VIOLATION(GCViolation); // TraceFrame GC-triggers
// This could be anywhere, especially b/c step could be on non-leaf frame.
if (g_pEEInterface->TraceFrame(this->GetThread(),
info->m_activeFrame.frame,
FALSE, &trace,
&(info->m_activeFrame.registers))
&& g_pEEInterface->FollowTrace(&trace)
&& PatchTrace(&trace, info->m_activeFrame.fp,
(m_rgfMappingStop&STOP_UNMANAGED)?
(true):(false)))
{
return true;
}
}
}
}
return false;
}
#ifdef _TARGET_X86_
LOG((LF_CORDB,LL_INFO1000, "GetJitInfo for pc = 0x%x (addr of "
"that value:0x%x)\n", (const BYTE*)(GetControlPC(&info->m_activeFrame.registers)),
info->m_activeFrame.registers.PCTAddr));
#endif
// Note: we used to pass in the IP from the active frame to GetJitInfo, but there seems to be no value in that, and
// it was causing problems creating a stepper while sitting in ndirect stubs after we'd returned from the unmanaged
// function that had been called.
DebuggerJitInfo *ji = info->m_activeFrame.GetJitInfoFromFrame();
if( ji != NULL )
{
LOG((LF_CORDB,LL_INFO10000,"DS::TS: For code 0x%p, got DJI 0x%p, "
"from 0x%p to 0x%p\n",
(const BYTE*)(GetControlPC(&info->m_activeFrame.registers)),
ji, ji->m_addrOfCode, ji->m_addrOfCode+ji->m_sizeOfCode));
}
else
{
LOG((LF_CORDB,LL_INFO10000,"DS::TS: For code 0x%p, "
"didn't get a DJI \n",
(const BYTE*)(GetControlPC(&info->m_activeFrame.registers))));
}
//
// We're in a normal managed frame - walk the code
//
NativeWalker walker;
LOG((LF_CORDB,LL_INFO1000, "DS::TS: &info->m_activeFrame.registers 0x%p\n", &info->m_activeFrame.registers));
// !!! Eventually when using the fjit, we'll want
// to walk the IL to get the next location, & then map
// it back to native.
walker.Init((BYTE*)GetControlPC(&(info->m_activeFrame.registers)), &info->m_activeFrame.registers);
// Is the active frame really the active frame?
// What if the thread is stopped at a managed debug event outside of a filter ctx? Eg, stopped
// somewhere directly in mscorwks (like sending a LogMsg or ClsLoad event) or even at WaitForSingleObject.
// ActiveFrame is either the stepper's initial frame or the frame of a filterctx.
bool fIsActivFrameLive = (info->m_activeFrame.fp == info->m_bottomFP);
// If this thread isn't stopped in managed code, it can't be at the active frame.
if (GetManagedStoppedCtx(this->GetThread()) == NULL)
{
fIsActivFrameLive = false;
}
bool fIsJump = false;
bool fCallingIntoFunclet = false;
// If m_activeFrame is not the actual active frame,
// we should skip this first switch - never single step, and
// assume our context is bogus.
if (fIsActivFrameLive)
{
LOG((LF_CORDB,LL_INFO10000, "DC::TS: immediate?\n"));
// Note that by definition our walker must always be able to step
// through a single instruction, so any return
// of NULL IP's from those cases on the first step
// means that an exception is going to be generated.
//
// (On future steps, it can also mean that the destination
// simply can't be computed.)
WALK_TYPE wt = walker.GetOpcodeWalkType();
{
switch (wt)
{
case WALK_RETURN:
{
LOG((LF_CORDB,LL_INFO10000, "DC::TS:Imm:WALK_RETURN\n"));
// Normally a 'ret' opcode means we're at the end of a function and doing a step-out.
// But the jit is free to use a 'ret' opcode to implement various goofy constructs like
// managed filters, in which case we may ret to the same function or we may ret to some
// internal CLR stub code.
// So we'll just ignore this and tell the Stepper to enable every notification it has
// and let the thread run free. This will include TrapStepOut() and EnableUnwind()
// to catch any potential filters.
// Go ahead and enable the single-step flag too. We know it's safe.
// If this lands in random code, then TriggerSingleStep will just ignore it.
EnableSingleStep();
// Don't set step-reason yet. If another trigger gets hit, it will set the reason.
return false;
}
case WALK_BRANCH:
LOG((LF_CORDB,LL_INFO10000, "DC::TS:Imm:WALK_BRANCH\n"));
// A branch can be handled just like a call. If the branch is within the current method, then we just
// down to WALK_UNKNOWN, otherwise we handle it just like a call. Note: we need to force in=true
// because for a jmp, in or over is the same thing, we're still going there, and the in==true case is
// the case we want to use...
fIsJump = true;
// fall through...
case WALK_CALL:
LOG((LF_CORDB,LL_INFO10000, "DC::TS:Imm:WALK_CALL ip=%p nextip=%p\n", walker.GetIP(), walker.GetNextIP()));
// If we're doing some sort of intra-method jump (usually, to get EIP in a clever way, via the CALL
// instruction), then put the bp where we're going, NOT at the instruction following the call
if (IsAddrWithinFrame(ji, info->m_activeFrame.md, walker.GetIP(), walker.GetNextIP()))
{
LOG((LF_CORDB, LL_INFO1000, "Walk call within method!" ));
goto LWALK_UNKNOWN;
}
if (walker.GetNextIP() != NULL)
{
#ifdef WIN64EXCEPTIONS
// There are 4 places we could be jumping:
// 1) to the beginning of the same method (recursive call)
// 2) somewhere in the same funclet, that isn't the method start
// 3) somewhere in the same method but different funclet
// 4) somewhere in a different method
//
// IsAddrWithinFrame ruled out option 2, IsAddrWithinMethodIncludingFunclet rules out option 4,
// and checking the IP against the start address rules out option 1. That leaves option only what we
// wanted, option #3
fCallingIntoFunclet = IsAddrWithinMethodIncludingFunclet(ji, info->m_activeFrame.md, walker.GetNextIP()) &&
((CORDB_ADDRESS)(SIZE_T)walker.GetNextIP() != ji->m_addrOfCode);
#endif
// At this point, we know that the call/branch target is not in the current method.
// So if the current instruction is a jump, this must be a tail call or possibly a jump to the finally.
// So, check if the call/branch target is the JIT helper for handling tail calls if we are not calling
// into the funclet.
if ((fIsJump && !fCallingIntoFunclet) || IsTailCall(walker.GetNextIP()))
{
// A step-over becomes a step-out for a tail call.
if (!in)
{
TrapStepOut(info);
return true;
}
}
// To preserve the old behaviour, if this is not a tail call, then we assume we want to
// follow the call/jump.
if (fIsJump)
{
in = true;
}
// There are two cases where we need to perform a step-in. One, if the step operation is
// a step-in. Two, if the target address of the call is in a funclet of the current method.
// In this case, we want to step into the funclet even if the step operation is a step-over.
if (in || fCallingIntoFunclet)
{
if (TrapStepInHelper(info, walker.GetNextIP(), walker.GetSkipIP(), fCallingIntoFunclet))
{
return true;
}
}
}
if (walker.GetSkipIP() == NULL)
{
LOG((LF_CORDB,LL_INFO10000,"DS::TS 0x%x m_reason = STEP_CALL (skip)\n",
this));
m_reason = STEP_CALL;
return true;
}
LOG((LF_CORDB,LL_INFO100000, "DC::TS:Imm:WALK_CALL Skip instruction\n"));
walker.Skip();
break;
case WALK_UNKNOWN:
LWALK_UNKNOWN:
LOG((LF_CORDB,LL_INFO10000,"DS::TS:WALK_UNKNOWN - curIP:0x%x "
"nextIP:0x%x skipIP:0x%x 1st byte of opcode:0x%x\n", (BYTE*)GetControlPC(&(info->m_activeFrame.
registers)), walker.GetNextIP(),walker.GetSkipIP(),
*(BYTE*)GetControlPC(&(info->m_activeFrame.registers))));
EnableSingleStep();
return true;
default:
if (walker.GetNextIP() == NULL)
{
return true;
}
walker.Next();
}
}
} // if (fIsActivFrameLive)
//
// Use our range, if we're in the original
// frame.
//
COR_DEBUG_STEP_RANGE *range;
SIZE_T rangeCount;
if (info->m_activeFrame.fp == m_fp)
{
range = m_range;
rangeCount = m_rangeCount;
}
else
{
range = NULL;
rangeCount = 0;
}
//
// Keep walking until either we're out of range, or
// else we can't predict ahead any more.
//
while (TRUE)
{
const BYTE *ip = walker.GetIP();
SIZE_T offset = CodeRegionInfo::GetCodeRegionInfo(ji, info->m_activeFrame.md).AddressToOffset(ip);
LOG((LF_CORDB, LL_INFO1000, "Walking to ip 0x%p (natOff:0x%x)\n",ip,offset));
if (!IsInRange(offset, range, rangeCount)
&& !ShouldContinueStep( info, offset ))
{
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
offset,
info->m_returnFrame.fp,
NULL);
return true;
}
switch (walker.GetOpcodeWalkType())
{
case WALK_RETURN:
LOG((LF_CORDB, LL_INFO10000, "DS::TS: WALK_RETURN Adding Patch.\n"));
// In the loop above, if we're at the return address, we'll check & see
// if we're returning to elsewhere within the same method, and if so,
// we'll single step rather than TrapStepOut. If we see a return in the
// code stream, then we'll set a breakpoint there, so that we can
// examine the return address, and decide whether to SS or TSO then
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
offset,
info->m_returnFrame.fp,
NULL);
return true;
case WALK_CALL:
LOG((LF_CORDB, LL_INFO10000, "DS::TS: WALK_CALL.\n"));
// If we're doing some sort of intra-method jump (usually, to get EIP in a clever way, via the CALL
// instruction), then put the bp where we're going, NOT at the instruction following the call
if (IsAddrWithinFrame(ji, info->m_activeFrame.md, walker.GetIP(), walker.GetNextIP()))
{
LOG((LF_CORDB, LL_INFO10000, "DS::TS: WALK_CALL IsAddrWithinFrame, Adding Patch.\n"));
// How else to detect this?
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
CodeRegionInfo::GetCodeRegionInfo(ji, info->m_activeFrame.md).AddressToOffset(walker.GetNextIP()),
info->m_returnFrame.fp,
NULL);
return true;
}
if (IsTailCall(walker.GetNextIP()))
{
if (!in)
{
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
offset,
info->m_returnFrame.fp,
NULL);
return true;
}
}
#ifdef WIN64EXCEPTIONS
fCallingIntoFunclet = IsAddrWithinMethodIncludingFunclet(ji, info->m_activeFrame.md, walker.GetNextIP());
#endif
if (in || fCallingIntoFunclet)
{
LOG((LF_CORDB, LL_INFO10000, "DS::TS: WALK_CALL step in is true\n"));
if (walker.GetNextIP() == NULL)
{
LOG((LF_CORDB, LL_INFO10000, "DS::TS: WALK_CALL NextIP == NULL\n"));
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
offset,
info->m_returnFrame.fp,
NULL);
LOG((LF_CORDB,LL_INFO10000,"DS0x%x m_reason=STEP_CALL 2\n",
this));
m_reason = STEP_CALL;
return true;
}
if (TrapStepInHelper(info, walker.GetNextIP(), walker.GetSkipIP(), fCallingIntoFunclet))
{
return true;
}
}
LOG((LF_CORDB, LL_INFO10000, "DS::TS: WALK_CALL Calling GetSkipIP\n"));
if (walker.GetSkipIP() == NULL)
{
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
offset,
info->m_returnFrame.fp,
NULL);
LOG((LF_CORDB,LL_INFO10000,"DS 0x%x m_reason=STEP_CALL4\n",this));
m_reason = STEP_CALL;
return true;
}
walker.Skip();
LOG((LF_CORDB, LL_INFO10000, "DS::TS: skipping over call.\n"));
break;
default:
if (walker.GetNextIP() == NULL)
{
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
ji,
offset,
info->m_returnFrame.fp,
NULL);
return true;
}
walker.Next();
break;
}
}
LOG((LF_CORDB,LL_INFO1000,"Ending TrapStep\n"));
}
bool DebuggerStepper::IsAddrWithinFrame(DebuggerJitInfo *dji,
MethodDesc* pMD,
const BYTE* currentAddr,
const BYTE* targetAddr)
{
_ASSERTE(dji != NULL);
bool result = IsAddrWithinMethodIncludingFunclet(dji, pMD, targetAddr);
// We need to check if this is a recursive call. In RTM we should see if this method is really necessary,
// since it looks like the X86 JIT doesn't emit intra-method jumps anymore.
if (result)
{
if ((CORDB_ADDRESS)(SIZE_T)targetAddr == dji->m_addrOfCode)
{
result = false;
}
}
#if defined(WIN64EXCEPTIONS)
// On WIN64, we also check whether the targetAddr and the currentAddr is in the same funclet.
_ASSERTE(currentAddr != NULL);
if (result)
{
int currentFuncletIndex = dji->GetFuncletIndex((CORDB_ADDRESS)currentAddr, DebuggerJitInfo::GFIM_BYADDRESS);
int targetFuncletIndex = dji->GetFuncletIndex((CORDB_ADDRESS)targetAddr, DebuggerJitInfo::GFIM_BYADDRESS);
result = (currentFuncletIndex == targetFuncletIndex);
}
#endif // WIN64EXCEPTIONS
return result;
}
// x86 shouldn't need to call this method directly. We should call IsAddrWithinFrame() on x86 instead.
// That's why I use a name with the word "funclet" in it to scare people off.
bool DebuggerStepper::IsAddrWithinMethodIncludingFunclet(DebuggerJitInfo *dji,
MethodDesc* pMD,
const BYTE* targetAddr)
{
_ASSERTE(dji != NULL);
return CodeRegionInfo::GetCodeRegionInfo(dji, pMD).IsMethodAddress(targetAddr);
}
void DebuggerStepper::TrapStepNext(ControllerStackInfo *info)
{
LOG((LF_CORDB, LL_INFO10000, "DS::TrapStepNext, this=%p\n", this));
// StepNext for a Normal stepper is just a step-out
TrapStepOut(info);
// @todo -should we also EnableTraceCall??
}
// Is this frame interesting?
// For a traditional stepper, all frames are interesting.
bool DebuggerStepper::IsInterestingFrame(FrameInfo * pFrame)
{
LIMITED_METHOD_CONTRACT;
return true;
}
// Place a single patch somewhere up the stack to do a step-out
void DebuggerStepper::TrapStepOut(ControllerStackInfo *info, bool fForceTraditional)
{
ControllerStackInfo returnInfo;
DebuggerJitInfo *dji;
LOG((LF_CORDB, LL_INFO10000, "DS::TSO this:0x%p\n", this));
bool fReturningFromFinallyFunclet = false;
#if defined(WIN64EXCEPTIONS)
// When we step out of a funclet, we should do one of two things, depending
// on the original stepping intention:
// 1) If we originally want to step out, then we should skip the parent method.
// 2) If we originally want to step in/over but we step off the end of the funclet,
// then we should resume in the parent, if possible.
if (info->m_activeFrame.IsNonFilterFuncletFrame())
{
// There should always be a frame for the parent method.
_ASSERTE(info->HasReturnFrame());
#ifdef _TARGET_ARM_
while (info->HasReturnFrame() && info->m_activeFrame.md != info->m_returnFrame.md)
{
StackTraceTicket ticket(info);
returnInfo.GetStackInfo(ticket, GetThread(), info->m_returnFrame.fp, NULL);
info = &returnInfo;
}
_ASSERTE(info->HasReturnFrame());
#endif
_ASSERTE(info->m_activeFrame.md == info->m_returnFrame.md);
if (m_eMode == cStepOut)
{
StackTraceTicket ticket(info);
returnInfo.GetStackInfo(ticket, GetThread(), info->m_returnFrame.fp, NULL);
info = &returnInfo;
}
else
{
_ASSERTE(info->m_returnFrame.managed);
_ASSERTE(info->m_returnFrame.frame == NULL);
MethodDesc *md = info->m_returnFrame.md;
dji = info->m_returnFrame.GetJitInfoFromFrame();
// The return value of a catch funclet is the control PC to resume to.
// The return value of a finally funclet has no meaning, so we need to check
// if the return value is in the main method.
LPVOID resumePC = GetRegdisplayReturnValue(&(info->m_activeFrame.registers));
// For finally funclet, there are two possible situations. Either the finally is
// called normally (i.e. no exception), in which case we simply fall through and
// let the normal loop do its work below, or the finally is called by the EH
// routines, in which case we need the unwind notification.
if (IsAddrWithinMethodIncludingFunclet(dji, md, (const BYTE *)resumePC))
{
SIZE_T reloffset = dji->m_codeRegionInfo.AddressToOffset((BYTE*)resumePC);
AddBindAndActivateNativeManagedPatch(info->m_returnFrame.md,
dji,
reloffset,
info->m_returnFrame.fp,
NULL);
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO:normally managed code AddPatch"
" in %s::%s, offset 0x%x, m_reason=%d\n",
info->m_returnFrame.md->m_pszDebugClassName,
info->m_returnFrame.md->m_pszDebugMethodName,
reloffset, m_reason));
// Do not set m_reason to STEP_RETURN here. Logically, the funclet and the parent method are the
// same method, so we should not "return" to the parent method.
LOG((LF_CORDB, LL_INFO10000,"DS::TSO: done\n"));
return;
}
else
{
// This is the case where we step off the end of a finally funclet.
fReturningFromFinallyFunclet = true;
}
}
}
#endif // WIN64EXCEPTIONS
#ifdef _DEBUG
FramePointer dbgLastFP; // for debug, make sure we're making progress through the stack.
#endif
while (info->HasReturnFrame())
{
#ifdef _DEBUG
dbgLastFP = info->m_activeFrame.fp;
#endif
// Continue walking up the stack & set a patch upon the next
// frame up. We will eventually either hit managed code
// (which we can set a definite patch in), or the top of the
// stack.
StackTraceTicket ticket(info);
// The last parameter here is part of a really targetted (*cough* dirty) fix to
// disable getting an unwanted UMChain to fix issue 650903 (See
// code:ControllerStackInfo::WalkStack and code:TrackUMChain for the other
// parts.) In the case of managed step out we know that we aren't interested in
// unmanaged frames, and generating that unmanaged frame causes the stackwalker
// not to report the managed frame that was at the same SP. However the unmanaged
// frame might be used in the mixed-mode step out case so I don't suppress it
// there.
returnInfo.GetStackInfo(ticket, GetThread(), info->m_returnFrame.fp, NULL, !(m_rgfMappingStop & STOP_UNMANAGED));
info = &returnInfo;
#ifdef _DEBUG
// If this assert fires, then it means that we're not making progress while
// tracing up the towards the root of the stack. Likely an issue in the Left-Side's
// stackwalker.
_ASSERTE(IsCloserToLeaf(dbgLastFP, info->m_activeFrame.fp));
#endif
#ifdef FEATURE_STUBS_AS_IL
if (info->m_activeFrame.md->IsILStub() && info->m_activeFrame.md->AsDynamicMethodDesc()->IsMulticastStub())
{
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: multicast frame.\n"));
// User break should always be called from managed code, so it should never actually hit this codepath.
_ASSERTE(GetDCType() != DEBUGGER_CONTROLLER_USER_BREAKPOINT);
// JMC steppers shouldn't be patching stubs.
if (DEBUGGER_CONTROLLER_JMC_STEPPER == this->GetDCType())
{
LOG((LF_CORDB, LL_INFO10000, "DS::TSO: JMC stepper skipping frame.\n"));
continue;
}
TraceDestination trace;
EnableTraceCall(info->m_activeFrame.fp);
PCODE ip = GetControlPC(&(info->m_activeFrame.registers));
if (g_pEEInterface->TraceStub((BYTE*)ip, &trace)
&& g_pEEInterface->FollowTrace(&trace)
&& PatchTrace(&trace, info->m_activeFrame.fp,
true))
break;
}
else
#endif // FEATURE_STUBS_AS_IL
if (info->m_activeFrame.managed)
{
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: return frame is managed.\n"));
if (info->m_activeFrame.frame == NULL)
{
// Returning normally to managed code.
_ASSERTE(info->m_activeFrame.md != NULL);
// Polymorphic check to skip over non-interesting frames.
if (!fForceTraditional && !this->IsInterestingFrame(&info->m_activeFrame))
continue;
dji = info->m_activeFrame.GetJitInfoFromFrame();
_ASSERTE(dji != NULL);
// Note: we used to pass in the IP from the active frame to GetJitInfo, but there seems to be no value
// in that, and it was causing problems creating a stepper while sitting in ndirect stubs after we'd
// returned from the unmanaged function that had been called.
ULONG reloffset = info->m_activeFrame.relOffset;
AddBindAndActivateNativeManagedPatch(info->m_activeFrame.md,
dji,
reloffset,
info->m_returnFrame.fp,
NULL);
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO:normally managed code AddPatch"
" in %s::%s, offset 0x%x, m_reason=%d\n",
info->m_activeFrame.md->m_pszDebugClassName,
info->m_activeFrame.md->m_pszDebugMethodName,
reloffset, m_reason));
// Do not set m_reason to STEP_RETURN here. Logically, the funclet and the parent method are the
// same method, so we should not "return" to the parent method.
if (!fReturningFromFinallyFunclet)
{
m_reason = STEP_RETURN;
}
break;
}
else if (info->m_activeFrame.frame == FRAME_TOP)
{
// Trad-stepper's step-out is actually like a step-next when we go off the top.
// JMC-steppers do a true-step out. So for JMC-steppers, don't enable trace-call.
if (DEBUGGER_CONTROLLER_JMC_STEPPER == this->GetDCType())
{
LOG((LF_CORDB, LL_EVERYTHING, "DS::TSO: JMC stepper skipping exit-frame case.\n"));
break;
}
// User break should always be called from managed code, so it should never actually hit this codepath.
_ASSERTE(GetDCType() != DEBUGGER_CONTROLLER_USER_BREAKPOINT);
// We're walking off the top of the stack. Note that if we call managed code again,
// this trace-call will cause us our stepper-to fire. So we'll actually do a
// step-next; not a true-step out.
EnableTraceCall(info->m_activeFrame.fp);
LOG((LF_CORDB, LL_INFO1000, "DS::TSO: Off top of frame!\n"));
m_reason = STEP_EXIT; //we're on the way out..
// <REVISIT_TODO>@todo not that it matters since we don't send a
// stepComplete message to the right side.</REVISIT_TODO>
break;
}
else if (info->m_activeFrame.frame->GetFrameType() == Frame::TYPE_FUNC_EVAL)
{
// Note: we treat walking off the top of the stack and
// walking off the top of a func eval the same way,
// except that we don't enable trace call since we
// know exactly where were going.
LOG((LF_CORDB, LL_INFO1000,
"DS::TSO: Off top of func eval!\n"));
m_reason = STEP_EXIT;
break;
}
else if (info->m_activeFrame.frame->GetFrameType() == Frame::TYPE_SECURITY &&
info->m_activeFrame.frame->GetInterception() == Frame::INTERCEPTION_NONE)
{
// If we're stepping out of something that was protected by (declarative) security,
// the security subsystem may leave a frame on the stack to cache it's computation.
// HOWEVER, this isn't a real frame, and so we don't want to stop here. On the other
// hand, if we're in the security goop (sec. executes managed code to do stuff), then
// we'll want to use the "returning to stub case", below. GetInterception()==NONE
// indicates that the frame is just a cache frame:
// Skip it and keep on going
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: returning to a non-intercepting frame. Keep unwinding\n"));
continue;
}
else
{
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: returning to a stub frame.\n"));
// User break should always be called from managed code, so it should never actually hit this codepath.
_ASSERTE(GetDCType() != DEBUGGER_CONTROLLER_USER_BREAKPOINT);
// JMC steppers shouldn't be patching stubs.
if (DEBUGGER_CONTROLLER_JMC_STEPPER == this->GetDCType())
{
LOG((LF_CORDB, LL_INFO10000, "DS::TSO: JMC stepper skipping frame.\n"));
continue;
}
// We're returning to some funky frame.
// (E.g. a security frame has called a native method.)
// Patch the frame from entering other methods. This effectively gives the Step-out
// a step-next behavior. For eg, this can be useful for step-out going between multicast delegates.
// This step-next could actually land us leaf-more on the callstack than we currently are!
// If we were a true-step out, we'd skip this and keep crawling.
// up the callstack.
//
// !!! For now, we assume that the TraceFrame entry
// point is smart enough to tell where it is in the
// calling sequence. We'll see how this holds up.
TraceDestination trace;
// We don't want notifications of trace-calls leaf-more than our current frame.
// For eg, if our current frame calls out to unmanaged code and then back in,
// we'll get a TraceCall notification. But since it's leaf-more than our current frame,
// we don't care because we just want to step out of our current frame (and everything
// our current frame may call).
EnableTraceCall(info->m_activeFrame.fp);
CONTRACT_VIOLATION(GCViolation); // TraceFrame GC-triggers
if (g_pEEInterface->TraceFrame(GetThread(),
info->m_activeFrame.frame, FALSE,
&trace, &(info->m_activeFrame.registers))
&& g_pEEInterface->FollowTrace(&trace)
&& PatchTrace(&trace, info->m_activeFrame.fp,
true))
break;
// !!! Problem: we don't know which return frame to use -
// the TraceFrame patch may be in a frame below the return
// frame, or in a frame parallel with it
// (e.g. prestub popping itself & then calling.)
//
// For now, I've tweaked the FP comparison in the
// patch dispatching code to allow either case.
}
}
else
{
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: return frame is not managed.\n"));
// Only step out to unmanaged code if we're actually
// marked to stop in unamanged code. Otherwise, just loop
// to get us past the unmanaged frames.
if (m_rgfMappingStop & STOP_UNMANAGED)
{
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: return to unmanaged code "
"m_reason=STEP_RETURN\n"));
// Do not set m_reason to STEP_RETURN here. Logically, the funclet and the parent method are the
// same method, so we should not "return" to the parent method.
if (!fReturningFromFinallyFunclet)
{
m_reason = STEP_RETURN;
}
// We're stepping out into unmanaged code
LOG((LF_CORDB, LL_INFO10000,
"DS::TSO: Setting unmanaged trace patch at 0x%x(%x)\n",
GetControlPC(&(info->m_activeFrame.registers)),
info->m_returnFrame.fp.GetSPValue()));
AddAndActivateNativePatchForAddress((CORDB_ADDRESS_TYPE *)GetControlPC(&(info->m_activeFrame.registers)),
info->m_returnFrame.fp,
FALSE,
TRACE_UNMANAGED);
break;
}
}
}
// <REVISIT_TODO>If we get here, we may be stepping out of the last frame. Our thread
// exit logic should catch this case. (@todo)</REVISIT_TODO>
LOG((LF_CORDB, LL_INFO10000,"DS::TSO: done\n"));
}
// void DebuggerStepper::StepOut()
// Called by Debugger::HandleIPCEvent to setup
// everything so that the process will step over the range of IL
// correctly.
// How: Converts the provided array of ranges from IL ranges to
// native ranges (if they're not native already), and then calls
// TrapStep or TrapStepOut, like so:
// Get the appropriate MethodDesc & JitInfo
// Iterate through array of IL ranges, use
// JitInfo::MapILRangeToMapEntryRange to translate IL to native
// ranges.
// Set member variables to remember that the DebuggerStepper now uses
// the ranges: m_range, m_rangeCount, m_stepIn, m_fp
// If (!TrapStep()) then {m_stepIn = true; TrapStepOut()}
// EnableUnwind( m_fp );
void DebuggerStepper::StepOut(FramePointer fp, StackTraceTicket ticket)
{
LOG((LF_CORDB, LL_INFO10000, "Attempting to step out, fp:0x%x this:0x%x"
"\n", fp.GetSPValue(), this ));
Thread *thread = GetThread();
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
ControllerStackInfo info;
// We pass in the ticket b/c this is called both when we're live (via
// DebuggerUserBreakpoint) and when we're stopped (via normal StepOut)
info.GetStackInfo(ticket, thread, fp, context);
ResetRange();
m_stepIn = FALSE;
m_fp = info.m_activeFrame.fp;
#if defined(WIN64EXCEPTIONS)
// We need to remember the parent method frame pointer here so that we will recognize
// the range of the stepper as being valid when we return to the parent method.
if (info.m_activeFrame.IsNonFilterFuncletFrame())
{
m_fpParentMethod = info.m_returnFrame.fp;
}
#endif // WIN64EXCEPTIONS
m_eMode = cStepOut;
_ASSERTE((fp == LEAF_MOST_FRAME) || (info.m_activeFrame.md != NULL) || (info.m_returnFrame.md != NULL));
TrapStepOut(&info);
EnableUnwind(m_fp);
}
#define GROW_RANGES_IF_NECESSARY() \
if (rTo == rToEnd) \
{ \
ULONG NewSize, OldSize; \
if (!ClrSafeInt<ULONG>::multiply(sizeof(COR_DEBUG_STEP_RANGE), (ULONG)(realRangeCount*2), NewSize) || \
!ClrSafeInt<ULONG>::multiply(sizeof(COR_DEBUG_STEP_RANGE), (ULONG)realRangeCount, OldSize) || \
NewSize < OldSize) \
{ \
DeleteInteropSafe(m_range); \
m_range = NULL; \
return false; \
} \
COR_DEBUG_STEP_RANGE *_pTmp = (COR_DEBUG_STEP_RANGE*) \
g_pDebugger->GetInteropSafeHeap()->Realloc(m_range, \
NewSize, \
OldSize); \
\
if (_pTmp == NULL) \
{ \
DeleteInteropSafe(m_range); \
m_range = NULL; \
return false; \
} \
\
m_range = _pTmp; \
rTo = m_range + realRangeCount; \
rToEnd = m_range + (realRangeCount*2); \
realRangeCount *= 2; \
}
//-----------------------------------------------------------------------------
// Given a set of IL ranges, convert them to native and cache them.
// Return true on success, false on error.
//-----------------------------------------------------------------------------
bool DebuggerStepper::SetRangesFromIL(DebuggerJitInfo *dji, COR_DEBUG_STEP_RANGE *ranges, SIZE_T rangeCount)
{
CONTRACTL
{
SO_NOT_MAINLINE;
WRAPPER(THROWS);
GC_NOTRIGGER;
PRECONDITION(ThisIsHelperThreadWorker()); // Only help initializes a stepper.
PRECONDITION(m_range == NULL); // shouldn't be set already.
PRECONDITION(CheckPointer(ranges));
PRECONDITION(CheckPointer(dji));
}
CONTRACTL_END;
// Note: we used to pass in the IP from the active frame to GetJitInfo, but there seems to be no value in that, and
// it was causing problems creating a stepper while sitting in ndirect stubs after we'd returned from the unmanaged
// function that had been called.
MethodDesc *fd = dji->m_fd;
// The "+1" is for internal use, when we need to
// set an intermediate patch in pitched code. Isn't
// used unless the method is pitched & a patch is set
// inside it. Thus we still pass cRanges as the
// range count.
m_range = new (interopsafe) COR_DEBUG_STEP_RANGE[rangeCount+1];
if (m_range == NULL)
return false;
TRACE_ALLOC(m_range);
SIZE_T realRangeCount = rangeCount;
if (dji != NULL)
{
LOG((LF_CORDB,LL_INFO10000,"DeSt::St: For code md=0x%x, got DJI 0x%x, from 0x%x to 0x%x\n",
fd,
dji, dji->m_addrOfCode, (ULONG)dji->m_addrOfCode
+ (ULONG)dji->m_sizeOfCode));
//
// Map ranges to native offsets for jitted code
//
COR_DEBUG_STEP_RANGE *r, *rEnd, *rTo, *rToEnd;
r = ranges;
rEnd = r + rangeCount;
rTo = m_range;
rToEnd = rTo + realRangeCount;
// <NOTE>
// rTo may also be incremented in the middle of the loop on WIN64 platforms.
// </NOTE>
for (/**/; r < rEnd; r++, rTo++)
{
// If we are already at the end of our allocated array, but there are still
// more ranges to copy over, then grow the array.
GROW_RANGES_IF_NECESSARY();
if (r->startOffset == 0 && r->endOffset == (ULONG) ~0)
{
// {0...-1} means use the entire method as the range
// Code dup'd from below case.
LOG((LF_CORDB, LL_INFO10000, "DS:Step: Have DJI, special (0,-1) entry\n"));
rTo->startOffset = 0;
rTo->endOffset = (ULONG32)g_pEEInterface->GetFunctionSize(fd);
}
else
{
//
// One IL range may consist of multiple
// native ranges.
//
DebuggerILToNativeMap *mStart, *mEnd;
dji->MapILRangeToMapEntryRange(r->startOffset,
r->endOffset,
&mStart,
&mEnd);
// Either mStart and mEnd are both NULL (we don't have any sequence point),
// or they are both non-NULL.
_ASSERTE( ((mStart == NULL) && (mEnd == NULL)) ||
((mStart != NULL) && (mEnd != NULL)) );
if (mStart == NULL)
{
// <REVISIT_TODO>@todo Won't this result in us stepping across
// the entire method?</REVISIT_TODO>
rTo->startOffset = 0;
rTo->endOffset = 0;
}
else if (mStart == mEnd)
{
rTo->startOffset = mStart->nativeStartOffset;
rTo->endOffset = mStart->nativeEndOffset;
}
else
{
// Account for more than one continuous range here.
// Move the pointer back to work with the loop increment below.
// Don't dereference this pointer now!
rTo--;
for (DebuggerILToNativeMap* pMap = mStart;
pMap <= mEnd;
pMap = pMap + 1)
{
if ((pMap == mStart) ||
(pMap->nativeStartOffset != (pMap-1)->nativeEndOffset))
{
rTo++;
GROW_RANGES_IF_NECESSARY();
rTo->startOffset = pMap->nativeStartOffset;
rTo->endOffset = pMap->nativeEndOffset;
}
else
{
// If we have continuous ranges, then lump them together.
_ASSERTE(rTo->endOffset == pMap->nativeStartOffset);
rTo->endOffset = pMap->nativeEndOffset;
}
}
LOG((LF_CORDB, LL_INFO10000, "DS:Step: nat off:0x%x to 0x%x\n", rTo->startOffset, rTo->endOffset));
}
}
}
rangeCount = (int)((BYTE*)rTo - (BYTE*)m_range) / sizeof(COR_DEBUG_STEP_RANGE);
}
else
{
// Even if we don't have debug info, we'll be able to
// step through the method
SIZE_T functionSize = g_pEEInterface->GetFunctionSize(fd);
COR_DEBUG_STEP_RANGE *r = ranges;
COR_DEBUG_STEP_RANGE *rEnd = r + rangeCount;
COR_DEBUG_STEP_RANGE *rTo = m_range;
for(/**/; r < rEnd; r++, rTo++)
{
if (r->startOffset == 0 && r->endOffset == (ULONG) ~0)
{
LOG((LF_CORDB, LL_INFO10000, "DS:Step:No DJI, (0,-1) special entry\n"));
// Code dup'd from above case.
// {0...-1} means use the entire method as the range
rTo->startOffset = 0;
rTo->endOffset = (ULONG32)functionSize;
}
else
{
LOG((LF_CORDB, LL_INFO10000, "DS:Step:No DJI, regular entry\n"));
// We can't just leave ths IL entry - we have to
// get rid of it.
// This will just be ignored
rTo->startOffset = rTo->endOffset = (ULONG32)functionSize;
}
}
}
m_rangeCount = rangeCount;
m_realRangeCount = rangeCount;
return true;
}
// void DebuggerStepper::Step() Tells the stepper to step over
// the provided ranges.
// void *fp: frame pointer.
// bool in: true if we want to step into a function within the range,
// false if we want to step over functions within the range.
// COR_DEBUG_STEP_RANGE *ranges: Assumed to be nonNULL, it will
// always hold at least one element.
// SIZE_T rangeCount: One less than the true number of elements in
// the ranges argument.
// bool rangeIL: true if the ranges are provided in IL (they'll be
// converted to native before the DebuggerStepper uses them,
// false if they already are native.
bool DebuggerStepper::Step(FramePointer fp, bool in,
COR_DEBUG_STEP_RANGE *ranges, SIZE_T rangeCount,
bool rangeIL)
{
LOG((LF_CORDB, LL_INFO1000, "DeSt:Step this:0x%x ", this));
if (rangeCount>0)
LOG((LF_CORDB,LL_INFO10000," start,end[0]:(0x%x,0x%x)\n",
ranges[0].startOffset, ranges[0].endOffset));
else
LOG((LF_CORDB,LL_INFO10000," single step\n"));
Thread *thread = GetThread();
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
// ControllerStackInfo doesn't report IL stubs, so if we are in an IL stub, we need
// to handle the single-step specially. There are probably other problems when we stop
// in an IL stub. We need to revisit this later.
bool fIsILStub = false;
if ((context != NULL) &&
g_pEEInterface->IsManagedNativeCode(reinterpret_cast<const BYTE *>(GetIP(context))))
{
MethodDesc * pMD = g_pEEInterface->GetNativeCodeMethodDesc(GetIP(context));
if (pMD != NULL)
{
fIsILStub = pMD->IsILStub();
}
}
LOG((LF_CORDB, LL_INFO10000, "DS::S - fIsILStub = %d\n", fIsILStub));
ControllerStackInfo info;
StackTraceTicket ticket(thread);
info.GetStackInfo(ticket, thread, fp, context);
_ASSERTE((fp == LEAF_MOST_FRAME) || (info.m_activeFrame.md != NULL) ||
(info.m_returnFrame.md != NULL));
m_stepIn = in;
DebuggerJitInfo *dji = info.m_activeFrame.GetJitInfoFromFrame();
if (dji == NULL)
{
// !!! ERROR range step in frame with no code
ranges = NULL;
rangeCount = 0;
}
if (m_range != NULL)
{
TRACE_FREE(m_range);
DeleteInteropSafe(m_range);
m_range = NULL;
m_rangeCount = 0;
m_realRangeCount = 0;
}
if (rangeCount > 0)
{
if (rangeIL)
{
// IL ranges supplied, we need to convert them to native ranges.
bool fOk = SetRangesFromIL(dji, ranges, rangeCount);
if (!fOk)
{
return false;
}
}
else
{
// Native ranges, already supplied. Just copy them over.
m_range = new (interopsafe) COR_DEBUG_STEP_RANGE[rangeCount];
if (m_range == NULL)
{
return false;
}
memcpy(m_range, ranges, sizeof(COR_DEBUG_STEP_RANGE) * rangeCount);
m_realRangeCount = m_rangeCount = rangeCount;
}
_ASSERTE(m_range != NULL);
_ASSERTE(m_rangeCount > 0);
_ASSERTE(m_realRangeCount > 0);
}
else
{
// !!! ERROR cannot map IL ranges
ranges = NULL;
rangeCount = 0;
}
if (fIsILStub)
{
// Don't use the ControllerStackInfo if we are in an IL stub.
m_fp = fp;
}
else
{
m_fp = info.m_activeFrame.fp;
#if defined(WIN64EXCEPTIONS)
// We need to remember the parent method frame pointer here so that we will recognize
// the range of the stepper as being valid when we return to the parent method.
if (info.m_activeFrame.IsNonFilterFuncletFrame())
{
m_fpParentMethod = info.m_returnFrame.fp;
}
#endif // WIN64EXCEPTIONS
}
m_eMode = m_stepIn ? cStepIn : cStepOver;
LOG((LF_CORDB,LL_INFO10000,"DS 0x%x STep: STEP_NORMAL\n",this));
m_reason = STEP_NORMAL; //assume it'll be a normal step & set it to
//something else if we walk over it
if (fIsILStub)
{
LOG((LF_CORDB, LL_INFO10000, "DS:Step: stepping in an IL stub\n"));
// Enable the right triggers if the user wants to step in.
if (in)
{
if (this->GetDCType() == DEBUGGER_CONTROLLER_STEPPER)
{
EnableTraceCall(info.m_activeFrame.fp);
}
else if (this->GetDCType() == DEBUGGER_CONTROLLER_JMC_STEPPER)
{
EnableMethodEnter();
}
}
// Also perform a step-out in case this IL stub is returning to managed code.
// However, we must fix up the ControllerStackInfo first, since it doesn't
// report IL stubs. The active frame reported by the ControllerStackInfo is
// actually the return frame in this case.
info.SetReturnFrameWithActiveFrame();
TrapStepOut(&info);
}
else if (!TrapStep(&info, in))
{
LOG((LF_CORDB,LL_INFO10000,"DS:Step: Did TS\n"));
m_stepIn = true;
TrapStepNext(&info);
}
LOG((LF_CORDB,LL_INFO10000,"DS:Step: Did TS,TSO\n"));
EnableUnwind(m_fp);
return true;
}
// TP_RESULT DebuggerStepper::TriggerPatch()
// What: Triggers patch if we're not in a stub, and we're
// outside of the stepping range. Otherwise sets another patch so as to
// step out of the stub, or in the next instruction within the range.
// How: If module==NULL & managed==> we're in a stub:
// TrapStepOut() and return false. Module==NULL&!managed==> return
// true. If m_range != NULL & execution is currently in the range,
// attempt a TrapStep (TrapStepOut otherwise) & return false. Otherwise,
// return true.
TP_RESULT DebuggerStepper::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
LOG((LF_CORDB, LL_INFO10000, "DeSt::TP\n"));
// If we're frozen, we may hit a patch but we just ignore it
if (IsFrozen())
{
LOG((LF_CORDB, LL_INFO1000000, "DS::TP, ignoring patch at %p during frozen state\n", patch->address));
return TPR_IGNORE;
}
Module *module = patch->key.module;
BOOL managed = patch->IsManagedPatch();
mdMethodDef md = patch->key.md;
SIZE_T offset = patch->offset;
_ASSERTE((this->GetThread() == thread) || !"Stepper should only get patches on its thread");
// Note we can only run a stack trace if:
// - the context is in managed code (eg, not a stub)
// - OR we have a frame in place to prime the stackwalk.
ControllerStackInfo info;
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
// Context should always be from patch.
_ASSERTE(context != NULL);
bool fSafeToDoStackTrace = true;
// If we're in a stub (module == NULL and still in managed code), then our context is off in lala-land
// Then, it's only safe to do a stackwalk if the top frame is protecting us. That's only true for a
// frame_push. If we're here on a manager_push, then we don't have any such protection, so don't do the
// stackwalk.
fSafeToDoStackTrace = patch->IsSafeForStackTrace();
if (fSafeToDoStackTrace)
{
StackTraceTicket ticket(patch);
info.GetStackInfo(ticket, thread, LEAF_MOST_FRAME, context);
LOG((LF_CORDB, LL_INFO10000, "DS::TP: this:0x%p in %s::%s (fp:0x%p, "
"off:0x%p md:0x%p), \n\texception source:%s::%s (fp:0x%p)\n",
this,
info.m_activeFrame.md!=NULL?info.m_activeFrame.md->m_pszDebugClassName:"Unknown",
info.m_activeFrame.md!=NULL?info.m_activeFrame.md->m_pszDebugMethodName:"Unknown",
info.m_activeFrame.fp.GetSPValue(), patch->offset, patch->key.md,
m_fdException!=NULL?m_fdException->m_pszDebugClassName:"None",
m_fdException!=NULL?m_fdException->m_pszDebugMethodName:"None",
m_fpException.GetSPValue()));
}
DisableAll();
if (DetectHandleLCGMethods(dac_cast<PCODE>(patch->address), NULL, &info))
{
return TPR_IGNORE;
}
if (module == NULL)
{
// JMC steppers should not be patching here...
_ASSERTE(DEBUGGER_CONTROLLER_JMC_STEPPER != this->GetDCType());
if (managed)
{
LOG((LF_CORDB, LL_INFO10000,
"Frame (stub) patch hit at offset 0x%x\n", offset));
// This is a stub patch. If it was a TRACE_FRAME_PUSH that
// got us here, then the stub's frame is pushed now, so we
// tell the frame to apply the real patch. If we got here
// via a TRACE_MGR_PUSH, however, then there is no frame
// and we tell the stub manager that generated the
// TRACE_MGR_PUSH to apply the real patch.
TraceDestination trace;
bool traceOk;
FramePointer frameFP;
PTR_BYTE traceManagerRetAddr = NULL;
if (patch->trace.GetTraceType() == TRACE_MGR_PUSH)
{
_ASSERTE(context != NULL);
CONTRACT_VIOLATION(GCViolation);
traceOk = g_pEEInterface->TraceManager(
thread,
patch->trace.GetStubManager(),
&trace,
context,
&traceManagerRetAddr);
// We don't hae an active frame here, so patch with a
// FP of NULL so anything will match.
//
// <REVISIT_TODO>@todo: should we take Esp out of the context?</REVISIT_TODO>
frameFP = LEAF_MOST_FRAME;
}
else
{
_ASSERTE(fSafeToDoStackTrace);
CONTRACT_VIOLATION(GCViolation); // TraceFrame GC-triggers
traceOk = g_pEEInterface->TraceFrame(thread,
thread->GetFrame(),
TRUE,
&trace,
&(info.m_activeFrame.registers));
frameFP = info.m_activeFrame.fp;
}
// Enable the JMC backstop for traditional steppers to catch us in case
// we didn't predict the call target properly.
EnableJMCBackStop(NULL);
if (!traceOk
|| !g_pEEInterface->FollowTrace(&trace)
|| !PatchTrace(&trace, frameFP,
(m_rgfMappingStop&STOP_UNMANAGED)?
(true):(false)))
{
//
// We can't set a patch in the frame -- we need
// to trap returning from this frame instead.
//
// Note: if we're in the TRACE_MGR_PUSH case from
// above, then we must place a patch where the
// TraceManager function told us to, since we can't
// actually unwind from here.
//
if (patch->trace.GetTraceType() != TRACE_MGR_PUSH)
{
_ASSERTE(fSafeToDoStackTrace);
LOG((LF_CORDB,LL_INFO10000,"TSO for non TRACE_MGR_PUSH case\n"));
TrapStepOut(&info);
}
else
{
LOG((LF_CORDB, LL_INFO10000,
"TSO for TRACE_MGR_PUSH case."));
// We'd better have a valid return address.
_ASSERTE(traceManagerRetAddr != NULL);
if (g_pEEInterface->IsManagedNativeCode(traceManagerRetAddr))
{
// Grab the jit info for the method.
DebuggerJitInfo *dji;
dji = g_pDebugger->GetJitInfoFromAddr((TADDR) traceManagerRetAddr);
MethodDesc * mdNative = (dji == NULL) ?
g_pEEInterface->GetNativeCodeMethodDesc(dac_cast<PCODE>(traceManagerRetAddr)) : dji->m_fd;
_ASSERTE(mdNative != NULL);
// Find the method that the return is to.
_ASSERTE(g_pEEInterface->GetFunctionAddress(mdNative) != NULL);
SIZE_T offsetRet = dac_cast<TADDR>(traceManagerRetAddr -
g_pEEInterface->GetFunctionAddress(mdNative));
// Place the patch.
AddBindAndActivateNativeManagedPatch(mdNative,
dji,
offsetRet,
LEAF_MOST_FRAME,
NULL);
LOG((LF_CORDB, LL_INFO10000,
"DS::TP: normally managed code AddPatch"
" in %s::%s, offset 0x%x\n",
mdNative->m_pszDebugClassName,
mdNative->m_pszDebugMethodName,
offsetRet));
}
else
{
// We're hitting this code path with MC++ assemblies
// that have an unmanaged entry point so the stub returns to CallDescrWorker.
_ASSERTE(g_pEEInterface->GetNativeCodeMethodDesc(dac_cast<PCODE>(patch->address))->IsILStub());
}
}
m_reason = STEP_NORMAL; //we tried to do a STEP_CALL, but since it didn't
//work, we're doing what amounts to a normal step.
LOG((LF_CORDB,LL_INFO10000,"DS 0x%x m_reason = STEP_NORMAL"
"(attempted call thru stub manager, SM didn't know where"
" we're going, so did a step out to original call\n",this));
}
else
{
m_reason = STEP_CALL;
}
EnableTraceCall(LEAF_MOST_FRAME);
EnableUnwind(m_fp);
return TPR_IGNORE;
}
else
{
// @todo - when would we hit this codepath?
// If we're not in managed, then we should have pushed a frame onto the Thread's frame chain,
// and thus we should still safely be able to do a stackwalk here.
_ASSERTE(fSafeToDoStackTrace);
if (DetectHandleInterceptors(&info) )
{
return TPR_IGNORE; //don't actually want to stop
}
LOG((LF_CORDB, LL_INFO10000,
"Unmanaged step patch hit at 0x%x\n", offset));
StackTraceTicket ticket(patch);
PrepareForSendEvent(ticket);
return TPR_TRIGGER;
}
} // end (module == NULL)
// If we're inside an interceptor but don't want to be,then we'll set a
// patch outside the current function.
_ASSERTE(fSafeToDoStackTrace);
if (DetectHandleInterceptors(&info) )
{
return TPR_IGNORE; //don't actually want to stop
}
LOG((LF_CORDB,LL_INFO10000, "DS: m_fp:0x%p, activeFP:0x%p fpExc:0x%p\n",
m_fp.GetSPValue(), info.m_activeFrame.fp.GetSPValue(), m_fpException.GetSPValue()));
if (IsInRange(offset, m_range, m_rangeCount, &info) ||
ShouldContinueStep( &info, offset))
{
LOG((LF_CORDB, LL_INFO10000,
"Intermediate step patch hit at 0x%x\n", offset));
if (!TrapStep(&info, m_stepIn))
TrapStepNext(&info);
EnableUnwind(m_fp);
return TPR_IGNORE;
}
else
{
LOG((LF_CORDB, LL_INFO10000, "Step patch hit at 0x%x\n", offset));
// For a JMC stepper, we have an additional constraint:
// skip non-user code. So if we're still in non-user code, then
// we've got to keep going
DebuggerMethodInfo * dmi = g_pDebugger->GetOrCreateMethodInfo(module, md);
if ((dmi != NULL) && DetectHandleNonUserCode(&info, dmi))
{
return TPR_IGNORE;
}
StackTraceTicket ticket(patch);
PrepareForSendEvent(ticket);
return TPR_TRIGGER;
}
}
// Return true if this should be skipped.
// For a non-jmc stepper, we don't care about non-user code, so we
// don't skip it and so we always return false.
bool DebuggerStepper::DetectHandleNonUserCode(ControllerStackInfo *info, DebuggerMethodInfo * pInfo)
{
LIMITED_METHOD_CONTRACT;
return false;
}
// For regular steppers, trace-call is just a trace-call.
void DebuggerStepper::EnablePolyTraceCall()
{
this->EnableTraceCall(LEAF_MOST_FRAME);
}
// Traditional steppers enable MethodEnter as a back-stop for step-in.
// We hope that the stub-managers will predict the step-in for us,
// but in case they don't the Method-Enter should catch us.
// MethodEnter is not fully correct for traditional steppers for a few reasons:
// - doesn't handle step-in to native
// - stops us *after* the prolog (a traditional stepper can stop us before the prolog).
// - only works for methods that have the JMC probe. That can exclude all optimized code.
void DebuggerStepper::TriggerMethodEnter(Thread * thread,
DebuggerJitInfo *dji,
const BYTE * ip,
FramePointer fp)
{
_ASSERTE(dji != NULL);
_ASSERTE(thread != NULL);
_ASSERTE(ip != NULL);
_ASSERTE(this->GetDCType() == DEBUGGER_CONTROLLER_STEPPER);
_ASSERTE(!IsFrozen());
MethodDesc * pDesc = dji->m_fd;
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper::TME, desc=%p, addr=%p\n",
pDesc, ip));
// JMC steppers won't stop in Lightweight delegates. Just return & keep executing.
if (pDesc->IsNoMetadata())
{
LOG((LF_CORDB, LL_INFO100000, "DJMCStepper::TME, skipping b/c it's lw-codegen\n"));
return;
}
// This is really just a heuristic. We don't want to trigger a JMC probe when we are
// executing in an IL stub, or in one of the marshaling methods called by the IL stub.
// The problem is that the IL stub can call into arbitrary code, including custom marshalers.
// In that case the user has to put a breakpoint to stop in the code.
if (g_pEEInterface->DetectHandleILStubs(thread))
{
return;
}
#ifdef _DEBUG
// To help trace down if a problem is related to a stubmanager,
// we add a knob that lets us skip the MethodEnter checks. This lets tests directly
// go against the Stub-managers w/o the MethodEnter check backstops.
int fSkip = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgSkipMEOnStep);
if (fSkip)
{
return;
}
// See EnableJMCBackStop() for details here. This check just makes sure that we don't fire
// the assert if we end up in the method we started in (which could happen if we trace call
// instructions before the JMC probe).
// m_StepInStartMethod may be null (if this step-in didn't start from managed code).
if ((m_StepInStartMethod != pDesc) &&
(!m_StepInStartMethod->IsLCGMethod()))
{
// Since normal step-in should stop us at the prolog, and TME is after the prolog,
// if a stub-manager did successfully find the address, we should get a TriggerPatch first
// at native offset 0 (before the prolog) and before we get the TME. That means if
// we do get the TME, then there was no stub-manager to find us.
SString sLog;
StubManager::DbgGetLog(&sLog);
// Assert b/c the Stub-manager should have caught us first.
// We don't want people relying on TriggerMethodEnter as the real implementation for Traditional Step-in
// (see above for reasons why). However, using TME will provide a bandage for the final retail product
// in cases where we are missing a stub-manager.
CONSISTENCY_CHECK_MSGF(false, (
"\nThe Stubmanagers failed to identify and trace a stub on step-in. The stub-managers for this code-path path need to be fixed.\n"
"See http://team/sites/clrdev/Devdocs/StubManagers.rtf for more information on StubManagers.\n"
"Stepper this=0x%p, startMethod='%s::%s'\n"
"---------------------------------\n"
"Stub manager log:\n%S"
"\n"
"The thread is now in managed method '%s::%s'.\n"
"---------------------------------\n",
this,
((m_StepInStartMethod == NULL) ? "unknown" : m_StepInStartMethod->m_pszDebugClassName),
((m_StepInStartMethod == NULL) ? "unknown" : m_StepInStartMethod->m_pszDebugMethodName),
sLog.GetUnicode(),
pDesc->m_pszDebugClassName, pDesc->m_pszDebugMethodName
));
}
#endif
// Place a patch to stopus.
// Don't bind to a particular AppDomain so that we can do a Cross-Appdomain step.
AddBindAndActivateNativeManagedPatch(pDesc,
dji,
CodeRegionInfo::GetCodeRegionInfo(dji, pDesc).AddressToOffset(ip),
fp,
NULL // AppDomain
);
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper::TME, after setting patch to stop\n"));
// Once we resume, we'll go hit that patch (duh, we patched our return address)
// Furthermore, we know the step will complete with reason = call, so set that now.
m_reason = STEP_CALL;
}
// We may have single-stepped over a return statement to land us up a frame.
// Or we may have single-stepped through a method.
// We never single-step into calls (we place a patch at the call destination).
bool DebuggerStepper::TriggerSingleStep(Thread *thread, const BYTE *ip)
{
LOG((LF_CORDB,LL_INFO10000,"DS:TSS this:0x%x, @ ip:0x%x\n", this, ip));
_ASSERTE(!IsFrozen());
// User break should only do a step-out and never actually need a singlestep flag.
_ASSERTE(GetDCType() != DEBUGGER_CONTROLLER_USER_BREAKPOINT);
//
// there's one weird case here - if the last instruction generated
// a hardware exception, we may be in lala land. If so, rely on the unwind
// handler to figure out what happened.
//
// <REVISIT_TODO>@todo this could be wrong when we have the incremental collector going</REVISIT_TODO>
//
if (!g_pEEInterface->IsManagedNativeCode(ip))
{
LOG((LF_CORDB,LL_INFO10000, "DS::TSS: not in managed code, Returning false (case 0)!\n"));
DisableSingleStep();
return false;
}
// If we EnC the method, we'll blast the function address,
// and so have to get it from teh DJI that we'll have. If
// we haven't gotten debugger info about a regular function, then
// we'll have to get the info from the EE, which will be valid
// since we're standing in the function at this point, and
// EnC couldn't have happened yet.
MethodDesc *fd = g_pEEInterface->GetNativeCodeMethodDesc((PCODE)ip);
SIZE_T offset;
DebuggerJitInfo *dji = g_pDebugger->GetJitInfoFromAddr((TADDR) ip);
offset = CodeRegionInfo::GetCodeRegionInfo(dji, fd).AddressToOffset(ip);
ControllerStackInfo info;
// Safe to stackwalk b/c we've already checked that our IP is in crawlable code.
StackTraceTicket ticket(ip);
info.GetStackInfo(ticket, GetThread(), LEAF_MOST_FRAME, NULL);
// This is a special case where we return from a managed method back to an IL stub. This can
// only happen if there's no more managed method frames closer to the root and we want to perform
// a step out, or if we step-next off the end of a method called by an IL stub. In either case,
// we'll get a single step in an IL stub, which we want to ignore. We also want to enable trace
// call here, just in case this IL stub is about to call the managed target (in the reverse interop case).
if (fd->IsILStub())
{
LOG((LF_CORDB,LL_INFO10000, "DS::TSS: not in managed code, Returning false (case 0)!\n"));
if (this->GetDCType() == DEBUGGER_CONTROLLER_STEPPER)
{
EnableTraceCall(info.m_activeFrame.fp);
}
else if (this->GetDCType() == DEBUGGER_CONTROLLER_JMC_STEPPER)
{
EnableMethodEnter();
}
DisableSingleStep();
return false;
}
DisableAll();
LOG((LF_CORDB,LL_INFO10000, "DS::TSS m_fp:0x%x, activeFP:0x%x fpExc:0x%x\n",
m_fp.GetSPValue(), info.m_activeFrame.fp.GetSPValue(), m_fpException.GetSPValue()));
if (DetectHandleLCGMethods((PCODE)ip, fd, &info))
{
return false;
}
if (IsInRange(offset, m_range, m_rangeCount, &info) ||
ShouldContinueStep( &info, offset))
{
if (!TrapStep(&info, m_stepIn))
TrapStepNext(&info);
EnableUnwind(m_fp);
LOG((LF_CORDB,LL_INFO10000, "DS::TSS: Returning false Case 1!\n"));
return false;
}
else
{
LOG((LF_CORDB,LL_INFO10000, "DS::TSS: Returning true Case 2 for reason STEP_%02x!\n", m_reason));
// @todo - when would a single-step (not a patch) land us in user-code?
// For a JMC stepper, we have an additional constraint:
// skip non-user code. So if we're still in non-user code, then
// we've got to keep going
DebuggerMethodInfo * dmi = g_pDebugger->GetOrCreateMethodInfo(fd->GetModule(), fd->GetMemberDef());
if ((dmi != NULL) && DetectHandleNonUserCode(&info, dmi))
return false;
PrepareForSendEvent(ticket);
return true;
}
}
void DebuggerStepper::TriggerTraceCall(Thread *thread, const BYTE *ip)
{
LOG((LF_CORDB,LL_INFO10000,"DS:TTC this:0x%x, @ ip:0x%x\n",this,ip));
TraceDestination trace;
if (IsFrozen())
{
LOG((LF_CORDB,LL_INFO10000,"DS:TTC exit b/c of Frozen\n"));
return;
}
// This is really just a heuristic. We don't want to trigger a JMC probe when we are
// executing in an IL stub, or in one of the marshaling methods called by the IL stub.
// The problem is that the IL stub can call into arbitrary code, including custom marshalers.
// In that case the user has to put a breakpoint to stop in the code.
if (g_pEEInterface->DetectHandleILStubs(thread))
{
return;
}
if (g_pEEInterface->TraceStub(ip, &trace)
&& g_pEEInterface->FollowTrace(&trace)
&& PatchTrace(&trace, LEAF_MOST_FRAME,
(m_rgfMappingStop&STOP_UNMANAGED)?(true):(false)))
{
// !!! We really want to know ahead of time if PatchTrace will succeed.
DisableAll();
PatchTrace(&trace, LEAF_MOST_FRAME, (m_rgfMappingStop&STOP_UNMANAGED)?
(true):(false));
// If we're triggering a trace call, and we're following a trace into either managed code or unjitted managed
// code, then we need to update our stepper's reason to STEP_CALL to reflect the fact that we're going to land
// into a new function because of a call.
if ((trace.GetTraceType() == TRACE_UNJITTED_METHOD) || (trace.GetTraceType() == TRACE_MANAGED))
{
m_reason = STEP_CALL;
}
EnableUnwind(m_fp);
LOG((LF_CORDB, LL_INFO10000, "DS::TTC potentially a step call!\n"));
}
}
void DebuggerStepper::TriggerUnwind(Thread *thread,
MethodDesc *fd, DebuggerJitInfo * pDJI, SIZE_T offset,
FramePointer fp,
CorDebugStepReason unwindReason)
{
CONTRACTL
{
SO_NOT_MAINLINE;
THROWS; // from GetJitInfo
GC_NOTRIGGER; // don't send IPC events
MODE_COOPERATIVE; // TriggerUnwind always is coop
PRECONDITION(!IsDbgHelperSpecialThread());
PRECONDITION(fd->IsDynamicMethod() || (pDJI != NULL));
}
CONTRACTL_END;
LOG((LF_CORDB,LL_INFO10000,"DS::TU this:0x%p, in %s::%s, offset 0x%p "
"frame:0x%p unwindReason:0x%x\n", this, fd->m_pszDebugClassName,
fd->m_pszDebugMethodName, offset, fp.GetSPValue(), unwindReason));
_ASSERTE(unwindReason == STEP_EXCEPTION_FILTER || unwindReason == STEP_EXCEPTION_HANDLER);
if (IsFrozen())
{
LOG((LF_CORDB,LL_INFO10000,"DS:TTC exit b/c of Frozen\n"));
return;
}
if (IsCloserToRoot(fp, GetUnwind()))
{
// Handler is in a parent frame . For all steps (in,out,over)
// we want to stop in the handler.
// This will be like a Step Out, so we don't need any range.
ResetRange();
}
else
{
// Handler/Filter is in the same frame as the stepper
// For a step-in/over, we want to patch the handler/filter.
// But for a step-out, we want to just continue executing (and don't change
// the step-reason either).
if (m_eMode == cStepOut)
{
LOG((LF_CORDB, LL_INFO10000, "DS::TU Step-out, returning for same-frame case.\n"));
return;
}
}
// Remember the origin of the exception, so that if the step looks like
// it's going to complete in a different frame, but the code comes from the
// same frame as the one we're in, we won't stop twice in the "same" range
m_fpException = fp;
m_fdException = fd;
//
// An exception is exiting the step region. Set a patch on
// the filter/handler.
//
DisableAll();
BOOL fOk;
fOk = AddBindAndActivateNativeManagedPatch(fd, pDJI, offset, LEAF_MOST_FRAME, NULL);
// Since we're unwinding to an already executed method, the method should already
// be jitted and placing the patch should work.
CONSISTENCY_CHECK_MSGF(fOk, ("Failed to place patch at TriggerUnwind.\npThis=0x%p md=0x%p, native offset=0x%x\n", this, fd, offset));
LOG((LF_CORDB,LL_INFO100000,"Step reason:%s\n", unwindReason==STEP_EXCEPTION_FILTER
? "STEP_EXCEPTION_FILTER":"STEP_EXCEPTION_HANDLER"));
m_reason = unwindReason;
}
// Prepare for sending an event.
// This is called 1:1 w/ SendEvent, but this guy can be called in a GC_TRIGGERABLE context
// whereas SendEvent is pretty strict.
// Caller ensures that it's safe to run a stack trace.
void DebuggerStepper::PrepareForSendEvent(StackTraceTicket ticket)
{
#ifdef _DEBUG
_ASSERTE(!m_fReadyToSend);
m_fReadyToSend = true;
#endif
LOG((LF_CORDB, LL_INFO10000, "DS::SE m_fpStepInto:0x%x\n", m_fpStepInto.GetSPValue()));
if (m_fpStepInto != LEAF_MOST_FRAME)
{
ControllerStackInfo csi;
csi.GetStackInfo(ticket, GetThread(), LEAF_MOST_FRAME, NULL);
if (csi.m_targetFrameFound &&
#if !defined(WIN64EXCEPTIONS)
IsCloserToRoot(m_fpStepInto, csi.m_activeFrame.fp)
#else
IsCloserToRoot(m_fpStepInto, (csi.m_activeFrame.IsNonFilterFuncletFrame() ? csi.m_returnFrame.fp : csi.m_activeFrame.fp))
#endif // WIN64EXCEPTIONS
)
{
m_reason = STEP_CALL;
LOG((LF_CORDB, LL_INFO10000, "DS::SE this:0x%x STEP_CALL!\n", this));
}
#ifdef _DEBUG
else
{
LOG((LF_CORDB, LL_INFO10000, "DS::SE this:0x%x not a step call!\n", this));
}
#endif
}
#ifdef _DEBUG
// Steppers should only stop in interesting code.
if (this->GetDCType() == DEBUGGER_CONTROLLER_JMC_STEPPER)
{
// If we're at either a patch or SS, we'll have a context.
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(GetThread());
if (context == NULL)
{
void * pIP = CORDbgGetIP(reinterpret_cast<DT_CONTEXT *>(context));
DebuggerJitInfo * dji = g_pDebugger->GetJitInfoFromAddr((TADDR) pIP);
DebuggerMethodInfo * dmi = NULL;
if (dji != NULL)
{
dmi = dji->m_methodInfo;
CONSISTENCY_CHECK_MSGF(dmi->IsJMCFunction(), ("JMC stepper %p stopping in non-jmc method, MD=%p, '%s::%s'",
this, dji->m_fd, dji->m_fd->m_pszDebugClassName, dji->m_fd->m_pszDebugMethodName));
}
}
}
#endif
}
bool DebuggerStepper::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
// We practically should never have a step interupted by SetIp.
// We'll still go ahead and send the Step-complete event because we've already
// deactivated our triggers by now and we haven't placed any new patches to catch us.
// We assert here because we don't believe we'll ever be able to hit this scenario.
// This is technically an issue, but we consider it benign enough to leave in.
_ASSERTE(!fIpChanged || !"Stepper interupted by SetIp");
LOG((LF_CORDB, LL_INFO10000, "DS::SE m_fpStepInto:0x%x\n", m_fpStepInto.GetSPValue()));
_ASSERTE(m_fReadyToSend);
_ASSERTE(GetThread() == thread);
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(thread);
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
// We need to send the stepper and delete the controller because our stepper
// no longer has any patches or other triggers that will let it send the step-complete event.
g_pDebugger->SendStep(thread, context, this, m_reason);
this->Delete();
#ifdef _DEBUG
// Now that we've sent the event, we can stop recording information.
StubManager::DbgFinishLog();
#endif
return true;
}
void DebuggerStepper::ResetRange()
{
if (m_range)
{
TRACE_FREE(m_range);
DeleteInteropSafe(m_range);
m_range = NULL;
}
}
//-----------------------------------------------------------------------------
// Return true if this stepper is alive, but frozen. (we freeze when the stepper
// enters a nested func-eval).
//-----------------------------------------------------------------------------
bool DebuggerStepper::IsFrozen()
{
return (m_cFuncEvalNesting > 0);
}
//-----------------------------------------------------------------------------
// Returns true if this stepper is 'dead' - which happens if a non-frozen stepper
// gets a func-eval exit.
//-----------------------------------------------------------------------------
bool DebuggerStepper::IsDead()
{
return (m_cFuncEvalNesting < 0);
}
// * ------------------------------------------------------------------------
// * DebuggerJMCStepper routines
// * ------------------------------------------------------------------------
DebuggerJMCStepper::DebuggerJMCStepper(Thread *thread,
CorDebugUnmappedStop rgfMappingStop,
CorDebugIntercept interceptStop,
AppDomain *appDomain) :
DebuggerStepper(thread, rgfMappingStop, interceptStop, appDomain)
{
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper ctor, this=%p\n", this));
}
DebuggerJMCStepper::~DebuggerJMCStepper()
{
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper dtor, this=%p\n", this));
}
// If we're a JMC stepper, then don't stop in non-user code.
bool DebuggerJMCStepper::IsInterestingFrame(FrameInfo * pFrame)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
DebuggerMethodInfo *pInfo = pFrame->GetMethodInfoFromFrameOrThrow();
_ASSERTE(pInfo != NULL); // throws on failure
bool fIsUserCode = pInfo->IsJMCFunction();
LOG((LF_CORDB, LL_INFO1000000, "DS::TSO, frame '%s::%s' is '%s' code\n",
pFrame->DbgGetClassName(), pFrame->DbgGetMethodName(),
fIsUserCode ? "user" : "non-user"));
return fIsUserCode;
}
// A JMC stepper's step-next stops at the next thing of code run.
// This may be a Step-Out, or any User code called before that.
// A1 -> B1 -> { A2, B2 -> B3 -> A3}
// So TrapStepNex at end of A2 should land us in A3.
void DebuggerJMCStepper::TrapStepNext(ControllerStackInfo *info)
{
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper::TrapStepNext, this=%p\n", this));
EnableMethodEnter();
// This will place a patch up the stack and set m_reason = STEP_RETURN.
// If we end up hitting JMC before that patch, we'll hit TriggerMethodEnter
// and that will set our reason to STEP_CALL.
TrapStepOut(info);
}
// ip - target address for call instruction
bool DebuggerJMCStepper::TrapStepInHelper(
ControllerStackInfo * pInfo,
const BYTE * ipCallTarget,
const BYTE * ipNext,
bool fCallingIntoFunclet)
{
#ifndef WIN64EXCEPTIONS
// There are no funclets on x86.
_ASSERTE(!fCallingIntoFunclet);
#endif
// If we are calling into a funclet, then we can't rely on the JMC probe to stop us because there are no
// JMC probes in funclets. Instead, we have to perform a traditional step-in here.
if (fCallingIntoFunclet)
{
TraceDestination td;
td.InitForManaged(reinterpret_cast<PCODE>(ipCallTarget));
PatchTrace(&td, LEAF_MOST_FRAME, false);
// If this succeeds, then we still need to put a patch at the return address. This is done below.
// If this fails, then we definitely need to put a patch at the return address to trap the thread.
// So in either case, we have to execute the rest of this function.
}
MethodDesc * pDesc = pInfo->m_activeFrame.md;
DebuggerJitInfo *dji = NULL;
// We may not have a DJI if we're in an attach case. We should still be able to do a JMC-step in though.
// So NULL is ok here.
dji = g_pDebugger->GetJitInfo(pDesc, (const BYTE*) ipNext);
// Place patch after call, which is at ipNext. Note we don't need an IL->Native map here
// since we disassembled native code to find the ip after the call.
SIZE_T offset = CodeRegionInfo::GetCodeRegionInfo(dji, pDesc).AddressToOffset(ipNext);
LOG((LF_CORDB, LL_INFO100000, "DJMCStepper::TSIH, at '%s::%s', calling=0x%p, next=0x%p, offset=%d\n",
pDesc->m_pszDebugClassName,
pDesc->m_pszDebugMethodName,
ipCallTarget, ipNext,
offset));
// Place a patch at the native address (inside the managed method).
AddBindAndActivateNativeManagedPatch(pInfo->m_activeFrame.md,
dji,
offset,
pInfo->m_returnFrame.fp,
NULL);
EnableMethodEnter();
// Return true means that we want to let the stepper run free. It will either
// hit the patch after the call instruction or it will hit a TriggerMethodEnter.
return true;
}
// For JMC-steppers, we don't enable trace-call; we enable Method-Enter.
void DebuggerJMCStepper::EnablePolyTraceCall()
{
_ASSERTE(!IsFrozen());
this->EnableMethodEnter();
}
// Return true if this is non-user code. This means we've setup the proper patches &
// triggers, etc and so we expect the controller to just run free.
// This is called when all other stepping criteria are met and we're about to
// send a step-complete. For JMC, this is when we see if we're in non-user code
// and if so, continue stepping instead of send the step complete.
// Return false if this is user-code.
bool DebuggerJMCStepper::DetectHandleNonUserCode(ControllerStackInfo *pInfo, DebuggerMethodInfo * dmi)
{
_ASSERTE(dmi != NULL);
bool fIsUserCode = dmi->IsJMCFunction();
if (!fIsUserCode)
{
LOG((LF_CORDB, LL_INFO10000, "JMC stepper stopped in non-user code, continuing.\n"));
// Not-user code, we want to skip through this.
// We may be here while trying to step-out.
// Step-out just means stop at the first interesting frame above us.
// So JMC TrapStepOut won't patch a non-user frame.
// But if we're skipping over other stuff (prolog, epilog, interceptors,
// trace calls), then we may still be in the middle of non-user
//_ASSERTE(m_eMode != cStepOut);
if (m_eMode == cStepOut)
{
TrapStepOut(pInfo);
}
else if (m_stepIn)
{
EnableMethodEnter();
TrapStepOut(pInfo);
// Run until we hit the next thing of managed code.
} else {
// Do a traditional step-out since we just want to go up 1 frame.
TrapStepOut(pInfo, true); // force trad step out.
// If we're not in the original frame anymore, then
// If we did a Step-over at the end of a method, and that did a single-step over the return
// then we may already be in our parent frame. In that case, we also want to behave
// like a step-in and TriggerMethodEnter.
if (this->m_fp != pInfo->m_activeFrame.fp)
{
// If we're a step-over, then we should only be stopped in a parent frame.
_ASSERTE(m_stepIn || IsCloserToLeaf(this->m_fp, pInfo->m_activeFrame.fp));
EnableMethodEnter();
}
// Step-over shouldn't stop in a frame below us in the same callstack.
// So we do a tradional step-out of our current frame, which guarantees
// that. After that, we act just like a step-in.
m_stepIn = true;
}
EnableUnwind(m_fp);
// Must keep going...
return true;
}
return false;
}
// Dispatched right after the prolog of a JMC function.
// We may be blocking the GC here, so let's be fast!
void DebuggerJMCStepper::TriggerMethodEnter(Thread * thread,
DebuggerJitInfo *dji,
const BYTE * ip,
FramePointer fp)
{
_ASSERTE(dji != NULL);
_ASSERTE(thread != NULL);
_ASSERTE(ip != NULL);
_ASSERTE(!IsFrozen());
MethodDesc * pDesc = dji->m_fd;
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper::TME, desc=%p, addr=%p\n",
pDesc, ip));
// JMC steppers won't stop in Lightweight delegates. Just return & keep executing.
if (pDesc->IsNoMetadata())
{
LOG((LF_CORDB, LL_INFO100000, "DJMCStepper::TME, skipping b/c it's lw-codegen\n"));
return;
}
// Is this user code?
DebuggerMethodInfo * dmi = dji->m_methodInfo;
bool fIsUserCode = dmi->IsJMCFunction();
LOG((LF_CORDB, LL_INFO100000, "DJMCStepper::TME, '%s::%s' is '%s' code\n",
pDesc->m_pszDebugClassName,
pDesc->m_pszDebugMethodName,
fIsUserCode ? "user" : "non-user"
));
// If this isn't user code, then just return and continue executing.
if (!fIsUserCode)
return;
// MethodEnter is only enabled when we want to stop in a JMC function.
// And that's where we are now. So patch the ip and resume.
// The stepper will hit the patch, and stop.
// It's a good thing we have the fp passed in, because we have no other
// way of getting it. We can't do a stack trace here (the stack trace
// would start at the last pushed Frame, which miss a lot of managed
// frames).
// Don't bind to a particular AppDomain so that we can do a Cross-Appdomain step.
AddBindAndActivateNativeManagedPatch(pDesc,
dji,
CodeRegionInfo::GetCodeRegionInfo(dji, pDesc).AddressToOffset(ip),
fp,
NULL // AppDomain
);
LOG((LF_CORDB, LL_INFO10000, "DJMCStepper::TME, after setting patch to stop\n"));
// Once we resume, we'll go hit that patch (duh, we patched our return address)
// Furthermore, we know the step will complete with reason = call, so set that now.
m_reason = STEP_CALL;
}
//-----------------------------------------------------------------------------
// Helper to convert form an EE Frame's interception enum to a CorDebugIntercept
// bitfield.
// The intercept value in EE Frame's is a 0-based enumeration (not a bitfield).
// The intercept value for ICorDebug is a bitfied.
//-----------------------------------------------------------------------------
CorDebugIntercept ConvertFrameBitsToDbg(Frame::Interception i)
{
_ASSERTE(i >= 0 && i < Frame::INTERCEPTION_COUNT);
// Since the ee frame is a 0-based enum, we can just use a map.
const CorDebugIntercept map[Frame::INTERCEPTION_COUNT] =
{
// ICorDebug EE Frame
INTERCEPT_NONE, // INTERCEPTION_NONE,
INTERCEPT_CLASS_INIT, // INTERCEPTION_CLASS_INIT
INTERCEPT_EXCEPTION_FILTER, // INTERCEPTION_EXCEPTION
INTERCEPT_CONTEXT_POLICY, // INTERCEPTION_CONTEXT
INTERCEPT_SECURITY, // INTERCEPTION_SECURITY
INTERCEPT_INTERCEPTION, // INTERCEPTION_OTHER
};
return map[i];
}
//-----------------------------------------------------------------------------
// This is a helper class to do a stack walk over a certain range and find all the interceptors.
// This allows a JMC stepper to see if there are any interceptors it wants to skip over (though
// there's nothing JMC-specific about this).
// Note that we only want to walk the stack range that the stepper is operating in.
// That's because we don't care about interceptors that happened _before_ the
// stepper was created.
//-----------------------------------------------------------------------------
class InterceptorStackInfo
{
public:
#ifdef _DEBUG
InterceptorStackInfo()
{
// since this ctor just nulls out fpTop (which is already done in Init), we
// only need it in debug.
m_fpTop = LEAF_MOST_FRAME;
}
#endif
// Get a CorDebugIntercept bitfield that contains a bit for each type of interceptor
// if that interceptor is present within our stack-range.
// Stack range is from leaf-most up to and including fp
CorDebugIntercept GetInterceptorsInRange()
{
_ASSERTE(m_fpTop != LEAF_MOST_FRAME || !"Must call Init first");
return (CorDebugIntercept) m_bits;
}
// Prime the stackwalk.
void Init(FramePointer fpTop, Thread *thread, CONTEXT *pContext, BOOL contextValid)
{
_ASSERTE(fpTop != LEAF_MOST_FRAME);
_ASSERTE(thread != NULL);
m_bits = 0;
m_fpTop = fpTop;
LOG((LF_CORDB,LL_EVERYTHING, "ISI::Init - fpTop=%p, thread=%p, pContext=%p, contextValid=%d\n",
fpTop.GetSPValue(), thread, pContext, contextValid));
int result;
result = DebuggerWalkStack(
thread,
LEAF_MOST_FRAME,
pContext,
contextValid,
WalkStack,
(void *) this,
FALSE
);
}
protected:
// This is a bitfield of all the interceptors we encounter in our stack-range
int m_bits;
// This is the top of our stack range.
FramePointer m_fpTop;
static StackWalkAction WalkStack(FrameInfo *pInfo, void *data)
{
_ASSERTE(pInfo != NULL);
_ASSERTE(data != NULL);
InterceptorStackInfo * pThis = (InterceptorStackInfo*) data;
// If there's an interceptor frame here, then set those
// bits in our bitfield.
Frame::Interception i = Frame::INTERCEPTION_NONE;
Frame * pFrame = pInfo->frame;
if ((pFrame != NULL) && (pFrame != FRAME_TOP))
{
i = pFrame->GetInterception();
if (i != Frame::INTERCEPTION_NONE)
{
pThis->m_bits |= (int) ConvertFrameBitsToDbg(i);
}
}
else if (pInfo->HasMethodFrame())
{
// Check whether we are executing in a class constructor.
_ASSERTE(pInfo->md != NULL);
// Need to be careful about an off-by-one error here! Imagine your stack looks like:
// Foo.DoSomething()
// Foo..cctor <--- step starts/ends in here
// Bar.Bar();
//
// and your code looks like this:
// Foo..cctor()
// {
// Foo.DoSomething(); <-- JMC step started here
// int x = 1; <-- step ends here
// }
// This stackwalk covers the inclusive range [Foo..cctor, Foo.DoSomething()] so we will see
// the static cctor in this walk. However executing inside a static class constructor does not
// count as an interceptor. You must start the step outside the static constructor and then call
// into it to have an interceptor. Therefore only static constructors that aren't the outermost
// frame should be treated as interceptors.
if (pInfo->md->IsClassConstructor() && (pInfo->fp != pThis->m_fpTop))
{
// We called a class constructor, add the appropriate flag
pThis->m_bits |= (int) INTERCEPT_CLASS_INIT;
}
}
LOG((LF_CORDB,LL_EVERYTHING,"ISI::WS- Frame=%p, fp=%p, Frame bits=%x, Cor bits=0x%x\n", pInfo->frame, pInfo->fp.GetSPValue(), i, pThis->m_bits));
// We can stop once we hit the top frame.
if (pInfo->fp == pThis->m_fpTop)
{
return SWA_ABORT;
}
else
{
return SWA_CONTINUE;
}
}
};
// Skip interceptors for JMC steppers.
// Return true if we patch something (and thus should keep stepping)
// Return false if we're done.
bool DebuggerJMCStepper::DetectHandleInterceptors(ControllerStackInfo * info)
{
LOG((LF_CORDB,LL_INFO10000,"DJMCStepper::DHI: Start DetectHandleInterceptors\n"));
// For JMC, we could stop very far way from an interceptor.
// So we have to do a stack walk to search for interceptors...
// If we find any in our stack range (from m_fp ... current fp), then we just do a trap-step-next.
// Note that this logic should also work for regular steppers, but we've left that in
// as to keep that code-path unchanged.
// ControllerStackInfo only gives us the bottom 2 frames on the stack, so we ignore it and
// have to do our own stack walk.
// @todo - for us to properly skip filters, we need to make sure that filters show up in our chains.
InterceptorStackInfo info2;
CONTEXT *context = g_pEEInterface->GetThreadFilterContext(this->GetThread());
CONTEXT tempContext;
_ASSERTE(!ISREDIRECTEDTHREAD(this->GetThread()));
if (context == NULL)
{
info2.Init(this->m_fp, this->GetThread(), &tempContext, FALSE);
}
else
{
info2.Init(this->m_fp, this->GetThread(), context, TRUE);
}
// The following casts are safe on WIN64 platforms.
int iOnStack = (int) info2.GetInterceptorsInRange();
int iSkip = ~((int) m_rgfInterceptStop);
LOG((LF_CORDB,LL_INFO10000,"DJMCStepper::DHI: iOnStack=%x, iSkip=%x\n", iOnStack, iSkip));
// If the bits on the stack contain any interceptors we want to skip, then we need to keep going.
if ((iOnStack & iSkip) != 0)
{
LOG((LF_CORDB,LL_INFO10000,"DJMCStepper::DHI: keep going!\n"));
TrapStepNext(info);
EnableUnwind(m_fp);
return true;
}
LOG((LF_CORDB,LL_INFO10000,"DJMCStepper::DHI: Done!!\n"));
return false;
}
// * ------------------------------------------------------------------------
// * DebuggerThreadStarter routines
// * ------------------------------------------------------------------------
DebuggerThreadStarter::DebuggerThreadStarter(Thread *thread)
: DebuggerController(thread, NULL)
{
LOG((LF_CORDB, LL_INFO1000, "DTS::DTS: this:0x%x Thread:0x%x\n",
this, thread));
// Check to make sure we only have 1 ThreadStarter on a given thread. (Inspired by NDPWhidbey issue 16888)
#if defined(_DEBUG)
EnsureUniqueThreadStarter(this);
#endif
}
// TP_RESULT DebuggerThreadStarter::TriggerPatch() If we're in a
// stub (module==NULL&&managed) then do a PatchTrace up the stack &
// return false. Otherwise DisableAll & return
// true
TP_RESULT DebuggerThreadStarter::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
Module *module = patch->key.module;
BOOL managed = patch->IsManagedPatch();
LOG((LF_CORDB,LL_INFO1000, "DebuggerThreadStarter::TriggerPatch for thread 0x%x\n", Debugger::GetThreadIdHelper(thread)));
if (module == NULL && managed)
{
// This is a stub patch. If it was a TRACE_FRAME_PUSH that got us here, then the stub's frame is pushed now, so
// we tell the frame to apply the real patch. If we got here via a TRACE_MGR_PUSH, however, then there is no
// frame and we go back to the stub manager that generated the stub for where to patch next.
TraceDestination trace;
bool traceOk;
if (patch->trace.GetTraceType() == TRACE_MGR_PUSH)
{
BYTE *dummy = NULL;
CONTEXT *context = GetManagedLiveCtx(thread);
CONTRACT_VIOLATION(GCViolation);
traceOk = g_pEEInterface->TraceManager(thread, patch->trace.GetStubManager(), &trace, context, &dummy);
}
else if ((patch->trace.GetTraceType() == TRACE_FRAME_PUSH) && (thread->GetFrame()->IsTransitionToNativeFrame()))
{
// If we've got a frame that is transitioning to native, there's no reason to try to keep tracing. So we
// bail early and save ourselves some effort. This also works around a problem where we deadlock trying to
// do too much work to determine the destination of a ComPlusMethodFrame. (See issue 87103.)
//
// Note: trace call is still enabled, so we can just ignore this patch and wait for trace call to fire
// again...
return TPR_IGNORE;
}
else
{
// It's questionable whether Trace_Frame_Push is actually safe or not.
ControllerStackInfo csi;
StackTraceTicket ticket(patch);
csi.GetStackInfo(ticket, thread, LEAF_MOST_FRAME, NULL);
CONTRACT_VIOLATION(GCViolation); // TraceFrame GC-triggers
traceOk = g_pEEInterface->TraceFrame(thread, thread->GetFrame(), TRUE, &trace, &(csi.m_activeFrame.registers));
}
if (traceOk && g_pEEInterface->FollowTrace(&trace))
{
PatchTrace(&trace, LEAF_MOST_FRAME, TRUE);
}
return TPR_IGNORE;
}
else
{
// We've hit user code; trigger our event.
DisableAll();
{
// Give the helper thread a chance to get ready. The temporary helper can't handle
// execution control well, and the RS won't do any execution control until it gets a
// create Thread event, which it won't get until here.
// So now's our best time to wait for the real helper thread.
g_pDebugger->PollWaitingForHelper();
}
return TPR_TRIGGER;
}
}
void DebuggerThreadStarter::TriggerTraceCall(Thread *thread, const BYTE *ip)
{
LOG((LF_CORDB, LL_EVERYTHING, "DTS::TTC called\n"));
#ifdef DEBUGGING_SUPPORTED
if (thread->GetDomain()->IsDebuggerAttached())
{
TraceDestination trace;
if (g_pEEInterface->TraceStub(ip, &trace) && g_pEEInterface->FollowTrace(&trace))
{
PatchTrace(&trace, LEAF_MOST_FRAME, true);
}
}
#endif //DEBUGGING_SUPPORTED
}
bool DebuggerThreadStarter::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
// This SendEvent can't be interupted by a SetIp because until the client
// gets a ThreadStarter event, it doesn't even know the thread exists, so
// it certainly can't change its ip.
_ASSERTE(!fIpChanged);
LOG((LF_CORDB, LL_INFO10000, "DTS::SE: in DebuggerThreadStarter's SendEvent\n"));
// Send the thread started event.
g_pDebugger->ThreadStarted(thread);
// We delete this now because its no longer needed. We can call
// delete here because the queued count is above 0. This object
// will really be deleted when its dequeued shortly after this
// call returns.
Delete();
return true;
}
// * ------------------------------------------------------------------------
// * DebuggerUserBreakpoint routines
// * ------------------------------------------------------------------------
bool DebuggerUserBreakpoint::IsFrameInDebuggerNamespace(FrameInfo * pFrame)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
// Steppers ignore internal frames, so should only be called on real frames.
_ASSERTE(pFrame->HasMethodFrame());
// Now get the namespace of the active frame
MethodDesc *pMD = pFrame->md;
if (pMD != NULL)
{
MethodTable * pMT = pMD->GetMethodTable();
LPCUTF8 szNamespace = NULL;
LPCUTF8 szClassName = pMT->GetFullyQualifiedNameInfo(&szNamespace);
if (szClassName != NULL && szNamespace != NULL)
{
MAKE_WIDEPTR_FROMUTF8(wszNamespace, szNamespace); // throw
MAKE_WIDEPTR_FROMUTF8(wszClassName, szClassName);
if (wcscmp(wszClassName, W("Debugger")) == 0 &&
wcscmp(wszNamespace, W("System.Diagnostics")) == 0)
{
// This will continue stepping
return true;
}
}
}
return false;
}
// Helper check if we're directly in a dynamic method (ignoring any chain goo
// or stuff in the Debugger namespace.
class IsLeafFrameDynamic
{
protected:
static StackWalkAction WalkStackWrapper(FrameInfo *pInfo, void *data)
{
IsLeafFrameDynamic * pThis = reinterpret_cast<IsLeafFrameDynamic*> (data);
return pThis->WalkStack(pInfo);
}
StackWalkAction WalkStack(FrameInfo *pInfo)
{
_ASSERTE(pInfo != NULL);
// A FrameInfo may have both Method + Chain rolled into one.
if (!pInfo->HasMethodFrame() && !pInfo->HasStubFrame())
{
// We're a chain. Ignore it and keep looking.
return SWA_CONTINUE;
}
// So now this is the first non-chain, non-Debugger namespace frame.
// LW frames don't have a name, so we check if it's LW first.
if (pInfo->eStubFrameType == STUBFRAME_LIGHTWEIGHT_FUNCTION)
{
m_fInLightWeightMethod = true;
return SWA_ABORT;
}
// Ignore Debugger.Break() frames.
// All Debugger.Break calls will have this on the stack.
if (DebuggerUserBreakpoint::IsFrameInDebuggerNamespace(pInfo))
{
return SWA_CONTINUE;
}
// We've now determined leafmost thing, so stop stackwalking.
_ASSERTE(m_fInLightWeightMethod == false);
return SWA_ABORT;
}
bool m_fInLightWeightMethod;
// Need this context to do stack trace.
CONTEXT m_tempContext;
public:
// On success, copies the leafmost non-chain frameinfo (including stubs) for the current thread into pInfo
// and returns true.
// On failure, returns false.
// Return true on success.
bool DoCheck(IN Thread * pThread)
{
CONTRACTL
{
GC_TRIGGERS;
THROWS;
MODE_ANY;
PRECONDITION(CheckPointer(pThread));
}
CONTRACTL_END;
m_fInLightWeightMethod = false;
DebuggerWalkStack(
pThread,
LEAF_MOST_FRAME,
&m_tempContext, false,
WalkStackWrapper,
(void *) this,
TRUE // includes everything
);
// We don't care whether the stackwalk succeeds or not because the
// callback sets our status via this field either way, so just return it.
return m_fInLightWeightMethod;
};
};
// Handle a Debug.Break() notification.
// This may create a controller to step-out out the Debug.Break() call (so that
// we appear stopped at the callsite).
// If we can't step-out (eg, we're directly in a dynamic method), then send
// the debug event immediately.
void DebuggerUserBreakpoint::HandleDebugBreak(Thread * pThread)
{
bool fDoStepOut = true;
// If the leaf frame is not a LW method, then step-out.
IsLeafFrameDynamic info;
fDoStepOut = !info.DoCheck(pThread);
if (fDoStepOut)
{
// Create a controller that will step out for us.
new (interopsafe) DebuggerUserBreakpoint(pThread);
}
else
{
// Send debug event immediately.
g_pDebugger->SendUserBreakpointAndSynchronize(pThread);
}
}
DebuggerUserBreakpoint::DebuggerUserBreakpoint(Thread *thread)
: DebuggerStepper(thread, (CorDebugUnmappedStop) (STOP_ALL & ~STOP_UNMANAGED), INTERCEPT_ALL, NULL)
{
// Setup a step out from the current frame (which we know is
// unmanaged, actually...)
// This happens to be safe, but it's a very special case (so we have a special case ticket)
// This is called while we're live (so no filter context) and from the fcall,
// and we pushed a HelperMethodFrame to protect us. We also happen to know that we have
// done anything illegal or dangerous since then.
StackTraceTicket ticket(this);
StepOut(LEAF_MOST_FRAME, ticket);
}
// Is this frame interesting?
// Use this to skip all code in the namespace "Debugger.Diagnostics"
bool DebuggerUserBreakpoint::IsInterestingFrame(FrameInfo * pFrame)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
return !IsFrameInDebuggerNamespace(pFrame);
}
bool DebuggerUserBreakpoint::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
// See DebuggerStepper::SendEvent for why we assert here.
// This is technically an issue, but it's too benign to fix.
_ASSERTE(!fIpChanged);
LOG((LF_CORDB, LL_INFO10000,
"DUB::SE: in DebuggerUserBreakpoint's SendEvent\n"));
// Send the user breakpoint event.
g_pDebugger->SendRawUserBreakpoint(thread);
// We delete this now because its no longer needed. We can call
// delete here because the queued count is above 0. This object
// will really be deleted when its dequeued shortly after this
// call returns.
Delete();
return true;
}
// * ------------------------------------------------------------------------
// * DebuggerFuncEvalComplete routines
// * ------------------------------------------------------------------------
DebuggerFuncEvalComplete::DebuggerFuncEvalComplete(Thread *thread,
void *dest)
: DebuggerController(thread, NULL)
{
#ifdef _TARGET_ARM_
m_pDE = reinterpret_cast<DebuggerEvalBreakpointInfoSegment*>(((DWORD)dest) & ~THUMB_CODE)->m_associatedDebuggerEval;
#else
m_pDE = reinterpret_cast<DebuggerEvalBreakpointInfoSegment*>(dest)->m_associatedDebuggerEval;
#endif
// Add an unmanaged patch at the destination.
AddAndActivateNativePatchForAddress((CORDB_ADDRESS_TYPE*)dest, LEAF_MOST_FRAME, FALSE, TRACE_UNMANAGED);
}
TP_RESULT DebuggerFuncEvalComplete::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
// It had better be an unmanaged patch...
_ASSERTE((patch->key.module == NULL) && !patch->IsManagedPatch());
// set ThreadFilterContext back here because we need make stack crawlable! In case,
// GC got triggered.
// Restore the thread's context to what it was before we hijacked it for this func eval.
CONTEXT *pCtx = GetManagedLiveCtx(thread);
CORDbgCopyThreadContext(reinterpret_cast<DT_CONTEXT *>(pCtx),
reinterpret_cast<DT_CONTEXT *>(&(m_pDE->m_context)));
// We've hit our patch, so simply disable all (which removes the
// patch) and trigger the event.
DisableAll();
return TPR_TRIGGER;
}
bool DebuggerFuncEvalComplete::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
THROWS;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
// This should not ever be interupted by a SetIp.
// The BP will be off in random native code for which SetIp would be illegal.
// However, func-eval conroller will restore the context from when we're at the patch,
// so that will look like the IP changed on us.
_ASSERTE(fIpChanged);
LOG((LF_CORDB, LL_INFO10000, "DFEC::SE: in DebuggerFuncEval's SendEvent\n"));
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
// The DebuggerEval is at our faulting address.
DebuggerEval *pDE = m_pDE;
// Send the func eval complete (or exception) event.
g_pDebugger->FuncEvalComplete(thread, pDE);
// We delete this now because its no longer needed. We can call
// delete here because the queued count is above 0. This object
// will really be deleted when its dequeued shortly after this
// call returns.
Delete();
return true;
}
#ifdef EnC_SUPPORTED
// * ------------------------------------------------------------------------ *
// * DebuggerEnCBreakpoint routines
// * ------------------------------------------------------------------------ *
//---------------------------------------------------------------------------------------
//
// DebuggerEnCBreakpoint constructor - creates and activates a new EnC breakpoint
//
// Arguments:
// offset - native offset in the function to place the patch
// jitInfo - identifies the function in which the breakpoint is being placed
// fTriggerType - breakpoint type: either REMAP_PENDING or REMAP_COMPLETE
// pAppDomain - the breakpoint applies to the specified AppDomain only
//
DebuggerEnCBreakpoint::DebuggerEnCBreakpoint(SIZE_T offset,
DebuggerJitInfo *jitInfo,
DebuggerEnCBreakpoint::TriggerType fTriggerType,
AppDomain *pAppDomain)
: DebuggerController(NULL, pAppDomain),
m_fTriggerType(fTriggerType),
m_jitInfo(jitInfo)
{
_ASSERTE( jitInfo != NULL );
// Add and activate the specified patch
AddBindAndActivateNativeManagedPatch(jitInfo->m_fd, jitInfo, offset, LEAF_MOST_FRAME, pAppDomain);
LOG((LF_ENC,LL_INFO1000, "DEnCBPDEnCBP::adding %S patch!\n",
fTriggerType == REMAP_PENDING ? W("remap pending") : W("remap complete")));
}
//---------------------------------------------------------------------------------------
//
// DebuggerEnCBreakpoint::TriggerPatch
// called by the debugging infrastructure when the patch is hit.
//
// Arguments:
// patch - specifies the patch that was hit
// thread - identifies the thread on which the patch was hit
// tyWhy - TY_SHORT_CIRCUIT for normal REMAP_PENDING EnC patches
//
// Return value:
// TPR_IGNORE if the debugger chooses not to take a remap opportunity
// TPR_IGNORE_AND_STOP when a remap-complete event is sent
// Doesn't return at all if the debugger remaps execution to the new version of the method
//
TP_RESULT DebuggerEnCBreakpoint::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
_ASSERTE(HasLock());
Module *module = patch->key.module;
mdMethodDef md = patch->key.md;
SIZE_T offset = patch->offset;
// Map the current native offset back to the IL offset in the old
// function. This will be mapped to the new native offset within
// ResumeInUpdatedFunction
CorDebugMappingResult map;
DWORD which;
SIZE_T currentIP = (SIZE_T)m_jitInfo->MapNativeOffsetToIL(offset,
&map, &which);
// We only lay DebuggerEnCBreakpoints at sequence points
_ASSERTE(map == MAPPING_EXACT);
LOG((LF_ENC, LL_ALWAYS,
"DEnCBP::TP: triggered E&C %S breakpoint: tid=0x%x, module=0x%08x, "
"method def=0x%08x, version=%d, native offset=0x%x, IL offset=0x%x\n this=0x%x\n",
m_fTriggerType == REMAP_PENDING ? W("ResumePending") : W("ResumeComplete"),
thread, module, md, m_jitInfo->m_encVersion, offset, currentIP, this));
// If this is a REMAP_COMPLETE patch, then dispatch the RemapComplete callback
if (m_fTriggerType == REMAP_COMPLETE)
{
return HandleRemapComplete(patch, thread, tyWhy);
}
// This must be a REMAP_PENDING patch
// unless we got here on an explicit short-circuit, don't do any work
if (tyWhy != TY_SHORT_CIRCUIT)
{
LOG((LF_ENC, LL_ALWAYS, "DEnCBP::TP: not short-circuit ... bailing\n"));
return TPR_IGNORE;
}
_ASSERTE(patch->IsManagedPatch());
// Grab the MethodDesc for this function.
_ASSERTE(module != NULL);
// GENERICS: @todo generics. This should be replaced by a similar loop
// over the DJIs for the DMI as in BindPatch up above.
MethodDesc *pFD = g_pEEInterface->FindLoadedMethodRefOrDef(module, md);
_ASSERTE(pFD != NULL);
LOG((LF_ENC, LL_ALWAYS,
"DEnCBP::TP: in %s::%s\n", pFD->m_pszDebugClassName,pFD->m_pszDebugMethodName));
// Grab the jit info for the original copy of the method, which is
// what we are executing right now.
DebuggerJitInfo *pJitInfo = m_jitInfo;
_ASSERTE(pJitInfo);
_ASSERTE(pJitInfo->m_fd == pFD);
// Grab the context for this thread. This is the context that was
// passed to COMPlusFrameHandler.
CONTEXT *pContext = GetManagedLiveCtx(thread);
// We use the module the current function is in.
_ASSERTE(module->IsEditAndContinueEnabled());
EditAndContinueModule *pModule = (EditAndContinueModule*)module;
// Release the controller lock for the rest of this method
CrstBase::UnsafeCrstInverseHolder inverseLock(&g_criticalSection);
// resumeIP is the native offset in the new version of the method the debugger wants
// to resume to. We'll pass the address of this variable over to the right-side
// and if it modifies the contents while we're stopped dispatching the RemapOpportunity,
// then we know it wants a remap.
// This form of side-channel communication seems like an error-prone workaround. Ideally the
// remap IP (if any) would just be returned in a response event.
SIZE_T resumeIP = (SIZE_T) -1;
// Debugging code to enable a break after N RemapOpportunities
#ifdef _DEBUG
static int breakOnRemapOpportunity = -1;
if (breakOnRemapOpportunity == -1)
breakOnRemapOpportunity = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_EnCBreakOnRemapOpportunity);
static int remapOpportunityCount = 0;
++remapOpportunityCount;
if (breakOnRemapOpportunity == 1 || breakOnRemapOpportunity == remapOpportunityCount)
{
_ASSERTE(!"BreakOnRemapOpportunity");
}
#endif
// Send an event to the RS to call the RemapOpportunity callback, passing the address of resumeIP.
// If the debugger responds with a call to RemapFunction, the supplied IP will be copied into resumeIP
// and we will know to update the context and resume the function at the new IP. Otherwise we just do
// nothing and try again on next RemapFunction breakpoint
g_pDebugger->LockAndSendEnCRemapEvent(pJitInfo, currentIP, &resumeIP);
LOG((LF_ENC, LL_ALWAYS,
"DEnCBP::TP: resume IL offset is 0x%x\n", resumeIP));
// Has the debugger requested a remap?
if (resumeIP != (SIZE_T) -1)
{
// This will jit the function, update the context, and resume execution at the new location.
g_pEEInterface->ResumeInUpdatedFunction(pModule,
pFD,
(void*)pJitInfo,
resumeIP,
pContext);
_ASSERTE(!"Returned from ResumeInUpdatedFunction!");
}
LOG((LF_CORDB, LL_ALWAYS, "DEnCB::TP: We've returned from ResumeInUpd"
"atedFunction, we're going to skip the EnC patch ####\n"));
// We're returning then we'll have to re-get this lock. Be careful that we haven't kept any controller/patches
// in the caller. They can move when we unlock, so when we release the lock and reget it here, things might have
// changed underneath us.
// inverseLock holder will reaquire lock.
return TPR_IGNORE;
}
//
// HandleResumeComplete is called for an EnC patch in the newly updated function
// so that we can notify the debugger that the remap has completed and they can
// now remap their steppers or anything else that depends on the new code actually
// being on the stack. We return TPR_IGNORE_AND_STOP because it's possible that the
// function was edited after we handled remap complete and want to make sure we
// start a fresh call to TriggerPatch
//
TP_RESULT DebuggerEnCBreakpoint::HandleRemapComplete(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
LOG((LF_ENC, LL_ALWAYS, "DEnCBP::HRC: HandleRemapComplete\n"));
// Debugging code to enable a break after N RemapCompletes
#ifdef _DEBUG
static int breakOnRemapComplete = -1;
if (breakOnRemapComplete == -1)
breakOnRemapComplete = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_EnCBreakOnRemapComplete);
static int remapCompleteCount = 0;
++remapCompleteCount;
if (breakOnRemapComplete == 1 || breakOnRemapComplete == remapCompleteCount)
{
_ASSERTE(!"BreakOnRemapComplete");
}
#endif
_ASSERTE(HasLock());
bool fApplied = m_jitInfo->m_encBreakpointsApplied;
// Need to delete this before unlock below so if any other thread come in after the unlock
// they won't handle this patch.
Delete();
// We just deleted ourselves. Can't access anything any instances after this point.
// if have somehow updated this function before we resume into it then just bail
if (fApplied)
{
LOG((LF_ENC, LL_ALWAYS, "DEnCBP::HRC: function already updated, ignoring\n"));
return TPR_IGNORE_AND_STOP;
}
// GENERICS: @todo generics. This should be replaced by a similar loop
// over the DJIs for the DMI as in BindPatch up above.
MethodDesc *pFD = g_pEEInterface->FindLoadedMethodRefOrDef(patch->key.module, patch->key.md);
LOG((LF_ENC, LL_ALWAYS, "DEnCBP::HRC: unlocking controller\n"));
// Unlock the controller lock and dispatch the remap complete event
CrstBase::UnsafeCrstInverseHolder inverseLock(&g_criticalSection);
LOG((LF_ENC, LL_ALWAYS, "DEnCBP::HRC: sending RemapCompleteEvent\n"));
g_pDebugger->LockAndSendEnCRemapCompleteEvent(pFD);
// We're returning then we'll have to re-get this lock. Be careful that we haven't kept any controller/patches
// in the caller. They can move when we unlock, so when we release the lock and reget it here, things might have
// changed underneath us.
// inverseLock holder will reacquire.
return TPR_IGNORE_AND_STOP;
}
#endif //EnC_SUPPORTED
// continuable-exceptions
// * ------------------------------------------------------------------------ *
// * DebuggerContinuableExceptionBreakpoint routines
// * ------------------------------------------------------------------------ *
//---------------------------------------------------------------------------------------
//
// constructor
//
// Arguments:
// pThread - the thread on which we are intercepting an exception
// nativeOffset - This is the target native offset. It is where we are going to resume execution.
// jitInfo - the DebuggerJitInfo of the method at which we are intercepting
// pAppDomain - the AppDomain in which the thread is executing
//
DebuggerContinuableExceptionBreakpoint::DebuggerContinuableExceptionBreakpoint(Thread *pThread,
SIZE_T nativeOffset,
DebuggerJitInfo *jitInfo,
AppDomain *pAppDomain)
: DebuggerController(pThread, pAppDomain)
{
_ASSERTE( jitInfo != NULL );
// Add a native patch at the specified native offset, which is where we are going to resume execution.
AddBindAndActivateNativeManagedPatch(jitInfo->m_fd, jitInfo, nativeOffset, LEAF_MOST_FRAME, pAppDomain);
}
//---------------------------------------------------------------------------------------
//
// This function is called when the patch added in the constructor is hit. At this point,
// we have already resumed execution, and the exception is no longer in flight.
//
// Arguments:
// patch - the patch added in the constructor; unused
// thread - the thread in question; unused
// tyWhy - a flag which is only useful for EnC; unused
//
// Return Value:
// This function always returns TPR_TRIGGER, meaning that it wants to send an event to notify the RS.
//
TP_RESULT DebuggerContinuableExceptionBreakpoint::TriggerPatch(DebuggerControllerPatch *patch,
Thread *thread,
TRIGGER_WHY tyWhy)
{
LOG((LF_CORDB, LL_INFO10000, "DCEBP::TP\n"));
//
// Disable the patch
//
DisableAll();
// We will send a notification to the RS when the patch is triggered.
return TPR_TRIGGER;
}
//---------------------------------------------------------------------------------------
//
// This function is called when we want to notify the RS that an interception is complete.
// At this point, we have already resumed execution, and the exception is no longer in flight.
//
// Arguments:
// thread - the thread in question
// fIpChanged - whether the IP has changed by SetIP after the patch is hit but
// before this function is called
//
bool DebuggerContinuableExceptionBreakpoint::SendEvent(Thread *thread, bool fIpChanged)
{
CONTRACTL
{
SO_NOT_MAINLINE;
NOTHROW;
SENDEVENT_CONTRACT_ITEMS;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO10000,
"DCEBP::SE: in DebuggerContinuableExceptionBreakpoint's SendEvent\n"));
if (!fIpChanged)
{
g_pDebugger->SendInterceptExceptionComplete(thread);
}
// On WIN64, by the time we get here the DebuggerExState is gone already.
// ExceptionTrackers are cleaned up before we resume execution for a handled exception.
#if !defined(WIN64EXCEPTIONS)
thread->GetExceptionState()->GetDebuggerState()->SetDebuggerInterceptContext(NULL);
#endif // !WIN64EXCEPTIONS
//
// We delete this now because its no longer needed. We can call
// delete here because the queued count is above 0. This object
// will really be deleted when its dequeued shortly after this
// call returns.
//
Delete();
return true;
}
#endif // !DACCESS_COMPILE
| parjong/coreclr | src/debug/ee/controller.cpp | C++ | mit | 325,373 |
import * as React from "react";
import { CarbonIconProps } from "../../";
declare const Opacity24: React.ForwardRefExoticComponent<
CarbonIconProps & React.RefAttributes<SVGSVGElement>
>;
export default Opacity24;
| mcliment/DefinitelyTyped | types/carbon__icons-react/lib/opacity/24.d.ts | TypeScript | mit | 216 |
import os
import pygtk
pygtk.require('2.0')
import gtk
from gtkcodebuffer import CodeBuffer, SyntaxLoader
class Ui(object):
"""
The user interface. This dialog is the LaTeX input window and includes
widgets to display compilation logs and a preview. It uses GTK2 which
must be installed an importable.
"""
app_name = 'InkTeX'
help_text = r"""You can set a preamble file and scale factor in the <b>settings</b> tab. The preamble should not include <b>\documentclass</b> and <b>\begin{document}</b>.
The LaTeX code you write is only the stuff between <b>\begin{document}</b> and <b>\end{document}</b>. Compilation errors are reported in the <b>log</b> tab.
The preamble file and scale factor are stored on a per-drawing basis, so in a new document, these information must be set again."""
about_text = r"""Written by <a href="mailto:janoliver@oelerich.org">Jan Oliver Oelerich <janoliver@oelerich.org></a>"""
def __init__(self, render_callback, src, settings):
"""Takes the following parameters:
* render_callback: callback function to execute with "apply" button
* src: source code that should be pre-inserted into the LaTeX input"""
self.render_callback = render_callback
self.src = src if src else ""
self.settings = settings
# init the syntax highlighting buffer
lang = SyntaxLoader("latex")
self.syntax_buffer = CodeBuffer(lang=lang)
self.setup_ui()
def render(self, widget, data=None):
"""Extracts the input LaTeX code and calls the render callback. If that
returns true, we quit and are happy."""
buf = self.text.get_buffer()
tex = buf.get_text(buf.get_start_iter(), buf.get_end_iter())
settings = dict()
if self.preamble.get_filename():
settings['preamble'] = self.preamble.get_filename()
settings['scale'] = self.scale.get_value()
if self.render_callback(tex, settings):
gtk.main_quit()
return False
def cancel(self, widget, data=None):
"""Close button pressed: Exit"""
raise SystemExit(1)
def destroy(self, widget, event, data=None):
"""Destroy hook for the GTK window. Quit and return False."""
gtk.main_quit()
return False
def setup_ui(self):
"""Creates the actual UI."""
# create a floating toplevel window and set some title and border
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DIALOG)
self.window.set_title(self.app_name)
self.window.set_border_width(8)
# connect delete and destroy events
self.window.connect("destroy", self.destroy)
self.window.connect("delete-event", self.destroy)
# This is our main container, vertically ordered.
self.box_container = gtk.VBox(False, 5)
self.box_container.show()
self.notebook = gtk.Notebook()
self.page_latex = gtk.HBox(False, 5)
self.page_latex.set_border_width(8)
self.page_latex.show()
self.page_log = gtk.HBox(False, 5)
self.page_log.set_border_width(8)
self.page_log.show()
self.page_settings = gtk.HBox(False, 5)
self.page_settings.set_border_width(8)
self.page_settings.show()
self.page_help = gtk.VBox(False, 5)
self.page_help.set_border_width(8)
self.page_help.show()
self.notebook.append_page(self.page_latex, gtk.Label("LaTeX"))
self.notebook.append_page(self.page_log, gtk.Label("Log"))
self.notebook.append_page(self.page_settings, gtk.Label("Settings"))
self.notebook.append_page(self.page_help, gtk.Label("Help"))
self.notebook.show()
# First component: The input text view for the LaTeX code.
# It lives in a ScrolledWindow so we can get some scrollbars when the
# text is too long.
self.text = gtk.TextView(self.syntax_buffer)
self.text.get_buffer().set_text(self.src)
self.text.show()
self.text_container = gtk.ScrolledWindow()
self.text_container.set_policy(gtk.POLICY_AUTOMATIC,
gtk.POLICY_AUTOMATIC)
self.text_container.set_shadow_type(gtk.SHADOW_IN)
self.text_container.add(self.text)
self.text_container.set_size_request(400, 200)
self.text_container.show()
self.page_latex.pack_start(self.text_container)
# Second component: The log view
self.log_view = gtk.TextView()
self.log_view.show()
self.log_container = gtk.ScrolledWindow()
self.log_container.set_policy(gtk.POLICY_AUTOMATIC,
gtk.POLICY_AUTOMATIC)
self.log_container.set_shadow_type(gtk.SHADOW_IN)
self.log_container.add(self.log_view)
self.log_container.set_size_request(400, 200)
self.log_container.show()
self.page_log.pack_start(self.log_container)
# third component: settings
self.settings_container = gtk.Table(2,2)
self.settings_container.set_row_spacings(8)
self.settings_container.show()
self.label_preamble = gtk.Label("Preamble")
self.label_preamble.set_alignment(0, 0.5)
self.label_preamble.show()
self.preamble = gtk.FileChooserButton("...")
if 'preamble' in self.settings and os.path.exists(self.settings['preamble']):
self.preamble.set_filename(self.settings['preamble'])
self.preamble.set_action(gtk.FILE_CHOOSER_ACTION_OPEN)
self.preamble.show()
self.settings_container.attach(self.label_preamble, yoptions=gtk.SHRINK,
left_attach=0, right_attach=1, top_attach=0, bottom_attach=1)
self.settings_container.attach(self.preamble, yoptions=gtk.SHRINK,
left_attach=1, right_attach=2, top_attach=0, bottom_attach=1)
self.label_scale = gtk.Label("Scale")
self.label_scale.set_alignment(0, 0.5)
self.label_scale.show()
self.scale_adjustment = gtk.Adjustment(value=1.0, lower=0, upper=100,
step_incr=0.1)
self.scale = gtk.SpinButton(adjustment=self.scale_adjustment, digits=1)
if 'scale' in self.settings:
self.scale.set_value(float(self.settings['scale']))
self.scale.show()
self.settings_container.attach(self.label_scale, yoptions=gtk.SHRINK,
left_attach=0, right_attach=1, top_attach=1, bottom_attach=2)
self.settings_container.attach(self.scale, yoptions=gtk.SHRINK,
left_attach=1, right_attach=2, top_attach=1, bottom_attach=2)
self.page_settings.pack_start(self.settings_container)
# help tab
self.help_label = gtk.Label()
self.help_label.set_markup(Ui.help_text)
self.help_label.set_line_wrap(True)
self.help_label.show()
self.about_label = gtk.Label()
self.about_label.set_markup(Ui.about_text)
self.about_label.set_line_wrap(True)
self.about_label.show()
self.separator_help = gtk.HSeparator()
self.separator_help.show()
self.page_help.pack_start(self.help_label)
self.page_help.pack_start(self.separator_help)
self.page_help.pack_start(self.about_label)
self.box_container.pack_start(self.notebook, True, True)
# separator between buttonbar and notebook
self.separator_buttons = gtk.HSeparator()
self.separator_buttons.show()
self.box_container.pack_start(self.separator_buttons, False, False)
# the button bar
self.box_buttons = gtk.HButtonBox()
self.box_buttons.set_layout(gtk.BUTTONBOX_END)
self.box_buttons.show()
self.button_render = gtk.Button(stock=gtk.STOCK_APPLY)
self.button_cancel = gtk.Button(stock=gtk.STOCK_CLOSE)
self.button_render.set_flags(gtk.CAN_DEFAULT)
self.button_render.connect("clicked", self.render, None)
self.button_cancel.connect("clicked", self.cancel, None)
self.button_render.show()
self.button_cancel.show()
self.box_buttons.pack_end(self.button_cancel)
self.box_buttons.pack_end(self.button_render)
self.box_container.pack_start(self.box_buttons, False, False)
self.window.add(self.box_container)
self.window.set_default(self.button_render)
self.window.show()
def log(self, msg):
buffer = self.log_view.get_buffer()
buffer.set_text(msg)
self.notebook.set_current_page(1)
def main(self):
gtk.main()
| hvwaldow/inktex | inktex/ui.py | Python | mit | 8,707 |
<?php
/**
* Functions related to starring private messages.
*
* @package BuddyPress
* @subpackage MessagesStar
* @since 2.3.0
*/
// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;
/** UTILITY **************************************************************/
/**
* Return the starred messages slug. Defaults to 'starred'.
*
* @since 2.3.0
*
* @return string
*/
function bp_get_messages_starred_slug() {
/**
* Filters the starred message slug.
*
* @since 2.3.0
*
* @param string
*/
return sanitize_title( apply_filters( 'bp_get_messages_starred_slug', 'starred' ) );
}
/**
* Function to determine if a message ID is starred.
*
* @since 2.3.0
*
* @param int $mid The message ID. Please note that this isn't the message thread ID.
* @param int $user_id The user ID.
* @return bool
*/
function bp_messages_is_message_starred( $mid = 0, $user_id = 0 ) {
if ( empty( $user_id ) ) {
$user_id = bp_displayed_user_id();
}
if ( empty( $mid ) ) {
return false;
}
$starred = array_flip( (array) bp_messages_get_meta( $mid, 'starred_by_user', false ) );
if ( isset( $starred[$user_id] ) ) {
return true;
} else {
return false;
}
}
/**
* Output the link or raw URL for starring or unstarring a message.
*
* @since 2.3.0
*
* @param array $args See bp_get_the_message_star_action_link() for full documentation.
*/
function bp_the_message_star_action_link( $args = array() ) {
echo bp_get_the_message_star_action_link( $args );
}
/**
* Return the link or raw URL for starring or unstarring a message.
*
* @since 2.3.0
*
* @param array $args {
* Array of arguments.
* @type int $user_id The user ID. Defaults to the logged-in user ID.
* @type int $thread_id The message thread ID. Default: 0. If not zero, this takes precedence over
* $message_id.
* @type int $message_id The individual message ID. If on a single thread page, defaults to the
* current message ID in the message loop.
* @type bool $url_only Whether to return the URL only. If false, returns link with markup.
* Default: false.
* @type string $text_unstar Link text for the 'unstar' action. Only applicable if $url_only is false.
* @type string $text_star Link text for the 'star' action. Only applicable if $url_only is false.
* @type string $title_unstar Link title for the 'unstar' action. Only applicable if $url_only is false.
* @type string $title_star Link title for the 'star' action. Only applicable if $url_only is false.
* @type string $title_unstar_thread Link title for the 'unstar' action when displayed in a thread loop.
* Only applicable if $message_id is set and if $url_only is false.
* @type string $title_star_thread Link title for the 'star' action when displayed in a thread loop.
* Only applicable if $message_id is set and if $url_only is false.
* }
* @return string
*/
function bp_get_the_message_star_action_link( $args = array() ) {
// Default user ID.
$user_id = bp_displayed_user_id()
? bp_displayed_user_id()
: bp_loggedin_user_id();
$r = bp_parse_args( $args, array(
'user_id' => (int) $user_id,
'thread_id' => 0,
'message_id' => (int) bp_get_the_thread_message_id(),
'url_only' => false,
'text_unstar' => __( 'Unstar', 'buddypress' ),
'text_star' => __( 'Star', 'buddypress' ),
'title_unstar' => __( 'Starred', 'buddypress' ),
'title_star' => __( 'Not starred', 'buddypress' ),
'title_unstar_thread' => __( 'Remove all starred messages in this thread', 'buddypress' ),
'title_star_thread' => __( 'Star the first message in this thread', 'buddypress' ),
), 'messages_star_action_link' );
// Check user ID and determine base user URL.
switch ( $r['user_id'] ) {
// Current user.
case bp_loggedin_user_id() :
$user_domain = bp_loggedin_user_domain();
break;
// Displayed user.
case bp_displayed_user_id() :
$user_domain = bp_displayed_user_domain();
break;
// Empty or other.
default :
$user_domain = bp_core_get_user_domain( $r['user_id'] );
break;
}
// Bail if no user domain was calculated.
if ( empty( $user_domain ) ) {
return '';
}
// Define local variables.
$retval = $bulk_attr = '';
// Thread ID.
if ( (int) $r['thread_id'] > 0 ) {
// See if we're in the loop.
if ( bp_get_message_thread_id() == $r['thread_id'] ) {
// Grab all message ids.
$mids = wp_list_pluck( $GLOBALS['messages_template']->thread->messages, 'id' );
// Make sure order is ASC.
// Order is DESC when used in the thread loop by default.
$mids = array_reverse( $mids );
// Pull up the thread.
} else {
$thread = new BP_Messages_Thread( $r['thread_id'] );
$mids = wp_list_pluck( $thread->messages, 'id' );
}
$is_starred = false;
$message_id = 0;
foreach ( $mids as $mid ) {
// Try to find the first msg that is starred in a thread.
if ( true === bp_messages_is_message_starred( $mid ) ) {
$is_starred = true;
$message_id = $mid;
break;
}
}
// No star, so default to first message in thread.
if ( empty( $message_id ) ) {
$message_id = $mids[0];
}
$message_id = (int) $message_id;
// Nonce.
$nonce = wp_create_nonce( "bp-messages-star-{$message_id}" );
if ( true === $is_starred ) {
$action = 'unstar';
$bulk_attr = ' data-star-bulk="1"';
$retval = $user_domain . bp_get_messages_slug() . '/unstar/' . $message_id . '/' . $nonce . '/all/';
} else {
$action = 'star';
$retval = $user_domain . bp_get_messages_slug() . '/star/' . $message_id . '/' . $nonce . '/';
}
$title = $r["title_{$action}_thread"];
// Message ID.
} else {
$message_id = (int) $r['message_id'];
$is_starred = bp_messages_is_message_starred( $message_id );
$nonce = wp_create_nonce( "bp-messages-star-{$message_id}" );
if ( true === $is_starred ) {
$action = 'unstar';
$retval = $user_domain . bp_get_messages_slug() . '/unstar/' . $message_id . '/' . $nonce . '/';
} else {
$action = 'star';
$retval = $user_domain . bp_get_messages_slug() . '/star/' . $message_id . '/' . $nonce . '/';
}
$title = $r["title_{$action}"];
}
/**
* Filters the star action URL for starring / unstarring a message.
*
* @since 2.3.0
*
* @param string $retval URL for starring / unstarring a message.
* @param array $r Parsed link arguments. See $args in bp_get_the_message_star_action_link().
*/
$retval = esc_url( apply_filters( 'bp_get_the_message_star_action_urlonly', $retval, $r ) );
if ( true === (bool) $r['url_only'] ) {
return $retval;
}
/**
* Filters the star action link, including markup.
*
* @since 2.3.0
*
* @param string $retval Link for starring / unstarring a message, including markup.
* @param array $r Parsed link arguments. See $args in bp_get_the_message_star_action_link().
*/
return apply_filters( 'bp_get_the_message_star_action_link', '<a data-bp-tooltip="' . esc_attr( $title ) . '" class="bp-tooltip message-action-' . esc_attr( $action ) . '" data-star-status="' . esc_attr( $action ) .'" data-star-nonce="' . esc_attr( $nonce ) . '"' . $bulk_attr . ' data-message-id="' . esc_attr( (int) $message_id ) . '" href="' . $retval . '" role="button" aria-pressed="false"><span class="icon"></span> <span class="bp-screen-reader-text">' . $r['text_' . $action] . '</span></a>', $r );
}
/**
* Save or delete star message meta according to a message's star status.
*
* @since 2.3.0
*
* @param array $args {
* Array of arguments.
* @type string $action The star action. Either 'star' or 'unstar'. Default: 'star'.
* @type int $thread_id The message thread ID. Default: 0. If not zero, this takes precedence over
* $message_id.
* @type int $message_id The indivudal message ID to star or unstar. Default: 0.
* @type int $user_id The user ID. Defaults to the logged-in user ID.
* @type bool $bulk Whether to mark all messages in a thread as a certain action. Only relevant
* when $action is 'unstar' at the moment. Default: false.
* }
* @return bool
*/
function bp_messages_star_set_action( $args = array() ) {
$r = wp_parse_args( $args, array(
'action' => 'star',
'thread_id' => 0,
'message_id' => 0,
'user_id' => bp_displayed_user_id(),
'bulk' => false
) );
// Set thread ID.
if ( ! empty( $r['thread_id'] ) ) {
$thread_id = (int) $r['thread_id'];
} else {
$thread_id = messages_get_message_thread_id( $r['message_id'] );
}
if ( empty( $thread_id ) ) {
return false;
}
// Check if user has access to thread.
if( ! messages_check_thread_access( $thread_id, $r['user_id'] ) ) {
return false;
}
$is_starred = bp_messages_is_message_starred( $r['message_id'], $r['user_id'] );
// Star.
if ( 'star' == $r['action'] ) {
if ( true === $is_starred ) {
return true;
} else {
bp_messages_add_meta( $r['message_id'], 'starred_by_user', $r['user_id'] );
return true;
}
// Unstar.
} else {
// Unstar one message.
if ( false === $r['bulk'] ) {
if ( false === $is_starred ) {
return true;
} else {
bp_messages_delete_meta( $r['message_id'], 'starred_by_user', $r['user_id'] );
return true;
}
// Unstar all messages in a thread.
} else {
$thread = new BP_Messages_Thread( $thread_id );
$mids = wp_list_pluck( $thread->messages, 'id' );
foreach ( $mids as $mid ) {
if ( true === bp_messages_is_message_starred( $mid, $r['user_id'] ) ) {
bp_messages_delete_meta( $mid, 'starred_by_user', $r['user_id'] );
}
}
return true;
}
}
}
/** SCREENS **************************************************************/
/**
* Screen handler to display a user's "Starred" private messages page.
*
* @since 2.3.0
*/
function bp_messages_star_screen() {
add_action( 'bp_template_content', 'bp_messages_star_content' );
/**
* Fires right before the loading of the "Starred" messages box.
*
* @since 2.3.0
*/
do_action( 'bp_messages_screen_star' );
bp_core_load_template( 'members/single/plugins' );
}
/**
* Screen content callback to display a user's "Starred" messages page.
*
* @since 2.3.0
*/
function bp_messages_star_content() {
// Add our message thread filter.
add_filter( 'bp_after_has_message_threads_parse_args', 'bp_messages_filter_starred_message_threads' );
// Load the message loop template part.
bp_get_template_part( 'members/single/messages/messages-loop' );
// Remove our filter.
remove_filter( 'bp_after_has_message_threads_parse_args', 'bp_messages_filter_starred_message_threads' );
}
/**
* Filter message threads by those starred by the logged-in user.
*
* @since 2.3.0
*
* @param array $r Current message thread arguments.
* @return array $r Array of starred message threads.
*/
function bp_messages_filter_starred_message_threads( $r = array() ) {
$r['box'] = 'starred';
$r['meta_query'] = array( array(
'key' => 'starred_by_user',
'value' => $r['user_id']
) );
return $r;
}
/** ACTIONS **************************************************************/
/**
* Action handler to set a message's star status for those not using JS.
*
* @since 2.3.0
*/
function bp_messages_star_action_handler() {
if ( ! bp_is_user_messages() ) {
return;
}
if ( false === ( bp_is_current_action( 'unstar' ) || bp_is_current_action( 'star' ) ) ) {
return;
}
if ( ! wp_verify_nonce( bp_action_variable( 1 ), 'bp-messages-star-' . bp_action_variable( 0 ) ) ) {
wp_die( "Oops! That's a no-no!" );
}
// Check capability.
if ( ! is_user_logged_in() || ! bp_core_can_edit_settings() ) {
return;
}
// Mark the star.
bp_messages_star_set_action( array(
'action' => bp_current_action(),
'message_id' => bp_action_variable(),
'bulk' => (bool) bp_action_variable( 2 )
) );
// Redirect back to previous screen.
$redirect = wp_get_referer() ? wp_get_referer() : bp_displayed_user_domain() . bp_get_messages_slug();
bp_core_redirect( $redirect );
die();
}
add_action( 'bp_actions', 'bp_messages_star_action_handler' );
/**
* Bulk manage handler to set the star status for multiple messages.
*
* @since 2.3.0
*/
function bp_messages_star_bulk_manage_handler() {
if ( empty( $_POST['messages_bulk_nonce' ] ) ) {
return;
}
// Check the nonce.
if ( ! wp_verify_nonce( $_POST['messages_bulk_nonce'], 'messages_bulk_nonce' ) ) {
return;
}
// Check capability.
if ( ! is_user_logged_in() || ! bp_core_can_edit_settings() ) {
return;
}
$action = ! empty( $_POST['messages_bulk_action'] ) ? $_POST['messages_bulk_action'] : '';
$threads = ! empty( $_POST['message_ids'] ) ? $_POST['message_ids'] : '';
$threads = wp_parse_id_list( $threads );
// Bail if action doesn't match our star actions or no IDs.
if ( false === in_array( $action, array( 'star', 'unstar' ), true ) || empty( $threads ) ) {
return;
}
// It's star time!
switch ( $action ) {
case 'star' :
$count = count( $threads );
// If we're starring a thread, we only star the first message in the thread.
foreach ( $threads as $thread ) {
$thread = new BP_Messages_thread( $thread );
$mids = wp_list_pluck( $thread->messages, 'id' );
bp_messages_star_set_action( array(
'action' => 'star',
'message_id' => $mids[0],
) );
}
bp_core_add_message( sprintf( _n( '%s message was successfully starred', '%s messages were successfully starred', $count, 'buddypress' ), $count ) );
break;
case 'unstar' :
$count = count( $threads );
foreach ( $threads as $thread ) {
bp_messages_star_set_action( array(
'action' => 'unstar',
'thread_id' => $thread,
'bulk' => true
) );
}
bp_core_add_message( sprintf( _n( '%s message was successfully unstarred', '%s messages were successfully unstarred', $count, 'buddypress' ), $count ) );
break;
}
// Redirect back to message box.
bp_core_redirect( bp_displayed_user_domain() . bp_get_messages_slug() . '/' . bp_current_action() . '/' );
die();
}
add_action( 'bp_actions', 'bp_messages_star_bulk_manage_handler', 5 );
/** HOOKS ****************************************************************/
/**
* Enqueues the dashicons font.
*
* The dashicons font is used for the star / unstar icon.
*
* @since 2.3.0
*/
function bp_messages_star_enqueue_scripts() {
if ( ! bp_is_user_messages() ) {
return;
}
wp_enqueue_style( 'dashicons' );
}
add_action( 'bp_enqueue_scripts', 'bp_messages_star_enqueue_scripts' );
/**
* Add the "Add star" and "Remove star" options to the bulk management list.
*
* @since 2.3.0
*/
function bp_messages_star_bulk_management_dropdown() {
?>
<option value="star"><?php _e( 'Add star', 'buddypress' ); ?></option>
<option value="unstar"><?php _e( 'Remove star', 'buddypress' ); ?></option>
<?php
}
add_action( 'bp_messages_bulk_management_dropdown', 'bp_messages_star_bulk_management_dropdown', 1 );
/**
* Add CSS class for the current message depending on starred status.
*
* @since 2.3.0
*
* @param array $retval Current CSS classes.
* @return array
*/
function bp_messages_star_message_css_class( $retval = array() ) {
if ( true === bp_messages_is_message_starred( bp_get_the_thread_message_id() ) ) {
$status = 'starred';
} else {
$status = 'not-starred';
}
// Add css class based on star status for the current message.
$retval[] = "message-{$status}";
return $retval;
}
add_filter( 'bp_get_the_thread_message_css_class', 'bp_messages_star_message_css_class' );
| jmelgarejo/Clan | wordpress/wp-content/plugins/buddypress/bp-messages/bp-messages-star.php | PHP | mit | 15,966 |
<?php
namespace Illuminate\Cache;
use Closure;
use Exception;
use Carbon\Carbon;
use Illuminate\Contracts\Cache\Store;
use Illuminate\Database\ConnectionInterface;
class DatabaseStore implements Store
{
use RetrievesMultipleKeys;
/**
* The database connection instance.
*
* @var \Illuminate\Database\ConnectionInterface
*/
protected $connection;
/**
* The name of the cache table.
*
* @var string
*/
protected $table;
/**
* A string that should be prepended to keys.
*
* @var string
*/
protected $prefix;
/**
* Create a new database store.
*
* @param \Illuminate\Database\ConnectionInterface $connection
* @param string $table
* @param string $prefix
* @return void
*/
public function __construct(ConnectionInterface $connection, $table, $prefix = '')
{
$this->table = $table;
$this->prefix = $prefix;
$this->connection = $connection;
}
/**
* Retrieve an item from the cache by key.
*
* @param string|array $key
* @return mixed
*/
public function get($key)
{
$prefixed = $this->prefix.$key;
$cache = $this->table()->where('key', '=', $prefixed)->first();
// If we have a cache record we will check the expiration time against current
// time on the system and see if the record has expired. If it has, we will
// remove the records from the database table so it isn't returned again.
if (is_null($cache)) {
return;
}
$cache = is_array($cache) ? (object) $cache : $cache;
// If this cache expiration date is past the current time, we will remove this
// item from the cache. Then we will return a null value since the cache is
// expired. We will use "Carbon" to make this comparison with the column.
if (Carbon::now()->getTimestamp() >= $cache->expiration) {
$this->forget($key);
return;
}
return unserialize($cache->value);
}
/**
* Store an item in the cache for a given number of minutes.
*
* @param string $key
* @param mixed $value
* @param float|int $minutes
* @return void
*/
public function put($key, $value, $minutes)
{
$key = $this->prefix.$key;
$value = serialize($value);
$expiration = $this->getTime() + (int) ($minutes * 60);
try {
$this->table()->insert(compact('key', 'value', 'expiration'));
} catch (Exception $e) {
$this->table()->where('key', $key)->update(compact('value', 'expiration'));
}
}
/**
* Increment the value of an item in the cache.
*
* @param string $key
* @param mixed $value
* @return int|bool
*/
public function increment($key, $value = 1)
{
return $this->incrementOrDecrement($key, $value, function ($current, $value) {
return $current + $value;
});
}
/**
* Decrement the value of an item in the cache.
*
* @param string $key
* @param mixed $value
* @return int|bool
*/
public function decrement($key, $value = 1)
{
return $this->incrementOrDecrement($key, $value, function ($current, $value) {
return $current - $value;
});
}
/**
* Increment or decrement an item in the cache.
*
* @param string $key
* @param mixed $value
* @param \Closure $callback
* @return int|bool
*/
protected function incrementOrDecrement($key, $value, Closure $callback)
{
return $this->connection->transaction(function () use ($key, $value, $callback) {
$prefixed = $this->prefix.$key;
$cache = $this->table()->where('key', $prefixed)
->lockForUpdate()->first();
// If there is no value in the cache, we will return false here. Otherwise the
// value will be decrypted and we will proceed with this function to either
// increment or decrement this value based on the given action callbacks.
if (is_null($cache)) {
return false;
}
$cache = is_array($cache) ? (object) $cache : $cache;
$current = unserialize($cache->value);
// Here we'll call this callback function that was given to the function which
// is used to either increment or decrement the function. We use a callback
// so we do not have to recreate all this logic in each of the functions.
$new = $callback((int) $current, $value);
if (! is_numeric($current)) {
return false;
}
// Here we will update the values in the table. We will also encrypt the value
// since database cache values are encrypted by default with secure storage
// that can't be easily read. We will return the new value after storing.
$this->table()->where('key', $prefixed)->update([
'value' => serialize($new),
]);
return $new;
});
}
/**
* Get the current system time.
*
* @return int
*/
protected function getTime()
{
return Carbon::now()->getTimestamp();
}
/**
* Store an item in the cache indefinitely.
*
* @param string $key
* @param mixed $value
* @return void
*/
public function forever($key, $value)
{
$this->put($key, $value, 5256000);
}
/**
* Remove an item from the cache.
*
* @param string $key
* @return bool
*/
public function forget($key)
{
$this->table()->where('key', '=', $this->prefix.$key)->delete();
return true;
}
/**
* Remove all items from the cache.
*
* @return bool
*/
public function flush()
{
return (bool) $this->table()->delete();
}
/**
* Get a query builder for the cache table.
*
* @return \Illuminate\Database\Query\Builder
*/
protected function table()
{
return $this->connection->table($this->table);
}
/**
* Get the underlying database connection.
*
* @return \Illuminate\Database\ConnectionInterface
*/
public function getConnection()
{
return $this->connection;
}
/**
* Get the cache key prefix.
*
* @return string
*/
public function getPrefix()
{
return $this->prefix;
}
}
| vetruvet/framework | src/Illuminate/Cache/DatabaseStore.php | PHP | mit | 6,680 |
package net.sf.esfinge.metadata.validate.minValue; | pedrocavalero/metadata | src/test/java/net/sf/esfinge/metadata/validate/minValue/package-info.java | Java | mit | 50 |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* Person object.
*
*/
class PersonResult {
/**
* Create a PersonResult.
* @member {string} personId personId of the target face list.
* @member {array} [persistedFaceIds] persistedFaceIds of registered faces in
* the person. These persistedFaceIds are returned from Person - Add a Person
* Face, and will not expire.
* @member {string} [name] Person's display name.
* @member {string} [userData] User-provided data attached to this person.
*/
constructor() {
}
/**
* Defines the metadata of PersonResult
*
* @returns {object} metadata of PersonResult
*
*/
mapper() {
return {
required: false,
serializedName: 'PersonResult',
type: {
name: 'Composite',
className: 'PersonResult',
modelProperties: {
personId: {
required: true,
serializedName: 'personId',
type: {
name: 'String'
}
},
persistedFaceIds: {
required: false,
serializedName: 'persistedFaceIds',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
name: {
required: false,
serializedName: 'name',
type: {
name: 'String'
}
},
userData: {
required: false,
serializedName: 'userData',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = PersonResult;
| lmazuel/azure-sdk-for-node | lib/services/face/lib/models/personResult.js | JavaScript | mit | 2,087 |
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Ical.Net.DataTypes;
namespace Ical.Net.Serialization.DataTypes
{
public class RequestStatusSerializer : StringSerializer
{
public RequestStatusSerializer() { }
public RequestStatusSerializer(SerializationContext ctx) : base(ctx) { }
public override Type TargetType => typeof (RequestStatus);
public override string SerializeToString(object obj)
{
try
{
var rs = obj as RequestStatus;
if (rs == null)
{
return null;
}
// Push the object onto the serialization stack
SerializationContext.Push(rs);
try
{
var factory = GetService<ISerializerFactory>();
var serializer = factory?.Build(typeof (StatusCode), SerializationContext) as IStringSerializer;
if (serializer == null)
{
return null;
}
var builder = new StringBuilder();
builder.Append(Escape(serializer.SerializeToString(rs.StatusCode)));
builder.Append(";");
builder.Append(Escape(rs.Description));
if (!string.IsNullOrWhiteSpace(rs.ExtraData))
{
builder.Append(";");
builder.Append(Escape(rs.ExtraData));
}
return Encode(rs, builder.ToString());
}
finally
{
// Pop the object off the serialization stack
SerializationContext.Pop();
}
}
catch
{
return null;
}
}
internal static readonly Regex NarrowRequestMatch = new Regex(@"(.*?[^\\]);(.*?[^\\]);(.+)", RegexOptions.Compiled);
internal static readonly Regex BroadRequestMatch = new Regex(@"(.*?[^\\]);(.+)", RegexOptions.Compiled);
public override object Deserialize(TextReader tr)
{
var value = tr.ReadToEnd();
var rs = CreateAndAssociate() as RequestStatus;
if (rs == null)
{
return null;
}
// Decode the value as needed
value = Decode(rs, value);
// Push the object onto the serialization stack
SerializationContext.Push(rs);
try
{
var factory = GetService<ISerializerFactory>();
if (factory == null)
{
return null;
}
var match = NarrowRequestMatch.Match(value);
if (!match.Success)
{
match = BroadRequestMatch.Match(value);
}
if (match.Success)
{
var serializer = factory.Build(typeof(StatusCode), SerializationContext) as IStringSerializer;
if (serializer == null)
{
return null;
}
rs.StatusCode = serializer.Deserialize(new StringReader(Unescape(match.Groups[1].Value))) as StatusCode;
rs.Description = Unescape(match.Groups[2].Value);
if (match.Groups.Count == 4)
{
rs.ExtraData = Unescape(match.Groups[3].Value);
}
return rs;
}
}
finally
{
// Pop the object off the serialization stack
SerializationContext.Pop();
}
return null;
}
}
} | rianjs/ical.net | src/Ical.Net/Serialization/DataTypes/RequestStatusSerializer.cs | C# | mit | 3,938 |
<?php return array(
//Use the below link to get the parameters to be passed.
//http://www.tig12.net/downloads/apidocs/wp/wp-includes/PHPMailer.class.html#det_fields_to
"type"=>array(
// Sets Mailer to send message using PHP mail() function. (true, false)
"IsMail"=>false,
// Sets Mailer to send message using SMTP. If set to true, other options are also available. (true, false )
"IsSMTP"=>true,
// Sets Mailer to send message using the Sendmail program. (true, false)
"IsSendmail"=>false,
// Sets Mailer to send message using the qmail MTA. (true, false )
"IsQmail"=>false
),
"smtp"=>array(
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
"SMTPDebug" => 0,
//Ask for HTML-friendly debug output
"Debugoutput" => 'html',
//Set the hostname of the mail server
"Host" => 'smtp.gmail.com',
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
"Port" => 587,
//Set the encryption system to use - ssl (deprecated) or tls
"SMTPSecure" => 'tls',
//Whether to use SMTP authentication
"SMTPAuth" => true,
//Username to use for SMTP authentication - use full email address for gmail
"Username" => "",
//Password to use for SMTP authentication
"Password" => "",
//Set who the message is to be sent from
"From" =>"",
//Set Name of the sender
"FromName"=>""
),
//Authenticate via POP3 (true, false)
//Now you should be clear to submit messages over SMTP for a while
//Only applies if your host supports POP-before-SMTP
"pop"=>array(false,"'pop3.example.com', 110, 30, 'username', 'password', 1")
); | alaksandarjesus/foreach2BiSmarty_master | app/mail.php | PHP | mit | 1,634 |
/*jshint maxstatements:false*/
define(function (require, exports) {
"use strict";
var moment = require("moment"),
Promise = require("bluebird"),
_ = brackets.getModule("thirdparty/lodash"),
CodeInspection = brackets.getModule("language/CodeInspection"),
CommandManager = brackets.getModule("command/CommandManager"),
Commands = brackets.getModule("command/Commands"),
Dialogs = brackets.getModule("widgets/Dialogs"),
DocumentManager = brackets.getModule("document/DocumentManager"),
EditorManager = brackets.getModule("editor/EditorManager"),
FileUtils = brackets.getModule("file/FileUtils"),
FileViewController = brackets.getModule("project/FileViewController"),
KeyBindingManager = brackets.getModule("command/KeyBindingManager"),
LanguageManager = brackets.getModule("language/LanguageManager"),
FileSystem = brackets.getModule("filesystem/FileSystem"),
Menus = brackets.getModule("command/Menus"),
FindInFiles = brackets.getModule("search/FindInFiles"),
PanelManager = brackets.getModule("view/PanelManager"),
ProjectManager = brackets.getModule("project/ProjectManager"),
StringUtils = brackets.getModule("utils/StringUtils"),
Svn = require("src/svn/Svn"),
Events = require("./Events"),
EventEmitter = require("./EventEmitter"),
Preferences = require("./Preferences"),
ErrorHandler = require("./ErrorHandler"),
ExpectedError = require("./ExpectedError"),
Main = require("./Main"),
GutterManager = require("./GutterManager"),
Strings = require("../strings"),
Utils = require("src/Utils"),
SettingsDialog = require("./SettingsDialog"),
PANEL_COMMAND_ID = "brackets-git.panel";
var svnPanelTemplate = require("text!templates/svn-panel.html"),
gitPanelResultsTemplate = require("text!templates/git-panel-results.html"),
gitAuthorsDialogTemplate = require("text!templates/authors-dialog.html"),
gitCommitDialogTemplate = require("text!templates/git-commit-dialog.html"),
gitDiffDialogTemplate = require("text!templates/git-diff-dialog.html"),
questionDialogTemplate = require("text!templates/git-question-dialog.html");
var showFileWhiteList = /^\.gitignore$/;
var gitPanel = null,
$gitPanel = $(null),
gitPanelDisabled = null,
gitPanelMode = null,
showingUntracked = true,
$tableContainer = $(null);
/**
* Reloads the Document's contents from disk, discarding any unsaved changes in the editor.
*
* @param {!Document} doc
* @return {Promise} Resolved after editor has been refreshed; rejected if unable to load the
* file's new content. Errors are logged but no UI is shown.
*/
function _reloadDoc(doc) {
return Promise.cast(FileUtils.readAsText(doc.file))
.then(function (text) {
doc.refreshText(text, new Date());
})
.catch(function (err) {
ErrorHandler.logError("Error reloading contents of " + doc.file.fullPath);
ErrorHandler.logError(err);
});
}
function lintFile(filename) {
return CodeInspection.inspectFile(FileSystem.getFileForPath(Utils.getProjectRoot() + filename));
}
function _makeDialogBig($dialog) {
var $wrapper = $dialog.parents(".modal-wrapper").first();
if ($wrapper.length === 0) { return; }
// We need bigger commit dialog
var minWidth = 500,
minHeight = 300,
maxWidth = $wrapper.width(),
maxHeight = $wrapper.height(),
desiredWidth = maxWidth / 2,
desiredHeight = maxHeight / 2;
if (desiredWidth < minWidth) { desiredWidth = minWidth; }
if (desiredHeight < minHeight) { desiredHeight = minHeight; }
$dialog
.width(desiredWidth)
.children(".modal-body")
.css("max-height", desiredHeight)
.end();
return { width: desiredWidth, height: desiredHeight };
}
function _showCommitDialog(stagedDiff, lintResults, prefilledMessage) {
// Flatten the error structure from various providers
lintResults.forEach(function (lintResult) {
lintResult.errors = [];
if (Array.isArray(lintResult.result)) {
lintResult.result.forEach(function (resultSet) {
if (!resultSet.result || !resultSet.result.errors) { return; }
var providerName = resultSet.provider.name;
resultSet.result.errors.forEach(function (e) {
lintResult.errors.push((e.pos.line + 1) + ": " + e.message + " (" + providerName + ")");
});
});
} else {
ErrorHandler.logError("[brackets-git] lintResults contain object in unexpected format: " + JSON.stringify(lintResult));
}
lintResult.hasErrors = lintResult.errors.length > 0;
});
// Filter out only results with errors to show
lintResults = _.filter(lintResults, function (lintResult) {
return lintResult.hasErrors;
});
// Open the dialog
var compiledTemplate = Mustache.render(gitCommitDialogTemplate, {
Strings: Strings,
hasLintProblems: lintResults.length > 0,
lintResults: lintResults
}),
dialog = Dialogs.showModalDialogUsingTemplate(compiledTemplate),
$dialog = dialog.getElement();
// We need bigger commit dialog
_makeDialogBig($dialog);
// Show nicely colored commit diff
$dialog.find(".commit-diff").append(Utils.formatDiff(stagedDiff));
function getCommitMessageElement() {
var r = $dialog.find("[name='commit-message']:visible");
if (r.length !== 1) {
r = $dialog.find("[name='commit-message']");
for (var i = 0; i < r.length; i++) {
if ($(r[i]).css("display") !== "none") {
return $(r[i]);
}
}
}
return r;
}
var $commitMessageCount = $dialog.find("input[name='commit-message-count']");
// Add event to count characters in commit message
var recalculateMessageLength = function () {
var val = getCommitMessageElement().val().trim(),
length = val.length;
if (val.indexOf("\n")) {
// longest line
length = Math.max.apply(null, val.split("\n").map(function (l) { return l.length; }));
}
$commitMessageCount
.val(length)
.toggleClass("over50", length > 50 && length <= 100)
.toggleClass("over100", length > 100);
};
var usingTextArea = false;
// commit message handling
function switchCommitMessageElement() {
usingTextArea = !usingTextArea;
var findStr = "[name='commit-message']",
currentValue = $dialog.find(findStr + ":visible").val();
$dialog.find(findStr).toggle();
$dialog.find(findStr + ":visible")
.val(currentValue)
.focus();
recalculateMessageLength();
}
$dialog.find("button.primary").on("click", function (e) {
var $commitMessage = getCommitMessageElement();
if ($commitMessage.val().trim().length === 0) {
e.stopPropagation();
$commitMessage.addClass("invalid");
} else {
$commitMessage.removeClass("invalid");
}
});
$dialog.find("button.extendedCommit").on("click", function () {
switchCommitMessageElement();
// this value will be set only when manually triggered
Preferences.set("useTextAreaForCommitByDefault", usingTextArea);
});
function prefillMessage(msg) {
if (msg.indexOf("\n") !== -1 && !usingTextArea) {
switchCommitMessageElement();
}
$dialog.find("[name='commit-message']:visible").val(msg);
recalculateMessageLength();
}
if (Preferences.get("useTextAreaForCommitByDefault")) {
switchCommitMessageElement();
}
if (prefilledMessage) {
prefillMessage(prefilledMessage.trim());
}
// Add focus to commit message input
getCommitMessageElement().focus();
$dialog.find("[name='commit-message']")
.on("keyup", recalculateMessageLength)
.on("change", recalculateMessageLength);
recalculateMessageLength();
dialog.done(function (buttonId) {
if (buttonId === "ok") {
// this event won't launch when commit-message is empty so its safe to assume that it is not
var commitMessage = getCommitMessageElement().val();
// if commit message is extended and has a newline, put an empty line after first line to separate subject and body
var s = commitMessage.split("\n");
if (s.length > 1 && s[1].trim() !== "") {
s.splice(1, 0, "");
}
commitMessage = s.join("\n");
// now we are going to be paranoid and we will check if some mofo didn't change our diff
_getStagedDiff().then(function (diff) {
if (diff === stagedDiff) {
return Svn.commit(commitMessage);
} else {
throw new Error("Index was changed while commit dialog was shown!");
}
}).catch(function (err) {
ErrorHandler.showError(err, "Git Commit failed");
}).finally(function () {
EventEmitter.emit(Events.GIT_COMMITED);
refresh();
});
} else {
// this will trigger refreshing where appropriate
Svn.status();
}
});
}
function _showAuthors(file, blame, fromLine, toLine) {
var linesTotal = blame.length;
var blameStats = blame.reduce(function (stats, lineInfo) {
var name = lineInfo.author + " " + lineInfo["author-mail"];
if (stats[name]) {
stats[name] += 1;
} else {
stats[name] = 1;
}
return stats;
}, {});
blameStats = _.reduce(blameStats, function (arr, val, key) {
arr.push({
authorName: key,
lines: val,
percentage: Math.round(val / (linesTotal / 100))
});
return arr;
}, []);
blameStats = _.sortBy(blameStats, "lines").reverse();
if (fromLine || toLine) {
file += " (" + Strings.LINES + " " + fromLine + "-" + toLine + ")";
}
var compiledTemplate = Mustache.render(gitAuthorsDialogTemplate, {
file: file,
blameStats: blameStats,
Strings: Strings
});
Dialogs.showModalDialogUsingTemplate(compiledTemplate);
}
function _getCurrentFilePath(editor) {
var projectRoot = Utils.getProjectRoot(),
document = editor ? editor.document : DocumentManager.getCurrentDocument(),
filePath = document.file.fullPath;
if (filePath.indexOf(projectRoot) === 0) {
filePath = filePath.substring(projectRoot.length);
}
return filePath;
}
function handleAuthorsSelection() {
var editor = EditorManager.getActiveEditor(),
filePath = _getCurrentFilePath(editor),
currentSelection = editor.getSelection(),
fromLine = currentSelection.start.line + 1,
toLine = currentSelection.end.line + 1;
// fix when nothing is selected on that line
if (currentSelection.end.ch === 0) { toLine = toLine - 1; }
var isSomethingSelected = currentSelection.start.line !== currentSelection.end.line ||
currentSelection.start.ch !== currentSelection.end.ch;
if (!isSomethingSelected) {
ErrorHandler.showError(new ExpectedError("Nothing is selected!"));
return;
}
Svn.getBlame(filePath, fromLine, toLine).then(function (blame) {
return _showAuthors(filePath, blame, fromLine, toLine);
}).catch(function (err) {
ErrorHandler.showError(err, "Git Blame failed");
});
}
function handleAuthorsFile() {
var filePath = _getCurrentFilePath();
Svn.getBlame(filePath).then(function (blame) {
return _showAuthors(filePath, blame);
}).catch(function (err) {
ErrorHandler.showError(err, "Git Blame failed");
});
}
function handleGitDiff(file) {
Svn.diffFileNice(file).then(function (diff) {
// show the dialog with the diff
var compiledTemplate = Mustache.render(gitDiffDialogTemplate, { file: file, Strings: Strings }),
dialog = Dialogs.showModalDialogUsingTemplate(compiledTemplate),
$dialog = dialog.getElement();
_makeDialogBig($dialog);
$dialog.find(".commit-diff").append(Utils.formatDiff(diff));
}).catch(function (err) {
ErrorHandler.showError(err, "SVN Diff failed");
});
}
function handleGitUndo(file) {
var compiledTemplate = Mustache.render(questionDialogTemplate, {
title: Strings.UNDO_CHANGES,
question: StringUtils.format(Strings.Q_UNDO_CHANGES, _.escape(file)),
Strings: Strings
});
Dialogs.showModalDialogUsingTemplate(compiledTemplate).done(function (buttonId) {
if (buttonId === "ok") {
Svn.discardFileChanges(file).then(function () {
var currentProjectRoot = Utils.getProjectRoot();
DocumentManager.getAllOpenDocuments().forEach(function (doc) {
if (doc.file.fullPath === currentProjectRoot + file) {
_reloadDoc(doc);
}
});
refresh();
}).catch(function (err) {
ErrorHandler.showError(err, "Git Checkout failed");
});
}
});
}
function handleGitDelete(file) {
var compiledTemplate = Mustache.render(questionDialogTemplate, {
title: Strings.DELETE_FILE,
question: StringUtils.format(Strings.Q_DELETE_FILE, _.escape(file)),
Strings: Strings
});
Dialogs.showModalDialogUsingTemplate(compiledTemplate).done(function (buttonId) {
if (buttonId === "ok") {
FileSystem.resolve(Utils.getProjectRoot() + file, function (err, fileEntry) {
if (err) {
ErrorHandler.showError(err, "Could not resolve file");
return;
}
Promise.cast(ProjectManager.deleteItem(fileEntry))
.then(function () {
refresh();
})
.catch(function (err) {
ErrorHandler.showError(err, "File deletion failed");
});
});
}
});
}
function handleGlobalUpdate(){
var files = [];
return handleSvnUpdate(files);
}
function handleSvnUpdate(files){
if(!_.isArray(files)) return;
return Svn.updateFile(files).then(function(stdout){
refresh();
});
}
/**
* strips trailing whitespace from all the diffs and adds \n to the end
*/
function stripWhitespaceFromFile(filename, clearWholeFile) {
return new Promise(function (resolve, reject) {
var fullPath = Utils.getProjectRoot() + filename,
removeBom = Preferences.get("removeByteOrderMark"),
normalizeLineEndings = Preferences.get("normalizeLineEndings");
var _cleanLines = function (lineNumbers) {
// clean the file
var fileEntry = FileSystem.getFileForPath(fullPath);
return FileUtils.readAsText(fileEntry).then(function (text) {
if (removeBom) {
// remove BOM - \ufeff
text = text.replace(/\ufeff/g, "");
}
if (normalizeLineEndings) {
// normalizes line endings
text = text.replace(/\r\n/g, "\n");
}
// process lines
var lines = text.split("\n");
if (lineNumbers) {
lineNumbers.forEach(function (lineNumber) {
lines[lineNumber] = lines[lineNumber].replace(/\s+$/, "");
});
} else {
lines.forEach(function (ln, lineNumber) {
lines[lineNumber] = lines[lineNumber].replace(/\s+$/, "");
});
}
// add empty line to the end, i've heard that git likes that for some reason
if (Preferences.get("addEndlineToTheEndOfFile")) {
var lastLineNumber = lines.length - 1;
if (lines[lastLineNumber].length > 0) {
lines[lastLineNumber] = lines[lastLineNumber].replace(/\s+$/, "");
}
if (lines[lastLineNumber].length > 0) {
lines.push("");
}
}
//-
text = lines.join("\n");
return Promise.cast(FileUtils.writeText(fileEntry, text))
.catch(function (err) {
ErrorHandler.logError("Wasn't able to clean whitespace from file: " + fullPath);
resolve();
throw err;
})
.then(function () {
// refresh the file if it's open in the background
DocumentManager.getAllOpenDocuments().forEach(function (doc) {
if (doc.file.fullPath === fullPath) {
_reloadDoc(doc);
}
});
// diffs were cleaned in this file
resolve();
});
});
};
if (clearWholeFile) {
_cleanLines(null);
} else {
Svn.diffFile(filename).then(function (diff) {
if (!diff) { return resolve(); }
var modified = [],
changesets = diff.split("\n").filter(function (l) { return l.match(/^@@/) !== null; });
// collect line numbers to clean
changesets.forEach(function (line) {
var i,
m = line.match(/^@@ -([,0-9]+) \+([,0-9]+) @@/),
s = m[2].split(","),
from = parseInt(s[0], 10),
to = from - 1 + (parseInt(s[1], 10) || 1);
for (i = from; i <= to; i++) { modified.push(i > 0 ? i - 1 : 0); }
});
_cleanLines(modified);
}).catch(function (ex) {
// This error will bubble up to preparing commit dialog so just log here
ErrorHandler.logError(ex);
reject(ex);
});
}
});
}
function _getStagedDiff() {
return Svn.getDiffOfStagedFiles().then(function (diff) {
if (!diff) {
return Svn.getListOfStagedFiles().then(function (filesList) {
return Strings.DIFF_FAILED_SEE_FILES + "\n\n" + filesList;
});
}
return diff;
});
}
// whatToDo gets values "continue" "skip" "abort"
function handleRebase(whatToDo) {
Svn.rebase(whatToDo).then(function () {
EventEmitter.emit(Events.REFRESH_ALL);
}).catch(function (err) {
ErrorHandler.showError(err, "Rebase " + whatToDo + " failed");
});
}
function abortMerge() {
Svn.discardAllChanges().then(function () {
EventEmitter.emit(Events.REFRESH_ALL);
}).catch(function (err) {
ErrorHandler.showError(err, "Merge abort failed");
});
}
function findConflicts() {
FindInFiles.doSearch(/^<<<<<<<\s|^=======\s|^>>>>>>>\s/gm);
}
function commitMerge() {
Utils.loadPathContent(Utils.getProjectRoot() + "/.git/MERGE_MSG").then(function (msg) {
handleGitCommit(msg);
}).catch(function (err) {
ErrorHandler.showError(err, "Merge commit failed");
});
}
function handleGitCommit(prefilledMessage) {
var codeInspectionEnabled = Preferences.get("useCodeInspection");
var stripWhitespace = Preferences.get("stripWhitespaceFromCommits");
// Disable button (it will be enabled when selecting files after reset)
Utils.setLoading($gitPanel.find(".git-commit"));
// First reset staged files, then add selected files to the index.
Svn.status().then(function (files) {
files = _.filter(files, function (file) {
return file.status.indexOf(Svn.FILE_STATUS.MODIFIED) !== -1;
});
if (files.length === 0) {
return ErrorHandler.showError(new Error("Commit button should have been disabled"), "Nothing staged to commit");
}
var lintResults = [],
promises = [];
files.forEach(function (fileObj) {
var queue = Promise.resolve();
var isDeleted = fileObj.status.indexOf(Svn.FILE_STATUS.DELETED) !== -1,
updateIndex = isDeleted;
// strip whitespace if configured to do so and file was not deleted
if (stripWhitespace && !isDeleted) {
// strip whitespace only for recognized languages so binary files won't get corrupted
var langId = LanguageManager.getLanguageForPath(fileObj.file).getId();
if (["unknown", "binary", "image", "markdown"].indexOf(langId) === -1) {
queue = queue.then(function () {
var clearWholeFile = fileObj.status.indexOf(Svn.FILE_STATUS.UNTRACKED) !== -1 ||
fileObj.status.indexOf(Svn.FILE_STATUS.RENAMED) !== -1;
return stripWhitespaceFromFile(fileObj.file, clearWholeFile);
});
}
}
// do a code inspection for the file, if it was not deleted
if (codeInspectionEnabled && !isDeleted) {
queue = queue.then(function () {
return lintFile(fileObj.file).then(function (result) {
if (result) {
lintResults.push({
filename: fileObj.file,
result: result
});
}
});
});
}
promises.push(queue);
});
return Promise.all(promises).then(function () {
// All files are in the index now, get the diff and show dialog.
return _getStagedDiff().then(function (diff) {
return _showCommitDialog(diff, lintResults, prefilledMessage);
});
});
}).catch(function (err) {
ErrorHandler.showError(err, "Preparing commit dialog failed");
}).finally(function () {
Utils.unsetLoading($gitPanel.find(".git-commit"));
});
}
function refreshCurrentFile() {
var currentProjectRoot = Utils.getProjectRoot();
var currentDoc = DocumentManager.getCurrentDocument();
if (currentDoc) {
$gitPanel.find("tr").each(function () {
var currentFullPath = currentDoc.file.fullPath,
thisFile = $(this).attr("x-file");
$(this).toggleClass("selected", currentProjectRoot + thisFile === currentFullPath);
});
} else {
$gitPanel.find("tr").removeClass("selected");
}
}
function shouldShow(fileObj) {
if (showFileWhiteList.test(fileObj.name)) {
return true;
}
return ProjectManager.shouldShow(fileObj);
}
function _refreshTableContainer(files) {
if (!gitPanel.isVisible()) {
return;
}
// remove files that we should not show
files = _.filter(files, function (file) {
return shouldShow(file);
});
var allStaged = files.length > 0 && _.all(files, function (file) { return file.status.indexOf(Svn.FILE_STATUS.STAGED) !== -1; });
$gitPanel.find(".check-all").prop("checked", allStaged).prop("disabled", files.length === 0);
var $editedList = $tableContainer.find(".git-edited-list");
var visibleBefore = $editedList.length ? $editedList.is(":visible") : true;
$editedList.remove();
if (files.length === 0) {
$tableContainer.append($("<p class='git-edited-list nothing-to-commit' />").text(Strings.NOTHING_TO_COMMIT));
} else {
// if desired, remove untracked files from the results
if (showingUntracked === false) {
files = _.filter(files, function (file) {
return file.status.indexOf(Svn.FILE_STATUS.UNTRACKED) === -1;
});
}
// -
files.forEach(function (file) {
file.staged = file.status.indexOf(Svn.FILE_STATUS.STAGED) !== -1;
file.statusText = file.status.map(function (status) {
return Strings["FILE_" + status];
}).join(", ");
file.allowDiff = file.status.indexOf(Svn.FILE_STATUS.UNTRACKED) === -1 &&
file.status.indexOf(Svn.FILE_STATUS.RENAMED) === -1 &&
file.status.indexOf(Svn.FILE_STATUS.DELETED) === -1;
file.allowDelete = file.status.indexOf(Svn.FILE_STATUS.UNTRACKED) !== -1;
file.allowUndo = !file.allowDelete && file.status.indexOf(Svn.FILE_STATUS.MODIFIED) !== -1;
file.allowUpdate = file.status.indexOf(Svn.FILE_STATUS.OUTOFDATE) !== -1;
file.allowAdd = file.status.indexOf(Svn.FILE_STATUS.UNTRACKED) > -1;
});
$tableContainer.append(Mustache.render(gitPanelResultsTemplate, {
files: files,
Strings: Strings
}));
refreshCurrentFile();
}
$tableContainer.find(".git-edited-list").toggle(visibleBefore);
}
function refresh() {
// set the history panel to false and remove the class that show the button history active when refresh
$gitPanel.find(".git-history-toggle").removeClass("active").attr("title", Strings.TOOLTIP_SHOW_HISTORY);
$gitPanel.find(".git-file-history").removeClass("active").attr("title", Strings.TOOLTIP_SHOW_FILE_HISTORY);
if (gitPanelMode === "not-repo") {
$tableContainer.empty();
return Promise.resolve();
}
$tableContainer.find("#git-history-list").remove();
$tableContainer.find(".git-edited-list").show();
var p1 = Svn.status(true);
//- push button
//var $pushBtn = $gitPanel.find(".git-push");
// var p2 = Svn.getCommitsAhead().then(function (commits) {
// $pushBtn.children("span").remove();
// if (commits.length > 0) {
// $pushBtn.append($("<span/>").text(" (" + commits.length + ")"));
// }
// }).catch(function () {
// $pushBtn.children("span").remove();
// });
// FUTURE: who listens for this?
return Promise.all([p1]);
}
function toggle(bool) {
if (gitPanelDisabled === true) {
return;
}
if (typeof bool !== "boolean") {
bool = !gitPanel.isVisible();
}
Preferences.persist("panelEnabled", bool);
Main.$icon.toggleClass("on", bool);
gitPanel.setVisible(bool);
// Mark menu item as enabled/disabled.
CommandManager.get(PANEL_COMMAND_ID).setChecked(bool);
if (bool) {
refresh();
}
}
function handleToggleUntracked() {
showingUntracked = !showingUntracked;
$gitPanel
.find(".git-toggle-untracked")
.text(showingUntracked ? Strings.HIDE_UNTRACKED : Strings.SHOW_UNTRACKED);
refresh();
}
function commitCurrentFile() {
return Promise.cast(CommandManager.execute("file.save"))
.then(function () {
return Svn.resetIndex();
})
.then(function () {
var currentProjectRoot = Utils.getProjectRoot();
var currentDoc = DocumentManager.getCurrentDocument();
if (currentDoc) {
var relativePath = currentDoc.file.fullPath.substring(currentProjectRoot.length);
return Svn.stage(relativePath).then(function () {
return handleGitCommit();
});
}
});
}
function commitAllFiles() {
return Promise.cast(CommandManager.execute("file.saveAll"))
.then(function () {
return Svn.resetIndex();
})
.then(function () {
return Svn.stageAll().then(function () {
return handleGitCommit();
});
});
}
// Disable "commit" button if there aren't staged files to commit
function _toggleCommitButton(files) {
var anyStaged = _.any(files, function (file) { return file.status.indexOf(Svn.FILE_STATUS.STAGED) !== -1; });
$gitPanel.find(".git-commit").prop("disabled", !anyStaged);
}
EventEmitter.on(Events.GIT_STATUS_RESULTS, function (results) {
_refreshTableContainer(results);
_toggleCommitButton(results);
});
function undoLastLocalCommit() {
Svn.undoLastLocalCommit()
.catch(function (err) {
ErrorHandler.showError(err, "Impossible to undo last commit");
})
.finally(function () {
refresh();
});
}
var lastCheckOneClicked = null;
function attachDefaultTableHandlers() {
$tableContainer = $gitPanel.find(".table-container")
.off()
.on("click", ".check-one", function (e) {
e.stopPropagation();
var $tr = $(this).closest("tr"),
file = $tr.attr("x-file"),
status = $tr.attr("x-status"),
isChecked = $(this).is(":checked");
if (e.shiftKey) {
// do something if we press shift. Right now? Nothing.
}
lastCheckOneClicked = file;
})
.on("dblclick", ".check-one", function (e) {
e.stopPropagation();
})
.on("click", ".btn-git-diff", function (e) {
e.stopPropagation();
handleGitDiff($(e.target).closest("tr").attr("x-file"));
})
.on("click", ".btn-git-undo", function (e) {
e.stopPropagation();
handleGitUndo($(e.target).closest("tr").attr("x-file"));
})
.on("click", ".btn-git-delete", function (e) {
e.stopPropagation();
handleGitDelete($(e.target).closest("tr").attr("x-file"));
})
.on("click", ".btn-svn-add", function(e) {
e.stopPropagation();
handleSvnAdd($(e.target).closest("tr").attr("x-file"));
})
.on("click", ".btn-svn-update", function (e) {
e.stopPropagation();
handleSvnUpdate([$(e.target).closest("tr").attr("x-file")]);
})
.on("click", ".modified-file", function (e) {
var $this = $(e.currentTarget);
if ($this.attr("x-status") === Svn.FILE_STATUS.DELETED) {
return;
}
CommandManager.execute(Commands.FILE_OPEN, {
fullPath: Utils.getProjectRoot() + $this.attr("x-file")
});
})
.on("dblclick", ".modified-file", function (e) {
var $this = $(e.currentTarget);
if ($this.attr("x-status") === Svn.FILE_STATUS.DELETED) {
return;
}
FileViewController.addToWorkingSetAndSelect(Utils.getProjectRoot() + $this.attr("x-file"));
});
}
function discardAllChanges() {
return Utils.askQuestion(Strings.RESET_LOCAL_REPO, Strings.RESET_LOCAL_REPO_CONFIRM, { booleanResponse: true })
.then(function (response) {
if (response) {
return Svn.discardAllChanges().catch(function (err) {
ErrorHandler.showError(err, "Reset of local repository failed");
}).then(function () {
refresh();
});
}
});
}
function init() {
// Add panel
var panelHtml = Mustache.render(svnPanelTemplate, {
enableAdvancedFeatures: Preferences.get("enableAdvancedFeatures"),
showBashButton: Preferences.get("showBashButton"),
showReportBugButton: Preferences.get("showReportBugButton"),
S: Strings
});
var $panelHtml = $(panelHtml);
$panelHtml.find(".git-available, .git-not-available").hide();
gitPanel = PanelManager.createBottomPanel("brackets-git.panel", $panelHtml, 100);
$gitPanel = gitPanel.$panel;
$gitPanel
.on("click", ".close", toggle)
.on("click", ".check-all", function () {
$('.check-one').attr('checked',true);
})
.on("click", ".git-refresh", EventEmitter.emitFactory(Events.REFRESH_ALL))
.on("click", ".git-commit", EventEmitter.emitFactory(Events.HANDLE_GIT_COMMIT))
.on("click", ".git-commit-merge", commitMerge)
.on("click", ".svn-update", handleGlobalUpdate)
.on("click", ".git-find-conflicts", findConflicts)
.on("click", ".git-prev-gutter", GutterManager.goToPrev)
.on("click", ".git-next-gutter", GutterManager.goToNext)
.on("click", ".git-toggle-untracked", handleToggleUntracked)
.on("click", ".authors-selection", handleAuthorsSelection)
.on("click", ".authors-file", handleAuthorsFile)
.on("click", ".git-file-history", EventEmitter.emitFactory(Events.HISTORY_SHOW, "FILE"))
.on("click", ".git-history-toggle", EventEmitter.emitFactory(Events.HISTORY_SHOW, "GLOBAL"))
.on("click", ".git-bug", ErrorHandler.reportBug)
.on("click", ".git-settings", SettingsDialog.show)
.on("contextmenu", "tr", function (e) {
var $this = $(this);
if ($this.hasClass("history-commit")) { return; }
$this.click();
setTimeout(function () {
Menus.getContextMenu("git-panel-context-menu").open(e);
}, 1);
})
.on("click", ".git-bash", EventEmitter.emitFactory(Events.TERMINAL_OPEN))
.on("click", ".reset-all", discardAllChanges);
// Attaching table handlers
attachDefaultTableHandlers();
// Commit current and all shortcuts
var COMMIT_CURRENT_CMD = "brackets-git.commitCurrent",
COMMIT_ALL_CMD = "brackets-git.commitAll",
BASH_CMD = "brackets-git.launchBash",
PUSH_CMD = "brackets-git.push",
PULL_CMD = "brackets-git.pull",
GOTO_PREV_CHANGE = "brackets-git.gotoPrevChange",
GOTO_NEXT_CHANGE = "brackets-git.gotoNextChange";
// Add command to menu.
// Register command for opening bottom panel.
CommandManager.register(Strings.PANEL_COMMAND, PANEL_COMMAND_ID, toggle);
KeyBindingManager.addBinding(PANEL_COMMAND_ID, Preferences.get("panelShortcut"));
CommandManager.register(Strings.COMMIT_CURRENT_SHORTCUT, COMMIT_CURRENT_CMD, commitCurrentFile);
KeyBindingManager.addBinding(COMMIT_CURRENT_CMD, Preferences.get("commitCurrentShortcut"));
CommandManager.register(Strings.COMMIT_ALL_SHORTCUT, COMMIT_ALL_CMD, commitAllFiles);
KeyBindingManager.addBinding(COMMIT_ALL_CMD, Preferences.get("commitAllShortcut"));
CommandManager.register(Strings.LAUNCH_BASH_SHORTCUT, BASH_CMD, EventEmitter.emitFactory(Events.TERMINAL_OPEN));
KeyBindingManager.addBinding(BASH_CMD, Preferences.get("bashShortcut"));
CommandManager.register(Strings.PUSH_SHORTCUT, PUSH_CMD, EventEmitter.emitFactory(Events.HANDLE_PUSH));
KeyBindingManager.addBinding(PUSH_CMD, Preferences.get("pushShortcut"));
CommandManager.register(Strings.PULL_SHORTCUT, PULL_CMD, EventEmitter.emitFactory(Events.HANDLE_PULL));
KeyBindingManager.addBinding(PULL_CMD, Preferences.get("pullShortcut"));
CommandManager.register(Strings.GOTO_PREVIOUS_GIT_CHANGE, GOTO_PREV_CHANGE, GutterManager.goToPrev);
KeyBindingManager.addBinding(GOTO_PREV_CHANGE, Preferences.get("gotoPrevChangeShortcut"));
CommandManager.register(Strings.GOTO_NEXT_GIT_CHANGE, GOTO_NEXT_CHANGE, GutterManager.goToNext);
KeyBindingManager.addBinding(GOTO_NEXT_CHANGE, Preferences.get("gotoNextChangeShortcut"));
// Init moment - use the correct language
moment.lang(brackets.getLocale());
if(Svn.isWorkingCopy()){
enable();
}
// Show gitPanel when appropriate
if (Preferences.get("panelEnabled")) {
toggle(true);
}
}
function enable() {
EventEmitter.emit(Events.SVN_ENABLED);
// this function is called after every Branch.refresh
gitPanelMode = null;
//
$gitPanel.find(".git-available").show();
$gitPanel.find(".git-not-available").hide();
//
Main.$icon.removeClass("warning").removeAttr("title");
gitPanelDisabled = false;
// after all is enabled
refresh();
}
function disable(cause) {
EventEmitter.emit(Events.GIT_DISABLED, cause);
gitPanelMode = cause;
// causes: not-repo
if (gitPanelMode === "not-repo") {
$gitPanel.find(".git-available").hide();
$gitPanel.find(".git-not-available").show();
} else {
Main.$icon.addClass("warning").attr("title", cause);
toggle(false);
gitPanelDisabled = true;
}
refresh();
}
// Event listeners
EventEmitter.on(Events.BRACKETS_CURRENT_DOCUMENT_CHANGE, function () {
if (!gitPanel) { return; }
refreshCurrentFile();
});
EventEmitter.on(Events.BRACKETS_DOCUMENT_SAVED, function () {
if (!gitPanel) { return; }
refresh();
});
EventEmitter.on(Events.REBASE_MERGE_MODE, function (rebaseEnabled, mergeEnabled) {
$gitPanel.find(".git-rebase").toggle(rebaseEnabled);
$gitPanel.find(".git-merge").toggle(mergeEnabled);
$gitPanel.find("button.git-commit").toggle(!rebaseEnabled && !mergeEnabled);
});
EventEmitter.on(Events.HANDLE_GIT_COMMIT, function () {
handleGitCommit();
});
exports.init = init;
exports.refresh = refresh;
exports.toggle = toggle;
exports.enable = enable;
exports.disable = disable;
exports.getPanel = function () { return $gitPanel; };
});
| seshurajup/brackets-svn | src/Panel.js | JavaScript | mit | 41,379 |
<article id="post-<?php print $ID ?>" <?php post_class(); ?>>
<div class="tb-short-img">
<?php
toebox\inc\ToeBox::HandleFeaturedImage();
?>
</div>
<?php
print \toebox\inc\ToeBox::FormatListTitle($post_title, get_the_permalink());
?>
<div class="entry-metadata">
<!-- TODO: allow setting for turning author and date off on posts -->
<span class="tb-date"><?php the_time(get_option('date_format')); ?></span>
|
<span class="tb-author"><?php print get_the_author(); ?></span>
|
<span class="tb-category"><?php the_category(', ') ?></span>
|
<span class="tb-tags"><?php the_tags( 'Tags: ', ', ', '' ); ?></span>
</div>
<div class="entry-excerpt">
<?php print $body ?>
</div>
</article>
| drydenmaker/Noga | theme/tpl/content/list_short_img.php | PHP | mit | 823 |
#include "stdafx.h"
#include "light.h"
using namespace graphic;
cLight::cLight()
{
}
cLight::~cLight()
{
}
void cLight::Init(TYPE type,
const Vector4 &ambient, // Vector4(1, 1, 1, 1),
const Vector4 &diffuse, // Vector4(0.2, 0.2, 0.2, 1)
const Vector4 &specular, // Vector4(1,1,1,1)
const Vector3 &direction) // Vector3(0,-1,0)
{
ZeroMemory(&m_light, sizeof(m_light));
m_light.Type = (D3DLIGHTTYPE)type;
m_light.Ambient = *(D3DCOLORVALUE*)&ambient;
m_light.Diffuse = *(D3DCOLORVALUE*)&diffuse;
m_light.Specular = *(D3DCOLORVALUE*)&specular;
m_light.Direction = *(D3DXVECTOR3*)&direction;
}
void cLight::SetDirection( const Vector3 &direction )
{
m_light.Direction = *(D3DXVECTOR3*)&direction;
}
void cLight::SetPosition( const Vector3 &pos )
{
m_light.Position = *(D3DXVECTOR3*)&pos;
}
// ±×¸²ÀÚ¸¦ Ãâ·ÂÇϱâ À§ÇÑ Á¤º¸¸¦ ¸®ÅÏÇÑ´Ù.
// modelPos : ±×¸²ÀÚ¸¦ Ãâ·ÂÇÒ ¸ðµ¨ÀÇ À§Ä¡ (¿ùµå»óÀÇ)
// lightPos : ±¤¿øÀÇ À§Ä¡°¡ ÀúÀåµÇ¾î ¸®ÅÏ.
// view : ±¤¿ø¿¡¼ ¸ðµ¨À» ¹Ù¶óº¸´Â ºä Çà·Ä
// proj : ±¤¿ø¿¡¼ ¸ðµ¨À» ¹Ù¶óº¸´Â Åõ¿µ Çà·Ä
// tt : Åõ¿µ ÁÂÇ¥¿¡¼ ÅØ½ºÃÄ ÁÂÇ¥·Î º¯È¯ÇÏ´Â Çà·Ä.
void cLight::GetShadowMatrix( const Vector3 &modelPos,
OUT Vector3 &lightPos, OUT Matrix44 &view, OUT Matrix44 &proj,
OUT Matrix44 &tt )
{
if (D3DLIGHT_DIRECTIONAL == m_light.Type)
{
// ¹æÇ⼺ Á¶¸íÀ̸é Direction º¤Å͸¦ ÅëÇØ À§Ä¡¸¦ °è»êÇÏ°Ô ÇÑ´Ù.
Vector3 pos = *(Vector3*)&m_light.Position;
Vector3 dir = *(Vector3*)&m_light.Direction;
lightPos = -dir * pos.Length();
}
else
{
lightPos = *(Vector3*)&m_light.Position;
}
view.SetView2( lightPos, modelPos, Vector3(0,1,0));
proj.SetProjection( D3DX_PI/8.f, 1, 0.1f, 10000);
D3DXMATRIX mTT= D3DXMATRIX(0.5f, 0.0f, 0.0f, 0.0f
, 0.0f,-0.5f, 0.0f, 0.0f
, 0.0f, 0.0f, 1.0f, 0.0f
, 0.5f, 0.5f, 0.0f, 1.0f);
tt = *(Matrix44*)&mTT;
}
void cLight::Bind(cRenderer &renderer, int lightIndex) const
{
renderer.GetDevice()->SetLight(lightIndex, &m_light); // ±¤¿ø ¼³Á¤.
}
// ¼ÎÀÌ´õ º¯¼ö¿¡ ¶óÀÌÆÃ¿¡ °ü·ÃµÈ º¯¼ö¸¦ ÃʱâÈ ÇÑ´Ù.
void cLight::Bind(cShader &shader) const
{
static cShader *oldPtr = NULL;
static D3DXHANDLE hDir = NULL;
static D3DXHANDLE hPos = NULL;
static D3DXHANDLE hAmbient = NULL;
static D3DXHANDLE hDiffuse = NULL;
static D3DXHANDLE hSpecular = NULL;
static D3DXHANDLE hTheta = NULL;
static D3DXHANDLE hPhi = NULL;
if (oldPtr != &shader)
{
hDir = shader.GetValueHandle("light.dir");
hPos = shader.GetValueHandle("light.pos");
hAmbient = shader.GetValueHandle("light.ambient");
hDiffuse = shader.GetValueHandle("light.diffuse");
hSpecular = shader.GetValueHandle("light.specular");
hTheta = shader.GetValueHandle("light.spotInnerCone");
hPhi = shader.GetValueHandle("light.spotOuterCone");
oldPtr = &shader;
}
shader.SetVector( hDir, *(Vector3*)&m_light.Direction);
shader.SetVector( hPos, *(Vector3*)&m_light.Position);
shader.SetVector( hAmbient, *(Vector4*)&m_light.Ambient);
shader.SetVector( hDiffuse, *(Vector4*)&m_light.Diffuse);
shader.SetVector( hSpecular, *(Vector4*)&m_light.Specular);
shader.SetFloat( hTheta, m_light.Theta);
shader.SetFloat( hPhi, m_light.Phi);
//shader.SetFloat( "light.radius", m_light.r);
}
| jjuiddong/Point-Cloud | Src/Sample/Graphic/base/light.cpp | C++ | mit | 3,142 |
<?php
declare(strict_types=1);
/*
* This file is part of eelly package.
*
* (c) eelly.com
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eelly\SDK\Order\Api;
use Eelly\SDK\EellyClient;
use Eelly\SDK\Order\Service\LikeInterface;
/**
* 订单点赞记录表
*
* @author zhangyingdi<zhangyingdi@eelly.net>
*/
class Like
{
/**
* 新增订单点赞记录
*
* @param array $data 订单点赞记录数据
* @param int $orderData["orderId"] 订单id
* @param int $orderData["userId"] 用户id
*
* @throws \Eelly\SDK\Order\Exception\OrderException
*
* @return bool 新增结果
* @requestExample({
* "data":{
* "orderId":123,
* "userId":148086
* }
* })
* @returnExample(true)
*
* @author zhangyingdi<zhangyingdi@eelly.net>
* @since 2018.04.28
*/
public function addOrderLike(array $data): bool
{
return EellyClient::request('order/like', 'addOrderLike', true, $data);
}
/**
* 新增订单点赞记录
*
* @param array $data 订单点赞记录数据
* @param int $orderData["orderId"] 订单id
* @param int $orderData["userId"] 用户id
*
* @throws \Eelly\SDK\Order\Exception\OrderException
*
* @return bool 新增结果
* @requestExample({
* "data":{
* "orderId":123,
* "userId":148086
* }
* })
* @returnExample(true)
*
* @author zhangyingdi<zhangyingdi@eelly.net>
* @since 2018.04.28
*/
public function addOrderLikeAsync(array $data)
{
return EellyClient::request('order/like', 'addOrderLike', false, $data);
}
/**
* 获取订单点赞信息
*
* @param $orderId 订单id
* @return array
*
* @requestExample({"orderId":162})
* @returnExample([{"oliId":"4","orderId":"161","userId":"148086","createdTime":"1524899508","updateTime":"2018-04-28 15:11:31"},{"oliId":"5","orderId":"161","userId":"11","createdTime":"1524899533","updateTime":"2018-04-28 15:11:55"}])
*
* @author wechan
* @since 2018年05月02日
*/
public function getOrderLikeInfo(int $orderId): array
{
return EellyClient::request('order/like', 'getOrderLikeInfo', true, $orderId);
}
/**
* 获取订单点赞信息
*
* @param $orderId 订单id
* @return array
*
* @requestExample({"orderId":162})
* @returnExample([{"oliId":"4","orderId":"161","userId":"148086","createdTime":"1524899508","updateTime":"2018-04-28 15:11:31"},{"oliId":"5","orderId":"161","userId":"11","createdTime":"1524899533","updateTime":"2018-04-28 15:11:55"}])
*
* @author wechan
* @since 2018年05月02日
*/
public function getOrderLikeInfoAsync(int $orderId)
{
return EellyClient::request('order/like', 'getOrderLikeInfo', false, $orderId);
}
/**
* 新增订单点赞记录 (新版--自定义商品点赞数控制).
*
* @param array $data 订单点赞记录数据
* @param int $orderData["orderId"] 订单id
* @param int $orderData["userId"] 用户id
* @param int $orderData["goodsId"] 商品id
* @param \Eelly\DTO\UidDTO $user 登录用户信息
*
* @throws \Eelly\SDK\Order\Exception\OrderException
*
* @return bool 新增结果
* @requestExample({
* "data":{
* "orderId":123,
* "userId":148086,
* "goodsId":123
* }
* })
* @returnExample(true)
*
* @author zhangyingdi<zhangyingdi@eelly.net>
*
* @since 2018.06.28
*/
public function addOrderLikeNew(array $data, UidDTO $user = null): bool
{
return EellyClient::request('order/like', 'addOrderLikeNew', true, $data, $user);
}
/**
* 新增订单点赞记录 (新版--自定义商品点赞数控制).
*
* @param array $data 订单点赞记录数据
* @param int $orderData["orderId"] 订单id
* @param int $orderData["userId"] 用户id
* @param int $orderData["goodsId"] 商品id
* @param \Eelly\DTO\UidDTO $user 登录用户信息
*
* @throws \Eelly\SDK\Order\Exception\OrderException
*
* @return bool 新增结果
* @requestExample({
* "data":{
* "orderId":123,
* "userId":148086,
* "goodsId":123
* }
* })
* @returnExample(true)
*
* @author zhangyingdi<zhangyingdi@eelly.net>
*
* @since 2018.06.28
*/
public function addOrderLikeNewAsync(array $data, UidDTO $user = null)
{
return EellyClient::request('order/like', 'addOrderLikeNew', false, $data, $user);
}
/**
* @return self
*/
public static function getInstance(): self
{
static $instance;
if (null === $instance) {
$instance = new self();
}
return $instance;
}
} | EellyDev/eelly-sdk-php | src/SDK/Order/Api/Like.php | PHP | mit | 5,298 |
#region "Copyright"
/*
FOR FURTHER DETAILS ABOUT LICENSING, PLEASE VISIT "LICENSE.txt" INSIDE THE SAGEFRAME FOLDER
*/
#endregion
#region "References"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using SageFrame.Web.Utilities;
#endregion
namespace SageFrame.Core.TemplateManagement
{
/// <summary>
/// Manipulates the data needed for template.
/// </summary>
public class TemplateDataProvider
{
/// <summary>
/// Connects to database and returns list of template list.
/// </summary>
/// <param name="PortalID">Portal ID.</param>
/// <param name="UserName">User's name.</param>
/// <returns>List of template.</returns>
public static List<TemplateInfo> GetTemplateList(int PortalID, string UserName)
{
string sp = "[dbo].[sp_TemplateGetList]";
SQLHandler sagesql = new SQLHandler();
List<KeyValuePair<string, object>> ParamCollInput = new List<KeyValuePair<string, object>>();
ParamCollInput.Add(new KeyValuePair<string, object>("@PortalID", PortalID));
ParamCollInput.Add(new KeyValuePair<string, object>("@UserName", UserName));
List<TemplateInfo> lstTemplate = new List<TemplateInfo>();
SqlDataReader reader = null;
try
{
reader = sagesql.ExecuteAsDataReader(sp, ParamCollInput);
while (reader.Read())
{
TemplateInfo obj = new TemplateInfo();
obj.TemplateID = int.Parse(reader["TemplateID"].ToString());
obj.TemplateTitle = reader["TemplateTitle"].ToString();
obj.PortalID = int.Parse(reader["PortalID"].ToString());
obj.Author = reader["Author"].ToString();
obj.AuthorURL = reader["AuthorURL"].ToString();
obj.Description = reader["Description"].ToString();
lstTemplate.Add(obj);
}
reader.Close();
return lstTemplate;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
if (reader != null)
{
reader.Close();
}
}
}
/// <summary>
/// Connects to database and adds template.
/// </summary>
/// <param name="obj">TemplateInfo object containing the template details.</param>
/// <returns>True if the template is added successfully.</returns>
public static bool AddTemplate(TemplateInfo obj)
{
string sp = "[dbo].[sp_TemplateAdd]";
SQLHandler sagesql = new SQLHandler();
List<KeyValuePair<string, object>> ParamCollInput = new List<KeyValuePair<string, object>>();
ParamCollInput.Add(new KeyValuePair<string, object>("@TemplateTitle", obj.TemplateTitle));
ParamCollInput.Add(new KeyValuePair<string, object>("@Author",obj.Author));
ParamCollInput.Add(new KeyValuePair<string, object>("@Description", obj.Description));
ParamCollInput.Add(new KeyValuePair<string, object>("@AuthorURL", obj.AuthorURL));
ParamCollInput.Add(new KeyValuePair<string, object>("@PortalID", obj.PortalID));
ParamCollInput.Add(new KeyValuePair<string, object>("@UserName", obj.AddedBy));
try
{
sagesql.ExecuteNonQuery(sp, ParamCollInput);
return true;
}
catch (Exception ex)
{
throw (ex);
}
}
}
}
| AspxCommerce/AspxCommerce2.7 | SageFrame.Core/TemplateManagement/TemplateDataProvider.cs | C# | mit | 3,799 |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
# import frappe
from frappe.model.document import Document
class WebPageBlock(Document):
pass
| adityahase/frappe | frappe/website/doctype/web_page_block/web_page_block.py | Python | mit | 272 |
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package cn.sharesdk.demo.utils;
import android.annotation.TargetApi;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore.Images.Media;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
@TargetApi(17)
public class ScreenShotListenManager {
private static final String TAG = "ScreenShotListenManager";
private static final String[] MEDIA_PROJECTIONS = new String[]{"_data", "datetaken"};
private static final String[] MEDIA_PROJECTIONS_API_16 = new String[]{"_data", "datetaken", "width", "height"};
private static final String[] KEYWORDS = new String[]{"screenshot", "screen_shot", "screen-shot", "screen shot", "screencapture",
"screen_capture", "screen-capture", "screen capture", "screencap", "screen_cap", "screen-cap", "screen cap"};
private static Point sScreenRealSize;
private final List<String> sHasCallbackPaths = new ArrayList();
private Context context;
private OnScreenShotListener listener;
private long startListenTime;
private MediaContentObserver internalObserver;
private MediaContentObserver externalObserver;
private final Handler uiHandler = new Handler(Looper.getMainLooper());
private ScreenShotListenManager(Context context) {
if(context == null) {
throw new IllegalArgumentException("The context must not be null.");
} else {
this.context = context;
if(sScreenRealSize == null) {
sScreenRealSize = this.getRealScreenSize();
if(sScreenRealSize != null) {
Log.d("ScreenShotListenManager", "Screen Real Size: " + sScreenRealSize.x + " * " + sScreenRealSize.y);
} else {
Log.w("ScreenShotListenManager", "Get screen real size failed.");
}
}
}
}
public static ScreenShotListenManager newInstance(Context context) {
assertInMainThread();
return new ScreenShotListenManager(context);
}
public void startListen() {
assertInMainThread();
this.sHasCallbackPaths.clear();
this.startListenTime = System.currentTimeMillis();
this.internalObserver = new MediaContentObserver(Media.INTERNAL_CONTENT_URI, this.uiHandler);
this.externalObserver = new MediaContentObserver(Media.EXTERNAL_CONTENT_URI, this.uiHandler);
this.context.getContentResolver().registerContentObserver(Media.INTERNAL_CONTENT_URI, false, this.internalObserver);
this.context.getContentResolver().registerContentObserver(Media.EXTERNAL_CONTENT_URI, false, this.externalObserver);
}
public void stopListen() {
assertInMainThread();
if(this.internalObserver != null) {
try {
this.context.getContentResolver().unregisterContentObserver(this.internalObserver);
} catch (Exception var3) {
var3.printStackTrace();
}
this.internalObserver = null;
}
if(this.externalObserver != null) {
try {
this.context.getContentResolver().unregisterContentObserver(this.externalObserver);
} catch (Exception var2) {
var2.printStackTrace();
}
this.externalObserver = null;
}
this.startListenTime = 0L;
this.sHasCallbackPaths.clear();
}
private void handleMediaContentChange(Uri contentUri) {
Cursor cursor = null;
try {
cursor = this.context.getContentResolver().query(contentUri, VERSION.SDK_INT < 16 ? MEDIA_PROJECTIONS : MEDIA_PROJECTIONS_API_16,
(String)null, (String[])null, "date_added desc limit 1");
if(cursor == null) {
Log.e("ScreenShotListenManager", "Deviant logic.");
return;
}
if(cursor.moveToFirst()) {
int e = cursor.getColumnIndex("_data");
int dateTakenIndex = cursor.getColumnIndex("datetaken");
int widthIndex = -1;
int heightIndex = -1;
if(VERSION.SDK_INT >= 16) {
widthIndex = cursor.getColumnIndex("width");
heightIndex = cursor.getColumnIndex("height");
}
String data = cursor.getString(e);
long dateTaken = cursor.getLong(dateTakenIndex);
boolean width = false;
boolean height = false;
int width1;
int height1;
if(widthIndex >= 0 && heightIndex >= 0) {
width1 = cursor.getInt(widthIndex);
height1 = cursor.getInt(heightIndex);
} else {
Point size = this.getImageSize(data);
width1 = size.x;
height1 = size.y;
}
this.handleMediaRowData(data, dateTaken, width1, height1);
return;
}
Log.d("ScreenShotListenManager", "Cursor no data.");
} catch (Exception var16) {
var16.printStackTrace();
return;
} finally {
if(cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
private Point getImageSize(String imagePath) {
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
return new Point(options.outWidth, options.outHeight);
}
private void handleMediaRowData(String data, long dateTaken, int width, int height) {
if(this.checkScreenShot(data, dateTaken, width, height)) {
Log.d("ScreenShotListenManager", "ScreenShot: path = " + data + "; size = " + width + " * " + height + "; date = " + dateTaken);
if(this.listener != null && !this.checkCallback(data)) {
this.listener.onShot(data);
}
} else {
Log.w("ScreenShotListenManager", "Media content changed, but not screenshot: path = " + data + "; size = " + width + " * "
+ height + "; date = " + dateTaken);
}
}
private boolean checkScreenShot(String data, long dateTaken, int width, int height) {
long currentTime = System.currentTimeMillis() - dateTaken;
if(dateTaken >= this.startListenTime && currentTime <= 20000L) {
if(sScreenRealSize == null || width <= sScreenRealSize.x && height <= sScreenRealSize.y || height <= sScreenRealSize.x
&& width <= sScreenRealSize.y) {
if(TextUtils.isEmpty(data)) {
return false;
} else {
data = data.toLowerCase();
String[] var11 = KEYWORDS;
int var10 = KEYWORDS.length;
for(int var9 = 0; var9 < var10; var9++) {
String keyWork = var11[var9];
if(data.contains(keyWork)) {
return true;
}
}
return false;
}
} else {
return false;
}
} else {
return false;
}
}
private boolean checkCallback(String imagePath) {
if(this.sHasCallbackPaths.contains(imagePath)) {
return true;
} else {
if(this.sHasCallbackPaths.size() >= 20) {
for(int i = 0; i < 5; i++) {
this.sHasCallbackPaths.remove(0);
}
}
this.sHasCallbackPaths.add(imagePath);
return false;
}
}
private Point getRealScreenSize() {
Point screenSize = null;
try {
screenSize = new Point();
WindowManager e = (WindowManager)this.context.getSystemService("window");
Display defaultDisplay = e.getDefaultDisplay();
if(VERSION.SDK_INT >= 17) {
defaultDisplay.getRealSize(screenSize);
} else {
try {
Method e1 = Display.class.getMethod("getRawWidth", new Class[0]);
Method getRawH = Display.class.getMethod("getRawHeight", new Class[0]);
screenSize.set(((Integer)e1.invoke(defaultDisplay, new Object[0])).intValue(),
((Integer)getRawH.invoke(defaultDisplay, new Object[0])).intValue());
} catch (Exception var6) {
screenSize.set(defaultDisplay.getWidth(), defaultDisplay.getHeight());
var6.printStackTrace();
}
}
} catch (Exception var7) {
var7.printStackTrace();
}
return screenSize;
}
public void setListener(ScreenShotListenManager.OnScreenShotListener listener) {
this.listener = listener;
}
private static void assertInMainThread() {
if(Looper.myLooper() != Looper.getMainLooper()) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
String methodMsg = null;
if(elements != null && elements.length >= 4) {
methodMsg = elements[3].toString();
}
throw new IllegalStateException("Call the method must be in main thread: " + methodMsg);
}
}
private class MediaContentObserver extends ContentObserver {
private Uri contentUri;
public MediaContentObserver(Uri contentUri, Handler handler) {
super(handler);
this.contentUri = contentUri;
}
public void onChange(boolean selfChange) {
super.onChange(selfChange);
handleMediaContentChange(this.contentUri);
}
}
public interface OnScreenShotListener {
void onShot(String var1);
}
}
| ShareSDKPlatform/ShareSDK-for-Android | SampleFresh/app/src/main/java/cn/sharesdk/demo/utils/ScreenShotListenManager.java | Java | mit | 8,651 |
var Path = require('path');
var Hapi = require('hapi');
var server = new Hapi.Server();
var port = process.env.PORT || 5000;
server.connection({ port: port });
server.views({
engines: {
html: require('handlebars')
},
path: Path.join(__dirname, 'views')
});
server.route([
{ path: '/',
method: 'GET',
config: {
auth: false,
handler: function(request, reply) {
reply.view("index");
}
}
},
{
method: 'GET',
path: '/public/{param*}',
handler: {
directory: {
path: Path.normalize(__dirname + '/public')
}
}
}
]);
server.start(function(){
console.log('Static Server Listening on : http://127.0.0.1:' +port);
});
module.exports = server; | rorysedgwick/learn-hapi | examples/staticfiles.js | JavaScript | mit | 753 |
//
// Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
//
// 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.
//
#include <Atomic/Atomic3D/StaticModel.h>
#include <Atomic/Atomic3D/CustomGeometry.h>
#include <Atomic/Atomic3D/BillboardSet.h>
#include "JSAtomic3D.h"
namespace Atomic
{
static int StaticModel_SetMaterialIndex(duk_context* ctx) {
unsigned index = (unsigned) duk_require_number(ctx, 0);
Material* material = js_to_class_instance<Material>(ctx, 1, 0);
duk_push_this(ctx);
// event receiver
StaticModel* model = js_to_class_instance<StaticModel>(ctx, -1, 0);
model->SetMaterial(index, material);
return 0;
}
static int CustomGeometry_SetMaterialIndex(duk_context* ctx) {
unsigned index = (unsigned)duk_require_number(ctx, 0);
Material* material = js_to_class_instance<Material>(ctx, 1, 0);
duk_push_this(ctx);
// event receiver
CustomGeometry* geometry = js_to_class_instance<CustomGeometry>(ctx, -1, 0);
geometry->SetMaterial(index, material);
return 0;
}
static int BillboardSet_GetBillboard(duk_context* ctx)
{
duk_push_this(ctx);
BillboardSet* billboardSet = js_to_class_instance<BillboardSet>(ctx, -1, 0);
unsigned index = (unsigned)duk_to_number(ctx, 0);
Billboard* billboard = billboardSet->GetBillboard(index);
js_push_class_object_instance(ctx, billboard, "Billboard");
return 1;
}
void jsapi_init_atomic3d(JSVM* vm)
{
duk_context* ctx = vm->GetJSContext();
js_class_get_prototype(ctx, "Atomic", "StaticModel");
duk_push_c_function(ctx, StaticModel_SetMaterialIndex, 2);
duk_put_prop_string(ctx, -2, "setMaterialIndex");
duk_pop(ctx); // pop AObject prototype
js_class_get_prototype(ctx, "Atomic", "CustomGeometry");
duk_push_c_function(ctx, CustomGeometry_SetMaterialIndex, 2);
duk_put_prop_string(ctx, -2, "setMaterialIndex");
duk_pop(ctx); // pop AObject prototype
js_class_get_prototype(ctx, "Atomic", "BillboardSet");
duk_push_c_function(ctx, BillboardSet_GetBillboard, 1);
duk_put_prop_string(ctx, -2, "getBillboard");
duk_pop(ctx); // pop AObject prototype
}
}
| rsredsq/AtomicGameEngine | Source/AtomicJS/Javascript/JSAtomic3D.cpp | C++ | mit | 3,193 |
//-----------------------------------------------------------------------------
// Verve
// Copyright (C) - Violent Tulip
//-----------------------------------------------------------------------------
function VControllerPropertyList::CreateInspectorGroup( %this, %targetStack )
{
%baseGroup = Parent::CreateInspectorGroup( %this, %targetStack );
if ( %baseGroup.getClassName() !$= "ScriptGroup" )
{
// Temp Store.
%temp = %baseGroup;
// Create SimSet.
%baseGroup = new SimSet();
// Add Original Control.
%baseGroup.add( %temp );
}
// Create Data Table Group.
%groupRollout = %targetStack.CreatePropertyRollout( "VController DataTable" );
%propertyStack = %groupRollout.Stack;
// Reference.
%propertyStack.InternalName = "DataTableStack";
// Store.
%baseGroup.add( %groupRollout );
// Return.
return %baseGroup;
}
function VControllerPropertyList::InspectObject( %this, %object )
{
if ( !%object.isMemberOfClass( "VController" ) )
{
// Invalid Object.
return;
}
// Default Inspect.
Parent::InspectObject( %this, %object );
// Update Data Table.
%dataTableStack = %this.ControlCache.findObjectByInternalName( "DataTableStack", true );
if ( !isObject( %dataTableStack ) )
{
// Invalid Table.
return;
}
// Clear Stack.
while ( %dataTableStack.getCount() > 1 )
{
// Delete Object.
%dataTableStack.getObject( 1 ).delete();
}
%dataFieldCount = %object.getDataFieldCount();
for ( %i = 0; %i < %dataFieldCount; %i++ )
{
// Add To List.
%dataFieldList = trim( %dataFieldList SPC %object.getDataFieldName( %i ) );
}
// Sort Word List.
%dataFieldList = sortWordList( %dataFieldList );
for ( %i = 0; %i < %dataFieldCount; %i++ )
{
// Fetch Field Name.
%dataFieldName = getWord( %dataFieldList, %i );
// Create Field.
VerveEditor::CreateField( %dataTableStack, %dataFieldName, "Data" );
}
// Create Add Field.
VerveEditor::CreateAddDataField( %dataTableStack );
// Update.
%dataTableStack.InspectObject( %object );
}
function VController::DisplayContextMenu( %this, %x, %y )
{
%contextMenu = $VerveEditor::VController::ContextMenu;
if ( !isObject( %contextMenu ) )
{
%contextMenu = new PopupMenu()
{
SuperClass = "VerveWindowMenu";
IsPopup = true;
Label = "VControllerContextMenu";
Position = 0;
Item[0] = "Add Group" TAB "";
Item[1] = "" TAB "";
Item[2] = "Cu&t" TAB "" TAB "";
Item[3] = "&Copy" TAB "" TAB "";
Item[4] = "&Paste" TAB "" TAB "VerveEditor::Paste();";
Item[5] = "" TAB "";
Item[6] = "&Delete" TAB "" TAB "";
PasteIndex = 4;
};
%contextMenu.Init();
// Disable Cut, Copy & Delete.
%contextMenu.enableItem( 2, false );
%contextMenu.enableItem( 3, false );
%contextMenu.enableItem( 6, false );
// Cache.
$VerveEditor::VController::ContextMenu = %contextMenu;
}
// Remove Add Menu.
%contextMenu.removeItem( %contextMenu.AddIndex );
// Insert Menu.
%contextMenu.insertSubMenu( %contextMenu.AddIndex, getField( %contextMenu.Item[0], 0 ), %this.GetAddGroupMenu() );
// Enable/Disable Pasting.
%contextMenu.enableItem( %contextMenu.PasteIndex, VerveEditor::CanPaste() );
if ( %x $= "" || %y $= "" )
{
%position = %this.getGlobalPosition();
%extent = %this.getExtent();
%x = getWord( %position, 0 ) + getWord( %extent, 0 );
%y = getWord( %position, 1 );
}
// Display.
%contextMenu.showPopup( VerveEditorWindow, %x, %y );
}
function VController::GetAddGroupMenu( %this )
{
%contextMenu = $VerveEditor::VController::ContextMenu[%this.getClassName()];
if ( !isObject( %contextMenu ) )
{
%customTemplateMenu = new PopupMenu()
{
Class = "VerveCustomTemplateMenu";
SuperClass = "VerveWindowMenu";
IsPopup = true;
Label = "VGroupAddGroupMenu";
Position = 0;
};
%customTemplateMenu.Init();
%contextMenu = new PopupMenu()
{
SuperClass = "VerveWindowMenu";
IsPopup = true;
Label = "VGroupAddGroupMenu";
Position = 0;
Item[0] = "Add Camera Group" TAB "" TAB "VerveEditor::AddGroup(\"VCameraGroup\");";
Item[1] = "Add Director Group" TAB "" TAB "VerveEditor::AddGroup(\"VDirectorGroup\");";
Item[2] = "Add Light Object Group" TAB "" TAB "VerveEditor::AddGroup(\"VLightObjectGroup\");";
Item[3] = "Add Particle Effect Group" TAB "" TAB "VerveEditor::AddGroup(\"VParticleEffectGroup\");";
Item[4] = "Add Scene Object Group" TAB "" TAB "VerveEditor::AddGroup(\"VSceneObjectGroup\");";
Item[5] = "Add Spawn Sphere Group" TAB "" TAB "VerveEditor::AddGroup(\"VSpawnSphereGroup\");";
Item[6] = "" TAB "";
Item[7] = "Add Custom Group" TAB %customTemplateMenu;
DirectorIndex = 1;
CustomIndex = 7;
CustomMenu = %customTemplateMenu;
};
%contextMenu.Init();
// Refresh Menu.
%customTemplateMenu = %contextMenu.CustomMenu;
if ( %customTemplateMenu.getItemCount() == 0 )
{
// Remove Item.
%contextMenu.removeItem( %contextMenu.CustomIndex );
// Add Dummy.
%contextMenu.insertItem( %contextMenu.CustomIndex, getField( %contextMenu.Item[%contextMenu.CustomIndex], 0 ) );
// Disable Custom Menu.
%contextMenu.enableItem( %contextMenu.CustomIndex, false );
}
// Cache.
$VerveEditor::VController::ContextMenu[%this.getClassName()] = %contextMenu;
}
// Enable / Disable Director Group.
%contextMenu.enableItem( %contextMenu.DirectorIndex, %this.CanAdd( "VDirectorGroup" ) );
// Return Menu.
return %contextMenu;
} | AnteSim/Verve | Templates/Verve/game/tools/VerveEditor/Scripts/Controller/VControllerProperties.cs | C# | mit | 6,641 |
module Cms::PublicFilter
extend ActiveSupport::Concern
include Cms::PublicFilter::Node
include Cms::PublicFilter::Page
include Mobile::PublicFilter
include Kana::PublicFilter
included do
rescue_from StandardError, with: :rescue_action
before_action :set_site
before_action :set_request_path
#before_action :redirect_slash, if: ->{ request.env["REQUEST_PATH"] =~ /\/[^\.]+[^\/]$/ }
before_action :deny_path
before_action :parse_path
before_action :compile_scss
before_action :x_sendfile, if: ->{ filters.blank? }
end
public
def index
if @cur_path =~ /\.p[1-9]\d*\.html$/
page = @cur_path.sub(/.*\.p(\d+)\.html$/, '\\1')
params[:page] = page.to_i
@cur_path.sub!(/\.p\d+\.html$/, ".html")
end
if @html =~ /\.part\.html$/
part = find_part(@html)
raise "404" unless part
@cur_path = params[:ref] || "/"
send_part render_part(part)
elsif page = find_page(@cur_path)
self.response = render_page(page)
send_page page
elsif node = find_node(@cur_path)
self.response = render_node(node)
send_page node
else
raise "404"
end
end
private
def set_site
host = request.env["HTTP_X_FORWARDED_HOST"] || request.env["HTTP_HOST"]
@cur_site ||= SS::Site.find_by_domain host
raise "404" if !@cur_site
end
def set_request_path
@cur_path ||= request.env["REQUEST_PATH"]
cur_path = @cur_path.dup
filter_methods = self.class.private_instance_methods.select { |m| m =~ /^set_request_path_with_/ }
filter_methods.each do |name|
send(name)
break if cur_path != @cur_path
end
end
def redirect_slash
return unless request.get?
redirect_to "#{request.path}/"
end
def deny_path
raise "404" if @cur_path =~ /^\/sites\/.\//
end
def parse_path
@cur_path.sub!(/\/$/, "/index.html")
@html = @cur_path.sub(/\.\w+$/, ".html")
@file = File.join(@cur_site.path, @cur_path)
end
def compile_scss
return if @cur_path !~ /\.css$/
return if @cur_path =~ /\/_[^\/]*$/
return unless Fs.exists? @scss = @file.sub(/\.css$/, ".scss")
css_mtime = Fs.exists?(@file) ? Fs.stat(@file).mtime : 0
return if Fs.stat(@scss).mtime.to_i <= css_mtime.to_i
css = ""
begin
opts = Rails.application.config.sass
sass = Sass::Engine.new Fs.read(@scss), filename: @scss, syntax: :scss, cache: false,
load_paths: opts.load_paths[1..-1],
style: :compressed,
debug_info: false
css = sass.render
rescue Sass::SyntaxError => e
msg = e.backtrace[0].sub(/.*?\/_\//, "")
msg = "[#{msg}]\\A #{e}".gsub('"', '\\"')
css = "body:before { position: absolute; top: 8px; right: 8px; display: block;"
css << " padding: 4px 8px; border: 1px solid #b88; background-color: #fff;"
css << " color: #822; font-size: 85%; font-family: tahoma, sans-serif; line-height: 1.6;"
css << " white-space: pre; z-index: 9; content: \"#{msg}\"; }"
end
Fs.write @file, css
end
def x_sendfile(file = @file)
return unless Fs.file?(file)
response.headers["Expires"] = 1.days.from_now.httpdate if file =~ /\.(css|js|gif|jpg|png)$/
response.headers["Last-Modified"] = CGI::rfc1123_date(Fs.stat(file).mtime)
if Fs.mode == :file
send_file file, disposition: :inline, x_sendfile: true
else
send_data Fs.binread(file), type: Fs.content_type(file)
end
end
def send_part(body)
respond_to do |format|
format.html { render inline: body, layout: false }
format.json { render json: body.to_json }
end
end
def send_page(page)
raise "404" unless response
if response.content_type == "text/html" && page.layout
render inline: render_layout(page.layout), layout: (request.xhr? ? false : "cms/page")
else
@_response_body = response.body
end
end
def rescue_action(e = nil)
return render_error(e, status: e.to_s.to_i) if e.to_s =~ /^\d+$/
return render_error(e, status: 404) if e.is_a? Mongoid::Errors::DocumentNotFound
return render_error(e, status: 404) if e.is_a? ActionController::RoutingError
raise e
end
def render_error(e, opts = {})
# for development
raise e if Rails.application.config.consider_all_requests_local
self.response = ActionDispatch::Response.new
status = opts[:status].presence || 500
render status: status, file: error_template(status), layout: false
end
def error_template(status)
if @cur_site
file = "#{@cur_site.path}/#{status}.html"
return file if Fs.exists?(file)
end
file = "#{Rails.public_path}/#{status}.html"
Fs.exists?(file) ? file : "#{Rails.public_path}/500.html"
end
end
| gouf/shirasagi | app/controllers/concerns/cms/public_filter.rb | Ruby | mit | 4,976 |
// Copyright 2019 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package queue
import (
"errors"
"strings"
"code.gitea.io/gitea/modules/log"
"github.com/go-redis/redis"
)
// RedisQueueType is the type for redis queue
const RedisQueueType Type = "redis"
// RedisQueueConfiguration is the configuration for the redis queue
type RedisQueueConfiguration struct {
ByteFIFOQueueConfiguration
RedisByteFIFOConfiguration
}
// RedisQueue redis queue
type RedisQueue struct {
*ByteFIFOQueue
}
// NewRedisQueue creates single redis or cluster redis queue
func NewRedisQueue(handle HandlerFunc, cfg, exemplar interface{}) (Queue, error) {
configInterface, err := toConfig(RedisQueueConfiguration{}, cfg)
if err != nil {
return nil, err
}
config := configInterface.(RedisQueueConfiguration)
byteFIFO, err := NewRedisByteFIFO(config.RedisByteFIFOConfiguration)
if err != nil {
return nil, err
}
byteFIFOQueue, err := NewByteFIFOQueue(RedisQueueType, byteFIFO, handle, config.ByteFIFOQueueConfiguration, exemplar)
if err != nil {
return nil, err
}
queue := &RedisQueue{
ByteFIFOQueue: byteFIFOQueue,
}
queue.qid = GetManager().Add(queue, RedisQueueType, config, exemplar)
return queue, nil
}
type redisClient interface {
RPush(key string, args ...interface{}) *redis.IntCmd
LPop(key string) *redis.StringCmd
LLen(key string) *redis.IntCmd
SAdd(key string, members ...interface{}) *redis.IntCmd
SRem(key string, members ...interface{}) *redis.IntCmd
SIsMember(key string, member interface{}) *redis.BoolCmd
Ping() *redis.StatusCmd
Close() error
}
var _ (ByteFIFO) = &RedisByteFIFO{}
// RedisByteFIFO represents a ByteFIFO formed from a redisClient
type RedisByteFIFO struct {
client redisClient
queueName string
}
// RedisByteFIFOConfiguration is the configuration for the RedisByteFIFO
type RedisByteFIFOConfiguration struct {
Network string
Addresses string
Password string
DBIndex int
QueueName string
}
// NewRedisByteFIFO creates a ByteFIFO formed from a redisClient
func NewRedisByteFIFO(config RedisByteFIFOConfiguration) (*RedisByteFIFO, error) {
fifo := &RedisByteFIFO{
queueName: config.QueueName,
}
dbs := strings.Split(config.Addresses, ",")
if len(dbs) == 0 {
return nil, errors.New("no redis host specified")
} else if len(dbs) == 1 {
fifo.client = redis.NewClient(&redis.Options{
Network: config.Network,
Addr: strings.TrimSpace(dbs[0]), // use default Addr
Password: config.Password, // no password set
DB: config.DBIndex, // use default DB
})
} else {
fifo.client = redis.NewClusterClient(&redis.ClusterOptions{
Addrs: dbs,
})
}
if err := fifo.client.Ping().Err(); err != nil {
return nil, err
}
return fifo, nil
}
// PushFunc pushes data to the end of the fifo and calls the callback if it is added
func (fifo *RedisByteFIFO) PushFunc(data []byte, fn func() error) error {
if fn != nil {
if err := fn(); err != nil {
return err
}
}
return fifo.client.RPush(fifo.queueName, data).Err()
}
// Pop pops data from the start of the fifo
func (fifo *RedisByteFIFO) Pop() ([]byte, error) {
data, err := fifo.client.LPop(fifo.queueName).Bytes()
if err == nil || err == redis.Nil {
return data, nil
}
return data, err
}
// Close this fifo
func (fifo *RedisByteFIFO) Close() error {
return fifo.client.Close()
}
// Len returns the length of the fifo
func (fifo *RedisByteFIFO) Len() int64 {
val, err := fifo.client.LLen(fifo.queueName).Result()
if err != nil {
log.Error("Error whilst getting length of redis queue %s: Error: %v", fifo.queueName, err)
return -1
}
return val
}
func init() {
queuesMap[RedisQueueType] = NewRedisQueue
}
| lafriks/gitea | modules/queue/queue_redis.go | GO | mit | 3,795 |
package velir.intellij.cq5.util;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import java.util.ArrayList;
import java.util.List;
/**
* Utility class for helping work with Repository objects.
*/
public class RepositoryUtils {
/**
* Hide default constructor for true static class.
*/
private RepositoryUtils() {
}
public static List<String> getAllNodeTypeNames(Session session) throws RepositoryException {
//get our child nodeTypes from our root
NodeIterator nodeTypes = getAllNodeTypes(session);
//go through each node type and pull out the name
List<String> nodeTypeNames = new ArrayList<String>();
while (nodeTypes.hasNext()) {
Node node = nodeTypes.nextNode();
nodeTypeNames.add(node.getName());
}
//return our node type names
return nodeTypeNames;
}
/**
* Will get all the nodes that represent the different node types.
*
* @param session Repository session to use for pulling out this information.
* @return
* @throws RepositoryException
*/
public static NodeIterator getAllNodeTypes(Session session) throws RepositoryException {
//get our node types root
Node nodeTypesRoot = session.getNode("/jcr:system/jcr:nodeTypes");
//get our child nodeTypes from our root
return nodeTypesRoot.getNodes();
}
}
| tmowad/intellij-jcr-plugin | source/src/velir/intellij/cq5/util/RepositoryUtils.java | Java | mit | 1,342 |
/****************************************************************************
Copyright (c) 2011-2013,WebJet Business Division,CYOU
http://www.genesis-3d.com.cn
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.
****************************************************************************/
#include "stdneb.h"
#include "exceptionbase.h"
namespace Exceptions
{
Exception::~Exception() throw()
{
}
Exception::Exception(const String& description_, const String& source_)
:line(0)
,type(EXT_UNDEF_TYPE)
,title("Exception")
,description(description_)
,source(source_)
{
// Log this error - not any more, allow catchers to do it
//LogManager::getSingleton().logMessage(this->getFullDescription());
}
Exception::Exception(const String& description_, const String& source_, const char* file_, long line_)
:type(EXT_UNDEF_TYPE)
,title("Exception")
,description(description_)
,source(source_)
,file(file_)
,line(line_)
{
// Log this error - not any more, allow catchers to do it
//LogManager::getSingleton().logMessage(this->getFullDescription());
}
Exception::Exception(int type_, const String& description_, const String& source_, const char* tile_, const char* file_, long line_)
:line(line_)
,type(type_)
,title(tile_)
,description(description_)
,source(source_)
,file(file_)
{
}
Exception::Exception(const Exception& rhs)
: line(rhs.line),
type(rhs.type),
title(rhs.title),
description(rhs.description),
source(rhs.source),
file(rhs.file)
{
}
void Exception::operator = (const Exception& rhs)
{
description = rhs.description;
type = rhs.type;
source = rhs.source;
file = rhs.file;
line = rhs.line;
title = rhs.title;
}
const String& Exception::GetFullDescription() const
{
if (0 == fullDesc.Length())
{
if( line > 0 )
{
fullDesc.Format("GENESIS EXCEPTION(%d:%s): \"%s\" in %s at %s(line, %d)",
type, title.AsCharPtr(), description.AsCharPtr(), source.AsCharPtr(), file.AsCharPtr(), line);
}
else
{
fullDesc.Format("GENESIS EXCEPTION(%d:%s): \"%s\" in %s", type, title.AsCharPtr(), description.AsCharPtr(), source.AsCharPtr());
}
}
return fullDesc;
}
int Exception::GetType(void) const throw()
{
return type;
}
const String &Exception::GetSource() const
{
return source;
}
const String &Exception::GetFile() const
{
return file;
}
long Exception::GetLine() const
{
return line;
}
const String &Exception::GetDescription(void) const
{
return description;
}
const char* Exception::what() const throw()
{
return GetFullDescription().AsCharPtr();
}
} | EngineDreamer/DreamEngine | Engine/foundation/exception/exceptionbase.cc | C++ | mit | 3,625 |
#include "GlobalSystems.h"
namespace globalSystem {
WindowManagerGL window;
TimeData time;
MouseData mouse;
KeyPressData keys;
TextureManager textures;
ModelManager models;
DynamicFloatMap runtimeData;
RandomNumberGenerator rng;
Font gameFont;
Font gameFontLarge;
Font gameFontHuge;
} | AndreSilvs/RTMasterThesis | RTHeightfieldScalable/GlobalSystems.cpp | C++ | mit | 347 |
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.ProjectOxford.Face;
using Microsoft.ProjectOxford.Face.Contract;
namespace Novanet
{
public static class FaceServiceClientExtensions
{
public static async Task CreatePersonGroupIfNotExising(this FaceServiceClient client, string personGroupId, string name)
{
var personGroups = await client.ListPersonGroupsAsync();
if (!personGroups.Any(pg => pg.PersonGroupId.Equals(personGroupId, StringComparison.InvariantCultureIgnoreCase)))
{
await client.CreatePersonGroupAsync(personGroupId, name);
}
}
public static async Task<Guid> CreateUserAsPersonIfNotExising(this FaceServiceClient client, string personGroupId, User user)
{
// Use person UserData property to store external UserId for matching
var persons = await client.GetPersonsAsync(personGroupId);
if (persons.Any(p => p.UserData.Equals(user.Id.ToString(), StringComparison.InvariantCultureIgnoreCase)))
{
return persons.First(p => p.UserData.Equals(user.Id.ToString(), StringComparison.InvariantCultureIgnoreCase)).PersonId;
}
var person = await client.CreatePersonAsync(personGroupId, user.Name, user.Id.ToString());
return person.PersonId;
}
public static async Task WaitForPersonGroupStatusNotRunning(this FaceServiceClient client, string personGroupId, TraceWriter log)
{
// WOW, this is ugly, should probably put back on queue?
try
{
var status = await client.GetPersonGroupTrainingStatusAsync(personGroupId);
while (status.Status == Status.Running)
{
log.Info("Waiting for training...");
await Task.Delay(5000);
}
} catch (FaceAPIException notTrainedException)
{
// Throws if never tained before, and I don't care.
}
}
}
} | novanet/ndc2017 | src/EmoApi/AzureFunctionsCCC/IdentificationTrainingFunction/FaceServiceClientExtensions.cs | C# | mit | 2,140 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="th_TH" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Linkcoin</source>
<translation>เกี่ยวกับ บิตคอย์น</translation>
</message>
<message>
<location line="+39"/>
<source><b>Linkcoin</b> version</source>
<translation><b>บิตคอย์น<b>รุ่น</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The Linkcoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>สมุดรายชื่อ</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>ดับเบิลคลิก เพื่อแก้ไขที่อยู่ หรือชื่อ</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>สร้างที่อยู่ใหม่</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>คัดลอกที่อยู่ที่ถูกเลือกไปยัง คลิปบอร์ดของระบบ</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Linkcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Linkcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Linkcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>ลบ</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Linkcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>ส่งออกรายชื่อทั้งหมด</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>ส่งออกผิดพลาด</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>ไม่สามารถเขียนไปยังไฟล์ %1</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>ชื่อ</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>ที่อยู่</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(ไม่มีชื่อ)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>ใส่รหัสผ่าน</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>รหัสผา่นใหม่</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>กรุณากรอกรหัสผ่านใหม่อีกครั้งหนึ่ง</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>กระเป๋าสตางค์ที่เข้ารหัส</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>เปิดกระเป๋าสตางค์</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>ถอดรหัสกระเป๋าสตางค์</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>เปลี่ยนรหัสผ่าน</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>กรอกรหัสผ่านเก่าและรหัสผ่านใหม่สำหรับกระเป๋าสตางค์</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>ยืนยันการเข้ารหัสกระเป๋าสตางค์</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LITECOINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>กระเป๋าสตางค์ถูกเข้ารหัสเรียบร้อยแล้ว</translation>
</message>
<message>
<location line="-56"/>
<source>Linkcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your linkcoins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>การเข้ารหัสกระเป๋าสตางค์ผิดพลาด</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>รหัสผ่านที่คุณกรอกไม่ตรงกัน</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Show information about Linkcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Linkcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Linkcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Linkcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About Linkcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Linkcoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Linkcoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Linkcoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Linkcoin network</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Linkcoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Linkcoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Linkcoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Linkcoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start Linkcoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start Linkcoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Linkcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the Linkcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Linkcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show Linkcoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Linkcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Linkcoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start linkcoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Linkcoin-Qt help message to get a list with possible Linkcoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>Linkcoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Linkcoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Linkcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Linkcoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Linkcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Linkcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Linkcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Linkcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter Linkcoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Linkcoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>ที่อยู่</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>วันนี้</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>ชื่อ</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>ที่อยู่</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>ส่งออกผิดพลาด</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>ไม่สามารถเขียนไปยังไฟล์ %1</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Linkcoin version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or linkcoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: linkcoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: linkcoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=linkcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Linkcoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Linkcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Linkcoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Linkcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Linkcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Linkcoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Linkcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS> | Linkproject/winpro | src/qt/locale/bitcoin_th_TH.ts | TypeScript | mit | 97,840 |
#region Using directives
using System;
using System.Data;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Nettiers.AdventureWorks.Entities;
using Nettiers.AdventureWorks.Data;
#endregion
namespace Nettiers.AdventureWorks.Data.Bases
{
///<summary>
/// This class is the base class for any <see cref="SalesOrderHeaderSalesReasonProviderBase"/> implementation.
/// It exposes CRUD methods as well as selecting on index, foreign keys and custom stored procedures.
///</summary>
public abstract partial class SalesOrderHeaderSalesReasonProviderBase : SalesOrderHeaderSalesReasonProviderBaseCore
{
} // end class
} // end namespace
| netTiers/netTiers | Samples/AdventureWorks/Generated/Nettiers.AdventureWorks.Data/Bases/SalesOrderHeaderSalesReasonProviderBase.cs | C# | mit | 735 |
<TS language="hi_IN" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Create a new address</source>
<translation>नया पता लिखिए !</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>चुनिन्दा पते को सिस्टम क्लिपबोर्ड पर कापी करे !</translation>
</message>
<message>
<source>&Copy Address</source>
<translation>&पता कॉपी करे</translation>
</message>
<message>
<source>&Delete</source>
<translation>&मिटाए !!</translation>
</message>
<message>
<source>Copy &Label</source>
<translation>&लेबल कॉपी करे </translation>
</message>
<message>
<source>&Edit</source>
<translation>&एडिट</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>लेबल</translation>
</message>
<message>
<source>Address</source>
<translation>पता</translation>
</message>
<message>
<source>(no label)</source>
<translation>(कोई लेबल नही !)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Enter passphrase</source>
<translation>पहचान शब्द/अक्षर डालिए !</translation>
</message>
<message>
<source>New passphrase</source>
<translation>नया पहचान शब्द/अक्षर डालिए !</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>दोबारा नया पहचान शब्द/अक्षर डालिए !</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>एनक्रिप्ट वॉलेट !</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>वॉलेट खोलने के आपका वॉलेट पहचान शब्द्/अक्षर चाईए !</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>वॉलेट खोलिए</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>वॉलेट डीक्रिप्ट( विकोड) करने के लिए आपका वॉलेट पहचान शब्द्/अक्षर चाईए !</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation> डीक्रिप्ट वॉलेट</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>पहचान शब्द/अक्षर बदलिये !</translation>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation>वॉलेट एनक्रिपशन को प्रमाणित कीजिए !</translation>
</message>
<message>
<source>Wallet encrypted</source>
<translation>वॉलेट एनक्रिप्ट हो गया !</translation>
</message>
<message>
<source>Wallet encryption failed</source>
<translation>वॉलेट एनक्रिप्ट नही हुआ!</translation>
</message>
<message>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>वॉलेट एनक्रिपशन नाकाम हो गया इंटर्नल एरर की वजह से! आपका वॉलेट एनक्रीपत नही हुआ है!</translation>
</message>
<message>
<source>The supplied passphrases do not match.</source>
<translation>आपके द्वारा डाले गये पहचान शब्द/अक्षर मिलते नही है !</translation>
</message>
<message>
<source>Wallet unlock failed</source>
<translation>वॉलेट का लॉक नही खुला !</translation>
</message>
<message>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>वॉलेट डीक्रिप्ट करने के लिए जो पहचान शब्द/अक्षर डाले गये है वो सही नही है!</translation>
</message>
<message>
<source>Wallet decryption failed</source>
<translation>वॉलेट का डीक्रिप्ट-ष्ण असफल !</translation>
</message>
</context>
<context>
<name>BanTableModel</name>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<source>Synchronizing with network...</source>
<translation>नेटवर्क से समकालिक (मिल) रहा है ...</translation>
</message>
<message>
<source>&Overview</source>
<translation>&विवरण</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>वॉलेट का सामानया विवरण दिखाए !</translation>
</message>
<message>
<source>&Transactions</source>
<translation>& लेन-देन
</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>देखिए पुराने लेन-देन के विवरण !</translation>
</message>
<message>
<source>E&xit</source>
<translation>बाहर जायें</translation>
</message>
<message>
<source>Quit application</source>
<translation>अप्लिकेशन से बाहर निकलना !</translation>
</message>
<message>
<source>&Options...</source>
<translation>&विकल्प</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>&बैकप वॉलेट</translation>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation>पहचान शब्द/अक्षर जो वॉलेट एनक्रिपशन के लिए इस्तेमाल किया है उसे बदलिए!</translation>
</message>
<message>
<source>FairCoin</source>
<translation>बीटकोइन</translation>
</message>
<message>
<source>Wallet</source>
<translation>वॉलेट</translation>
</message>
<message>
<source>&File</source>
<translation>&फाइल</translation>
</message>
<message>
<source>&Settings</source>
<translation>&सेट्टिंग्स</translation>
</message>
<message>
<source>&Help</source>
<translation>&मदद</translation>
</message>
<message>
<source>Tabs toolbar</source>
<translation>टैबस टूलबार</translation>
</message>
<message>
<source>%1 behind</source>
<translation>%1 पीछे</translation>
</message>
<message>
<source>Error</source>
<translation>भूल</translation>
</message>
<message>
<source>Warning</source>
<translation>चेतावनी</translation>
</message>
<message>
<source>Information</source>
<translation>जानकारी</translation>
</message>
<message>
<source>Up to date</source>
<translation>नवीनतम</translation>
</message>
<message>
<source>Sent transaction</source>
<translation>भेजी ट्रांजक्शन</translation>
</message>
<message>
<source>Incoming transaction</source>
<translation>प्राप्त हुई ट्रांजक्शन</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड नहीं है</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड है</translation>
</message>
</context>
<context>
<name>ClientModel</name>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Amount:</source>
<translation>राशि :</translation>
</message>
<message>
<source>Amount</source>
<translation>राशि</translation>
</message>
<message>
<source>Date</source>
<translation>taareek</translation>
</message>
<message>
<source>Confirmed</source>
<translation>पक्का</translation>
</message>
<message>
<source>Copy address</source>
<translation>पता कॉपी करे</translation>
</message>
<message>
<source>Copy label</source>
<translation>लेबल कॉपी करे </translation>
</message>
<message>
<source>Copy amount</source>
<translation>कॉपी राशि</translation>
</message>
<message>
<source>(no label)</source>
<translation>(कोई लेबल नही !)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>पता एडिट करना</translation>
</message>
<message>
<source>&Label</source>
<translation>&लेबल</translation>
</message>
<message>
<source>&Address</source>
<translation>&पता</translation>
</message>
<message>
<source>New receiving address</source>
<translation>नया स्वीकार्य पता</translation>
</message>
<message>
<source>New sending address</source>
<translation>नया भेजने वाला पता</translation>
</message>
<message>
<source>Edit receiving address</source>
<translation>एडिट स्वीकार्य पता </translation>
</message>
<message>
<source>Edit sending address</source>
<translation>एडिट भेजने वाला पता</translation>
</message>
<message>
<source>The entered address "%1" is already in the address book.</source>
<translation>डाला गया पता "%1" एड्रेस बुक में पहले से ही मोजूद है|</translation>
</message>
<message>
<source>Could not unlock wallet.</source>
<translation>वॉलेट को unlock नहीं किया जा सकता|</translation>
</message>
<message>
<source>New key generation failed.</source>
<translation>नयी कुंजी का निर्माण असफल रहा|</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>version</source>
<translation>संस्करण</translation>
</message>
<message>
<source>Usage:</source>
<translation>खपत :</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Error</source>
<translation>भूल</translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>विकल्प</translation>
</message>
<message>
<source>W&allet</source>
<translation>वॉलेट</translation>
</message>
<message>
<source>&OK</source>
<translation>&ओके</translation>
</message>
<message>
<source>&Cancel</source>
<translation>&कैन्सल</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation>फार्म</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>राशि</translation>
</message>
<message>
<source>N/A</source>
<translation>लागू नही
</translation>
</message>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>N/A</source>
<translation>लागू नही
</translation>
</message>
<message>
<source>&Information</source>
<translation>जानकारी</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Amount:</source>
<translation>राशि :</translation>
</message>
<message>
<source>&Label:</source>
<translation>लेबल:</translation>
</message>
<message>
<source>Copy label</source>
<translation>लेबल कॉपी करे </translation>
</message>
<message>
<source>Copy amount</source>
<translation>कॉपी राशि</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>Copy &Address</source>
<translation>&पता कॉपी करे</translation>
</message>
<message>
<source>Address</source>
<translation>पता</translation>
</message>
<message>
<source>Amount</source>
<translation>राशि</translation>
</message>
<message>
<source>Label</source>
<translation>लेबल</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation>taareek</translation>
</message>
<message>
<source>Label</source>
<translation>लेबल</translation>
</message>
<message>
<source>Amount</source>
<translation>राशि</translation>
</message>
<message>
<source>(no label)</source>
<translation>(कोई लेबल नही !)</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>सिक्के भेजें|</translation>
</message>
<message>
<source>Amount:</source>
<translation>राशि :</translation>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation>एक साथ कई प्राप्तकर्ताओं को भेजें</translation>
</message>
<message>
<source>Balance:</source>
<translation>बाकी रकम :</translation>
</message>
<message>
<source>Confirm the send action</source>
<translation>भेजने की पुष्टि करें</translation>
</message>
<message>
<source>Confirm send coins</source>
<translation>सिक्के भेजने की पुष्टि करें</translation>
</message>
<message>
<source>Copy amount</source>
<translation>कॉपी राशि</translation>
</message>
<message>
<source>The amount to pay must be larger than 0.</source>
<translation>भेजा गया अमाउंट शुन्य से अधिक होना चाहिए|</translation>
</message>
<message>
<source>(no label)</source>
<translation>(कोई लेबल नही !)</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>अमाउंट:</translation>
</message>
<message>
<source>Pay &To:</source>
<translation>प्राप्तकर्ता:</translation>
</message>
<message>
<source>Enter a label for this address to add it to your address book</source>
<translation>आपकी एड्रेस बुक में इस एड्रेस के लिए एक लेबल लिखें</translation>
</message>
<message>
<source>&Label:</source>
<translation>लेबल:</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt-A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Clipboard से एड्रेस paste करें</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt-P</translation>
</message>
<message>
<source>Pay To:</source>
<translation>प्राप्तकर्ता:</translation>
</message>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>Alt+A</source>
<translation>Alt-A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Clipboard से एड्रेस paste करें</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt-P</translation>
</message>
<message>
<source>Signature</source>
<translation>हस्ताक्षर</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<source>[testnet]</source>
<translation>[टेस्टनेट]</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
</context>
<context>
<name>TransactionDesc</name>
<message>
<source>Open until %1</source>
<translation>खुला है जबतक %1</translation>
</message>
<message>
<source>%1/unconfirmed</source>
<translation>%1/अपुष्ट</translation>
</message>
<message>
<source>%1 confirmations</source>
<translation>%1 पुष्टियाँ</translation>
</message>
<message>
<source>Date</source>
<translation>taareek</translation>
</message>
<message>
<source>Transaction ID</source>
<translation>ID</translation>
</message>
<message>
<source>Amount</source>
<translation>राशि</translation>
</message>
<message>
<source>true</source>
<translation>सही</translation>
</message>
<message>
<source>false</source>
<translation>ग़लत</translation>
</message>
<message>
<source>, has not been successfully broadcast yet</source>
<translation>, अभी तक सफलतापूर्वक प्रसारित नहीं किया गया है</translation>
</message>
<message>
<source>unknown</source>
<translation>अज्ञात</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<source>Transaction details</source>
<translation>लेन-देन का विवरण</translation>
</message>
<message>
<source>This pane shows a detailed description of the transaction</source>
<translation> ये खिड़की आपको लेन-देन का विस्तृत विवरण देगी !</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation>taareek</translation>
</message>
<message>
<source>Type</source>
<translation>टाइप</translation>
</message>
<message>
<source>Open until %1</source>
<translation>खुला है जबतक %1</translation>
</message>
<message>
<source>Confirmed (%1 confirmations)</source>
<translation>पक्के ( %1 पक्का करना)</translation>
</message>
<message>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>यह ब्लॉक किसी भी और नोड को मिला नही है ! शायद यह ब्लॉक कोई भी नोड स्वीकारे गा नही !</translation>
</message>
<message>
<source>Generated but not accepted</source>
<translation>जेनरेट किया गया किंतु स्वीकारा नही गया !</translation>
</message>
<message>
<source>Label</source>
<translation>लेबल</translation>
</message>
<message>
<source>Received with</source>
<translation>स्वीकार करना</translation>
</message>
<message>
<source>Received from</source>
<translation>स्वीकार्य ओर से</translation>
</message>
<message>
<source>Sent to</source>
<translation>भेजा गया</translation>
</message>
<message>
<source>Payment to yourself</source>
<translation>भेजा खुद को भुगतान</translation>
</message>
<message>
<source>Mined</source>
<translation>माइंड</translation>
</message>
<message>
<source>(n/a)</source>
<translation>(लागू नहीं)</translation>
</message>
<message>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>ट्रांसेक्शन स्तिथि| पुष्टियों की संख्या जानने के लिए इस जगह पर माउस लायें|</translation>
</message>
<message>
<source>Date and time that the transaction was received.</source>
<translation>तारीख तथा समय जब ये ट्रांसेक्शन प्राप्त हुई थी|</translation>
</message>
<message>
<source>Type of transaction.</source>
<translation>ट्रांसेक्शन का प्रकार|</translation>
</message>
<message>
<source>Amount removed from or added to balance.</source>
<translation>अमाउंट बैलेंस से निकला या जमा किया गया |</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>All</source>
<translation>सभी</translation>
</message>
<message>
<source>Today</source>
<translation>आज</translation>
</message>
<message>
<source>This week</source>
<translation>इस हफ्ते</translation>
</message>
<message>
<source>This month</source>
<translation>इस महीने</translation>
</message>
<message>
<source>Last month</source>
<translation>पिछले महीने</translation>
</message>
<message>
<source>This year</source>
<translation>इस साल</translation>
</message>
<message>
<source>Range...</source>
<translation>विस्तार...</translation>
</message>
<message>
<source>Received with</source>
<translation>स्वीकार करना</translation>
</message>
<message>
<source>Sent to</source>
<translation>भेजा गया</translation>
</message>
<message>
<source>To yourself</source>
<translation>अपनेआप को</translation>
</message>
<message>
<source>Mined</source>
<translation>माइंड</translation>
</message>
<message>
<source>Other</source>
<translation>अन्य</translation>
</message>
<message>
<source>Enter address or label to search</source>
<translation>ढूँदने के लिए कृपा करके पता या लेबल टाइप करे !</translation>
</message>
<message>
<source>Min amount</source>
<translation>लघुत्तम राशि</translation>
</message>
<message>
<source>Copy address</source>
<translation>पता कॉपी करे</translation>
</message>
<message>
<source>Copy label</source>
<translation>लेबल कॉपी करे </translation>
</message>
<message>
<source>Copy amount</source>
<translation>कॉपी राशि</translation>
</message>
<message>
<source>Edit label</source>
<translation>एडिट लेबल</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<source>Confirmed</source>
<translation>पक्का</translation>
</message>
<message>
<source>Date</source>
<translation>taareek</translation>
</message>
<message>
<source>Type</source>
<translation>टाइप</translation>
</message>
<message>
<source>Label</source>
<translation>लेबल</translation>
</message>
<message>
<source>Address</source>
<translation>पता</translation>
</message>
<message>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<source>Range:</source>
<translation>विस्तार:</translation>
</message>
<message>
<source>to</source>
<translation>तक</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
<message>
<source>Send Coins</source>
<translation>सिक्के भेजें|</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<source>Backup Wallet</source>
<translation>बैकप वॉलेट</translation>
</message>
<message>
<source>Wallet Data (*.dat)</source>
<translation>वॉलेट डेटा (*.dat)</translation>
</message>
<message>
<source>Backup Failed</source>
<translation>बैकप असफल</translation>
</message>
<message>
<source>Backup Successful</source>
<translation>बैकप सफल</translation>
</message>
</context>
<context>
<name>FairCoin-core</name>
<message>
<source>Options:</source>
<translation>विकल्प:</translation>
</message>
<message>
<source>Specify data directory</source>
<translation>डेटा डायरेक्टरी बताएं </translation>
</message>
<message>
<source>Run in the background as a daemon and accept commands</source>
<translation>बैकग्राउंड में डेमॉन बन कर रन करे तथा कमांड्स स्वीकार करें </translation>
</message>
<message>
<source>Verifying blocks...</source>
<translation>ब्लॉक्स जाँचे जा रहा है...</translation>
</message>
<message>
<source>Verifying wallet...</source>
<translation>वॉलेट जाँचा जा रहा है...</translation>
</message>
<message>
<source>Information</source>
<translation>जानकारी</translation>
</message>
<message>
<source>Warning</source>
<translation>चेतावनी</translation>
</message>
<message>
<source>Loading addresses...</source>
<translation>पता पुस्तक आ रही है...</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>ब्लॉक इंडेक्स आ रहा है...</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>वॉलेट आ रहा है...</translation>
</message>
<message>
<source>Rescanning...</source>
<translation>रि-स्केनी-इंग...</translation>
</message>
<message>
<source>Done loading</source>
<translation>लोड हो गया|</translation>
</message>
<message>
<source>Error</source>
<translation>भूल</translation>
</message>
</context>
</TS> | faircoin/faircoin2 | src/qt/locale/bitcoin_hi_IN.ts | TypeScript | mit | 30,726 |
// © 2000 NEOSYS Software Ltd. All Rights Reserved.//**Start Encode**
function form_postinit() {
//enable/disable password changing button
neosyssetexpression('button_password', 'disabled', '!gusers_authorisation_update&&gkey!=gusername')
//force retrieval of own record
if (gro.dictitem('USER_ID').defaultvalue)
window.setTimeout('focuson("USER_NAME")', 100)
gwhatsnew = neosysgetcookie(glogincode, 'NEOSYS2', 'wn').toLowerCase()
if (gwhatsnew) {
if (window.location.href.toString().slice(0, 5) == 'file:') gwhatsnew = 'file:///' + gwhatsnew
else gwhatsnew = '..' + gwhatsnew.slice(gwhatsnew.indexOf('\\data\\'))
neosyssetcookie(glogincode, 'NEOSYS2', '', 'wn')
neosyssetcookie(glogincode, 'NEOSYS2', gwhatsnew, 'wn2')
window.setTimeout('windowopen(gwhatsnew)', 1000)
//windowopen(gwhatsnew)
}
$$('button_password').onclick = user_setpassword
return true
}
//just to avoid confirmation
function form_prewrite() {
return true
}
//in authorisation.js and users.htm
var gtasks_newpassword
function form_postwrite() {
//if change own password then login with the new one
//otherwise cannot continue/unlock document so the lock hangs
if (gtasks_newpassword) db.login(gusername, gtasks_newpassword)
gtasks_newpassword = false
//to avoid need full login to get new font/colors
neosyssetcookie(glogincode, 'NEOSYS2', gds.getx('SCREEN_BODY_COLOR'), 'fc')
neosyssetcookie(glogincode, 'NEOSYS2', gds.getx('SCREEN_FONT'), 'ff')
neosyssetcookie(glogincode, 'NEOSYS2', gds.getx('SCREEN_FONT_SIZE'), 'fs')
return true
}
function users_postdisplay() {
var signatureimageelement = document.getElementById('signature_image')
if (signatureimageelement) {
signatureimageelement.src = ''
signatureimageelement.height = 0
signatureimageelement.width = 0
signatureimageelement.src = '../images/'+gdataset+'SHARP/UPLOAD/USERS/' + gkey.neosysconvert(' ', '') + '_signature.jpg'
}
//show only first five lines
form_filter('refilter', 'LOGIN_DATE', '', 4)
var reminderdays = 6
var passwordexpires = gds.getx('PASSWORD_EXPIRY_DATE')
$passwordexpiryelement = $$('passwordexpiryelement')
$passwordexpiryelement.innerHTML = ''
if (passwordexpires) {
var expirydays = (neosysint(passwordexpires) - neosysdate())
if (expirydays <= reminderdays)
$passwordexpiryelement.innerHTML = '<font color=red> Password expires in ' + expirydays + ' days.</font>'
}
return true
}
function form_postread() {
window.setTimeout('users_postdisplay()', 10)
return true
}
function users_upload_signature() {
//return openwindow('EXECUTE\r\MEDIA\r\OPENMATERIAL',scheduleno+'.'+materialletter)
/*
params=new Object()
params.scheduleno=scheduleno
params.materialletter=materialletter
neosysshowmodaldialog('../NEOSYS/upload.htm',params)
*/
//images are not stored per dataset at the moment so that they can be
//nor are they stored per file or per key so that they can be easily saved into a shared folder instead of going by web upload
params = {}
params.database = gdataset
params.filename = 'USERS'
params.key = gkey.neosysconvert(' ', '') + '_signature'
params.versionno = ''//newarchiveno
params.updateallowed = true
params.deleteallowed = true
//params.allowimages = true
//we only allow one image type merely so that the signature file name
//is always know and doesnt need saving in the user file
//and no possibility of uploading two image files with different extensions
params.allowablefileextensions = 'jpg'
var targetfilename = neosysshowmodaldialog('../NEOSYS/upload.htm', params)
window.setTimeout('users_postdisplay()', 1)
if (!targetfilename)
return false
return true
}
function user_signature_onload(el) {
el.removeAttribute("width")
el.removeAttribute("height")
}
| tectronics/exodusdb | www/neosys/scripts/users.js | JavaScript | mit | 4,156 |
// MIT License. Copyright (c) 2016 Maxim Kuzmin. Contacts: https://github.com/maxim-kuzmin
// Author: Maxim Kuzmin
using Autofac;
using Autofac.Core;
using Makc2017.Core.App;
using System.Collections.Generic;
using System.Linq;
namespace Makc2017.Modules.Dummy.Caching
{
/// <summary>
/// Модули. Модуль "Dummy". Кэширование. Плагин.
/// </summary>
public class ModuleDummyCachingPlugin : ModuleDummyPlugin
{
#region Properties
/// <summary>
/// Конфигурация кэширования.
/// </summary>
private ModuleDummyCachingConfig CachingConfig { get; set; }
#endregion Properties
#region Public methods
/// <summary>
/// Инициализировать.
/// </summary>
/// <param name="pluginEnvironment">Окружение плагинов.</param>
public sealed override void Init(CoreAppPluginEnvironment pluginEnvironment)
{
base.Init(pluginEnvironment);
CachingConfig.Init(ConfigurationProvider);
}
/// <summary>
/// Распознать зависимости.
/// </summary>
/// <param name="componentContext">Контекст компонентов.</param>
public sealed override void Resolve(IComponentContext componentContext)
{
base.Resolve(componentContext);
CachingConfig = componentContext.Resolve<ModuleDummyCachingConfig>();
}
#endregion Public methods
#region Protected methods
/// <summary>
/// Создать распознаватель зависимостей.
/// </summary>
/// <returns>Распознаватель зависимостей.</returns>
protected sealed override IModule CreateResolver()
{
return new ModuleDummyCachingResolver();
}
/// <summary>
/// Создать пути к файлам конфигурации.
/// </summary>
/// <returns>Пути к файлам конфигурации.</returns>
protected sealed override IEnumerable<string> CreateConfigFilePaths()
{
return base.CreateConfigFilePaths().Concat(new[] { @"Makc2017.Modules.Dummy.Caching\config.json" });
}
#endregion Protected methods
}
} | maxim-kuzmin/Makc2017 | src/Makc2017.Modules.Dummy.Caching/ModuleDummyCachingPlugin.cs | C# | mit | 2,426 |
package queue;
/**
* Queue server metadata manager.
*
* @author Thanh Nguyen <btnguyen2k@gmail.com>
* @since 0.1.0
*/
public interface IQsMetadataManager {
}
| kangkot/queue-server | app/queue/IQsMetadataManager.java | Java | mit | 166 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Routing\Generator;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Exception\InvalidParameterException;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
use Psr\Log\LoggerInterface;
/**
* UrlGenerator can generate a URL or a path for any route in the RouteCollection
* based on the passed parameters.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Tobias Schultze <http://tobion.de>
*/
class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInterface
{
protected $routes;
protected $context;
/**
* @var bool|null
*/
protected $strictRequirements = true;
protected $logger;
/**
* This array defines the characters (besides alphanumeric ones) that will not be percent-encoded in the path segment of the generated URL.
*
* PHP's rawurlencode() encodes all chars except "a-zA-Z0-9-._~" according to RFC 3986. But we want to allow some chars
* to be used in their literal form (reasons below). Other chars inside the path must of course be encoded, e.g.
* "?" and "#" (would be interpreted wrongly as query and fragment identifier),
* "'" and """ (are used as delimiters in HTML).
*/
protected $decodedChars = array(
// the slash can be used to designate a hierarchical structure and we want allow using it with this meaning
// some webservers don't allow the slash in encoded form in the path for security reasons anyway
// see http://stackoverflow.com/questions/4069002/http-400-if-2f-part-of-get-url-in-jboss
'%2F' => '/',
// the following chars are general delimiters in the URI specification but have only special meaning in the authority component
// so they can safely be used in the path in unencoded form
'%40' => '@',
'%3A' => ':',
// these chars are only sub-delimiters that have no predefined meaning and can therefore be used literally
// so URI producing applications can use these chars to delimit subcomponents in a path segment without being encoded for better readability
'%3B' => ';',
'%2C' => ',',
'%3D' => '=',
'%2B' => '+',
'%21' => '!',
'%2A' => '*',
'%7C' => '|',
);
public function __construct(RouteCollection $routes, RequestContext $context, LoggerInterface $logger = null)
{
$this->routes = $routes;
$this->context = $context;
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public function setContext(RequestContext $context)
{
$this->context = $context;
}
/**
* {@inheritdoc}
*/
public function getContext()
{
return $this->context;
}
/**
* {@inheritdoc}
*/
public function setStrictRequirements($enabled)
{
$this->strictRequirements = null === $enabled ? null : (bool) $enabled;
}
/**
* {@inheritdoc}
*/
public function isStrictRequirements()
{
return $this->strictRequirements;
}
/**
* {@inheritdoc}
*/
public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
{
if (null === $route = $this->routes->get($name)) {
throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name));
}
// the Route has a cache of its own and is not recompiled as long as it does not get modified
$compiledRoute = $route->compile();
return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $name, $referenceType, $compiledRoute->getHostTokens(), $route->getSchemes());
}
/**
* @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route
* @throws InvalidParameterException When a parameter value for a placeholder is not correct because
* it does not match the requirement
*/
protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, array $requiredSchemes = array())
{
if (is_bool($referenceType) || is_string($referenceType)) {
@trigger_error('The hardcoded value you are using for the $referenceType argument of the '.__CLASS__.'::generate method is deprecated since version 2.8 and will not be supported anymore in 3.0. Use the constants defined in the UrlGeneratorInterface instead.', E_USER_DEPRECATED);
if (true === $referenceType) {
$referenceType = self::ABSOLUTE_URL;
} elseif (false === $referenceType) {
$referenceType = self::ABSOLUTE_PATH;
} elseif ('relative' === $referenceType) {
$referenceType = self::RELATIVE_PATH;
} elseif ('network' === $referenceType) {
$referenceType = self::NETWORK_PATH;
}
}
$variables = array_flip($variables);
$mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);
// all params must be given
if ($diff = array_diff_key($variables, $mergedParams)) {
throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name));
}
$url = '';
$optional = true;
foreach ($tokens as $token) {
if ('variable' === $token[0]) {
if (!$optional || !array_key_exists($token[3], $defaults) || null !== $mergedParams[$token[3]] && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) {
// check requirement
if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#', $mergedParams[$token[3]])) {
$message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]);
if ($this->strictRequirements) {
throw new InvalidParameterException($message);
}
if ($this->logger) {
$this->logger->error($message);
}
return;
}
$url = $token[1].$mergedParams[$token[3]].$url;
$optional = false;
}
} else {
// static text
$url = $token[1].$url;
$optional = false;
}
}
if ('' === $url) {
$url = '/';
}
// the contexts base URL is already encoded (see Symfony\Component\HttpFoundation\Request)
$url = strtr(rawurlencode($url), $this->decodedChars);
// the path segments "." and ".." are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3
// so we need to encode them as they are not used for this purpose here
// otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route
$url = strtr($url, array('/../' => '/%2E%2E/', '/./' => '/%2E/'));
if ('/..' === substr($url, -3)) {
$url = substr($url, 0, -2).'%2E%2E';
} elseif ('/.' === substr($url, -2)) {
$url = substr($url, 0, -1).'%2E';
}
$schemeAuthority = '';
if ($host = $this->context->getHost()) {
$scheme = $this->context->getScheme();
if ($requiredSchemes) {
if (!in_array($scheme, $requiredSchemes, true)) {
$referenceType = self::ABSOLUTE_URL;
$scheme = current($requiredSchemes);
}
} elseif (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme !== $req) {
// We do this for BC; to be removed if _scheme is not supported anymore
$referenceType = self::ABSOLUTE_URL;
$scheme = $req;
}
if ($hostTokens) {
$routeHost = '';
foreach ($hostTokens as $token) {
if ('variable' === $token[0]) {
if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#i', $mergedParams[$token[3]])) {
$message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]);
if ($this->strictRequirements) {
throw new InvalidParameterException($message);
}
if ($this->logger) {
$this->logger->error($message);
}
return;
}
$routeHost = $token[1].$mergedParams[$token[3]].$routeHost;
} else {
$routeHost = $token[1].$routeHost;
}
}
if ($routeHost !== $host) {
$host = $routeHost;
if (self::ABSOLUTE_URL !== $referenceType) {
$referenceType = self::NETWORK_PATH;
}
}
}
if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) {
$port = '';
if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
$port = ':'.$this->context->getHttpPort();
} elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
$port = ':'.$this->context->getHttpsPort();
}
$schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "$scheme://";
$schemeAuthority .= $host.$port;
}
}
if (self::RELATIVE_PATH === $referenceType) {
$url = self::getRelativePath($this->context->getPathInfo(), $url);
} else {
$url = $schemeAuthority.$this->context->getBaseUrl().$url;
}
// add a query string if needed
$extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) {
return $a == $b ? 0 : 1;
});
if ($extra && $query = http_build_query($extra, '', '&')) {
// "/" and "?" can be left decoded for better user experience, see
// http://tools.ietf.org/html/rfc3986#section-3.4
$url .= '?'.strtr($query, array('%2F' => '/'));
}
return $url;
}
/**
* Returns the target path as relative reference from the base path.
*
* Only the URIs path component (no schema, host etc.) is relevant and must be given, starting with a slash.
* Both paths must be absolute and not contain relative parts.
* Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
* Furthermore, they can be used to reduce the link size in documents.
*
* Example target paths, given a base path of "/a/b/c/d":
* - "/a/b/c/d" -> ""
* - "/a/b/c/" -> "./"
* - "/a/b/" -> "../"
* - "/a/b/c/other" -> "other"
* - "/a/x/y" -> "../../x/y"
*
* @param string $basePath The base path
* @param string $targetPath The target path
*
* @return string The relative target path
*/
public static function getRelativePath($basePath, $targetPath)
{
if ($basePath === $targetPath) {
return '';
}
$sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
$targetDirs = explode('/', isset($targetPath[0]) && '/' === $targetPath[0] ? substr($targetPath, 1) : $targetPath);
array_pop($sourceDirs);
$targetFile = array_pop($targetDirs);
foreach ($sourceDirs as $i => $dir) {
if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
unset($sourceDirs[$i], $targetDirs[$i]);
} else {
break;
}
}
$targetDirs[] = $targetFile;
$path = str_repeat('../', count($sourceDirs)).implode('/', $targetDirs);
// A reference to the same base directory or an empty subdirectory must be prefixed with "./".
// This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
// as the first segment of a relative-path reference, as it would be mistaken for a scheme name
// (see http://tools.ietf.org/html/rfc3986#section-4.2).
return '' === $path || '/' === $path[0]
|| false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
? "./$path" : $path;
}
}
| BaderLab/openPIP | vendor/symfony/symfony/src/Symfony/Component/Routing/Generator/UrlGenerator.php | PHP | mit | 13,796 |
'use strict';
const path = require('path'),
mongoose = require('mongoose'),
Promise = require('bluebird'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
_ = require('lodash');
mongoose.Promise = Promise;
const User = mongoose.model('User');
const Project = mongoose.model('Project');
/**
* Patch Update User Fields
*/
exports.patchUser = (req, res) => {
_.extend(req.model, req.body)
.save()
.then(updatedUser => {
res.jsonp(updatedUser);
})
.catch(err => {
console.error('ERROR on patch update for user `err`:\n', err);
res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
});
};
/**
* Return list of projects by contributor - query param `publishedOnly`, if true, returns only published projects
*
* @param req
* @param req.query.publishedOnly
* @param res
*/
exports.getContributorProjects = (req, res) => {
const projectIdsArray = [];
const projectsArray = [];
req.model.associatedProjects.map(assocProjId => { projectIdsArray.push(assocProjId); });
Project.find({
'_id': { $in: projectIdsArray }
})
.then(projects => {
if (req.query.publishedOnly===true) {
projects.map(project => {
if(project.status[0]==='published') {
projectsArray.push(project);
}
});
projects = projectsArray;
}
res.jsonp(projects);
})
.catch(err => {
console.error('error:\n', err);
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
});
};
| mapping-slc/mapping-slc | modules/users/server/controllers/admin.v2.server.controller.js | JavaScript | mit | 1,576 |
using System.Linq;
using System.Threading.Tasks;
using JSONAPI.Documents;
using Newtonsoft.Json;
namespace JSONAPI.Json
{
/// <summary>
/// Default implementation of ISingleResourceDocumentFormatter
/// </summary>
public class SingleResourceDocumentFormatter : ISingleResourceDocumentFormatter
{
private readonly IResourceObjectFormatter _resourceObjectFormatter;
private readonly IMetadataFormatter _metadataFormatter;
private const string PrimaryDataKeyName = "data";
private const string RelatedDataKeyName = "included";
private const string MetaKeyName = "meta";
/// <summary>
/// Creates a SingleResourceDocumentFormatter
/// </summary>
/// <param name="resourceObjectFormatter"></param>
/// <param name="metadataFormatter"></param>
public SingleResourceDocumentFormatter(IResourceObjectFormatter resourceObjectFormatter, IMetadataFormatter metadataFormatter)
{
_resourceObjectFormatter = resourceObjectFormatter;
_metadataFormatter = metadataFormatter;
}
public Task Serialize(ISingleResourceDocument document, JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName(PrimaryDataKeyName);
_resourceObjectFormatter.Serialize(document.PrimaryData, writer);
if (document.RelatedData != null && document.RelatedData.Any())
{
writer.WritePropertyName(RelatedDataKeyName);
writer.WriteStartArray();
foreach (var resourceObject in document.RelatedData)
{
_resourceObjectFormatter.Serialize(resourceObject, writer);
}
writer.WriteEndArray();
}
if (document.Metadata != null)
{
writer.WritePropertyName(MetaKeyName);
_metadataFormatter.Serialize(document.Metadata, writer);
}
writer.WriteEndObject();
return Task.FromResult(0);
}
public async Task<ISingleResourceDocument> Deserialize(JsonReader reader, string currentPath)
{
if (reader.TokenType != JsonToken.StartObject)
throw new DeserializationException("Invalid document root", "Document root is not an object!", currentPath);
IResourceObject primaryData = null;
IMetadata metadata = null;
while (reader.Read())
{
if (reader.TokenType != JsonToken.PropertyName) break;
// Has to be a property name
var propertyName = (string)reader.Value;
reader.Read();
switch (propertyName)
{
case RelatedDataKeyName:
// TODO: If we want to capture related resources, this would be the place to do it
reader.Skip();
break;
case PrimaryDataKeyName:
primaryData = await DeserializePrimaryData(reader, currentPath + "/" + PrimaryDataKeyName);
break;
case MetaKeyName:
metadata = await _metadataFormatter.Deserialize(reader, currentPath + "/" + MetaKeyName);
break;
default:
reader.Skip();
break;
}
}
return new SingleResourceDocument(primaryData, new IResourceObject[] { }, metadata);
}
private async Task<IResourceObject> DeserializePrimaryData(JsonReader reader, string currentPath)
{
if (reader.TokenType == JsonToken.Null) return null;
var primaryData = await _resourceObjectFormatter.Deserialize(reader, currentPath);
return primaryData;
}
}
} | danshapir/JSONAPI.NET | JSONAPI/Json/SingleResourceDocumentFormatter.cs | C# | mit | 3,963 |
/*jshint unused:false*/
var chai = require('chai'),
expect = chai.expect;
var request = require('supertest');
module.exports = function() {
'use strict';
this.Then(/^The JSON is returned by issuing a "GET" at the specified uri:$/, function(json, callback) {
request(this.serverLocation)
.get('/hello')
.expect('Content-Type', /json/)
.expect(200)
.end(function(error, res) {
if(error) {
expect(false).to.equal(true, error);
}
else {
expect(res.body).to.deep.equal(JSON.parse(json));
}
callback();
});
});
}; | bustardcelly/caddis | features/step_definitions/add-get.steps.js | JavaScript | mit | 615 |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// FontFamilyNameEditor.
/// </summary>
public class FontFamilyNameEditor : UITypeEditor
{
#region Fields
private IWindowsFormsEditorService _dialogProvider;
#endregion
#region Properties
/// <summary>
/// Gets a value indicating whether the drop down is resizeable.
/// </summary>
public override bool IsDropDownResizable => true;
#endregion
#region Methods
/// <summary>
/// Edits a value based on some user input which is collected from a character control.
/// </summary>
/// <param name="context">The type descriptor context.</param>
/// <param name="provider">The service provider.</param>
/// <param name="value">Not used.</param>
/// <returns>The selected font family name.</returns>
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
_dialogProvider = provider?.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
ListBox cmb = new ListBox();
FontFamily[] fams = FontFamily.Families;
cmb.SuspendLayout();
foreach (FontFamily fam in fams)
{
cmb.Items.Add(fam.Name);
}
cmb.SelectedValueChanged += CmbSelectedValueChanged;
cmb.ResumeLayout();
_dialogProvider?.DropDownControl(cmb);
string test = (string)cmb.SelectedItem;
return test;
}
/// <summary>
/// Gets the UITypeEditorEditStyle, which in this case is drop down.
/// </summary>
/// <param name="context">The type descriptor context.</param>
/// <returns>The UITypeEditorEditStyle.</returns>
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.DropDown;
}
private void CmbSelectedValueChanged(object sender, EventArgs e)
{
_dialogProvider.CloseDropDown();
}
#endregion
}
} | DotSpatial/DotSpatial | Source/DotSpatial.Symbology.Forms/FontFamilyNameEditor.cs | C# | mit | 2,604 |
/* global sinon, setup, teardown */
/**
* __init.test.js is run before every test case.
*/
window.debug = true;
var AScene = require('aframe').AScene;
beforeEach(function () {
this.sinon = sinon.sandbox.create();
// Stub to not create a WebGL context since Travis CI runs headless.
this.sinon.stub(AScene.prototype, 'attachedCallback');
});
afterEach(function () {
// Clean up any attached elements.
['canvas', 'a-assets', 'a-scene'].forEach(function (tagName) {
var els = document.querySelectorAll(tagName);
for (var i = 0; i < els.length; i++) {
els[i].parentNode.removeChild(els[i]);
}
});
AScene.scene = null;
this.sinon.restore();
});
| donmccurdy/aframe-gamepad-controls | tests/__init.test.js | JavaScript | mit | 664 |
public enum CoffeePrice
{
Small = 50,
Normal = 100,
Double =200
} | zrusev/SoftUni_2016 | 06. C# OOP Advanced - July 2017/04. Enums And Attributes/04. Enums And Attributes - Lab/Lab Enumerations and Attributes/02. Coffee Machine/CoffeePrice.cs | C# | mit | 80 |
"use strict";
var mathUtils = require("./math-utils");
exports.shuffle = function(array) {
var len = array.length;
for ( var i=0; i<len; i++ ) {
var rand = mathUtils.randomInt(0,len-1);
var temp = array[i];
array[i] = array[rand];
array[rand] = temp;
}
}; | jedrichards/portfolio | api/utils/array-utils.js | JavaScript | mit | 303 |
# -*- coding: utf-8 -*-
#
# Cloud Robotics FX 会話理解API用メッセージ
#
# @author: Osamu Noguchi <noguchi@headwaters.co.jp>
# @version: 0.0.1
import cloudrobotics.message as message
APP_ID = 'SbrApiServices'
PROCESSING_ID = 'RbAppConversationApi'
# 会話メッセージ
#
class ConversationMessage(message.CRFXMessage):
def __init__(self, visitor, visitor_id, talkByMe, type):
super(ConversationMessage, self).__init__()
self.header['RoutingType'] = message.ROUTING_TYPE_CALL
self.header['AppProcessingId'] = PROCESSING_ID
self.header['MessageId'] = type
self.body = {
'visitor': visitor,
'visitor_id': visitor_id,
'talkByMe': talkByMe
}
| seijim/cloud-robotics-fx-v2 | CloudRoboticsApi/ClientCode_Pepper/HeadWaters/PepperCode2/lib/cloudrobotics/conversation/message.py | Python | mit | 746 |
Rails.application.routes.draw do
namespace :admin do
namespace :reports do
get 'deliveries' => 'deliveries#index'
end
get 'users' => 'users#index'
get 'users/:id' => 'users#show'
end
root to: 'pages#index'
end
| mmontossi/crumbs | test/dummy/config/routes.rb | Ruby | mit | 241 |
/* eslint quote-props: ["error", "consistent"] */
// Japanese Hirajoshi scale
// 1-4-2-1-4
// Gb G B Db D Gb
export default {
'a': { instrument: 'piano', note: 'a4' },
'b': { instrument: 'piano', note: 'eb3' },
'c': { instrument: 'piano', note: 'd6' },
'd': { instrument: 'piano', note: 'eb4' },
'e': { instrument: 'piano', note: 'd4' },
'f': { instrument: 'piano', note: 'bb5' },
'g': { instrument: 'piano', note: 'd7' },
'h': { instrument: 'piano', note: 'g3' },
'i': { instrument: 'piano', note: 'g5' },
'j': { instrument: 'piano', note: 'bb6' },
'k': { instrument: 'piano', note: 'eb6' },
'l': { instrument: 'piano', note: 'bb4' },
'm': { instrument: 'piano', note: 'a6' },
'n': { instrument: 'piano', note: 'a5' },
'o': { instrument: 'piano', note: 'd5' },
'p': { instrument: 'piano', note: 'a2' },
'q': { instrument: 'piano', note: 'bb2' },
'r': { instrument: 'piano', note: 'a3' },
's': { instrument: 'piano', note: 'd3' },
't': { instrument: 'piano', note: 'g4' },
'u': { instrument: 'piano', note: 'g6' },
'v': { instrument: 'piano', note: 'bb3' },
'w': { instrument: 'piano', note: 'eb5' },
'x': { instrument: 'piano', note: 'eb2' },
'y': { instrument: 'piano', note: 'g2' },
'z': { instrument: 'piano', note: 'eb7' },
'A': { instrument: 'celesta', note: 'a4' },
'B': { instrument: 'celesta', note: 'eb3' },
'C': { instrument: 'celesta', note: 'd6' },
'D': { instrument: 'celesta', note: 'eb4' },
'E': { instrument: 'celesta', note: 'd4' },
'F': { instrument: 'celesta', note: 'bb4' },
'G': { instrument: 'celesta', note: 'd2' },
'H': { instrument: 'celesta', note: 'g3' },
'I': { instrument: 'celesta', note: 'g5' },
'J': { instrument: 'celesta', note: 'bb6' },
'K': { instrument: 'celesta', note: 'eb6' },
'L': { instrument: 'celesta', note: 'bb5' },
'M': { instrument: 'celesta', note: 'a6' },
'N': { instrument: 'celesta', note: 'a5' },
'O': { instrument: 'celesta', note: 'd5' },
'P': { instrument: 'celesta', note: 'a7' },
'Q': { instrument: 'celesta', note: 'bb7' },
'R': { instrument: 'celesta', note: 'a3' },
'S': { instrument: 'celesta', note: 'd3' },
'T': { instrument: 'celesta', note: 'g4' },
'U': { instrument: 'celesta', note: 'g6' },
'V': { instrument: 'celesta', note: 'bb3' },
'W': { instrument: 'celesta', note: 'eb5' },
'X': { instrument: 'celesta', note: 'eb7' },
'Y': { instrument: 'celesta', note: 'g7' },
'Z': { instrument: 'celesta', note: 'eb2' },
'$': { instrument: 'swell', note: 'eb3' },
',': { instrument: 'swell', note: 'eb3' },
'/': { instrument: 'swell', note: 'bb3' },
'\\': { instrument: 'swell', note: 'eb3' },
':': { instrument: 'swell', note: 'g3' },
';': { instrument: 'swell', note: 'bb3' },
'-': { instrument: 'swell', note: 'bb3' },
'+': { instrument: 'swell', note: 'g3' },
'|': { instrument: 'swell', note: 'bb3' },
'{': { instrument: 'swell', note: 'bb3' },
'}': { instrument: 'swell', note: 'eb3' },
'[': { instrument: 'swell', note: 'g3' },
']': { instrument: 'swell', note: 'bb3' },
'%': { instrument: 'swell', note: 'bb3' },
'&': { instrument: 'swell', note: 'eb3' },
'*': { instrument: 'swell', note: 'eb3' },
'^': { instrument: 'swell', note: 'bb3' },
'#': { instrument: 'swell', note: 'g3' },
'!': { instrument: 'swell', note: 'g3' },
'@': { instrument: 'swell', note: 'eb3' },
'(': { instrument: 'swell', note: 'g3' },
')': { instrument: 'swell', note: 'eb3' },
'=': { instrument: 'swell', note: 'eb3' },
'~': { instrument: 'swell', note: 'g3' },
'`': { instrument: 'swell', note: 'eb3' },
'_': { instrument: 'swell', note: 'g3' },
'"': { instrument: 'swell', note: 'eb3' },
"'": { instrument: 'swell', note: 'bb3' },
'<': { instrument: 'swell', note: 'g3' },
'>': { instrument: 'swell', note: 'g3' },
'.': { instrument: 'swell', note: 'g3' },
'?': { instrument: 'swell', note: 'bb3' },
'0': { instrument: 'fluteorgan', note: 'd3' },
'1': { instrument: 'fluteorgan', note: 'eb3' },
'2': { instrument: 'fluteorgan', note: 'g3' },
'3': { instrument: 'fluteorgan', note: 'a3' },
'4': { instrument: 'fluteorgan', note: 'bb3' },
'5': { instrument: 'fluteorgan', note: 'd2' },
'6': { instrument: 'fluteorgan', note: 'eb2' },
'7': { instrument: 'fluteorgan', note: 'g2' },
'8': { instrument: 'fluteorgan', note: 'a2' },
'9': { instrument: 'fluteorgan', note: 'bb2' },
's1': { instrument: 'swell', note: 'eb3' },
's2': { instrument: 'swell', note: 'g3' },
's3': { instrument: 'swell', note: 'bb3' }
};
| sctang/opera | src/scheme/scheme_Hirajoshi_D.js | JavaScript | mit | 4,555 |
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
namespace PInvoke
{
using System.Runtime.InteropServices;
/// <content>
/// Contains the <see cref="WIN32_FIND_DATA"/> nested type.
/// </content>
public partial class Kernel32
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WIN32_FIND_DATA
{
/// <summary>
/// The file attributes of a file.
/// </summary>
/// <remarks>
/// Although the enum we bind to here exists in the .NET Framework
/// as System.IO.FileAttributes, it is not reliably present.
/// Portable profiles don't include it, for example. So we have to define our own.
/// </remarks>
public FileAttribute dwFileAttributes;
/// <summary>
/// A FILETIME structure that specifies when a file or directory was created.
/// If the underlying file system does not support creation time, this member is zero.
/// </summary>
public FILETIME ftCreationTime;
/// <summary>
/// A FILETIME structure.
/// For a file, the structure specifies when the file was last read from, written to, or for executable files, run.
/// For a directory, the structure specifies when the directory is created.If the underlying file system does not support last access time, this member is zero.
/// On the FAT file system, the specified date for both files and directories is correct, but the time of day is always set to midnight.
/// </summary>
public FILETIME ftLastAccessTime;
/// <summary>
/// A FILETIME structure.
/// For a file, the structure specifies when the file was last written to, truncated, or overwritten, for example, when WriteFile or SetEndOfFile are used.The date and time are not updated when file attributes or security descriptors are changed.
/// For a directory, the structure specifies when the directory is created.If the underlying file system does not support last write time, this member is zero.
/// </summary>
public FILETIME ftLastWriteTime;
/// <summary>
/// The high-order DWORD value of the file size, in bytes.
/// This value is zero unless the file size is greater than MAXDWORD.
/// The size of the file is equal to(nFileSizeHigh* (MAXDWORD+1)) + nFileSizeLow.
/// </summary>
public uint nFileSizeHigh;
/// <summary>
/// The low-order DWORD value of the file size, in bytes.
/// </summary>
public uint nFileSizeLow;
/// <summary>
/// If the dwFileAttributes member includes the FILE_ATTRIBUTE_REPARSE_POINT attribute, this member specifies the reparse point tag.
/// Otherwise, this value is undefined and should not be used.
/// For more information see Reparse Point Tags.
/// </summary>
public uint dwReserved0;
/// <summary>
/// Reserved for future use.
/// </summary>
public uint dwReserved1;
/// <summary>
/// The name of the file.
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string cFileName;
/// <summary>
/// An alternative name for the file.
/// This name is in the classic 8.3 file name format.
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string cAlternateFileName;
}
}
}
| vbfox/pinvoke | src/Kernel32/Kernel32+WIN32_FIND_DATA.cs | C# | mit | 3,947 |
package arn
// PersonName represents the name of a person.
type PersonName struct {
English Name `json:"english" editable:"true"`
Japanese Name `json:"japanese" editable:"true"`
}
// String returns the default visualization of the name.
func (name *PersonName) String() string {
return name.ByUser(nil)
}
// ByUser returns the preferred name for the given user.
func (name *PersonName) ByUser(user *User) string {
if user == nil {
return name.English.String()
}
switch user.Settings().TitleLanguage {
case "japanese":
if name.Japanese.String() == "" {
return name.English.String()
}
return name.Japanese.String()
default:
return name.English.String()
}
}
| animenotifier/arn | PersonName.go | GO | mit | 684 |
package testdata
import (
. "goa.design/goa/v3/dsl"
)
var ConflictWithAPINameAndServiceNameDSL = func() {
var _ = API("aloha", func() {
Title("conflict with API name and service names")
})
var _ = Service("aloha", func() {}) // same as API name
var _ = Service("alohaapi", func() {}) // API name + 'api' suffix
var _ = Service("alohaapi1", func() {}) // API name + 'api' suffix + sequential no.
}
var ConflictWithGoifiedAPINameAndServiceNamesDSL = func() {
var _ = API("good-by", func() {
Title("conflict with goified API name and goified service names")
})
var _ = Service("good-by-", func() {}) // Goify name is same as API name
var _ = Service("good-by-api", func() {}) // API name + 'api' suffix
var _ = Service("good-by-api-1", func() {}) // API name + 'api' suffix + sequential no.
}
| goadesign/goa | codegen/service/testdata/example_svc_dsls.go | GO | mit | 820 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {async, fakeAsync, tick} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, describe, inject, it} from '@angular/core/testing/testing_internal';
import {AbstractControl, FormArray, FormControl, FormGroup, Validators} from '@angular/forms';
import {EventEmitter} from '../src/facade/async';
import {isPresent} from '../src/facade/lang';
export function main() {
function asyncValidator(expected: string, timeouts = {}) {
return (c: AbstractControl) => {
let resolve: (result: any) => void;
const promise = new Promise(res => { resolve = res; });
const t = isPresent((timeouts as any)[c.value]) ? (timeouts as any)[c.value] : 0;
const res = c.value != expected ? {'async': true} : null;
if (t == 0) {
resolve(res);
} else {
setTimeout(() => { resolve(res); }, t);
}
return promise;
};
}
function asyncValidatorReturningObservable(c: FormControl) {
const e = new EventEmitter();
Promise.resolve(null).then(() => { e.emit({'async': true}); });
return e;
}
describe('FormGroup', () => {
describe('value', () => {
it('should be the reduced value of the child controls', () => {
const g = new FormGroup({'one': new FormControl('111'), 'two': new FormControl('222')});
expect(g.value).toEqual({'one': '111', 'two': '222'});
});
it('should be empty when there are no child controls', () => {
const g = new FormGroup({});
expect(g.value).toEqual({});
});
it('should support nested groups', () => {
const g = new FormGroup({
'one': new FormControl('111'),
'nested': new FormGroup({'two': new FormControl('222')})
});
expect(g.value).toEqual({'one': '111', 'nested': {'two': '222'}});
(<FormControl>(g.get('nested.two'))).setValue('333');
expect(g.value).toEqual({'one': '111', 'nested': {'two': '333'}});
});
});
describe('getRawValue', () => {
let fg: FormGroup;
it('should work with nested form groups/arrays', () => {
fg = new FormGroup({
'c1': new FormControl('v1'),
'group': new FormGroup({'c2': new FormControl('v2'), 'c3': new FormControl('v3')}),
'array': new FormArray([new FormControl('v4'), new FormControl('v5')])
});
fg.get('group').get('c3').disable();
(fg.get('array') as FormArray).at(1).disable();
expect(fg.getRawValue())
.toEqual({'c1': 'v1', 'group': {'c2': 'v2', 'c3': 'v3'}, 'array': ['v4', 'v5']});
});
});
describe('adding and removing controls', () => {
it('should update value and validity when control is added', () => {
const g = new FormGroup({'one': new FormControl('1')});
expect(g.value).toEqual({'one': '1'});
expect(g.valid).toBe(true);
g.addControl('two', new FormControl('2', Validators.minLength(10)));
expect(g.value).toEqual({'one': '1', 'two': '2'});
expect(g.valid).toBe(false);
});
it('should update value and validity when control is removed', () => {
const g = new FormGroup(
{'one': new FormControl('1'), 'two': new FormControl('2', Validators.minLength(10))});
expect(g.value).toEqual({'one': '1', 'two': '2'});
expect(g.valid).toBe(false);
g.removeControl('two');
expect(g.value).toEqual({'one': '1'});
expect(g.valid).toBe(true);
});
});
describe('errors', () => {
it('should run the validator when the value changes', () => {
const simpleValidator = (c: FormGroup) =>
c.controls['one'].value != 'correct' ? {'broken': true} : null;
const c = new FormControl(null);
const g = new FormGroup({'one': c}, simpleValidator);
c.setValue('correct');
expect(g.valid).toEqual(true);
expect(g.errors).toEqual(null);
c.setValue('incorrect');
expect(g.valid).toEqual(false);
expect(g.errors).toEqual({'broken': true});
});
});
describe('dirty', () => {
let c: FormControl, g: FormGroup;
beforeEach(() => {
c = new FormControl('value');
g = new FormGroup({'one': c});
});
it('should be false after creating a control', () => { expect(g.dirty).toEqual(false); });
it('should be true after changing the value of the control', () => {
c.markAsDirty();
expect(g.dirty).toEqual(true);
});
});
describe('touched', () => {
let c: FormControl, g: FormGroup;
beforeEach(() => {
c = new FormControl('value');
g = new FormGroup({'one': c});
});
it('should be false after creating a control', () => { expect(g.touched).toEqual(false); });
it('should be true after control is marked as touched', () => {
c.markAsTouched();
expect(g.touched).toEqual(true);
});
});
describe('setValue', () => {
let c: FormControl, c2: FormControl, g: FormGroup;
beforeEach(() => {
c = new FormControl('');
c2 = new FormControl('');
g = new FormGroup({'one': c, 'two': c2});
});
it('should set its own value', () => {
g.setValue({'one': 'one', 'two': 'two'});
expect(g.value).toEqual({'one': 'one', 'two': 'two'});
});
it('should set child values', () => {
g.setValue({'one': 'one', 'two': 'two'});
expect(c.value).toEqual('one');
expect(c2.value).toEqual('two');
});
it('should set child control values if disabled', () => {
c2.disable();
g.setValue({'one': 'one', 'two': 'two'});
expect(c2.value).toEqual('two');
expect(g.value).toEqual({'one': 'one'});
expect(g.getRawValue()).toEqual({'one': 'one', 'two': 'two'});
});
it('should set group value if group is disabled', () => {
g.disable();
g.setValue({'one': 'one', 'two': 'two'});
expect(c.value).toEqual('one');
expect(c2.value).toEqual('two');
expect(g.value).toEqual({'one': 'one', 'two': 'two'});
});
it('should set parent values', () => {
const form = new FormGroup({'parent': g});
g.setValue({'one': 'one', 'two': 'two'});
expect(form.value).toEqual({'parent': {'one': 'one', 'two': 'two'}});
});
it('should not update the parent when explicitly specified', () => {
const form = new FormGroup({'parent': g});
g.setValue({'one': 'one', 'two': 'two'}, {onlySelf: true});
expect(form.value).toEqual({parent: {'one': '', 'two': ''}});
});
it('should throw if fields are missing from supplied value (subset)', () => {
expect(() => g.setValue({
'one': 'one'
})).toThrowError(new RegExp(`Must supply a value for form control with name: 'two'`));
});
it('should throw if a value is provided for a missing control (superset)', () => {
expect(() => g.setValue({'one': 'one', 'two': 'two', 'three': 'three'}))
.toThrowError(new RegExp(`Cannot find form control with name: three`));
});
it('should throw if a value is not provided for a disabled control', () => {
c2.disable();
expect(() => g.setValue({
'one': 'one'
})).toThrowError(new RegExp(`Must supply a value for form control with name: 'two'`));
});
it('should throw if no controls are set yet', () => {
const empty = new FormGroup({});
expect(() => empty.setValue({
'one': 'one'
})).toThrowError(new RegExp(`no form controls registered with this group`));
});
describe('setValue() events', () => {
let form: FormGroup;
let logger: any[];
beforeEach(() => {
form = new FormGroup({'parent': g});
logger = [];
});
it('should emit one valueChange event per control', () => {
form.valueChanges.subscribe(() => logger.push('form'));
g.valueChanges.subscribe(() => logger.push('group'));
c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2'));
g.setValue({'one': 'one', 'two': 'two'});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
it('should not fire an event when explicitly specified', fakeAsync(() => {
form.valueChanges.subscribe((value) => { throw 'Should not happen'; });
g.valueChanges.subscribe((value) => { throw 'Should not happen'; });
c.valueChanges.subscribe((value) => { throw 'Should not happen'; });
g.setValue({'one': 'one', 'two': 'two'}, {emitEvent: false});
tick();
}));
it('should emit one statusChange event per control', () => {
form.statusChanges.subscribe(() => logger.push('form'));
g.statusChanges.subscribe(() => logger.push('group'));
c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2'));
g.setValue({'one': 'one', 'two': 'two'});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
});
});
describe('patchValue', () => {
let c: FormControl, c2: FormControl, g: FormGroup;
beforeEach(() => {
c = new FormControl('');
c2 = new FormControl('');
g = new FormGroup({'one': c, 'two': c2});
});
it('should set its own value', () => {
g.patchValue({'one': 'one', 'two': 'two'});
expect(g.value).toEqual({'one': 'one', 'two': 'two'});
});
it('should set child values', () => {
g.patchValue({'one': 'one', 'two': 'two'});
expect(c.value).toEqual('one');
expect(c2.value).toEqual('two');
});
it('should patch disabled control values', () => {
c2.disable();
g.patchValue({'one': 'one', 'two': 'two'});
expect(c2.value).toEqual('two');
expect(g.value).toEqual({'one': 'one'});
expect(g.getRawValue()).toEqual({'one': 'one', 'two': 'two'});
});
it('should patch disabled control groups', () => {
g.disable();
g.patchValue({'one': 'one', 'two': 'two'});
expect(c.value).toEqual('one');
expect(c2.value).toEqual('two');
expect(g.value).toEqual({'one': 'one', 'two': 'two'});
});
it('should set parent values', () => {
const form = new FormGroup({'parent': g});
g.patchValue({'one': 'one', 'two': 'two'});
expect(form.value).toEqual({'parent': {'one': 'one', 'two': 'two'}});
});
it('should not update the parent when explicitly specified', () => {
const form = new FormGroup({'parent': g});
g.patchValue({'one': 'one', 'two': 'two'}, {onlySelf: true});
expect(form.value).toEqual({parent: {'one': '', 'two': ''}});
});
it('should ignore fields that are missing from supplied value (subset)', () => {
g.patchValue({'one': 'one'});
expect(g.value).toEqual({'one': 'one', 'two': ''});
});
it('should not ignore fields that are null', () => {
g.patchValue({'one': null});
expect(g.value).toEqual({'one': null, 'two': ''});
});
it('should ignore any value provided for a missing control (superset)', () => {
g.patchValue({'three': 'three'});
expect(g.value).toEqual({'one': '', 'two': ''});
});
describe('patchValue() events', () => {
let form: FormGroup;
let logger: any[];
beforeEach(() => {
form = new FormGroup({'parent': g});
logger = [];
});
it('should emit one valueChange event per control', () => {
form.valueChanges.subscribe(() => logger.push('form'));
g.valueChanges.subscribe(() => logger.push('group'));
c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2'));
g.patchValue({'one': 'one', 'two': 'two'});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
it('should not emit valueChange events for skipped controls', () => {
form.valueChanges.subscribe(() => logger.push('form'));
g.valueChanges.subscribe(() => logger.push('group'));
c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2'));
g.patchValue({'one': 'one'});
expect(logger).toEqual(['control1', 'group', 'form']);
});
it('should not fire an event when explicitly specified', fakeAsync(() => {
form.valueChanges.subscribe((value) => { throw 'Should not happen'; });
g.valueChanges.subscribe((value) => { throw 'Should not happen'; });
c.valueChanges.subscribe((value) => { throw 'Should not happen'; });
g.patchValue({'one': 'one', 'two': 'two'}, {emitEvent: false});
tick();
}));
it('should emit one statusChange event per control', () => {
form.statusChanges.subscribe(() => logger.push('form'));
g.statusChanges.subscribe(() => logger.push('group'));
c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2'));
g.patchValue({'one': 'one', 'two': 'two'});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
});
});
describe('reset()', () => {
let c: FormControl, c2: FormControl, g: FormGroup;
beforeEach(() => {
c = new FormControl('initial value');
c2 = new FormControl('');
g = new FormGroup({'one': c, 'two': c2});
});
it('should set its own value if value passed', () => {
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset({'one': 'initial value', 'two': ''});
expect(g.value).toEqual({'one': 'initial value', 'two': ''});
});
it('should set its own value if boxed value passed', () => {
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset({'one': {value: 'initial value', disabled: false}, 'two': ''});
expect(g.value).toEqual({'one': 'initial value', 'two': ''});
});
it('should clear its own value if no value passed', () => {
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset();
expect(g.value).toEqual({'one': null, 'two': null});
});
it('should set the value of each of its child controls if value passed', () => {
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset({'one': 'initial value', 'two': ''});
expect(c.value).toBe('initial value');
expect(c2.value).toBe('');
});
it('should clear the value of each of its child controls if no value passed', () => {
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset();
expect(c.value).toBe(null);
expect(c2.value).toBe(null);
});
it('should set the value of its parent if value passed', () => {
const form = new FormGroup({'g': g});
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset({'one': 'initial value', 'two': ''});
expect(form.value).toEqual({'g': {'one': 'initial value', 'two': ''}});
});
it('should clear the value of its parent if no value passed', () => {
const form = new FormGroup({'g': g});
g.setValue({'one': 'new value', 'two': 'new value'});
g.reset();
expect(form.value).toEqual({'g': {'one': null, 'two': null}});
});
it('should not update the parent when explicitly specified', () => {
const form = new FormGroup({'g': g});
g.reset({'one': 'new value', 'two': 'new value'}, {onlySelf: true});
expect(form.value).toEqual({g: {'one': 'initial value', 'two': ''}});
});
it('should mark itself as pristine', () => {
g.markAsDirty();
expect(g.pristine).toBe(false);
g.reset();
expect(g.pristine).toBe(true);
});
it('should mark all child controls as pristine', () => {
c.markAsDirty();
c2.markAsDirty();
expect(c.pristine).toBe(false);
expect(c2.pristine).toBe(false);
g.reset();
expect(c.pristine).toBe(true);
expect(c2.pristine).toBe(true);
});
it('should mark the parent as pristine if all siblings pristine', () => {
const c3 = new FormControl('');
const form = new FormGroup({'g': g, 'c3': c3});
g.markAsDirty();
expect(form.pristine).toBe(false);
g.reset();
expect(form.pristine).toBe(true);
});
it('should not mark the parent pristine if any dirty siblings', () => {
const c3 = new FormControl('');
const form = new FormGroup({'g': g, 'c3': c3});
g.markAsDirty();
c3.markAsDirty();
expect(form.pristine).toBe(false);
g.reset();
expect(form.pristine).toBe(false);
});
it('should mark itself as untouched', () => {
g.markAsTouched();
expect(g.untouched).toBe(false);
g.reset();
expect(g.untouched).toBe(true);
});
it('should mark all child controls as untouched', () => {
c.markAsTouched();
c2.markAsTouched();
expect(c.untouched).toBe(false);
expect(c2.untouched).toBe(false);
g.reset();
expect(c.untouched).toBe(true);
expect(c2.untouched).toBe(true);
});
it('should mark the parent untouched if all siblings untouched', () => {
const c3 = new FormControl('');
const form = new FormGroup({'g': g, 'c3': c3});
g.markAsTouched();
expect(form.untouched).toBe(false);
g.reset();
expect(form.untouched).toBe(true);
});
it('should not mark the parent untouched if any touched siblings', () => {
const c3 = new FormControl('');
const form = new FormGroup({'g': g, 'c3': c3});
g.markAsTouched();
c3.markAsTouched();
expect(form.untouched).toBe(false);
g.reset();
expect(form.untouched).toBe(false);
});
it('should retain previous disabled state', () => {
g.disable();
g.reset();
expect(g.disabled).toBe(true);
});
it('should set child disabled state if boxed value passed', () => {
g.disable();
g.reset({'one': {value: '', disabled: false}, 'two': ''});
expect(c.disabled).toBe(false);
expect(g.disabled).toBe(false);
});
describe('reset() events', () => {
let form: FormGroup, c3: FormControl, logger: any[];
beforeEach(() => {
c3 = new FormControl('');
form = new FormGroup({'g': g, 'c3': c3});
logger = [];
});
it('should emit one valueChange event per reset control', () => {
form.valueChanges.subscribe(() => logger.push('form'));
g.valueChanges.subscribe(() => logger.push('group'));
c.valueChanges.subscribe(() => logger.push('control1'));
c2.valueChanges.subscribe(() => logger.push('control2'));
c3.valueChanges.subscribe(() => logger.push('control3'));
g.reset();
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
it('should not fire an event when explicitly specified', fakeAsync(() => {
form.valueChanges.subscribe((value) => { throw 'Should not happen'; });
g.valueChanges.subscribe((value) => { throw 'Should not happen'; });
c.valueChanges.subscribe((value) => { throw 'Should not happen'; });
g.reset({}, {emitEvent: false});
tick();
}));
it('should emit one statusChange event per reset control', () => {
form.statusChanges.subscribe(() => logger.push('form'));
g.statusChanges.subscribe(() => logger.push('group'));
c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2'));
c3.statusChanges.subscribe(() => logger.push('control3'));
g.reset();
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
it('should emit one statusChange event per reset control', () => {
form.statusChanges.subscribe(() => logger.push('form'));
g.statusChanges.subscribe(() => logger.push('group'));
c.statusChanges.subscribe(() => logger.push('control1'));
c2.statusChanges.subscribe(() => logger.push('control2'));
c3.statusChanges.subscribe(() => logger.push('control3'));
g.reset({'one': {value: '', disabled: true}});
expect(logger).toEqual(['control1', 'control2', 'group', 'form']);
});
});
});
describe('contains', () => {
let group: FormGroup;
beforeEach(() => {
group = new FormGroup({
'required': new FormControl('requiredValue'),
'optional': new FormControl({value: 'disabled value', disabled: true})
});
});
it('should return false when the component is disabled',
() => { expect(group.contains('optional')).toEqual(false); });
it('should return false when there is no component with the given name',
() => { expect(group.contains('something else')).toEqual(false); });
it('should return true when the component is enabled', () => {
expect(group.contains('required')).toEqual(true);
group.enable('optional');
expect(group.contains('optional')).toEqual(true);
});
it('should support controls with dots in their name', () => {
expect(group.contains('some.name')).toBe(false);
group.addControl('some.name', new FormControl());
expect(group.contains('some.name')).toBe(true);
});
});
describe('statusChanges', () => {
let control: FormControl;
let group: FormGroup;
beforeEach(async(() => {
control = new FormControl('', asyncValidatorReturningObservable);
group = new FormGroup({'one': control});
}));
// TODO(kara): update these tests to use fake Async
it('should fire a statusChange if child has async validation change',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
const loggedValues: string[] = [];
group.statusChanges.subscribe({
next: (status: string) => {
loggedValues.push(status);
if (loggedValues.length === 2) {
expect(loggedValues).toEqual(['PENDING', 'INVALID']);
}
async.done();
}
});
control.setValue('');
}));
});
describe('getError', () => {
it('should return the error when it is present', () => {
const c = new FormControl('', Validators.required);
const g = new FormGroup({'one': c});
expect(c.getError('required')).toEqual(true);
expect(g.getError('required', ['one'])).toEqual(true);
});
it('should return null otherwise', () => {
const c = new FormControl('not empty', Validators.required);
const g = new FormGroup({'one': c});
expect(c.getError('invalid')).toEqual(null);
expect(g.getError('required', ['one'])).toEqual(null);
expect(g.getError('required', ['invalid'])).toEqual(null);
});
});
describe('asyncValidator', () => {
it('should run the async validator', fakeAsync(() => {
const c = new FormControl('value');
const g = new FormGroup({'one': c}, null, asyncValidator('expected'));
expect(g.pending).toEqual(true);
tick(1);
expect(g.errors).toEqual({'async': true});
expect(g.pending).toEqual(false);
}));
it('should set the parent group\'s status to pending', fakeAsync(() => {
const c = new FormControl('value', null, asyncValidator('expected'));
const g = new FormGroup({'one': c});
expect(g.pending).toEqual(true);
tick(1);
expect(g.pending).toEqual(false);
}));
it('should run the parent group\'s async validator when children are pending',
fakeAsync(() => {
const c = new FormControl('value', null, asyncValidator('expected'));
const g = new FormGroup({'one': c}, null, asyncValidator('expected'));
tick(1);
expect(g.errors).toEqual({'async': true});
expect(g.get('one').errors).toEqual({'async': true});
}));
});
describe('disable() & enable()', () => {
it('should mark the group as disabled', () => {
const g = new FormGroup({'one': new FormControl(null)});
expect(g.disabled).toBe(false);
expect(g.valid).toBe(true);
g.disable();
expect(g.disabled).toBe(true);
expect(g.valid).toBe(false);
g.enable();
expect(g.disabled).toBe(false);
expect(g.valid).toBe(true);
});
it('should set the group status as disabled', () => {
const g = new FormGroup({'one': new FormControl(null)});
expect(g.status).toEqual('VALID');
g.disable();
expect(g.status).toEqual('DISABLED');
g.enable();
expect(g.status).toBe('VALID');
});
it('should mark children of the group as disabled', () => {
const c1 = new FormControl(null);
const c2 = new FormControl(null);
const g = new FormGroup({'one': c1, 'two': c2});
expect(c1.disabled).toBe(false);
expect(c2.disabled).toBe(false);
g.disable();
expect(c1.disabled).toBe(true);
expect(c2.disabled).toBe(true);
g.enable();
expect(c1.disabled).toBe(false);
expect(c2.disabled).toBe(false);
});
it('should ignore disabled controls in validation', () => {
const g = new FormGroup({
nested: new FormGroup({one: new FormControl(null, Validators.required)}),
two: new FormControl('two')
});
expect(g.valid).toBe(false);
g.get('nested').disable();
expect(g.valid).toBe(true);
g.get('nested').enable();
expect(g.valid).toBe(false);
});
it('should ignore disabled controls when serializing value', () => {
const g = new FormGroup(
{nested: new FormGroup({one: new FormControl('one')}), two: new FormControl('two')});
expect(g.value).toEqual({'nested': {'one': 'one'}, 'two': 'two'});
g.get('nested').disable();
expect(g.value).toEqual({'two': 'two'});
g.get('nested').enable();
expect(g.value).toEqual({'nested': {'one': 'one'}, 'two': 'two'});
});
it('should update its value when disabled with disabled children', () => {
const g = new FormGroup(
{nested: new FormGroup({one: new FormControl('one'), two: new FormControl('two')})});
g.get('nested.two').disable();
expect(g.value).toEqual({nested: {one: 'one'}});
g.get('nested').disable();
expect(g.value).toEqual({nested: {one: 'one', two: 'two'}});
g.get('nested').enable();
expect(g.value).toEqual({nested: {one: 'one', two: 'two'}});
});
it('should update its value when enabled with disabled children', () => {
const g = new FormGroup(
{nested: new FormGroup({one: new FormControl('one'), two: new FormControl('two')})});
g.get('nested.two').disable();
expect(g.value).toEqual({nested: {one: 'one'}});
g.get('nested').enable();
expect(g.value).toEqual({nested: {one: 'one', two: 'two'}});
});
it('should ignore disabled controls when determining dirtiness', () => {
const g = new FormGroup(
{nested: new FormGroup({one: new FormControl('one')}), two: new FormControl('two')});
g.get('nested.one').markAsDirty();
expect(g.dirty).toBe(true);
g.get('nested').disable();
expect(g.get('nested').dirty).toBe(true);
expect(g.dirty).toEqual(false);
g.get('nested').enable();
expect(g.dirty).toEqual(true);
});
it('should ignore disabled controls when determining touched state', () => {
const g = new FormGroup(
{nested: new FormGroup({one: new FormControl('one')}), two: new FormControl('two')});
g.get('nested.one').markAsTouched();
expect(g.touched).toBe(true);
g.get('nested').disable();
expect(g.get('nested').touched).toBe(true);
expect(g.touched).toEqual(false);
g.get('nested').enable();
expect(g.touched).toEqual(true);
});
it('should keep empty, disabled groups disabled when updating validity', () => {
const group = new FormGroup({});
expect(group.status).toEqual('VALID');
group.disable();
expect(group.status).toEqual('DISABLED');
group.updateValueAndValidity();
expect(group.status).toEqual('DISABLED');
group.addControl('one', new FormControl({value: '', disabled: true}));
expect(group.status).toEqual('DISABLED');
group.addControl('two', new FormControl());
expect(group.status).toEqual('VALID');
});
it('should re-enable empty, disabled groups', () => {
const group = new FormGroup({});
group.disable();
expect(group.status).toEqual('DISABLED');
group.enable();
expect(group.status).toEqual('VALID');
});
it('should not run validators on disabled controls', () => {
const validator = jasmine.createSpy('validator');
const g = new FormGroup({'one': new FormControl()}, validator);
expect(validator.calls.count()).toEqual(1);
g.disable();
expect(validator.calls.count()).toEqual(1);
g.setValue({one: 'value'});
expect(validator.calls.count()).toEqual(1);
g.enable();
expect(validator.calls.count()).toEqual(2);
});
describe('disabled errors', () => {
it('should clear out group errors when disabled', () => {
const g = new FormGroup({'one': new FormControl()}, () => ({'expected': true}));
expect(g.errors).toEqual({'expected': true});
g.disable();
expect(g.errors).toEqual(null);
g.enable();
expect(g.errors).toEqual({'expected': true});
});
it('should re-populate group errors when enabled from a child', () => {
const g = new FormGroup({'one': new FormControl()}, () => ({'expected': true}));
g.disable();
expect(g.errors).toEqual(null);
g.addControl('two', new FormControl());
expect(g.errors).toEqual({'expected': true});
});
it('should clear out async group errors when disabled', fakeAsync(() => {
const g = new FormGroup({'one': new FormControl()}, null, asyncValidator('expected'));
tick();
expect(g.errors).toEqual({'async': true});
g.disable();
expect(g.errors).toEqual(null);
g.enable();
tick();
expect(g.errors).toEqual({'async': true});
}));
it('should re-populate async group errors when enabled from a child', fakeAsync(() => {
const g = new FormGroup({'one': new FormControl()}, null, asyncValidator('expected'));
tick();
expect(g.errors).toEqual({'async': true});
g.disable();
expect(g.errors).toEqual(null);
g.addControl('two', new FormControl());
tick();
expect(g.errors).toEqual({'async': true});
}));
});
describe('disabled events', () => {
let logger: string[];
let c: FormControl;
let g: FormGroup;
let form: FormGroup;
beforeEach(() => {
logger = [];
c = new FormControl('', Validators.required);
g = new FormGroup({one: c});
form = new FormGroup({g: g});
});
it('should emit value change events in the right order', () => {
c.valueChanges.subscribe(() => logger.push('control'));
g.valueChanges.subscribe(() => logger.push('group'));
form.valueChanges.subscribe(() => logger.push('form'));
g.disable();
expect(logger).toEqual(['control', 'group', 'form']);
});
it('should emit status change events in the right order', () => {
c.statusChanges.subscribe(() => logger.push('control'));
g.statusChanges.subscribe(() => logger.push('group'));
form.statusChanges.subscribe(() => logger.push('form'));
g.disable();
expect(logger).toEqual(['control', 'group', 'form']);
});
});
});
describe('updateTreeValidity()', () => {
let c: FormControl, c2: FormControl, c3: FormControl;
let nested: FormGroup, form: FormGroup;
let logger: string[];
beforeEach(() => {
c = new FormControl('one');
c2 = new FormControl('two');
c3 = new FormControl('three');
nested = new FormGroup({one: c, two: c2});
form = new FormGroup({nested: nested, three: c3});
logger = [];
c.statusChanges.subscribe(() => logger.push('one'));
c2.statusChanges.subscribe(() => logger.push('two'));
c3.statusChanges.subscribe(() => logger.push('three'));
nested.statusChanges.subscribe(() => logger.push('nested'));
form.statusChanges.subscribe(() => logger.push('form'));
});
it('should update tree validity', () => {
form._updateTreeValidity();
expect(logger).toEqual(['one', 'two', 'nested', 'three', 'form']);
});
it('should not emit events when turned off', () => {
form._updateTreeValidity({emitEvent: false});
expect(logger).toEqual([]);
});
});
describe('setControl()', () => {
let c: FormControl;
let g: FormGroup;
beforeEach(() => {
c = new FormControl('one');
g = new FormGroup({one: c});
});
it('should replace existing control with new control', () => {
const c2 = new FormControl('new!', Validators.minLength(10));
g.setControl('one', c2);
expect(g.controls['one']).toEqual(c2);
expect(g.value).toEqual({one: 'new!'});
expect(g.valid).toBe(false);
});
it('should add control if control did not exist before', () => {
const c2 = new FormControl('new!', Validators.minLength(10));
g.setControl('two', c2);
expect(g.controls['two']).toEqual(c2);
expect(g.value).toEqual({one: 'one', two: 'new!'});
expect(g.valid).toBe(false);
});
it('should remove control if new control is null', () => {
g.setControl('one', null);
expect(g.controls['one']).not.toBeDefined();
expect(g.value).toEqual({});
});
it('should only emit value change event once', () => {
const logger: string[] = [];
const c2 = new FormControl('new!');
g.valueChanges.subscribe(() => logger.push('change!'));
g.setControl('one', c2);
expect(logger).toEqual(['change!']);
});
});
});
}
| tolemac/angular | modules/@angular/forms/test/form_group_spec.ts | TypeScript | mit | 36,063 |
require 'rubygems'
require 'active_support'
require 'active_merchant'
class GatewaySupport #:nodoc:
ACTIONS = [:purchase, :authorize, :capture, :void, :credit, :recurring]
include ActiveMerchant::Billing
attr_reader :gateways
def initialize
Dir[File.expand_path(File.dirname(__FILE__) + '/../active_merchant/billing/gateways/*.rb')].each do |f|
filename = File.basename(f, '.rb')
gateway_name = filename + '_gateway'
begin
gateway_class = ('ActiveMerchant::Billing::' + gateway_name.camelize).constantize
rescue NameError
puts 'Could not load gateway ' + gateway_name.camelize + ' from ' + f + '.'
end
end
@gateways = Gateway.implementations.sort_by(&:name)
@gateways.delete(ActiveMerchant::Billing::BogusGateway)
end
def each_gateway
@gateways.each{|g| yield g }
end
def features
width = 15
print 'Name'.center(width + 20)
ACTIONS.each{|f| print "#{f.to_s.capitalize.center(width)}" }
puts
each_gateway do |g|
print "#{g.display_name.ljust(width + 20)}"
ACTIONS.each do |f|
print "#{(g.instance_methods.include?(f.to_s) ? "Y" : "N").center(width)}"
end
puts
end
end
def to_rdoc
each_gateway do |g|
puts "* {#{g.display_name}}[#{g.homepage_url}] - #{g.supported_countries.join(', ')}"
end
end
def to_textile
each_gateway do |g|
puts %/ * "#{g.display_name}":#{g.homepage_url} [#{g.supported_countries.join(', ')}]/
end
end
def to_markdown
each_gateway do |g|
puts %/* [#{g.display_name}](#{g.homepage_url}) - #{g.supported_countries.join(', ')}/
end
end
def to_s
each_gateway do |g|
puts "#{g.display_name} - #{g.homepage_url} [#{g.supported_countries.join(', ')}]"
end
end
end
| reinteractive/active_merchant | lib/support/gateway_support.rb | Ruby | mit | 1,804 |
/*
* Copyright (c) 2011-2015 Håkan Edling
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
* http://github.com/piranhacms/piranha
*
*/
using System;
using System.Collections.Generic;
namespace Piranha.Extend
{
/// <summary>
/// Base class for easily defining a page type.
/// </summary>
public abstract class PageType : IPageType
{
/// <summary>
/// Gets the name.
/// </summary>
public virtual string Name { get; protected set; }
/// <summary>
/// Gets the optional description.
/// </summary>
public virtual string Description { get; protected set; }
/// <summary>
/// Gets the html preview.
/// </summary>
public virtual string Preview { get; protected set; }
/// <summary>
/// Gets the controller/viewtemplate depending on the current
/// application is using WebPages or Mvc.
/// </summary>
public virtual string Controller { get; protected set; }
/// <summary>
/// Gets if pages of the current type should be able to
/// override the controller.
/// </summary>
public virtual bool ShowController { get; protected set; }
/// <summary>
/// Gets the view. This is only relevant for Mvc applications.
/// </summary>
public virtual string View { get; protected set; }
/// <summary>
/// Gets if pages of the current type should be able to
/// override the controller.
/// </summary>
public virtual bool ShowView { get; protected set; }
/// <summary>
/// Gets/sets the optional permalink of a page this sould redirect to.
/// </summary>
public virtual string Redirect { get; protected set; }
/// <summary>
/// Gets/sets if the redirect can be overriden by the implementing page.
/// </summary>
public virtual bool ShowRedirect { get; protected set; }
/// <summary>
/// Gets the defíned properties.
/// </summary>
public virtual IList<string> Properties { get; protected set; }
/// <summary>
/// Gets the defined regions.
/// </summary>
public virtual IList<RegionType> Regions { get; protected set; }
public PageType() {
Properties = new List<string>();
Regions = new List<RegionType>();
Preview = "<table class=\"template\"><tr><td></td></tr></table>";
}
}
} | timbrown81/Piranha | Core/Piranha/Extend/PageType.cs | C# | mit | 2,364 |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="GetNodeScriptsTest.cs" company="automotiveMastermind and contributors">
// © automotiveMastermind and contributors. Licensed under MIT. See LICENSE and CREDITS for details.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace AM.Condo.Tasks
{
using System.IO;
using Microsoft.Build.Utilities;
using Newtonsoft.Json;
using Xunit;
using AM.Condo.IO;
[Class(nameof(GetNodeMetadata))]
public class GetNodeScriptsTest
{
[Fact]
[Priority(2)]
[Purpose(PurposeType.Integration)]
public void Execute_WithValidProject_Succeeds()
{
using (var temp = new TemporaryPath())
{
// arrange
var project = new
{
name = "test",
version = "1.0.0",
description = "",
main = "index.js",
scripts = new
{
test = "echo this is a test script",
ci = "echo this is a ci script"
},
author = "automotiveMastermind",
license = "MIT"
};
var expected = new[] { "test", "ci" };
var path = temp.Combine("package.json");
using (var writer = File.CreateText(path))
{
var serializer = new JsonSerializer();
serializer.Serialize(writer, project);
writer.Flush();
}
var items = new[] { new TaskItem(path) };
var engine = MSBuildMocks.CreateEngine();
var instance = new GetNodeMetadata
{
Projects = items,
BuildEngine = engine
};
// act
var result = instance.Execute();
// assert
Assert.True(result);
}
}
}
}
| automotiveMastermind/condo | test/AM.Condo.Test/Tasks/GetNodeScriptsTest.cs | C# | mit | 2,251 |
<?php
/* SonataAdminBundle:CRUD:base_list_flat_inner_row.html.twig */
class __TwigTemplate_16b98d4be50387198a258942bcac860cb5e7d142e913464f9538849439128cff extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
'row' => array($this, 'block_row'),
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 11
echo "
";
// line 12
if (($this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "has", array(0 => "batch"), "method") && !$this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : null), "request", array()), "isXmlHttpRequest", array()))) {
// line 13
echo " <td class=\"sonata-ba-list-field sonata-ba-list-field-batch\">
";
// line 14
echo $this->env->getExtension('sonata_admin')->renderListElement((isset($context["object"]) ? $context["object"] : null), $this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "batch", array(), "array"));
echo "
</td>
";
}
// line 17
echo "
<td class=\"sonata-ba-list-field sonata-ba-list-field-inline-fields\" colspan=\"";
// line 18
echo twig_escape_filter($this->env, (twig_length_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "elements", array())) - ($this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "has", array(0 => "_action"), "method") + $this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "has", array(0 => "batch"), "method"))), "html", null, true);
echo "\" objectId=\"";
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "id", array(0 => (isset($context["object"]) ? $context["object"] : null)), "method"), "html", null, true);
echo "\">
";
// line 19
$this->displayBlock('row', $context, $blocks);
// line 20
echo "</td>
";
// line 22
if (($this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "has", array(0 => "_action"), "method") && !$this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : null), "request", array()), "isXmlHttpRequest", array()))) {
// line 23
echo " <td class=\"sonata-ba-list-field sonata-ba-list-field-_action\" objectId=\"";
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "id", array(0 => (isset($context["object"]) ? $context["object"] : null)), "method"), "html", null, true);
echo "\">
";
// line 24
echo $this->env->getExtension('sonata_admin')->renderListElement((isset($context["object"]) ? $context["object"] : null), $this->getAttribute($this->getAttribute((isset($context["admin"]) ? $context["admin"] : null), "list", array()), "_action", array(), "array"));
echo "
</td>
";
}
}
// line 19
public function block_row($context, array $blocks = array())
{
}
public function getTemplateName()
{
return "SonataAdminBundle:CRUD:base_list_flat_inner_row.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 64 => 19, 56 => 24, 51 => 23, 49 => 22, 45 => 20, 43 => 19, 37 => 18, 34 => 17, 28 => 14, 25 => 13, 23 => 12, 20 => 11,);
}
}
| chicho2114/Proy_Frameworks | app/cache/prod/twig/16/b9/8d4be50387198a258942bcac860cb5e7d142e913464f9538849439128cff.php | PHP | mit | 3,962 |
var Promise = require('ember-cli/lib/ext/promise');
module.exports = {
normalizeEntityName: function() {},
afterInstall: function() {
var addonContext = this;
return this.addBowerPackageToProject('jquery-ui', '1.10.1')
.then(function() {
return addonContext.addBowerPackageToProject('jquery-mousewheel', '~3.1.4');
})
.then(function() {
return addonContext.addBowerPackageToProject('taras/antiscroll', '92505e0e0d0ef9383630df509883bce558215b22');
});
}
};
| ming-codes/ember-cli-ember-table | blueprints/ember-cli-ember-table/index.js | JavaScript | mit | 515 |
import time
import random
from random import randint
# from library import Trigger, Axis
# from library import PS4
from library import Joystick
import RPi.GPIO as GPIO # remove!!!
from emotions import angry, happy, confused
# from pysabertooth import Sabertooth
# from smc import SMC
from library import LEDDisplay
from library import factory
from library import reset_all_hw
# Leg Motor Speed Global
global_LegMotor = 70
# # Happy Emotion
# def happy(leds, servos, mc, audio):
# print("4")
# print("Happy")
#
# # Dome Motor Initialization
# # mc = SMC(dome_motor_port, 115200)
# # mc.init()
#
# # Spins Motor
# # mc.init()
# mc.speed(3200)
#
# # LED Matrix Green
# # breadboard has mono
# # R2 has bi-color leds
# # mono:0 bi:1
# # led_type = 0
# # leds = [0]*5
# # leds[1] = LEDDisplay(0x70, led_type)
# # leds[2] = LEDDisplay(0x71, led_type)
# # leds[3] = LEDDisplay(0x72, led_type)
# # leds[4] = LEDDisplay(0x73, led_type)
#
# for x in [0, 1, 2, 3, 4, 5, 6, 7]:
# for y in [0, 1, 2, 3, 4, 5, 6, 7]:
# for i in range(1, 5):
# leds[i].set(x, y, 1)
#
# for i in range(1, 5):
# leds[i].write()
#
# # Servo Wave
# # s0.angle = 0
# # time.sleep(0.2)
# # s1.angle = 0
# # time.sleep(0.2)
# # s2.angle = 0
# # time.sleep(0.2)
# # s3.angle = 0
# # time.sleep(0.2)
# # s4.angle = 0
# # time.sleep(0.5)
# # s4.angle = 130
# # time.sleep(0.2)
# # s3.angle = 130
# # time.sleep(0.2)
# # s2.angle = 130
# # time.sleep(0.2)
# # s1.angle = 130
# # time.sleep(0.2)
# # s0.angle = 130
#
# for a in [0, 130]:
# for i in range(4):
# servos[i].angle = a
# time.sleep(0.2)
# time.sleep(0.5)
#
# time.sleep(1.5)
# mc.stop()
# time.sleep(1.5)
# for i in range(1, 5):
# leds[i].clear()
#
#
# # Confused Emotion
# def confused(leds, servos, mc, audio):
# print("5")
# print("Confused")
# # LED Matrix Yellow
# # leds = [0]*5
# # leds[1] = LEDDisplay(0x70, 1)
# # leds[2] = LEDDisplay(0x71, 1)
# # leds[3] = LEDDisplay(0x72, 1)
# # leds[4] = LEDDisplay(0x73, 1)
#
# for x in [0, 1, 2, 3, 4, 5, 6, 7]:
# for y in [0, 1, 2, 3, 4, 5, 6, 7]:
# for i in range(1, 5):
# leds[i].set(x, y, 3)
# for i in range(1, 5):
# leds[i].write()
# time.sleep(3)
# for i in range(1, 5):
# leds[i].clear()
#
#
# # Angry Emotion
# def angry(leds, servos, mc, audio):
# print("6")
# print("Angry")
# # LED Matrix Red
# # leds = [0]*5
# # leds[1] = LEDDisplay(0x70, 1)
# # leds[2] = LEDDisplay(0x71, 1)
# # leds[3] = LEDDisplay(0x72, 1)
# # leds[4] = LEDDisplay(0x73, 1)
#
# for x in [0, 1, 2, 3, 4, 5, 6, 7]:
# for y in [0, 1, 2, 3, 4, 5, 6, 7]:
# for i in range(1, 5):
# leds[i].set(x, y, 2)
#
# for i in range(1, 5):
# leds[i].write()
#
# # Plays Imperial Theme Sound
# audio.sound('imperial')
#
# # Servo Open and Close
# # s0.angle = 0
# # s1.angle = 0
# # s2.angle = 0
# # s3.angle = 0
# # s4.angle = 0
# # time.sleep(1)
# # s4.angle = 130
# # s3.angle = 130
# # s2.angle = 130
# # s1.angle = 130
# # s0.angle = 130
#
# for a in [0, 130]:
# for i in range(5):
# servos[i].angle = a
# time.sleep(1)
#
# time.sleep(3)
# for i in range(1, 5):
# leds[i].clear()
#######################################
# original remote
#######################################
# # Remote Mode
# def remote(remoteflag, namespace):
# print("Remote")
#
# # create objects
# (leds, dome, legs, servos, Flash) = factory(['leds', 'dome', 'legs', 'servos', 'flashlight'])
#
# # initalize everything
# dome.init()
# dome.speed(0)
#
# legs.drive(1, 0)
# legs.drive(2, 0)
#
# for s in servos:
# s.angle = 0
# time.sleep(0.25)
#
# # what is this???
# GPIO.setmode(GPIO.BCM)
# GPIO.setwarnings(False)
# GPIO.setup(26, GPIO.OUT)
#
# # Joystick Initialization
# js = Joystick()
#
# # get audio
# audio = namespace.audio
#
# # Flash = FlashlightPWM(15)
# # Flash = namespace.flashlight
#
# while(remoteflag.is_set()):
# try:
# # Button Initialization
# ps4 = js.get()
# btnSquare = ps4.buttons[0]
# btnTriangle = ps4.buttons[1]
# btnCircle = ps4.buttons[2]
# btnX = ps4.buttons[3]
# btnLeftStickLeftRight = ps4.leftStick.y
# btnLeftStickUpDown = ps4.leftStick.x
# btnRightStickLeftRight = ps4.rightStick.y
# btnRightStickUpDown = ps4.rightStick.x
# Left1 = ps4.shoulder[0]
# Right1 = ps4.shoulder[1]
# Left2 = ps4.triggers.x
# Right2 = ps4.triggers.y
# hat = ps4.hat
#
# # print("PRINT")
#
# # Button Controls
# if hat == 1:
# # Happy Emotion
# print("Arrow Up Pressed")
# happy(leds, servos, dome, audio) # namespace.emotions['happy'](leds, servos, mc, audio)
# if hat == 8:
# # Confused Emotion
# print("Arrow Left Pressed")
# confused(leds, servos, dome, audio)
# if hat == 2:
# # Angry Emotion
# print("Arrow Right Pressed")
# angry(leds, servos, dome, audio)
# if hat == 4:
# print("Arrow Down Pressed")
# if btnSquare == 1:
# # word = random_char(2)
# audio.speak_random(2)
# time.sleep(0.5)
# if btnTriangle == 1:
# # FlashLight ON
# GPIO.output(26, GPIO.HIGH)
# Flash.pwm.set_pwm(15, 0, 130)
# if btnCircle == 1:
# # FlashLight OFF
# GPIO.output(26, GPIO.LOW)
# Flash.pwm.set_pwm(15, 0, 0)
# if btnX == 1:
# for x in [0, 1, 2, 3, 4, 5, 6, 7]:
# for y in [0, 1, 2, 3, 4, 5, 6, 7]:
# if x == randint(0, 8) or y == randint(0, 8):
# for i in range(1, 5):
# leds[i].set(x, y, randint(0, 4))
# else:
# for i in range(1, 5):
# leds[i].set(x, y, 4)
# for i in range(1, 5):
# leds[i].write()
# time.sleep(0.1)
# for i in range(1, 5):
# leds[i].clear()
# if Left1 == 1:
# # Dome Motor Forward
# dome.speed(3200)
# time.sleep(2)
# dome.speed(0)
# if Right1 == 1:
# # Dome Motor Backward
# dome.speed(-3200)
# time.sleep(2)
# dome.speed(0)
# # if Left1 == 0 or Right1 == 0:
# # # Dome Motor Stop
# # dome.speed(0)
# # if Left2 > 1:
# # # Servo Open
# # s0.angle = 0
# # s1.angle = 0
# # s2.angle = 0
# # s3.angle = 0
# # s4.angle = 0
# # Flash.pwm.set_pwm(15, 0, 3000)
# #
# # if Right2 > 1:
# # # Servo Close
# # s0.angle = 130
# # s1.angle = 130
# # s2.angle = 130
# # s3.angle = 130
# # s4.angle = 130
# # Flash.pwm.set_pwm(15, 0, 130)
# if Left2 > 1:
# for s in servos:
# s.angle = 0
# time.sleep(0.25)
# Flash.pwm.set_pwm(15, 0, 300)
# if Right2 > 1:
# for s in servos:
# s.angle = 130
# time.sleep(0.25)
# Flash.pwm.set_pwm(15, 0, 130)
# if btnLeftStickLeftRight < 0.3 and btnLeftStickLeftRight > -0.3:
# legs.drive(1, 0)
# if btnRightStickUpDown < 0.3 and btnRightStickUpDown > -0.3:
# legs.drive(2, 0)
# if btnRightStickUpDown >= 0.3:
# # Right and Left Motor Forward
# legs.drive(1, btnRightStickUpDown*global_LegMotor)
# legs.drive(2, btnRightStickUpDown*-global_LegMotor)
# if btnRightStickUpDown <= -0.3:
# # Right and Left Motor Backward
# legs.drive(1, btnRightStickUpDown*global_LegMotor)
# legs.drive(2, btnRightStickUpDown*-global_LegMotor)
# if btnLeftStickLeftRight <= 0.3:
# # Turn Left
# legs.drive(1, btnLeftStickLeftRight*(-global_LegMotor))
# legs.drive(2, btnLeftStickLeftRight*-global_LegMotor)
# if btnLeftStickLeftRight >= -0.3:
# # Turn Right
# legs.drive(1, btnLeftStickLeftRight*(-global_LegMotor))
# legs.drive(2, btnLeftStickLeftRight*-global_LegMotor)
#
# except KeyboardInterrupt:
# print('js exiting ...')
# return
# return
def remote_func(hw, ns):
print("Remote")
dome = hw['dome']
dome.speed(0)
legs = hw['legs']
legs.drive(1, 0)
legs.drive(2, 0)
flashlight = hw['flashlight']
audio = hw['audio']
audio.speak('start')
while ns.current_state == 3:
print('remote ...')
spd = random.randint(0, 40)
legs.drive(1, spd)
legs.drive(2, spd)
dome.speed(spd)
time.sleep(0.5)
legs.drive(1, 0)
legs.drive(2, 0)
dome.speed(0)
time.sleep(0.1)
return
###### real loop here #####
# Joystick Initialization
js = Joystick()
while ns.current_state == 3:
try:
# Button Initialization
ps4 = js.get()
btnSquare = ps4.buttons[0]
btnTriangle = ps4.buttons[1]
btnCircle = ps4.buttons[2]
btnX = ps4.buttons[3]
btnLeftStickLeftRight = ps4.leftStick.y
btnLeftStickUpDown = ps4.leftStick.x
btnRightStickLeftRight = ps4.rightStick.y
btnRightStickUpDown = ps4.rightStick.x
Left1 = ps4.shoulder[0]
Right1 = ps4.shoulder[1]
Left2 = ps4.triggers.x
Right2 = ps4.triggers.y
hat = ps4.hat
# print("PRINT")
# Button Controls
if hat == 1:
# Happy Emotion
print("Arrow Up Pressed")
happy(leds, servos, dome, audio) # namespace.emotions['happy'](leds, servos, mc, audio)
if hat == 8:
# Confused Emotion
print("Arrow Left Pressed")
confused(leds, servos, dome, audio)
if hat == 2:
# Angry Emotion
print("Arrow Right Pressed")
angry(leds, servos, dome, audio)
if hat == 4:
print("Arrow Down Pressed")
if btnSquare == 1:
# word = random_char(2)
audio.speak_random(2)
time.sleep(0.5)
if btnTriangle == 1:
# FlashLight ON
GPIO.output(26, GPIO.HIGH)
Flash.pwm.set_pwm(15, 0, 130)
if btnCircle == 1:
# FlashLight OFF
GPIO.output(26, GPIO.LOW)
Flash.pwm.set_pwm(15, 0, 0)
if btnX == 1:
for x in [0, 1, 2, 3, 4, 5, 6, 7]:
for y in [0, 1, 2, 3, 4, 5, 6, 7]:
if x == randint(0, 8) or y == randint(0, 8):
for i in range(1, 5):
leds[i].set(x, y, randint(0, 4))
else:
for i in range(1, 5):
leds[i].set(x, y, 4)
for i in range(1, 5):
leds[i].write()
time.sleep(0.1)
for i in range(1, 5):
leds[i].clear()
if Left1 == 1:
# Dome Motor Forward
dome.speed(3200)
time.sleep(2)
dome.speed(0)
if Right1 == 1:
# Dome Motor Backward
dome.speed(-3200)
time.sleep(2)
dome.speed(0)
# if Left1 == 0 or Right1 == 0:
# # Dome Motor Stop
# dome.speed(0)
# if Left2 > 1:
# # Servo Open
# s0.angle = 0
# s1.angle = 0
# s2.angle = 0
# s3.angle = 0
# s4.angle = 0
# Flash.pwm.set_pwm(15, 0, 3000)
#
# if Right2 > 1:
# # Servo Close
# s0.angle = 130
# s1.angle = 130
# s2.angle = 130
# s3.angle = 130
# s4.angle = 130
# Flash.pwm.set_pwm(15, 0, 130)
if Left2 > 1:
for s in servos:
s.angle = 0
time.sleep(0.25)
Flash.pwm.set_pwm(15, 0, 300)
if Right2 > 1:
for s in servos:
s.angle = 130
time.sleep(0.25)
Flash.pwm.set_pwm(15, 0, 130)
if btnLeftStickLeftRight < 0.3 and btnLeftStickLeftRight > -0.3:
legs.drive(1, 0)
if btnRightStickUpDown < 0.3 and btnRightStickUpDown > -0.3:
legs.drive(2, 0)
if btnRightStickUpDown >= 0.3:
# Right and Left Motor Forward
legs.drive(1, btnRightStickUpDown*global_LegMotor)
legs.drive(2, btnRightStickUpDown*-global_LegMotor)
if btnRightStickUpDown <= -0.3:
# Right and Left Motor Backward
legs.drive(1, btnRightStickUpDown*global_LegMotor)
legs.drive(2, btnRightStickUpDown*-global_LegMotor)
if btnLeftStickLeftRight <= 0.3:
# Turn Left
legs.drive(1, btnLeftStickLeftRight*(-global_LegMotor))
legs.drive(2, btnLeftStickLeftRight*-global_LegMotor)
if btnLeftStickLeftRight >= -0.3:
# Turn Right
legs.drive(1, btnLeftStickLeftRight*(-global_LegMotor))
legs.drive(2, btnLeftStickLeftRight*-global_LegMotor)
except KeyboardInterrupt:
print('js exiting ...')
return
# exiting, reset all hw
reset_all_hw(hw)
return
| DFEC-R2D2/r2d2 | pygecko/states/remote.py | Python | mit | 11,721 |
##
# This code was generated by
# \ / _ _ _| _ _
# | (_)\/(_)(_|\/| |(/_ v1.0.0
# / /
#
# frozen_string_literal: true
module Twilio
module REST
class Api < Domain
class V2010 < Version
class AccountContext < InstanceContext
class ApplicationList < ListResource
##
# Initialize the ApplicationList
# @param [Version] version Version that contains the resource
# @param [String] account_sid The SID of the
# {Account}[https://www.twilio.com/docs/iam/api/account] that created the
# Application resource.
# @return [ApplicationList] ApplicationList
def initialize(version, account_sid: nil)
super(version)
# Path Solution
@solution = {account_sid: account_sid}
@uri = "/Accounts/#{@solution[:account_sid]}/Applications.json"
end
##
# Create the ApplicationInstance
# @param [String] api_version The API version to use to start a new TwiML session.
# Can be: `2010-04-01` or `2008-08-01`. The default value is the account's default
# API version.
# @param [String] voice_url The URL we should call when the phone number assigned
# to this application receives a call.
# @param [String] voice_method The HTTP method we should use to call `voice_url`.
# Can be: `GET` or `POST`.
# @param [String] voice_fallback_url The URL that we should call when an error
# occurs retrieving or executing the TwiML requested by `url`.
# @param [String] voice_fallback_method The HTTP method we should use to call
# `voice_fallback_url`. Can be: `GET` or `POST`.
# @param [String] status_callback The URL we should call using the
# `status_callback_method` to send status information to your application.
# @param [String] status_callback_method The HTTP method we should use to call
# `status_callback`. Can be: `GET` or `POST`.
# @param [Boolean] voice_caller_id_lookup Whether we should look up the caller's
# caller-ID name from the CNAM database (additional charges apply). Can be: `true`
# or `false`.
# @param [String] sms_url The URL we should call when the phone number receives an
# incoming SMS message.
# @param [String] sms_method The HTTP method we should use to call `sms_url`. Can
# be: `GET` or `POST`.
# @param [String] sms_fallback_url The URL that we should call when an error
# occurs while retrieving or executing the TwiML from `sms_url`.
# @param [String] sms_fallback_method The HTTP method we should use to call
# `sms_fallback_url`. Can be: `GET` or `POST`.
# @param [String] sms_status_callback The URL we should call using a POST method
# to send status information about SMS messages sent by the application.
# @param [String] message_status_callback The URL we should call using a POST
# method to send message status information to your application.
# @param [String] friendly_name A descriptive string that you create to describe
# the new application. It can be up to 64 characters long.
# @return [ApplicationInstance] Created ApplicationInstance
def create(api_version: :unset, voice_url: :unset, voice_method: :unset, voice_fallback_url: :unset, voice_fallback_method: :unset, status_callback: :unset, status_callback_method: :unset, voice_caller_id_lookup: :unset, sms_url: :unset, sms_method: :unset, sms_fallback_url: :unset, sms_fallback_method: :unset, sms_status_callback: :unset, message_status_callback: :unset, friendly_name: :unset)
data = Twilio::Values.of({
'ApiVersion' => api_version,
'VoiceUrl' => voice_url,
'VoiceMethod' => voice_method,
'VoiceFallbackUrl' => voice_fallback_url,
'VoiceFallbackMethod' => voice_fallback_method,
'StatusCallback' => status_callback,
'StatusCallbackMethod' => status_callback_method,
'VoiceCallerIdLookup' => voice_caller_id_lookup,
'SmsUrl' => sms_url,
'SmsMethod' => sms_method,
'SmsFallbackUrl' => sms_fallback_url,
'SmsFallbackMethod' => sms_fallback_method,
'SmsStatusCallback' => sms_status_callback,
'MessageStatusCallback' => message_status_callback,
'FriendlyName' => friendly_name,
})
payload = @version.create('POST', @uri, data: data)
ApplicationInstance.new(@version, payload, account_sid: @solution[:account_sid], )
end
##
# Lists ApplicationInstance records from the API as a list.
# Unlike stream(), this operation is eager and will load `limit` records into
# memory before returning.
# @param [String] friendly_name The string that identifies the Application
# resources to read.
# @param [Integer] limit Upper limit for the number of records to return. stream()
# guarantees to never return more than limit. Default is no limit
# @param [Integer] page_size Number of records to fetch per request, when
# not set will use the default value of 50 records. If no page_size is defined
# but a limit is defined, stream() will attempt to read the limit with the most
# efficient page size, i.e. min(limit, 1000)
# @return [Array] Array of up to limit results
def list(friendly_name: :unset, limit: nil, page_size: nil)
self.stream(friendly_name: friendly_name, limit: limit, page_size: page_size).entries
end
##
# Streams ApplicationInstance records from the API as an Enumerable.
# This operation lazily loads records as efficiently as possible until the limit
# is reached.
# @param [String] friendly_name The string that identifies the Application
# resources to read.
# @param [Integer] limit Upper limit for the number of records to return. stream()
# guarantees to never return more than limit. Default is no limit.
# @param [Integer] page_size Number of records to fetch per request, when
# not set will use the default value of 50 records. If no page_size is defined
# but a limit is defined, stream() will attempt to read the limit with the most
# efficient page size, i.e. min(limit, 1000)
# @return [Enumerable] Enumerable that will yield up to limit results
def stream(friendly_name: :unset, limit: nil, page_size: nil)
limits = @version.read_limits(limit, page_size)
page = self.page(friendly_name: friendly_name, page_size: limits[:page_size], )
@version.stream(page, limit: limits[:limit], page_limit: limits[:page_limit])
end
##
# When passed a block, yields ApplicationInstance records from the API.
# This operation lazily loads records as efficiently as possible until the limit
# is reached.
def each
limits = @version.read_limits
page = self.page(page_size: limits[:page_size], )
@version.stream(page,
limit: limits[:limit],
page_limit: limits[:page_limit]).each {|x| yield x}
end
##
# Retrieve a single page of ApplicationInstance records from the API.
# Request is executed immediately.
# @param [String] friendly_name The string that identifies the Application
# resources to read.
# @param [String] page_token PageToken provided by the API
# @param [Integer] page_number Page Number, this value is simply for client state
# @param [Integer] page_size Number of records to return, defaults to 50
# @return [Page] Page of ApplicationInstance
def page(friendly_name: :unset, page_token: :unset, page_number: :unset, page_size: :unset)
params = Twilio::Values.of({
'FriendlyName' => friendly_name,
'PageToken' => page_token,
'Page' => page_number,
'PageSize' => page_size,
})
response = @version.page('GET', @uri, params: params)
ApplicationPage.new(@version, response, @solution)
end
##
# Retrieve a single page of ApplicationInstance records from the API.
# Request is executed immediately.
# @param [String] target_url API-generated URL for the requested results page
# @return [Page] Page of ApplicationInstance
def get_page(target_url)
response = @version.domain.request(
'GET',
target_url
)
ApplicationPage.new(@version, response, @solution)
end
##
# Provide a user friendly representation
def to_s
'#<Twilio.Api.V2010.ApplicationList>'
end
end
class ApplicationPage < Page
##
# Initialize the ApplicationPage
# @param [Version] version Version that contains the resource
# @param [Response] response Response from the API
# @param [Hash] solution Path solution for the resource
# @return [ApplicationPage] ApplicationPage
def initialize(version, response, solution)
super(version, response)
# Path Solution
@solution = solution
end
##
# Build an instance of ApplicationInstance
# @param [Hash] payload Payload response from the API
# @return [ApplicationInstance] ApplicationInstance
def get_instance(payload)
ApplicationInstance.new(@version, payload, account_sid: @solution[:account_sid], )
end
##
# Provide a user friendly representation
def to_s
'<Twilio.Api.V2010.ApplicationPage>'
end
end
class ApplicationContext < InstanceContext
##
# Initialize the ApplicationContext
# @param [Version] version Version that contains the resource
# @param [String] account_sid The SID of the
# {Account}[https://www.twilio.com/docs/iam/api/account] that created the
# Application resource to fetch.
# @param [String] sid The Twilio-provided string that uniquely identifies the
# Application resource to fetch.
# @return [ApplicationContext] ApplicationContext
def initialize(version, account_sid, sid)
super(version)
# Path Solution
@solution = {account_sid: account_sid, sid: sid, }
@uri = "/Accounts/#{@solution[:account_sid]}/Applications/#{@solution[:sid]}.json"
end
##
# Delete the ApplicationInstance
# @return [Boolean] true if delete succeeds, false otherwise
def delete
@version.delete('DELETE', @uri)
end
##
# Fetch the ApplicationInstance
# @return [ApplicationInstance] Fetched ApplicationInstance
def fetch
payload = @version.fetch('GET', @uri)
ApplicationInstance.new(
@version,
payload,
account_sid: @solution[:account_sid],
sid: @solution[:sid],
)
end
##
# Update the ApplicationInstance
# @param [String] friendly_name A descriptive string that you create to describe
# the resource. It can be up to 64 characters long.
# @param [String] api_version The API version to use to start a new TwiML session.
# Can be: `2010-04-01` or `2008-08-01`. The default value is your account's
# default API version.
# @param [String] voice_url The URL we should call when the phone number assigned
# to this application receives a call.
# @param [String] voice_method The HTTP method we should use to call `voice_url`.
# Can be: `GET` or `POST`.
# @param [String] voice_fallback_url The URL that we should call when an error
# occurs retrieving or executing the TwiML requested by `url`.
# @param [String] voice_fallback_method The HTTP method we should use to call
# `voice_fallback_url`. Can be: `GET` or `POST`.
# @param [String] status_callback The URL we should call using the
# `status_callback_method` to send status information to your application.
# @param [String] status_callback_method The HTTP method we should use to call
# `status_callback`. Can be: `GET` or `POST`.
# @param [Boolean] voice_caller_id_lookup Whether we should look up the caller's
# caller-ID name from the CNAM database (additional charges apply). Can be: `true`
# or `false`.
# @param [String] sms_url The URL we should call when the phone number receives an
# incoming SMS message.
# @param [String] sms_method The HTTP method we should use to call `sms_url`. Can
# be: `GET` or `POST`.
# @param [String] sms_fallback_url The URL that we should call when an error
# occurs while retrieving or executing the TwiML from `sms_url`.
# @param [String] sms_fallback_method The HTTP method we should use to call
# `sms_fallback_url`. Can be: `GET` or `POST`.
# @param [String] sms_status_callback Same as message_status_callback: The URL we
# should call using a POST method to send status information about SMS messages
# sent by the application. Deprecated, included for backwards compatibility.
# @param [String] message_status_callback The URL we should call using a POST
# method to send message status information to your application.
# @return [ApplicationInstance] Updated ApplicationInstance
def update(friendly_name: :unset, api_version: :unset, voice_url: :unset, voice_method: :unset, voice_fallback_url: :unset, voice_fallback_method: :unset, status_callback: :unset, status_callback_method: :unset, voice_caller_id_lookup: :unset, sms_url: :unset, sms_method: :unset, sms_fallback_url: :unset, sms_fallback_method: :unset, sms_status_callback: :unset, message_status_callback: :unset)
data = Twilio::Values.of({
'FriendlyName' => friendly_name,
'ApiVersion' => api_version,
'VoiceUrl' => voice_url,
'VoiceMethod' => voice_method,
'VoiceFallbackUrl' => voice_fallback_url,
'VoiceFallbackMethod' => voice_fallback_method,
'StatusCallback' => status_callback,
'StatusCallbackMethod' => status_callback_method,
'VoiceCallerIdLookup' => voice_caller_id_lookup,
'SmsUrl' => sms_url,
'SmsMethod' => sms_method,
'SmsFallbackUrl' => sms_fallback_url,
'SmsFallbackMethod' => sms_fallback_method,
'SmsStatusCallback' => sms_status_callback,
'MessageStatusCallback' => message_status_callback,
})
payload = @version.update('POST', @uri, data: data)
ApplicationInstance.new(
@version,
payload,
account_sid: @solution[:account_sid],
sid: @solution[:sid],
)
end
##
# Provide a user friendly representation
def to_s
context = @solution.map {|k, v| "#{k}: #{v}"}.join(',')
"#<Twilio.Api.V2010.ApplicationContext #{context}>"
end
##
# Provide a detailed, user friendly representation
def inspect
context = @solution.map {|k, v| "#{k}: #{v}"}.join(',')
"#<Twilio.Api.V2010.ApplicationContext #{context}>"
end
end
class ApplicationInstance < InstanceResource
##
# Initialize the ApplicationInstance
# @param [Version] version Version that contains the resource
# @param [Hash] payload payload that contains response from Twilio
# @param [String] account_sid The SID of the
# {Account}[https://www.twilio.com/docs/iam/api/account] that created the
# Application resource.
# @param [String] sid The Twilio-provided string that uniquely identifies the
# Application resource to fetch.
# @return [ApplicationInstance] ApplicationInstance
def initialize(version, payload, account_sid: nil, sid: nil)
super(version)
# Marshaled Properties
@properties = {
'account_sid' => payload['account_sid'],
'api_version' => payload['api_version'],
'date_created' => Twilio.deserialize_rfc2822(payload['date_created']),
'date_updated' => Twilio.deserialize_rfc2822(payload['date_updated']),
'friendly_name' => payload['friendly_name'],
'message_status_callback' => payload['message_status_callback'],
'sid' => payload['sid'],
'sms_fallback_method' => payload['sms_fallback_method'],
'sms_fallback_url' => payload['sms_fallback_url'],
'sms_method' => payload['sms_method'],
'sms_status_callback' => payload['sms_status_callback'],
'sms_url' => payload['sms_url'],
'status_callback' => payload['status_callback'],
'status_callback_method' => payload['status_callback_method'],
'uri' => payload['uri'],
'voice_caller_id_lookup' => payload['voice_caller_id_lookup'],
'voice_fallback_method' => payload['voice_fallback_method'],
'voice_fallback_url' => payload['voice_fallback_url'],
'voice_method' => payload['voice_method'],
'voice_url' => payload['voice_url'],
}
# Context
@instance_context = nil
@params = {'account_sid' => account_sid, 'sid' => sid || @properties['sid'], }
end
##
# Generate an instance context for the instance, the context is capable of
# performing various actions. All instance actions are proxied to the context
# @return [ApplicationContext] ApplicationContext for this ApplicationInstance
def context
unless @instance_context
@instance_context = ApplicationContext.new(@version, @params['account_sid'], @params['sid'], )
end
@instance_context
end
##
# @return [String] The SID of the Account that created the resource
def account_sid
@properties['account_sid']
end
##
# @return [String] The API version used to start a new TwiML session
def api_version
@properties['api_version']
end
##
# @return [Time] The RFC 2822 date and time in GMT that the resource was created
def date_created
@properties['date_created']
end
##
# @return [Time] The RFC 2822 date and time in GMT that the resource was last updated
def date_updated
@properties['date_updated']
end
##
# @return [String] The string that you assigned to describe the resource
def friendly_name
@properties['friendly_name']
end
##
# @return [String] The URL to send message status information to your application
def message_status_callback
@properties['message_status_callback']
end
##
# @return [String] The unique string that identifies the resource
def sid
@properties['sid']
end
##
# @return [String] The HTTP method used with sms_fallback_url
def sms_fallback_method
@properties['sms_fallback_method']
end
##
# @return [String] The URL that we call when an error occurs while retrieving or executing the TwiML
def sms_fallback_url
@properties['sms_fallback_url']
end
##
# @return [String] The HTTP method to use with sms_url
def sms_method
@properties['sms_method']
end
##
# @return [String] The URL to send status information to your application
def sms_status_callback
@properties['sms_status_callback']
end
##
# @return [String] The URL we call when the phone number receives an incoming SMS message
def sms_url
@properties['sms_url']
end
##
# @return [String] The URL to send status information to your application
def status_callback
@properties['status_callback']
end
##
# @return [String] The HTTP method we use to call status_callback
def status_callback_method
@properties['status_callback_method']
end
##
# @return [String] The URI of the resource, relative to `https://api.twilio.com`
def uri
@properties['uri']
end
##
# @return [Boolean] Whether to lookup the caller's name
def voice_caller_id_lookup
@properties['voice_caller_id_lookup']
end
##
# @return [String] The HTTP method used with voice_fallback_url
def voice_fallback_method
@properties['voice_fallback_method']
end
##
# @return [String] The URL we call when a TwiML error occurs
def voice_fallback_url
@properties['voice_fallback_url']
end
##
# @return [String] The HTTP method used with the voice_url
def voice_method
@properties['voice_method']
end
##
# @return [String] The URL we call when the phone number receives a call
def voice_url
@properties['voice_url']
end
##
# Delete the ApplicationInstance
# @return [Boolean] true if delete succeeds, false otherwise
def delete
context.delete
end
##
# Fetch the ApplicationInstance
# @return [ApplicationInstance] Fetched ApplicationInstance
def fetch
context.fetch
end
##
# Update the ApplicationInstance
# @param [String] friendly_name A descriptive string that you create to describe
# the resource. It can be up to 64 characters long.
# @param [String] api_version The API version to use to start a new TwiML session.
# Can be: `2010-04-01` or `2008-08-01`. The default value is your account's
# default API version.
# @param [String] voice_url The URL we should call when the phone number assigned
# to this application receives a call.
# @param [String] voice_method The HTTP method we should use to call `voice_url`.
# Can be: `GET` or `POST`.
# @param [String] voice_fallback_url The URL that we should call when an error
# occurs retrieving or executing the TwiML requested by `url`.
# @param [String] voice_fallback_method The HTTP method we should use to call
# `voice_fallback_url`. Can be: `GET` or `POST`.
# @param [String] status_callback The URL we should call using the
# `status_callback_method` to send status information to your application.
# @param [String] status_callback_method The HTTP method we should use to call
# `status_callback`. Can be: `GET` or `POST`.
# @param [Boolean] voice_caller_id_lookup Whether we should look up the caller's
# caller-ID name from the CNAM database (additional charges apply). Can be: `true`
# or `false`.
# @param [String] sms_url The URL we should call when the phone number receives an
# incoming SMS message.
# @param [String] sms_method The HTTP method we should use to call `sms_url`. Can
# be: `GET` or `POST`.
# @param [String] sms_fallback_url The URL that we should call when an error
# occurs while retrieving or executing the TwiML from `sms_url`.
# @param [String] sms_fallback_method The HTTP method we should use to call
# `sms_fallback_url`. Can be: `GET` or `POST`.
# @param [String] sms_status_callback Same as message_status_callback: The URL we
# should call using a POST method to send status information about SMS messages
# sent by the application. Deprecated, included for backwards compatibility.
# @param [String] message_status_callback The URL we should call using a POST
# method to send message status information to your application.
# @return [ApplicationInstance] Updated ApplicationInstance
def update(friendly_name: :unset, api_version: :unset, voice_url: :unset, voice_method: :unset, voice_fallback_url: :unset, voice_fallback_method: :unset, status_callback: :unset, status_callback_method: :unset, voice_caller_id_lookup: :unset, sms_url: :unset, sms_method: :unset, sms_fallback_url: :unset, sms_fallback_method: :unset, sms_status_callback: :unset, message_status_callback: :unset)
context.update(
friendly_name: friendly_name,
api_version: api_version,
voice_url: voice_url,
voice_method: voice_method,
voice_fallback_url: voice_fallback_url,
voice_fallback_method: voice_fallback_method,
status_callback: status_callback,
status_callback_method: status_callback_method,
voice_caller_id_lookup: voice_caller_id_lookup,
sms_url: sms_url,
sms_method: sms_method,
sms_fallback_url: sms_fallback_url,
sms_fallback_method: sms_fallback_method,
sms_status_callback: sms_status_callback,
message_status_callback: message_status_callback,
)
end
##
# Provide a user friendly representation
def to_s
values = @params.map{|k, v| "#{k}: #{v}"}.join(" ")
"<Twilio.Api.V2010.ApplicationInstance #{values}>"
end
##
# Provide a detailed, user friendly representation
def inspect
values = @properties.map{|k, v| "#{k}: #{v}"}.join(" ")
"<Twilio.Api.V2010.ApplicationInstance #{values}>"
end
end
end
end
end
end
end | philnash/twilio-ruby | lib/twilio-ruby/rest/api/v2010/account/application.rb | Ruby | mit | 28,693 |
<?php
namespace Omnipay\Braintree\Message;
/**
* Find Customer Request
*
* @method CustomerResponse send()
*/
class FindCustomerRequest extends AbstractRequest
{
public function getData()
{
return $this->getCustomerData();
}
/**
* Send the request with specified data
*
* @param mixed $data The data to send
* @return CustomerResponse
*/
public function sendData($data)
{
$response = $this->braintree->customer()->find($this->getCustomerId());
return $this->response = new CustomerResponse($this, $response);
}
} | Shimmi/omnipay-braintree | src/Message/FindCustomerRequest.php | PHP | mit | 597 |
require_relative 'base'
module Terjira
module Client
class StatusCategory < Base
class << self
def all
@all_statuscategory ||= file_cache.fetch("all") do
resp = api_get "statuscategory"
resp.map { |category| build(category) }
end
end
def file_cache
Terjira::FileCache.new("resource/statuscategory", 60 * 60 * 48)
end
end
end
end
end
| keepcosmos/terjira | lib/terjira/client/status_category.rb | Ruby | mit | 445 |
Date.CultureInfo = {
/* Culture Name */
name: "fr-FR",
englishName: "French (France)",
nativeName: "français (France)",
/* Day Name Strings */
dayNames: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"],
abbreviatedDayNames: ["dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam."],
shortestDayNames: ["di", "lu", "ma", "me", "je", "ve", "sa"],
firstLetterDayNames: ["d", "l", "m", "m", "j", "v", "s"],
/* Month Name Strings */
monthNames: ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"],
abbreviatedMonthNames: ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc."],
/* AM/PM Designators */
amDesignator: "",
pmDesignator: "",
firstDayOfWeek: 1,
twoDigitYearMax: 2029,
/**
* The dateElementOrder is based on the order of the
* format specifiers in the formatPatterns.DatePattern.
*
* Example:
<pre>
shortDatePattern dateElementOrder
------------------ ----------------
"M/d/yyyy" "mdy"
"dd/MM/yyyy" "dmy"
"yyyy-MM-dd" "ymd"
</pre>
*
* The correct dateElementOrder is required by the parser to
* determine the expected order of the date elements in the
* string being parsed.
*/
dateElementOrder: "dmy",
/* Standard date and time format patterns */
formatPatterns: {
shortDate: "dd/MM/yyyy",
longDate: "dddd d MMMM yyyy",
shortTime: "HH:mm",
longTime: "HH:mm:ss",
fullDateTime: "dddd d MMMM yyyy HH:mm:ss",
sortableDateTime: "yyyy-MM-ddTHH:mm:ss",
universalSortableDateTime: "yyyy-MM-dd HH:mm:ssZ",
rfc1123: "ddd, dd MMM yyyy HH:mm:ss GMT",
monthDay: "d MMMM",
yearMonth: "MMMM yyyy"
},
/**
* NOTE: If a string format is not parsing correctly, but
* you would expect it parse, the problem likely lies below.
*
* The following regex patterns control most of the string matching
* within the parser.
*
* The Month name and Day name patterns were automatically generated
* and in general should be (mostly) correct.
*
* Beyond the month and day name patterns are natural language strings.
* Example: "next", "today", "months"
*
* These natural language string may NOT be correct for this culture.
* If they are not correct, please translate and edit this file
* providing the correct regular expression pattern.
*
* If you modify this file, please post your revised CultureInfo file
* to the Datejs Forum located at http://www.datejs.com/forums/.
*
* Please mark the subject of the post with [CultureInfo]. Example:
* Subject: [CultureInfo] Translated "da-DK" Danish(Denmark)
*
* We will add the modified patterns to the master source files.
*
* As well, please review the list of "Future Strings" section below.
*/
regexPatterns: {
jan: /^janv(\.|ier)?/i,
feb: /^févr(\.|ier)?/i,
mar: /^mars/i,
apr: /^avr(\.|il)?/i,
may: /^mai/i,
jun: /^juin/i,
jul: /^juil(\.|let)?/i,
aug: /^août/i,
sep: /^sept(\.|embre)?/i,
oct: /^oct(\.|obre)?/i,
nov: /^nov(\.|embre)?/i,
dec: /^déc(\.|embre)?/i,
sun: /^di(\.|m|m\.|anche)?/i,
mon: /^lu(\.|n|n\.|di)?/i,
tue: /^ma(\.|r|r\.|di)?/i,
wed: /^me(\.|r|r\.|credi)?/i,
thu: /^je(\.|u|u\.|di)?/i,
fri: /^ve(\.|n|n\.|dredi)?/i,
sat: /^sa(\.|m|m\.|edi)?/i,
future: /^next/i,
past: /^last|past|prev(ious)?/i,
add: /^(\+|aft(er)?|from|hence)/i,
subtract: /^(\-|bef(ore)?|ago)/i,
yesterday: /^yes(terday)?/i,
today: /^t(od(ay)?)?/i,
tomorrow: /^tom(orrow)?/i,
now: /^n(ow)?/i,
millisecond: /^ms|milli(second)?s?/i,
second: /^sec(ond)?s?/i,
minute: /^mn|min(ute)?s?/i,
hour: /^h(our)?s?/i,
week: /^w(eek)?s?/i,
month: /^m(onth)?s?/i,
day: /^d(ay)?s?/i,
year: /^y(ear)?s?/i,
shortMeridian: /^(a|p)/i,
longMeridian: /^(a\.?m?\.?|p\.?m?\.?)/i,
timezone: /^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt|utc)/i,
ordinalSuffix: /^\s*(st|nd|rd|th)/i,
timeContext: /^\s*(\:|a(?!u|p)|p)/i
},
timezones: [{name:"UTC", offset:"-000"}, {name:"GMT", offset:"-000"}, {name:"EST", offset:"-0500"}, {name:"EDT", offset:"-0400"}, {name:"CST", offset:"-0600"}, {name:"CDT", offset:"-0500"}, {name:"MST", offset:"-0700"}, {name:"MDT", offset:"-0600"}, {name:"PST", offset:"-0800"}, {name:"PDT", offset:"-0700"}]
};
/********************
** Future Strings **
********************
*
* The following list of strings may not be currently being used, but
* may be incorporated into the Datejs library later.
*
* We would appreciate any help translating the strings below.
*
* If you modify this file, please post your revised CultureInfo file
* to the Datejs Forum located at http://www.datejs.com/forums/.
*
* Please mark the subject of the post with [CultureInfo]. Example:
* Subject: [CultureInfo] Translated "da-DK" Danish(Denmark)b
*
* English Name Translated
* ------------------ -----------------
* about about
* ago ago
* date date
* time time
* calendar calendar
* show show
* hourly hourly
* daily daily
* weekly weekly
* bi-weekly bi-weekly
* fortnight fortnight
* monthly monthly
* bi-monthly bi-monthly
* quarter quarter
* quarterly quarterly
* yearly yearly
* annual annual
* annually annually
* annum annum
* again again
* between between
* after after
* from now from now
* repeat repeat
* times times
* per per
* min (abbrev minute) min
* morning morning
* noon noon
* night night
* midnight midnight
* mid-night mid-night
* evening evening
* final final
* future future
* spring spring
* summer summer
* fall fall
* winter winter
* end of end of
* end end
* long long
* short short
*/ | TDXDigital/TPS | js/Datejs-master/src/globalization/fr-FR.js | JavaScript | mit | 6,781 |
#include "UniformBuffer.hpp"
#include <iostream>
#include <cstring>
UniformBuffer::UniformBuffer(const void* data, unsigned int size, VkDevice device, VkPhysicalDevice physicalDevice, VkDescriptorPool descriptorPool, VkShaderStageFlags flags) : Buffer(device, physicalDevice, descriptorPool) {
this->device = device;
this->physicalDevice = physicalDevice;
this->descriptorPool = descriptorPool;
createBuffer(size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &buffer, &bufferMemory);
// Copy data to mapped memory.
setData(data, size);
// Create descriptor set.
createDescriptorSetLayout(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, flags);
createDescriptorSet(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, buffer, size);
}
UniformBuffer::~UniformBuffer() {
vkDestroyBuffer(device, buffer, nullptr);
vkFreeMemory(device, bufferMemory, nullptr);
}
void UniformBuffer::setData(const void* data, unsigned int size) {
void* mappedMemory;
vkMapMemory(device, bufferMemory, 0, size, 0, &mappedMemory);
memcpy(mappedMemory, data, size);
vkUnmapMemory(device, bufferMemory);
}
| Chainsawkitten/AsyncCompute | src/UniformBuffer.cpp | C++ | mit | 1,194 |
import { Component, ViewChild, ElementRef } from '@angular/core';
import { jqxButtonGroupComponent } from '../../../../../jqwidgets-ts/angular_jqxbuttongroup';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('myButtonGroup') myButtonGroup: jqxButtonGroupComponent;
@ViewChild('myLog') myLog: ElementRef;
myDefaultModeButtonChecked(): void {
this.myButtonGroup.mode('default');
};
myRadioModeButtonChecked(): void {
this.myButtonGroup.mode('radio');
};
myCheckBoxModeButtonChecked(): void {
this.myButtonGroup.mode('checkbox');
};
groupOnBtnClick(event: any): void {
let clickedButton = event.args.button;
this.myLog.nativeElement.innerHTML = `Clicked: ${clickedButton[0].id}`;
}
}
| juannelisalde/holter | assets/jqwidgets/demos/angular/app/buttongroup/defaultfunctionality/app.component.ts | TypeScript | mit | 844 |
using System;
using System.Windows.Input;
namespace CustomBA.Commands
{
/// <summary>
/// Based on http://wpftutorial.net/DelegateCommand.html
/// </summary>
public class DelegateCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
public event EventHandler CanExecuteChanged;
public DelegateCommand(Action<object> execute)
: this(execute, null)
{
}
public DelegateCommand(Action<object> execute,
Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
if (_canExecute == null)
{
return true;
}
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
} | Sufflavus/WixExamples | CustomBurnUiWithOptionsOnPureWpf/Source/CustomBA/Commands/DelegateCommand.cs | C# | mit | 1,268 |
export declare class SampleComponent {
constructor();
}
| UrbanRiskSlumRedevelopment/Maya | node_modules/ng2-bootstrap-grid/dist/src/sample.component.d.ts | TypeScript | mit | 63 |
import {Component} from '@angular/core';
@Component({
selector: 'not-found',
templateUrl: 'app/404.component/404.component.html',
styleUrls: ['app/404.component/404.component.css'],
})
export class NotFoundComponent {} | Nandtel/spring-boot-angular2-starter | src/main/javascript/app/404.component/404.component.ts | TypeScript | mit | 231 |
<?php
require_once('library/HTML5/Parser.php');
require_once('library/HTMLPurifier.auto.php');
function arr_add_hashes(&$item,$k) {
$item = '#' . $item;
}
function parse_url_content(&$a) {
$text = null;
$str_tags = '';
if(x($_GET,'binurl'))
$url = trim(hex2bin($_GET['binurl']));
else
$url = trim($_GET['url']);
if($_GET['title'])
$title = strip_tags(trim($_GET['title']));
if($_GET['description'])
$text = strip_tags(trim($_GET['description']));
if($_GET['tags']) {
$arr_tags = str_getcsv($_GET['tags']);
if(count($arr_tags)) {
array_walk($arr_tags,'arr_add_hashes');
$str_tags = '<br />' . implode(' ',$arr_tags) . '<br />';
}
}
logger('parse_url: ' . $url);
$template = "<br /><a class=\"bookmark\" href=\"%s\" >%s</a>%s<br />";
$arr = array('url' => $url, 'text' => '');
call_hooks('parse_link', $arr);
if(strlen($arr['text'])) {
echo $arr['text'];
killme();
}
if($url && $title && $text) {
$text = '<br /><br /><blockquote>' . $text . '</blockquote><br />';
$title = str_replace(array("\r","\n"),array('',''),$title);
$result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
logger('parse_url (unparsed): returns: ' . $result);
echo $result;
killme();
}
if($url) {
$s = fetch_url($url);
} else {
echo '';
killme();
}
// logger('parse_url: data: ' . $s, LOGGER_DATA);
if(! $s) {
echo sprintf($template,$url,$url,'') . $str_tags;
killme();
}
$matches = '';
$c = preg_match('/\<head(.*?)\>(.*?)\<\/head\>/ism',$s,$matches);
if($c) {
// logger('parse_url: header: ' . $matches[2], LOGGER_DATA);
try {
$domhead = HTML5_Parser::parse($matches[2]);
} catch (DOMException $e) {
logger('scrape_dfrn: parse error: ' . $e);
}
if($domhead)
logger('parsed header');
}
if(! $title) {
if(strpos($s,'<title>')) {
$title = substr($s,strpos($s,'<title>')+7,64);
if(strpos($title,'<') !== false)
$title = strip_tags(substr($title,0,strpos($title,'<')));
}
}
$config = HTMLPurifier_Config::createDefault();
$config->set('Cache.DefinitionImpl', null);
$purifier = new HTMLPurifier($config);
$s = $purifier->purify($s);
// logger('purify_output: ' . $s);
try {
$dom = HTML5_Parser::parse($s);
} catch (DOMException $e) {
logger('scrape_dfrn: parse error: ' . $e);
}
if(! $dom) {
echo sprintf($template,$url,$url,'') . $str_tags;
killme();
}
$items = $dom->getElementsByTagName('title');
if($items) {
foreach($items as $item) {
$title = trim($item->textContent);
break;
}
}
if(! $text) {
$divs = $dom->getElementsByTagName('div');
if($divs) {
foreach($divs as $div) {
$class = $div->getAttribute('class');
if($class && (stristr($class,'article') || stristr($class,'content'))) {
$items = $div->getElementsByTagName('p');
if($items) {
foreach($items as $item) {
$text = $item->textContent;
if(stristr($text,'<script')) {
$text = '';
continue;
}
$text = strip_tags($text);
if(strlen($text) < 100) {
$text = '';
continue;
}
$text = substr($text,0,250) . '...' ;
break;
}
}
}
if($text)
break;
}
}
if(! $text) {
$items = $dom->getElementsByTagName('p');
if($items) {
foreach($items as $item) {
$text = $item->textContent;
if(stristr($text,'<script'))
continue;
$text = strip_tags($text);
if(strlen($text) < 100) {
$text = '';
continue;
}
$text = substr($text,0,250) . '...' ;
break;
}
}
}
}
if(! $text) {
logger('parsing meta');
$items = $domhead->getElementsByTagName('meta');
if($items) {
foreach($items as $item) {
$property = $item->getAttribute('property');
if($property && (stristr($property,':description'))) {
$text = $item->getAttribute('content');
if(stristr($text,'<script')) {
$text = '';
continue;
}
$text = strip_tags($text);
$text = substr($text,0,250) . '...' ;
}
if($property && (stristr($property,':image'))) {
$image = $item->getAttribute('content');
if(stristr($text,'<script')) {
$image = '';
continue;
}
$image = strip_tags($image);
$i = fetch_url($image);
if($i) {
require_once('include/Photo.php');
$ph = new Photo($i);
if($ph->is_valid()) {
if($ph->getWidth() > 300 || $ph->getHeight() > 300) {
$ph->scaleImage(300);
$new_width = $ph->getWidth();
$new_height = $ph->getHeight();
$image = '<br /><br /><img height="' . $new_height . '" width="' . $new_width . '" src="' .$image . '" alt="photo" />';
}
else
$image = '<br /><br /><img src="' . $image . '" alt="photo" />';
}
else
$image = '';
}
}
}
}
}
if(strlen($text)) {
$text = '<br /><br /><blockquote>' . $text . '</blockquote><br />';
}
if($image) {
$text = $image . '<br />' . $text;
}
$title = str_replace(array("\r","\n"),array('',''),$title);
$result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
logger('parse_url: returns: ' . $result);
echo $result;
killme();
}
| kyriakosbrastianos/friendica-deb | mod/parse_url.php | PHP | mit | 5,224 |
using System.Runtime.Serialization;
namespace BungieNetPlatform.Enums {
[DataContract]
public enum ForumPostSort {
[EnumMember]
Default = 0,
[EnumMember]
OldestFirst = 1
}
} | dazarobbo/BungieNetPlatform-CSharp | BungieNetPlatform/BungieNetPlatform/Enums/ForumPostSort.cs | C# | mit | 193 |
using System.Net.Http;
using System.Threading.Tasks;
namespace WebApiContrib.IoC.Mef.Tests.Parts
{
public class PrecannedMessageHandler : DelegatingHandler
{
private readonly HttpResponseMessage _response;
public PrecannedMessageHandler(HttpResponseMessage response)
{
_response = response;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
if (request.Method == HttpMethod.Get)
{
_response.RequestMessage = request;
var tcs = new TaskCompletionSource<HttpResponseMessage>();
tcs.SetResult(_response);
return tcs.Task;
}
return null;
}
}
} | WebApiContrib/WebApiContrib.IoC.Mef | test/WebApiContrib.IoC.Mef.Tests/Helpers/PrecannedMessageHandler.cs | C# | mit | 826 |
#include "gamelib/components/editor/LineBrushComponent.hpp"
#include "gamelib/components/geometry/Polygon.hpp"
#include "gamelib/components/rendering/MeshRenderer.hpp"
#include "gamelib/core/ecs/Entity.hpp"
#include "gamelib/properties/PropComponent.hpp"
namespace gamelib
{
LineBrushComponent::LineBrushComponent() :
_linewidth(32)
{
auto cb = +[](const ComponentReference<PolygonCollider>* val, LineBrushComponent* self) {
self->_line = *val;
self->regenerate();
};
_props.registerProperty("linewidth", _linewidth, PROP_METHOD(_linewidth, setWidth), this);
registerProperty(_props, "line", _line, *this, cb);
}
void LineBrushComponent::setWidth(int width)
{
if (_linewidth == width)
return;
_linewidth = width;
regenerate();
}
int LineBrushComponent::getWidth() const
{
return _linewidth;
}
PolygonCollider* LineBrushComponent::getBrushPolygon() const
{
return _line.get();
}
void LineBrushComponent::regenerate() const
{
if (!_shape || !_pol || !_line || _line->size() == 0)
return;
math::Vec2f lastd, dir;
bool start = true;
auto cb = [&](const math::Line2f& seg) {
float area = 0;
auto norm = seg.d.normalized();
if (start)
{
start = false;
lastd = seg.d;
}
else
{
// Compute if the line turns clockwise or counter clockwise
// Total hours wasted here because I didn't google the
// problem / didn't knew what exactly to google for: 11
auto p1 = seg.p - lastd;
auto p3 = seg.p + seg.d;
// Break if the direction hasn't changed
if (lastd.normalized() == norm)
return false;
area = (seg.p.x - p1.x) * (seg.p.y + p1.y)
+ (p3.x - seg.p.x) * (p3.y + seg.p.y)
+ (p1.x - p3.x) * (p1.y + p3.y);
}
dir = (norm + lastd.normalized()).right().normalized();
dir *= (_linewidth / 2.0) / dir.angle_cos(lastd.right());
_pol->add(seg.p - dir);
_pol->add(seg.p + dir);
// depending on clockwise or counter clockwise line direction,
// different vertices have to be added.
if (area != 0)
{
auto len = norm.right() * _linewidth;
if (area > 0) // clockwise
{
_pol->add(seg.p - dir);
_pol->add(seg.p - dir + len);
}
else // counter clockwise
{
_pol->add(seg.p + dir - len);
_pol->add(seg.p + dir);
}
}
lastd = seg.d;
return false;
};
auto& linepol = _line->getLocal();
_pol->clear();
linepol.foreachSegment(cb);
dir = lastd.right().normalized() * (_linewidth / 2.0);
_pol->add(linepol.get(linepol.size() - 1) - dir);
_pol->add(linepol.get(linepol.size() - 1) + dir);
_shape->fetch(_pol->getLocal(), sf::TriangleStrip);
}
}
| mall0c/TileEngine | src/gamelib/components/editor/LineBrushComponent.cpp | C++ | mit | 3,353 |
///////////////////////
/// UTILS ///
///////////////////////
var u = {};
u.distance = function (p1, p2) {
var dx = p2.x - p1.x;
var dy = p2.y - p1.y;
return Math.sqrt((dx * dx) + (dy * dy));
};
u.angle = function(p1, p2) {
var dx = p2.x - p1.x;
var dy = p2.y - p1.y;
return u.degrees(Math.atan2(dy, dx));
};
u.findCoord = function(p, d, a) {
var b = {x: 0, y: 0};
a = u.radians(a);
b.x = p.x - d * Math.cos(a);
b.y = p.y - d * Math.sin(a);
return b;
};
u.radians = function(a) {
return a * (Math.PI / 180);
};
u.degrees = function(a) {
return a * (180 / Math.PI);
};
u.bindEvt = function (el, type, handler) {
if (el.addEventListener) {
el.addEventListener(type, handler, false);
} else if (el.attachEvent) {
el.attachEvent(type, handler);
}
};
u.unbindEvt = function (el, type, handler) {
if (el.removeEventListener) {
el.removeEventListener(type, handler);
} else if (el.detachEvent) {
el.detachEvent(type, handler);
}
};
u.trigger = function (el, type, data) {
var evt = new CustomEvent(type, data);
el.dispatchEvent(evt);
};
u.prepareEvent = function (evt) {
evt.preventDefault();
return isTouch ? evt.changedTouches : evt;
};
u.getScroll = function () {
var x = (window.pageXOffset !== undefined) ?
window.pageXOffset :
(document.documentElement || document.body.parentNode || document.body)
.scrollLeft;
var y = (window.pageYOffset !== undefined) ?
window.pageYOffset :
(document.documentElement || document.body.parentNode || document.body)
.scrollTop;
return {
x: x,
y: y
};
};
u.applyPosition = function (el, pos) {
if (pos.x && pos.y) {
el.style.left = pos.x + 'px';
el.style.top = pos.y + 'px';
} else if (pos.top || pos.right || pos.bottom || pos.left) {
el.style.top = pos.top;
el.style.right = pos.right;
el.style.bottom = pos.bottom;
el.style.left = pos.left;
}
};
u.getTransitionStyle = function (property, values, time) {
var obj = u.configStylePropertyObject(property);
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
if (typeof values === 'string') {
obj[i] = values + ' ' + time;
} else {
var st = '';
for (var j = 0, max = values.length; j < max; j += 1) {
st += values[j] + ' ' + time + ', ';
}
obj[i] = st.slice(0, -2);
}
}
}
return obj;
};
u.getVendorStyle = function (property, value) {
var obj = u.configStylePropertyObject(property);
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
obj[i] = value;
}
}
return obj;
};
u.configStylePropertyObject = function (prop) {
var obj = {};
obj[prop] = '';
var vendors = ['webkit', 'Moz', 'o'];
vendors.forEach(function (vendor) {
obj[vendor + prop.charAt(0).toUpperCase() + prop.slice(1)] = '';
});
return obj;
};
u.extend = function (objA, objB) {
for (var i in objB) {
if (objB.hasOwnProperty(i)) {
objA[i] = objB[i];
}
}
};
| Antariano/nipplejs | src/utils.js | JavaScript | mit | 3,278 |
package styles
import (
"github.com/alecthomas/chroma"
)
// Doom One 2 style. Inspired by Atom One and Doom Emacs's Atom One theme
var DoomOne2 = Register(chroma.MustNewStyle("doom-one2", chroma.StyleEntries{
chroma.Text: "#b0c4de",
chroma.Error: "#b0c4de",
chroma.Comment: "italic #8a93a5",
chroma.CommentHashbang: "bold",
chroma.Keyword: "#76a9f9",
chroma.KeywordConstant: "#e5c07b",
chroma.KeywordType: "#e5c07b",
chroma.Operator: "#54b1c7",
chroma.OperatorWord: "bold #b756ff",
chroma.Punctuation: "#abb2bf",
chroma.Name: "#aa89ea",
chroma.NameAttribute: "#cebc3a",
chroma.NameBuiltin: "#e5c07b",
chroma.NameClass: "#ca72ff",
chroma.NameConstant: "bold",
chroma.NameDecorator: "#e5c07b",
chroma.NameEntity: "#bda26f",
chroma.NameException: "bold #fd7474",
chroma.NameFunction: "#00b1f7",
chroma.NameProperty: "#cebc3a",
chroma.NameLabel: "#f5a40d",
chroma.NameNamespace: "#ca72ff",
chroma.NameTag: "#76a9f9",
chroma.NameVariable: "#DCAEEA",
chroma.NameVariableClass: "#DCAEEA",
chroma.NameVariableGlobal: "bold #DCAEEA",
chroma.NameVariableInstance: "#e06c75",
chroma.NameVariableMagic: "#DCAEEA",
chroma.Literal: "#98c379",
chroma.LiteralDate: "#98c379",
chroma.Number: "#d19a66",
chroma.NumberBin: "#d19a66",
chroma.NumberFloat: "#d19a66",
chroma.NumberHex: "#d19a66",
chroma.NumberInteger: "#d19a66",
chroma.NumberIntegerLong: "#d19a66",
chroma.NumberOct: "#d19a66",
chroma.String: "#98c379",
chroma.StringAffix: "#98c379",
chroma.StringBacktick: "#98c379",
chroma.StringDelimiter: "#98c379",
chroma.StringDoc: "#7e97c3",
chroma.StringDouble: "#63c381",
chroma.StringEscape: "bold #d26464",
chroma.StringHeredoc: "#98c379",
chroma.StringInterpol: "#98c379",
chroma.StringOther: "#70b33f",
chroma.StringRegex: "#56b6c2",
chroma.StringSingle: "#98c379",
chroma.StringSymbol: "#56b6c2",
chroma.Generic: "#b0c4de",
chroma.GenericDeleted: "#b0c4de",
chroma.GenericEmph: "italic",
chroma.GenericHeading: "bold #a2cbff",
chroma.GenericInserted: "#a6e22e",
chroma.GenericOutput: "#a6e22e",
chroma.GenericUnderline: "underline",
chroma.GenericPrompt: "#a6e22e",
chroma.GenericStrong: "bold",
chroma.GenericSubheading: "#a2cbff",
chroma.GenericTraceback: "#a2cbff",
chroma.Background: "#b0c4de bg:#282c34",
}))
| xyproto/algernon | vendor/github.com/alecthomas/chroma/styles/doom-one2.go | GO | mit | 2,793 |
#include <assert.h>
#include <stdint.h>
#include <OpenP2P/Buffer.hpp>
#include <OpenP2P/Stream/BinaryStream.hpp>
#include <OpenP2P/Event/Source.hpp>
#include <OpenP2P/Event/Wait.hpp>
#include <OpenP2P/RootNetwork/Endpoint.hpp>
#include <OpenP2P/RootNetwork/Packet.hpp>
#include <OpenP2P/RootNetwork/PacketSocket.hpp>
#include <OpenP2P/RootNetwork/SignedPacket.hpp>
namespace OpenP2P {
namespace RootNetwork {
PacketSocket::PacketSocket(Socket<UDP::Endpoint, Buffer>& udpSocket)
: udpSocket_(udpSocket) { }
bool PacketSocket::isValid() const {
return udpSocket_.isValid();
}
Event::Source PacketSocket::eventSource() const {
return udpSocket_.eventSource();
}
bool PacketSocket::receive(Endpoint& endpoint, SignedPacket& signedPacket) {
UDP::Endpoint udpEndpoint;
Buffer buffer;
if (!udpSocket_.receive(udpEndpoint, buffer)) {
return false;
}
endpoint.kind = Endpoint::UDPIPV6;
endpoint.udpEndpoint = udpEndpoint;
BufferIterator bufferIterator(buffer);
BinaryIStream blockingReader(bufferIterator);
signedPacket.packet = ReadPacket(blockingReader);
signedPacket.signature = ReadSignature(blockingReader);
return true;
}
bool PacketSocket::send(const Endpoint& endpoint, const SignedPacket& signedPacket) {
assert(endpoint.kind == Endpoint::UDPIPV6);
Buffer buffer;
BufferBuilder bufferBuilder(buffer);
BinaryOStream blockingWriter(bufferBuilder);
WritePacket(blockingWriter, signedPacket.packet);
WriteSignature(blockingWriter, signedPacket.signature);
return udpSocket_.send(endpoint.udpEndpoint, buffer);
}
}
}
| goodspeed24e/2014iOT | test/openp2p/src/OpenP2P/RootNetwork/PacketSocket.cpp | C++ | mit | 1,642 |
/* -*- C++ -*- */
#include <QtGlobal>
#include <QtAlgorithms>
#include <QChar>
#include <QDebug>
#include <QList>
#include <QMap>
#include <QPointer>
#include <QRegExp>
#include <QSettings>
#include <QSharedData>
#include <QSharedDataPointer>
#include "qluaapplication.h"
#include "qtluaengine.h"
#include "qluamainwindow.h"
#include "qluatextedit.h"
#include "qluamode.h"
#include <string.h>
#include <ctype.h>
#define DEBUG 0
// ========================================
// USERDATA
namespace {
enum TokenType {
// generic tokens
Other, Identifier, Number, String,
// tokens
SemiColon, ThreeDots, Comma, Dot, Colon,
LParen, RParen, LBracket, RBracket, LBrace, RBrace,
// keywords
Kand, Kfalse, Kfunction, Knil,
Knot, Kor, Ktrue, Kin,
// keywords that kill statements
Kbreak, Kdo, Kelse, Kelseif, Kend, Kfor,
Kif, Klocal, Krepeat, Kreturn,
Kthen, Kuntil, Kwhile,
// special
Eof,
Chunk,
Statement,
StatementCont,
FunctionBody,
FunctionName,
FirstKeyword = Kand,
FirstStrictKeyword = Kbreak,
};
struct Keywords {
const char *text;
TokenType type;
};
Keywords skeywords[] = {
{"and", Kand}, {"break", Kbreak}, {"do", Kdo}, {"else", Kelse},
{"elseif", Kelseif}, {"end", Kend}, {"false", Kfalse}, {"for", Kfor},
{"function", Kfunction}, {"if", Kif}, {"in", Kin}, {"local", Klocal},
{"nil", Knil}, {"not", Knot}, {"or", Kor}, {"repeat", Krepeat},
{"return", Kreturn}, {"then", Kthen}, {"true", Ktrue},
{"until", Kuntil}, {"while", Kwhile},
{";", SemiColon}, {"...", ThreeDots}, {",", Comma},
{".", Dot}, {":", Colon},
{"(", LParen}, {")", RParen}, {"[", LBracket},
{"]", RBracket}, {"{", LBrace}, {"}", RBrace},
{0}
};
struct Node;
struct PNode : public QSharedDataPointer<Node> {
PNode();
PNode(TokenType t, int p, int l, PNode n);
PNode(TokenType t, int p, int l, int i, PNode n);
TokenType type() const;
int pos() const;
int len() const;
int indent() const;
PNode next() const;
};
struct Node : public QSharedData {
Node(TokenType t, int p, int l, PNode n)
: next(n), type(t),pos(p),len(l),indent(-1) {}
Node(TokenType t, int p, int l, int i, PNode n)
: next(n), type(t),pos(p),len(l),indent(i) {}
PNode next;
TokenType type;
int pos;
int len;
int indent;
};
PNode::PNode()
: QSharedDataPointer<Node>() {}
PNode::PNode(TokenType t, int p, int l, PNode n)
: QSharedDataPointer<Node>(new Node(t,p,l,n)) {}
PNode::PNode(TokenType t, int p, int l, int i, PNode n)
: QSharedDataPointer<Node>(new Node(t,p,l,i,n)) {}
inline TokenType PNode::type() const {
const Node *n = constData();
return (n) ? n->type : Chunk;
}
inline int PNode::pos() const {
const Node *n = constData();
return (n) ? n->pos : 0;
}
inline int PNode::len() const {
const Node *n = constData();
return (n) ? n->len : 0;
}
inline int PNode::indent() const {
const Node *n = constData();
return (n) ? n->indent : 0;
}
inline PNode PNode::next() const {
const Node *n = constData();
return (n) ? n->next : PNode();
}
struct UserData : public QLuaModeUserData
{
// lexical state
int lexState;
int lexPos;
int lexN;
// parser state
PNode nodes;
int lastPos;
// initialize
UserData() : lexState(0), lexPos(0), lexN(0), lastPos(0) {}
virtual int highlightState() { return (lexState<<16)^lexN; }
};
}
// ========================================
// QLUAMODELUA
class QLuaModeLua : public QLuaMode
{
Q_OBJECT
public:
QLuaModeLua(QLuaTextEditModeFactory *f, QLuaTextEdit *e);
void gotLine(UserData *d, int pos, int len, QString);
void gotToken(UserData *d, int pos, int len, QString, TokenType);
bool supportsComplete() { return true; }
bool supportsLua() { return true; }
virtual void parseBlock(int pos, const QTextBlock &block,
const QLuaModeUserData *idata,
QLuaModeUserData *&odata );
QStringList computeFileCompletions(QString s, bool escape, QString &stem);
QStringList computeSymbolCompletions(QString s, QString &stem);
virtual bool doComplete();
private:
QMap<QString,TokenType> keywords;
QRegExp reNum, reSym, reId;
int bi;
};
QLuaModeLua::QLuaModeLua(QLuaTextEditModeFactory *f, QLuaTextEdit *e)
: QLuaMode(f,e),
reNum("^(0x[0-9a-fA-F]+|\\.[0-9]+|[0-9]+(\\.[0-9]*)?([Ee][-+]?[0-9]*)?)"),
reSym("^(\\.\\.\\.|<=|>=|==|~=|.)"),
reId("^[A-Za-z_][A-Za-z0-9_]*"),
bi(3)
{
// basic indent
QSettings s;
s.beginGroup("luaMode");
bi = s.value("basicIndent", 3).toInt();
// tokens
for (int i=0; skeywords[i].text; i++)
keywords[QString(skeywords[i].text)] = skeywords[i].type;
}
void
QLuaModeLua::parseBlock(int pos, const QTextBlock &block,
const QLuaModeUserData *idata,
QLuaModeUserData *&odata )
{
QString text = block.text();
UserData *data = new UserData;
// input state
if (idata)
*data = *static_cast<const UserData*>(idata);
// hack for statements that seem complete
if (data->nodes.type() == Statement)
setIndent(data->lastPos, data->nodes.next().indent());
// process line
gotLine(data, pos, block.length(), block.text());
// flush parser stack on last block
if (! block.next().isValid())
gotToken(data, data->lastPos+1, 0, QString(), Eof);
// output state
odata = data;
}
// ========================================
// QLUAMODELUA - LEXICAL ANALYSIS
void
QLuaModeLua::gotLine(UserData *d, int pos, int len, QString s)
{
// default indent
if (pos == 0)
setIndent(-1, 0);
// lexical analysis
int p = 0;
int n = d->lexN;
int r = d->lexPos - pos;
int state = d->lexState;
int slen = s.size();
while (p < len)
{
int c = (p < slen) ? s[p].toAscii() : '\n';
switch(state)
{
case 0:
state = -1;
if (c == '#') {
r = p; n = 0; state = -4;
}
continue;
default:
case -1:
if (isspace(c)) {
break;
} if (isalpha(c) || c=='_') {
r = p; state = -2;
} else if (c=='\'') {
setIndentOverlay(pos+p+1, -1);
r = p; n = -c; state = -3;
} else if (c=='\"') {
setIndentOverlay(pos+p+1, -1);
r = p; n = -c; state = -3;
} else if (c=='[') {
r = p; n = 0; state = -3;
int t = p + 1;
while (t < slen && s[t] == '=')
t += 1;
if (t < slen && s[t] == '[') {
n = t - p;
setIndentOverlay(pos+p, -1);
} else {
state = -1;
gotToken(d, pos+p, 1, QString(), LBracket);
}
} else if (c=='-' && p+1 < slen && s[p+1]=='-') {
r = p; n = 0; state = -4;
if (p+2 < slen && s[p+2]=='[') {
int t = p + 3;
while (t < slen && s[t] == '=')
t += 1;
if (t < slen && s[t] == '[') {
n = t - p - 2;
setIndentOverlay(pos+p, 0);
setIndentOverlay(pos+t+1, (n > 1) ? -1 :
e->indentAfter(pos+t+1, +1) );
}
}
} else if (reNum.indexIn(s,p,QRegExp::CaretAtOffset)>=0) {
int l = reNum.matchedLength();
QString m = s.mid(p,l);
setFormat(pos+p, l, "number");
gotToken(d, pos+p, l, m, Number);
p += l - 1;
} else if (reSym.indexIn(s,p,QRegExp::CaretAtOffset)>=0) {
int l = reSym.matchedLength();
QString m = s.mid(p,l);
if (keywords.contains(m))
gotToken(d, pos+p, l, QString(), keywords[m]);
else
gotToken(d, pos+p, l, m, Other);
p += l - 1;
}
break;
case -2: // identifier
if (!isalnum(c) && c!='_') {
QString m = s.mid(r, p-r);
if (keywords.contains(m)) {
setFormat(pos+r, p-r, "keyword");
gotToken(d, pos+r, p-r, QString(), keywords[m]);
} else
gotToken(d, pos+r, p-r, m, Identifier);
state = -1; continue;
}
break;
case -3: // string
if (n <= 0 && (c == -n || c == '\n' || c == '\r')) {
setFormat(pos+r,p-r+1,"string");
setIndentOverlay(pos+p+1);
gotToken(d, pos+r,p-r+1, QString(), String);
state = -1;
} else if (n <= 0 && c=='\\') {
p += 1;
} else if (n > 0 && c==']' && p>=n && s[p-n]==']') {
int t = p - n + 1;
while (t < slen && s[t] == '=')
t += 1;
if (t == p) {
setFormat(pos+r,p-r+1,"string");
setIndentOverlay(pos+p+1);
gotToken(d, pos+r,p-r+1,QString(),String);
state = -1;
}
}
break;
case -4: // comment
if (n <= 0 && (c == '\n' || c == '\r')) {
setFormat(pos+r, p-r, "comment");
state = -1;
} else if (n > 0 && c==']' && p>=n && s[p-n]==']') {
int t = p - n + 1;
while (t < slen && s[t] == '=')
t += 1;
if (t == p) {
setFormat(pos+r, p-r+1, "comment");
setIndentOverlay(pos+p-n, 2);
setIndentOverlay(pos+p+1);
state = -1;
}
}
break;
}
p += 1;
}
// save state
d->lexN = n;
d->lexPos = r + pos;
d->lexState = state;
// format incomplete tokens
if (state == -4)
setFormat(qMax(pos,pos+r),qMin(len,len-r),"comment");
else if (state == -3)
setFormat(qMax(pos,pos+r),qMin(len,len-r),"string");
}
// ========================================
// QLUAMODELUA - PARSING
#if DEBUG
QDebug operator<<(QDebug d, const TokenType &t)
{
d.nospace();
# define DO(x) if (t==x) d << #x; else
DO(Other) DO(Identifier) DO(Number) DO(String)
DO(SemiColon) DO(ThreeDots) DO(Comma) DO(Dot) DO(Colon)
DO(LParen) DO(RParen) DO(LBracket)
DO(RBracket) DO(LBrace) DO(RBrace)
DO(Kand) DO(Kfalse) DO(Kfunction) DO(Knil)
DO(Knot) DO(Kor) DO(Ktrue) DO(Kin)
DO(Kbreak) DO(Kdo) DO(Kelse) DO(Kelseif) DO(Kend) DO(Kfor)
DO(Kif) DO(Klocal) DO(Krepeat) DO(Kreturn)
DO(Kthen) DO(Kuntil) DO(Kwhile)
DO(Statement) DO(StatementCont) DO(Chunk)
DO(FunctionBody) DO(FunctionName) DO(Eof)
# undef DO
d << "<Unknown>";
return d.space();
}
#endif
void
QLuaModeLua::gotToken(UserData *d, int pos, int len,
QString s, TokenType ltype)
{
PNode &n = d->nodes;
TokenType ntype = n.type();
#if DEBUG
qDebug() << " node:" << n << ntype << n.pos() << n.len()
<< n.indent() << n.next().type() << n.next().next().type();
if (s.isEmpty())
qDebug() << " token:" << pos << len << ltype;
else
qDebug() << " token:" << pos << len << ltype << s;
#endif
// close statements
if ( ((ntype==Statement)
&& (ltype==Identifier || ltype==Kfunction) ) ||
((ntype==Statement || ntype==StatementCont ||
ntype==Klocal || ntype==Kreturn )
&& (ltype==SemiColon || ltype>=FirstStrictKeyword) ) )
{
int epos = (ltype==SemiColon) ? pos+len : d->lastPos;
int spos = n.pos();
n = n.next();
setBalance(spos, epos, n.type()==Chunk);
setIndent(epos, n.indent());
}
if ((ntype == FunctionName || ntype == Kfunction) &&
(ltype!=Identifier && ltype!=Dot && ltype!=Colon) )
{
if (ntype == FunctionName) n=n.next();
ntype = n->type = FunctionBody;
setIndent(pos, n.indent());
}
ntype = n.type();
// fixup hacked indents
if (ntype == StatementCont)
n->type = Statement;
if (d->lastPos < pos && ntype == Statement)
setIndent(pos, n.indent());
d->lastPos = pos + len;
// parse
switch (ltype)
{
badOne:
{
setIndent(pos, -1);
while (n.type() != Chunk && n.len() == 0) n = n.next();
setErrorMatch(pos, len, n.pos(), n.len());
n = n.next();
setIndent(pos+len, n.indent());
break;
}
case RParen:
if (ntype != LParen)
goto badOne;
goto rightOne;
case RBracket:
if (ntype != LBracket)
goto badOne;
goto rightOne;
case RBrace:
if (ntype != LBrace)
goto badOne;
goto rightOne;
case Kend:
if (ntype!=Kdo && ntype!=Kelse && ntype!=Kthen
&& ntype!=Kfunction && ntype!=FunctionBody)
goto badOne;
rightOne:
{
setRightMatch(pos, len, n.pos(), n.len());
int fpos = followMatch(n.pos(),n.len());
int indent = n.indent();
n = n.next();
if (ltype < FirstKeyword)
indent = qMin(qMax(0,indent-bi),e->indentAt(fpos));
else
indent = n.indent();
setIndent(pos, indent);
setIndent(pos+len, n.indent());
setBalance(fpos, pos+len, n.type()==Chunk);
break;
}
case Kuntil:
if (ntype != Krepeat)
goto badOne;
{
setRightMatch(pos, len, n.pos(), n.len());
setIndent(pos, n.next().indent());
setIndent(pos+len, n.indent());
n->len = 0;
n->type = StatementCont;
break;
}
case Kthen:
if (ntype!=Kif && ntype!=Kelseif)
goto badOne;
goto middleOne;
case Kelse: case Kelseif:
if (ntype!=Kthen)
goto badOne;
middleOne:
{
setMiddleMatch(pos, len, n.pos(), n.len());
setIndent(pos, n.next().indent());
setIndent(pos+len, n.indent());
n->type = ltype;
n->pos = pos;
n->len = len;
break;
}
case Kdo:
if (ntype==Kfor || ntype==Kwhile)
goto middleOne;
goto leftOne;
case Kfunction:
if (ntype == Klocal)
goto middleOne;
goto leftOne;
case Kfor: case Kif: case Kwhile:
case Krepeat: case Klocal: case Kreturn:
case LParen: case LBracket: case LBrace:
leftOne:
{
int indent = n.indent() + bi;
if (ltype == LBrace && ntype == StatementCont)
indent = n.indent();
else if (ltype < FirstKeyword)
indent = e->indentAfter(pos+len);
setIndent(pos, n.indent());
n = PNode(ltype, pos, len, indent, n);
setIndent(pos+len, indent);
setLeftMatch(pos, len);
break;
}
case SemiColon:
case Eof:
break;
case Identifier:
if (ntype == Kfunction)
n = PNode(FunctionName, pos, len, n.indent(), n);
if (n.type() == FunctionName)
setFormat(pos, len, "function");
goto openStatement;
case Dot: case Colon:
if (ntype == FunctionName)
setFormat(pos, len, "function");
case Kand: case Kor: case Knot:
case Kin: case Comma: case Other:
if (n.type() == Statement)
{
n->type = StatementCont;
setIndent(pos, n.indent());
}
default:
openStatement:
{
if (ntype==Chunk || ntype==Kdo || ntype==Kthen ||
ntype==Kelse || ntype==Krepeat || ntype==FunctionBody)
{
int indent = n.indent() + bi;
n = PNode(Statement, pos, 0, indent, n);
setIndent(pos+len, indent);
}
else if (ntype==Klocal)
n->type = StatementCont;
else if (ntype==Kreturn)
n->type = Statement;
break;
}
}
}
// ========================================
// COMPLETION
static int
comp_lex(QString s, int len, int state, int n, int &q)
{
QChar z;
int p = 0;
while (p < len)
{
switch(state)
{
default:
case -1: // misc
if (isalpha(s[p].toAscii()) || s[p]=='_') {
q = p; state = -2;
} else if (s[p]=='\'') {
q = p+1; z = s[p]; n = 0; state = -3;
} else if (s[p]=='\"') {
q = p+1; z = s[p]; n = 0; state = -3;
} else if (s[p]=='[') {
n = 0; state = -3;
int t = p + 1;
while (t < len && s[t] == '=')
t += 1;
if (t < len && s[t] == '[') {
q = t + 1;
n = t - p;
} else
state = -1;
} else if (s[p]=='-' && s[p+1]=='-') {
n = 0; state = -4;
if (s[p+2]=='[') {
int t = p + 3;
while (t < len && s[t] == '=')
t += 1;
if (t < len && s[t] == '[')
n = t - p - 2;
}
}
break;
case -2: // identifier
if (!isalnum(s[p].toAscii()) && s[p]!='_' && s[p]!='.' && s[p]!=':') {
state = -1; continue;
}
break;
case -3: // string
if (n == 0 && s[p] == z) {
state = -1;
} else if (n == 0 && s[p]=='\\') {
p += 1;
} else if (n && s[p]==']' && p>=n && s[p-n]==']') {
int t = p - n + 1;
while (t < len && s[t] == '=')
t += 1;
if (t == p)
state = -1;
}
break;
case -4: // comment
if (n == 0 && (s[p] == '\n' || s[p] == '\r')) {
state = -1;
} else if (n && s[p]==']' && p>=n && s[p-n]==']') {
int t = p - n + 1;
while (t < len && s[t] == '=')
t += 1;
if (t == p)
state = -1;
}
break;
}
p += 1;
}
return state;
}
bool
QLuaModeLua::doComplete()
{
QString stem;
QStringList completions;
QTextCursor c = e->textCursor();
QTextBlock b = c.block();
int len = c.position() - b.position();
QString text = b.text().left(len);
int state = -1;
int q = 0;
int n = 0;
QTextBlock pb = b.previous();
if (pb.isValid())
{
UserData *data = static_cast<UserData*>(pb.userData());
if (! data)
return false;
state = data->lexState;
n = data->lexN;
}
state = comp_lex(text, len, state, n, q);
if (state == -3 && q >= 0 && q <= len)
completions = computeFileCompletions(text.mid(q, len-q), n>0, stem);
if (state == -2 && q >= 0 && q <= len)
completions = computeSymbolCompletions(text.mid(q, len-q), stem);
int selected = 0;
if (completions.size() > 1)
{
qSort(completions.begin(), completions.end());
for (int i=completions.size()-2; i>=0; i--)
if (completions[i] == completions[i+1])
completions.removeAt(i);
selected = askCompletion(stem, completions);
}
if (selected >= 0 && selected < completions.size())
{
c.insertText(completions[selected]);
e->setTextCursor(c);
return true;
}
return false;
}
static const char *escape1 = "abfnrtv";
static const char *escape2 = "\a\b\f\n\r\t\v";
static QByteArray
unescapeString(const char *s)
{
int c;
QByteArray r;
while ((c = *s++))
{
if (c != '\\')
r += c;
else {
c = *s++;
const char *e = strchr(escape1, c);
if (e)
r += escape2[e - escape1];
else if (c >= '0' && c <= '7') {
c = c - '0';
if (*s >= '0' && *s <= '7')
c = c * 8 + *s++ - '0';
if (*s >= '0' && *s <= '7')
c = c * 8 + *s++ - '0';
r += c;
} else
r += c;
}
}
return r;
}
static QString
unescapeString(QString s)
{
return QString::fromLocal8Bit(unescapeString(s.toLocal8Bit().constData()));
}
static QByteArray
escapeString(const char *s)
{
int c;
QByteArray r;
while ((c = *s++))
{
const char *e;
if (! isascii(c))
r += c;
else if (iscntrl(c) && (e = strchr(escape2, c)))
r += escape1[e - escape2];
else if (isprint(c) || isspace(c))
r += c;
else {
char buffer[8];
sprintf(buffer, "\\%03o", c);
r += buffer;
}
}
return r;
}
static QString
escapeString(QString s)
{
return QString::fromLocal8Bit(escapeString(s.toLocal8Bit().constData()));
}
QStringList
QLuaModeLua::computeFileCompletions(QString s, bool escape, QString &stem)
{
QStringList list;
s.remove(QRegExp("^.*\\s"));
stem = s;
if (escape)
stem = unescapeString(s);
fileCompletion(stem, list);
if (escape)
{
QStringList nl;
foreach(QString s, list)
nl += escapeString(s);
stem = escapeString(stem);
list = nl;
}
return list;
}
static const char *
comp_keywords[] =
{
"and", "break", "do", "else", "elseif",
"end", "false", "for", "function",
"if", "in", "local", "nil", "not",
"or", "repeat", "return", "then",
"true", "until", "while", 0
};
QStringList
QLuaModeLua::computeSymbolCompletions(QString s, QString &stem)
{
QStringList list;
QByteArray f = s.toLocal8Bit();
int flen = f.size();
// stem
stem = s.remove(QRegExp("^.*[.:]"));
// keywords
for (const char **k = comp_keywords; *k; k++)
if (!strncmp(f.constData(), *k, flen))
list += QString::fromLocal8Bit(*k + flen);
// symbols
QtLuaEngine *engine = QLuaApplication::engine();
if (engine)
{
QtLuaLocker lua(engine, 250);
struct lua_State *L = lua;
if (lua)
{
lua_pushcfunction(L, luaQ_complete);
lua_pushlstring(L, f.constData(), flen);
if (!lua_pcall(L, 1, 1, 0) && lua_istable(L, -1)) {
int n = lua_objlen(L, -1);
for (int j=1; j<=n; j++) {
lua_rawgeti(L, -1, j);
list += QString::fromLocal8Bit(lua_tostring(L, -1));
lua_pop(L, 1);
}
}
lua_pop(L, 1);
}
else
{
QWidget *w = e->window();
QLuaMainWindow *m = qobject_cast<QLuaMainWindow*>(w);
if (m)
m->showStatusMessage(tr("Auto-completions is restricted "
"while Lua is running.") );
QLuaApplication::beep();
}
}
return list;
}
// ========================================
// FACTORY
static QLuaModeFactory<QLuaModeLua> textModeFactory("Lua", "lua");
// ========================================
// MOC
#include "qluamode_lua.moc"
/* -------------------------------------------------------------
Local Variables:
c++-font-lock-extra-types: ("\\sw+_t" "\\(lua_\\)?[A-Z]\\sw*[a-z]\\sw*")
End:
------------------------------------------------------------- */
| EliHar/Pattern_recognition | torch1/exe/qtlua/packages/qtide/qluamode_lua.cpp | C++ | mit | 22,831 |
// Copyright (c) 2020 The Gulden developers
// Authored by: Malcolm MacLeod (mmacleod@gmx.com)
// Distributed under the GULDEN software license, see the accompanying
// file COPYING
//Workaround braindamaged 'hack' in libtool.m4 that defines DLL_EXPORT when building a dll via libtool (this in turn imports unwanted symbols from e.g. pthread that breaks static pthread linkage)
#ifdef DLL_EXPORT
#undef DLL_EXPORT
#endif
// Unity specific includes
#include "unity_impl.h"
#include "libinit.h"
// Standard gulden headers
#include "appname.h"
#include "clientversion.h"
#include "util.h"
#include "witnessutil.h"
#include "ui_interface.h"
#include "unity/appmanager.h"
#include "utilmoneystr.h"
#include <chain.h>
#include "consensus/validation.h"
#include "net.h"
#include "wallet/mnemonic.h"
#include "net_processing.h"
#include "wallet/spvscanner.h"
#include "sync.h"
#include "init.h"
// Djinni generated files
#include "i_library_controller.hpp"
#include "i_library_listener.hpp"
#include "qr_code_record.hpp"
#include "balance_record.hpp"
#include "uri_record.hpp"
#include "uri_recipient.hpp"
#include "mutation_record.hpp"
#include "input_record.hpp"
#include "output_record.hpp"
#include "address_record.hpp"
#include "peer_record.hpp"
#include "block_info_record.hpp"
#include "monitor_record.hpp"
#include "monitor_listener.hpp"
#include "payment_result_status.hpp"
#include "mnemonic_record.hpp"
#ifdef __ANDROID__
#include "djinni_support.hpp"
#endif
// External libraries
#include <boost/algorithm/string.hpp>
#include <boost/program_options/parsers.hpp>
#include <qrencode.h>
#include <memory>
#include "pow/pow.h"
#include <crypto/hash/sigma/sigma.h>
#include <algorithm>
std::shared_ptr<ILibraryListener> signalHandler;
CCriticalSection cs_monitoringListeners;
std::set<std::shared_ptr<MonitorListener> > monitoringListeners;
boost::asio::io_context ioctx;
boost::asio::executor_work_guard<boost::asio::io_context::executor_type> work = boost::asio::make_work_guard(ioctx);
boost::thread run_thread(boost::bind(&boost::asio::io_context::run, boost::ref(ioctx)));
static const int64_t nClientStartupTime = GetTime();
std::vector<CAccount*> GetAccountsForAccount(CAccount* forAccount)
{
std::vector<CAccount*> forAccounts;
forAccounts.push_back(forAccount);
for (const auto& [accountUUID, account] : pactiveWallet->mapAccounts)
{
(unused) accountUUID;
if (account->getParentUUID() == forAccount->getUUID())
{
forAccounts.push_back(account);
}
}
return forAccounts;
}
TransactionStatus getStatusForTransaction(const CWalletTx* wtx)
{
TransactionStatus status;
int depth = wtx->GetDepthInMainChain();
if (depth < 0)
status = TransactionStatus::CONFLICTED;
else if (depth == 0) {
if (wtx->isAbandoned())
status = TransactionStatus::ABANDONED;
else
status = TransactionStatus::UNCONFIRMED;
}
else if (depth < RECOMMENDED_CONFIRMATIONS) {
status = TransactionStatus::CONFIRMING;
}
else {
status = TransactionStatus::CONFIRMED;
}
return status;
}
std::string getRecipientAddressesForWalletTransaction(CAccount* forAccount, CWallet* pWallet, const CWalletTx* wtx, bool isSentByUs)
{
std::string address = "";
for (const CTxOut& txout: wtx->tx->vout)
{
bool isMine = false;
if (forAccount && IsMine(*forAccount, txout))
{
isMine = true;
}
if (!forAccount && pWallet && IsMine(*pWallet, txout))
{
isMine = true;
}
if ((isSentByUs && !isMine) || (!isSentByUs && isMine))
{
CNativeAddress addr;
CTxDestination dest;
if (!ExtractDestination(txout, dest) && !txout.IsUnspendable())
{
dest = CNoDestination();
}
if (addr.Set(dest))
{
if (!address.empty())
address += ", ";
address += addr.ToString();
}
}
}
return address;
}
void addMutationsForTransaction(const CWalletTx* wtx, std::vector<MutationRecord>& mutations, CAccount* forAccount)
{
// exclude generated that are orphaned
if (wtx->IsCoinBase() && wtx->GetDepthInMainChain() < 1)
return;
int64_t subtracted = wtx->GetDebit(ISMINE_SPENDABLE, forAccount, true);
int64_t added = wtx->GetCredit(ISMINE_SPENDABLE, forAccount, true) +
wtx->GetImmatureCredit(false, forAccount, true);
uint64_t time = wtx->nTimeSmart;
std::string hash = wtx->GetHash().ToString();
TransactionStatus status = getStatusForTransaction(wtx);
int depth = wtx->GetDepthInMainChain();
// if any funds were subtracted the transaction was sent by us
if (subtracted > 0)
{
int64_t fee = subtracted - wtx->tx->GetValueOut();
int64_t change = wtx->GetChange();
std::string recipientAddresses = getRecipientAddressesForWalletTransaction(forAccount, pactiveWallet, wtx, true);
// detect internal transfer and split it
if (subtracted - fee == added)
{
// amount received
mutations.push_back(MutationRecord(added - change, time, hash, recipientAddresses, status, depth));
// amount send including fee
mutations.push_back(MutationRecord(change - subtracted, time, hash, recipientAddresses, status, depth));
}
else
{
mutations.push_back(MutationRecord(added - subtracted, time, hash, recipientAddresses, status, depth));
}
}
else if (added != 0) // nothing subtracted so we received funds
{
std::string recipientAddresses = getRecipientAddressesForWalletTransaction(forAccount, pactiveWallet, wtx, false);
mutations.push_back(MutationRecord(added, time, hash, recipientAddresses, status, depth));
}
}
TransactionRecord calculateTransactionRecordForWalletTransaction(const CWalletTx& wtx, std::vector<CAccount*>& forAccounts, bool& anyInputsOrOutputsAreMine)
{
CWallet* pwallet = pactiveWallet;
std::vector<InputRecord> inputs;
std::vector<OutputRecord> outputs;
int64_t subtracted=0;
int64_t added=0;
for (const auto& account : forAccounts)
{
subtracted += wtx.GetDebit(ISMINE_SPENDABLE, account, true);
added += wtx.GetCredit(ISMINE_SPENDABLE, account, true);
}
CAmount fee = 0;
// if any funds were subtracted the transaction was sent by us
if (subtracted > 0)
fee = subtracted - wtx.tx->GetValueOut();
const CTransaction& tx = *wtx.tx;
for (const CTxIn& txin: tx.vin)
{
std::string address;
CNativeAddress addr;
CTxDestination dest = CNoDestination();
// Try to extract destination, this is not possible in general. Only if the previous
// ouput of our input happens to be in our wallet. Which will usually only be the case for
// our own transactions.
uint256 txHash;
if (txin.GetPrevOut().isHash)
{
txHash = txin.GetPrevOut().getTransactionHash();
}
else
{
if (!pwallet->GetTxHash(txin.GetPrevOut(), txHash))
{
LogPrintf("Transaction with no corresponding hash found, txid [%d] [%d]\n", txin.GetPrevOut().getTransactionBlockNumber(), txin.GetPrevOut().getTransactionIndex());
continue;
}
}
std::map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(txHash);
if (mi != pwallet->mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.GetPrevOut().n < prev.tx->vout.size())
{
const auto& prevOut = prev.tx->vout[txin.GetPrevOut().n];
if (!ExtractDestination(prevOut, dest) && !prevOut.IsUnspendable())
{
LogPrintf("Unknown transaction type found, txid %s\n", wtx.GetHash().ToString());
dest = CNoDestination();
}
}
}
if (addr.Set(dest))
{
address = addr.ToString();
}
std::string label;
std::string description;
if (pwallet->mapAddressBook.count(address))
{
const auto& data = pwallet->mapAddressBook[address];
label = data.name;
description = data.description;
}
bool isMine = false;
for (const auto& account : forAccounts)
{
if (static_cast<const CExtWallet*>(pwallet)->IsMine(*account, txin))
{
isMine = true;
anyInputsOrOutputsAreMine = true;
}
}
inputs.push_back(InputRecord(address, label, description, isMine));
}
for (const CTxOut& txout: tx.vout)
{
std::string address;
CNativeAddress addr;
CTxDestination dest;
if (!ExtractDestination(txout, dest) && !txout.IsUnspendable())
{
LogPrintf("Unknown transaction type found, txid %s\n", tx.GetHash().ToString());
dest = CNoDestination();
}
if (addr.Set(dest))
{
address = addr.ToString();
}
std::string label;
std::string description;
if (pwallet->mapAddressBook.count(address))
{
const auto& data = pwallet->mapAddressBook[address];
label = data.name;
description = data.description;
}
bool isMine = false;
for (const auto& account : forAccounts)
{
if (IsMine(*account, txout))
{
isMine = true;
anyInputsOrOutputsAreMine = true;
}
}
outputs.push_back(OutputRecord(txout.nValue, address, label, description, isMine));
}
TransactionStatus status = getStatusForTransaction(&wtx);
return TransactionRecord(wtx.GetHash().ToString(), wtx.nTimeSmart,
added - subtracted,
fee, status, wtx.nHeight, wtx.nBlockTime, wtx.GetDepthInMainChain(),
inputs, outputs);
}
// rate limited balance change notifier
static CRateLimit<int>* balanceChangeNotifier=nullptr;
// rate limited new mutations notifier
static CRateLimit<std::pair<uint256, bool>>* newMutationsNotifier=nullptr;
void terminateUnityFrontend()
{
if (signalHandler)
{
signalHandler->notifyShutdown();
}
// Allow frontend time to clean up and free any references to objects before unloading the library
// Otherwise we get a free after close (on macOS at least)
while (signalHandler.use_count() > 1)
{
MilliSleep(50);
}
signalHandler=nullptr;
}
#include <boost/chrono/thread_clock.hpp>
static float lastProgress=0;
void handlePostInitMain()
{
//fixme: (SIGMA) (PHASE4) Remove this once we have witness-header-sync
// Select appropriate verification factor based on devices performance.
std::thread([=]
{
// When available measure thread relative cpu time to avoid effects of thread suspension
// which occur when observing system time.
#if false && defined(BOOST_CHRONO_HAS_THREAD_CLOCK) && BOOST_CHRONO_THREAD_CLOCK_IS_STEADY
boost::chrono::time_point tpStart = boost::chrono::thread_clock::now();
#else
uint64_t nStart = GetTimeMicros();
#endif
// note that measurement is on single thread, which makes the measurement more stable
// actual verification might use more threads which helps overall app performance
sigma_verify_context verify(defaultSigmaSettings, 1);
CBlockHeader header;
verify.verifyHeader<1>(header);
// We want at least 1000 blocks per second
#if false && defined(BOOST_CHRONO_HAS_THREAD_CLOCK) && BOOST_CHRONO_THREAD_CLOCK_IS_STEADY
boost::chrono::microseconds ms = boost::chrono::duration_cast<boost::chrono::microseconds>(boost::chrono::thread_clock::now() - tpStart);
uint64_t nTotal = ms.count();
#else
uint64_t nTotal = GetTimeMicros() - nStart;
#endif
uint64_t nPerSec = 1000000/nTotal;
if (nPerSec > 1000) // Fast enough to do most the blocks
{
verifyFactor = 5;
}
else if(nPerSec > 0) // Slower so reduce the number of blocks
{
// 2 in verifyFactor chance of verifying.
// We verify 2 in verifyFactor blocks - or target_speed/(num_per_sec/2)
verifyFactor = 1000/(nPerSec/2.0);
verifyFactor = std::max((uint64_t)5, verifyFactor);
verifyFactor = std::min((uint64_t)200, verifyFactor);
}
LogPrintf("unity: selected verification factor %d", verifyFactor);
}).detach();
if (signalHandler)
{
signalHandler->notifyCoreReady();
}
// unified progress notification
if (!GetBoolArg("-spv", DEFAULT_SPV))
{
static bool haveFinishedHeaderSync=false;
static int totalHeaderCount=0;
static int startHeight = chainActive.Tip() ? chainActive.Tip()->nHeight : 0;
// If tip is relatively recent set progress to "completed" to begin with
if (chainActive.Tip() && ((GetTime() - chainActive.Tip()->nTime) < 3600))
{
lastProgress = 1.0;
}
// Weight a full header sync as 20%, blocks as rest
uiInterface.NotifyHeaderProgress.connect([=](int currentCount, int probableHeight, int headerTipHeight, int64_t headerTipTime)
{
totalHeaderCount = currentCount;
if (currentCount == probableHeight)
{
haveFinishedHeaderSync = true;
}
if (!haveFinishedHeaderSync && signalHandler && IsInitialBlockDownload())
{
float progress = ((((float)currentCount-startHeight)/((float)probableHeight-startHeight))*0.20);
if (lastProgress != 1 && (progress-lastProgress > 0.02 || progress == 1))
{
lastProgress = progress;
signalHandler->notifyUnifiedProgress(progress);
}
}
});
uiInterface.NotifyBlockTip.connect([=](bool isInitialBlockDownload, const CBlockIndex* pNewTip)
{
if (haveFinishedHeaderSync && signalHandler)
{
float progress = pNewTip->nHeight==totalHeaderCount?1:((0.20+((((float)pNewTip->nHeight-startHeight)/((float)totalHeaderCount-startHeight))*0.80)));
if (lastProgress != 1 && (progress-lastProgress > 0.02 || progress == 1))
{
lastProgress = progress;
signalHandler->notifyUnifiedProgress(progress);
}
}
});
}
else
{
uiInterface.NotifyUnifiedProgress.connect([=](float progress)
{
if (signalHandler)
{
signalHandler->notifyUnifiedProgress(progress);
}
});
// monitoring listeners notifications
uiInterface.NotifyHeaderProgress.connect([=](int, int, int, int64_t)
{
int32_t height, probable_height, offset;
{
LOCK(cs_main);
height = partialChain.Height();
probable_height = GetProbableHeight();
offset = partialChain.HeightOffset();
}
LOCK(cs_monitoringListeners);
for (const auto &listener: monitoringListeners)
{
listener->onPartialChain(height, probable_height, offset);
}
});
uiInterface.NotifySPVPrune.connect([=](int height)
{
LOCK(cs_monitoringListeners);
for (const auto &listener: monitoringListeners)
{
listener->onPruned(height);
}
});
uiInterface.NotifySPVProgress.connect([=](int /*start_height*/, int processed_height, int /*probable_height*/)
{
LOCK(cs_monitoringListeners);
for (const auto &listener: monitoringListeners)
{
listener->onProcessedSPVBlocks(processed_height);
}
});
}
// Update transaction/balance changes
if (pactiveWallet)
{
// Fire events for transaction depth changes (up to depth 10 only)
pactiveWallet->NotifyTransactionDepthChanged.connect( [&](CWallet* pwallet, const uint256& hash)
{
LOCK2(cs_main, pwallet->cs_wallet);
if (pwallet->mapWallet.find(hash) != pwallet->mapWallet.end())
{
const CWalletTx& wtx = pwallet->mapWallet[hash];
LogPrintf("unity: notify transaction depth changed %s",hash.ToString().c_str());
if (signalHandler)
{
std::vector<CAccount*> forAccounts = GetAccountsForAccount(pactiveWallet->activeAccount);
bool anyInputsOrOutputsAreMine = false;
TransactionRecord walletTransaction = calculateTransactionRecordForWalletTransaction(wtx, forAccounts, anyInputsOrOutputsAreMine);
if (anyInputsOrOutputsAreMine)
{
signalHandler->notifyUpdatedTransaction(walletTransaction);
}
}
}
} );
// Fire events for transaction status changes, or new transactions (this won't fire for simple depth changes)
pactiveWallet->NotifyTransactionChanged.connect( [&](CWallet* pwallet, const uint256& hash, ChangeType status, bool fSelfComitted) {
LOCK2(cs_main, pwallet->cs_wallet);
if (pwallet->mapWallet.find(hash) != pwallet->mapWallet.end())
{
if (status == CT_NEW) {
newMutationsNotifier->trigger(std::make_pair(hash, fSelfComitted));
}
else if (status == CT_UPDATED && signalHandler)
{
LogPrintf("unity: notify tx updated %s",hash.ToString().c_str());
const CWalletTx& wtx = pwallet->mapWallet[hash];
std::vector<CAccount*> forAccounts = GetAccountsForAccount(pactiveWallet->activeAccount);
bool anyInputsOrOutputsAreMine = false;
TransactionRecord walletTransaction = calculateTransactionRecordForWalletTransaction(wtx, forAccounts, anyInputsOrOutputsAreMine);
if (anyInputsOrOutputsAreMine)
{
signalHandler->notifyUpdatedTransaction(walletTransaction);
}
}
//fixme: (UNITY) - Consider implementing f.e.x if a 0 conf transaction gets deleted...
// else if (status == CT_DELETED)
}
balanceChangeNotifier->trigger(0);
});
// Fire once immediately to update with latest on load.
balanceChangeNotifier->trigger(0);
}
}
void handleInitWithExistingWallet()
{
if (signalHandler)
{
signalHandler->notifyInitWithExistingWallet();
}
AppLifecycleManager::gApp->initialize();
}
void handleInitWithoutExistingWallet()
{
signalHandler->notifyInitWithoutExistingWallet();
}
std::string ILibraryController::BuildInfo()
{
std::string info = FormatThreeDigitVersion();
#if defined(__aarch64__)
info += " aarch64";
#elif defined(__arm__)
info += " arm (32bit)";
#elif defined(__x86_64__)
info += " x86_64";
#elif defined(__i386__)
info += " x86";
#endif
return info;
}
bool ILibraryController::InitWalletFromRecoveryPhrase(const std::string& phrase, const std::string& password)
{
// Refuse to acknowledge an empty recovery phrase, or one that doesn't pass even the most obvious requirement
if (phrase.length() < 16)
{
return false;
}
//fixme: (UNITY) (SPV) - Handle all the various birth date (or lack of birthdate) cases here instead of just the one.
SecureString phraseOnly;
int phraseBirthNumber = 0;
AppLifecycleManager::gApp->splitRecoveryPhraseAndBirth(phrase.c_str(), phraseOnly, phraseBirthNumber);
if (!checkMnemonic(phraseOnly))
{
return false;
}
// ensure that wallet is initialized with a starting time (else it will start from now and old tx will not be scanned)
// Use the hardcoded timestamp 1441212522 of block 250000, we didn't have any recovery phrase style wallets (using current phrase system) before that.
if (phraseBirthNumber == 0)
phraseBirthNumber = timeToBirthNumber(1441212522L);
//fixme: (UNITY) (SPV) - Handle all the various birth date (or lack of birthdate) cases here instead of just the one.
AppLifecycleManager::gApp->setRecoveryPhrase(phraseOnly);
AppLifecycleManager::gApp->setRecoveryBirthNumber(phraseBirthNumber);
AppLifecycleManager::gApp->setRecoveryPassword(password.c_str());
AppLifecycleManager::gApp->isRecovery = true;
AppLifecycleManager::gApp->initialize();
return true;
}
void DoRescanInternal()
{
if (pactiveWallet)
{
ResetSPVStartRescanThread();
}
}
bool ValidateAndSplitRecoveryPhrase(const std::string & phrase, SecureString& mnemonic, int& birthNumber)
{
if (phrase.length() < 16)
return false;
AppLifecycleManager::gApp->splitRecoveryPhraseAndBirth(phrase.c_str(), mnemonic, birthNumber);
return checkMnemonic(mnemonic) && (birthNumber == 0 || Base10ChecksumDecode(birthNumber, nullptr));
}
bool ILibraryController::ContinueWalletFromRecoveryPhrase(const std::string& phrase, const std::string& password)
{
SecureString phraseOnly;
int phraseBirthNumber;
if (!ValidateAndSplitRecoveryPhrase(phrase, phraseOnly, phraseBirthNumber))
return false;
// ensure that wallet is initialized with a starting time (else it will start from now and old tx will not be scanned)
// Use the hardcoded timestamp 1441212522 of block 250000, we didn't have any recovery phrase style wallets (using current phrase system) before that.
if (phraseBirthNumber == 0)
phraseBirthNumber = timeToBirthNumber(1441212522L);
if (!pactiveWallet)
{
LogPrintf("ContineWalletFromRecoveryPhrase: No active wallet");
return false;
}
LOCK2(cs_main, pactiveWallet->cs_wallet);
AppLifecycleManager::gApp->setRecoveryPhrase(phraseOnly);
AppLifecycleManager::gApp->setRecoveryBirthNumber(phraseBirthNumber);
AppLifecycleManager::gApp->setRecoveryPassword(password.c_str());
AppLifecycleManager::gApp->isRecovery = true;
CWallet::CreateSeedAndAccountFromPhrase(pactiveWallet);
// Allow update of balance for deleted accounts/transactions
LogPrintf("%s: Update balance and rescan", __func__);
balanceChangeNotifier->trigger(0);
// Rescan for transactions on the linked account
DoRescanInternal();
return true;
}
bool ILibraryController::IsValidRecoveryPhrase(const std::string & phrase)
{
SecureString dummyMnemonic;
int dummyNumber;
return ValidateAndSplitRecoveryPhrase(phrase, dummyMnemonic, dummyNumber);
}
#include "base58.h"
std::string ILibraryController::GenerateGenesisKeys()
{
std::string address = GetReceiveAddress();
CNativeAddress addr(address);
CTxDestination dest = addr.Get();
CPubKey vchPubKeyDevSubsidy;
pactiveWallet->GetPubKey(boost::get<CKeyID>(dest), vchPubKeyDevSubsidy);
std::string devSubsidyPubKey = HexStr(vchPubKeyDevSubsidy);
std::string devSubsidyPubKeyID = boost::get<CKeyID>(dest).GetHex();
CKey key;
key.MakeNewKey(true);
CPrivKey vchPrivKey = key.GetPrivKey();
CPubKey vchPubKey = key.GetPubKey();
std::string privkey = HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end()).c_str();
std::string pubKeyID = vchPubKey.GetID().GetHex();
std::string witnessKeys = GLOBAL_APP_URIPREFIX"://witnesskeys?keys=" + CEncodedSecretKey(key).ToString() + strprintf("#%s", GetAdjustedTime());
return "privkey: "+privkey+"\n"+"pubkeyID: "+pubKeyID+"\n"+"witness: "+witnessKeys+"\n"+"dev subsidy addr: "+address+"\n"+"dev subsidy pubkey: "+devSubsidyPubKey+"\n"+"dev subsidy pubkey ID: "+devSubsidyPubKeyID+"\n";
}
MnemonicRecord ILibraryController::GenerateRecoveryMnemonic()
{
std::vector<unsigned char> entropy(16);
GetStrongRandBytes(&entropy[0], 16);
int64_t birthTime = GetAdjustedTime();
SecureString phraseOnly = mnemonicFromEntropy(entropy, entropy.size()*8);
return ComposeRecoveryPhrase(phraseOnly.c_str(), birthTime);
}
MnemonicRecord ILibraryController::ComposeRecoveryPhrase(const std::string & mnemonic, int64_t birthTime)
{
const auto& result = AppLifecycleManager::composeRecoveryPhrase(SecureString(mnemonic), birthTime);
return MnemonicRecord(result.first.c_str(), mnemonic.c_str(), result.second);
}
bool ILibraryController::InitWalletLinkedFromURI(const std::string& linked_uri, const std::string& password)
{
CEncodedSecretKeyExt<CExtKey> linkedKey;
if (!linkedKey.fromURIString(linked_uri))
{
return false;
}
AppLifecycleManager::gApp->setLinkKey(linkedKey);
AppLifecycleManager::gApp->isLink = true;
AppLifecycleManager::gApp->setRecoveryPassword(password.c_str());
AppLifecycleManager::gApp->initialize();
return true;
}
bool ILibraryController::ContinueWalletLinkedFromURI(const std::string & linked_uri, const std::string& password)
{
if (!pactiveWallet)
{
LogPrintf("%s: No active wallet", __func__);
return false;
}
LOCK2(cs_main, pactiveWallet->cs_wallet);
CEncodedSecretKeyExt<CExtKey> linkedKey;
if (!linkedKey.fromURIString(linked_uri))
{
LogPrintf("%s: Failed to parse link URI", __func__);
return false;
}
AppLifecycleManager::gApp->setLinkKey(linkedKey);
AppLifecycleManager::gApp->setRecoveryPassword(password.c_str());
AppLifecycleManager::gApp->isLink = true;
CWallet::CreateSeedAndAccountFromLink(pactiveWallet);
// Allow update of balance for deleted accounts/transactions
LogPrintf("%s: Update balance and rescan", __func__);
balanceChangeNotifier->trigger(0);
// Rescan for transactions on the linked account
DoRescanInternal();
return true;
}
bool ILibraryController::ReplaceWalletLinkedFromURI(const std::string& linked_uri, const std::string& password)
{
LOCK2(cs_main, pactiveWallet->cs_wallet);
if (!pactiveWallet || !pactiveWallet->activeAccount)
{
LogPrintf("ReplaceWalletLinkedFromURI: No active wallet");
return false;
}
// Create ext key for new linked account from parsed data
CEncodedSecretKeyExt<CExtKey> linkedKey;
if (!linkedKey.fromURIString(linked_uri))
{
LogPrintf("ReplaceWalletLinkedFromURI: Failed to parse link URI");
return false;
}
// Ensure we have a valid location to send all the funds
CNativeAddress address(linkedKey.getPayAccount());
if (!address.IsValid())
{
LogPrintf("ReplaceWalletLinkedFromURI: invalid address %s", linkedKey.getPayAccount().c_str());
return false;
}
// Empty wallet to target address
LogPrintf("ReplaceWalletLinkedFromURI: Empty accounts into linked address");
bool fSubtractFeeFromAmount = true;
std::vector<std::tuple<CWalletTx*, CReserveKeyOrScript*>> transactionsToCommit;
for (const auto& [accountUUID, pAccount] : pactiveWallet->mapAccounts)
{
CAmount nBalance = pactiveWallet->GetBalance(pAccount, false, true, true);
if (nBalance > 0)
{
LogPrintf("ReplaceWalletLinkedFromURI: Empty account into linked address [%s]", getUUIDAsString(accountUUID).c_str());
std::vector<CRecipient> vecSend;
CRecipient recipient = GetRecipientForDestination(address.Get(), nBalance, fSubtractFeeFromAmount, GetPoW2Phase(chainTip()));
vecSend.push_back(recipient);
CWalletTx* pWallettx = new CWalletTx();
CAmount nFeeRequired;
int nChangePosRet = -1;
std::string strError;
CReserveKeyOrScript* pReserveKey = new CReserveKeyOrScript(pactiveWallet, pAccount, KEYCHAIN_CHANGE);
std::vector<CKeyStore*> accountsToTry;
for ( const auto& accountPair : pactiveWallet->mapAccounts )
{
if(accountPair.second->getParentUUID() == pAccount->getUUID())
{
accountsToTry.push_back(accountPair.second);
}
accountsToTry.push_back(pAccount);
}
if (!pactiveWallet->CreateTransaction(accountsToTry, vecSend, *pWallettx, *pReserveKey, nFeeRequired, nChangePosRet, strError))
{
LogPrintf("ReplaceWalletLinkedFromURI: Failed to create transaction %s [%d]",strError.c_str(), nBalance);
return false;
}
transactionsToCommit.push_back(std::tuple(pWallettx, pReserveKey));
}
else
{
LogPrintf("ReplaceWalletLinkedFromURI: Account already empty [%s]", getUUIDAsString(accountUUID).c_str());
}
}
if (!EraseWalletSeedsAndAccounts())
{
LogPrintf("ReplaceWalletLinkedFromURI: Failed to erase seed and accounts");
return false;
}
AppLifecycleManager::gApp->setLinkKey(linkedKey);
AppLifecycleManager::gApp->setRecoveryPassword(password.c_str());
AppLifecycleManager::gApp->isLink = true;
CWallet::CreateSeedAndAccountFromLink(pactiveWallet);
for (auto& [pWalletTx, pReserveKey] : transactionsToCommit)
{
CValidationState state;
//NB! We delibritely pass nullptr for connman here to prevent transaction from relaying
//We allow the relaying to occur inside DoRescan instead
if (!pactiveWallet->CommitTransaction(*pWalletTx, *pReserveKey, nullptr, state))
{
LogPrintf("ReplaceWalletLinkedFromURI: Failed to commit transaction");
return false;
}
delete pWalletTx;
delete pReserveKey;
}
// Allow update of balance for deleted accounts/transactions
LogPrintf("ReplaceWalletLinkedFromURI: Update balance and rescan");
balanceChangeNotifier->trigger(0);
// Rescan for transactions on the linked account
DoRescanInternal();
return true;
}
bool ILibraryController::EraseWalletSeedsAndAccounts()
{
pactiveWallet->EraseWalletSeedsAndAccounts();
return true;
}
bool ILibraryController::IsValidLinkURI(const std::string& linked_uri)
{
CEncodedSecretKeyExt<CExtKey> linkedKey;
if (!linkedKey.fromURIString(linked_uri))
return false;
return true;
}
bool testnet_;
bool spvMode_;
std::string extraArgs_;
std::string staticFilterPath_;
int64_t staticFilterOffset_;
int64_t staticFilterLength_;
int32_t ILibraryController::InitUnityLib(const std::string& dataDir, const std::string& staticFilterPath, int64_t staticFilterOffset, int64_t staticFilterLength, bool testnet, bool spvMode, const std::shared_ptr<ILibraryListener>& signalHandler_, const std::string& extraArgs)
{
balanceChangeNotifier = new CRateLimit<int>([](int)
{
if (pactiveWallet && signalHandler)
{
WalletBalances balances;
pactiveWallet->GetBalances(balances, pactiveWallet->activeAccount, true);
signalHandler->notifyBalanceChange(BalanceRecord(balances.availableIncludingLocked, balances.availableExcludingLocked, balances.availableLocked, balances.unconfirmedIncludingLocked, balances.unconfirmedExcludingLocked, balances.unconfirmedLocked, balances.immatureIncludingLocked, balances.immatureExcludingLocked, balances.immatureLocked, balances.totalLocked));
}
}, std::chrono::milliseconds(BALANCE_NOTIFY_THRESHOLD_MS));
newMutationsNotifier = new CRateLimit<std::pair<uint256, bool>>([](const std::pair<uint256, bool>& txInfo)
{
if (pactiveWallet && signalHandler)
{
const uint256& txHash = txInfo.first;
const bool fSelfComitted = txInfo.second;
LOCK2(cs_main, pactiveWallet->cs_wallet);
if (pactiveWallet->mapWallet.find(txHash) != pactiveWallet->mapWallet.end())
{
const CWalletTx& wtx = pactiveWallet->mapWallet[txHash];
std::vector<MutationRecord> mutations;
addMutationsForTransaction(&wtx, mutations, pactiveWallet->activeAccount);
for (auto& m: mutations)
{
LogPrintf("unity: notify new mutation for tx %s", txHash.ToString().c_str());
signalHandler->notifyNewMutation(m, fSelfComitted);
}
}
}
}, std::chrono::milliseconds(NEW_MUTATIONS_NOTIFY_THRESHOLD_MS));
// Force the datadir to specific place on e.g. android devices
defaultDataDirOverride = dataDir;
signalHandler = signalHandler_;
testnet_ = testnet;
spvMode_ = spvMode;
extraArgs_ = extraArgs;
staticFilterPath_ = staticFilterPath;
staticFilterOffset_ = staticFilterOffset;
staticFilterLength_ = staticFilterLength;
return InitUnity();
}
void InitAppSpecificConfigParamaters()
{
if (spvMode_)
{
// SPV wallets definitely shouldn't be listening for incoming connections at all
SoftSetArg("-listen", "0");
// Minimise logging for performance reasons
SoftSetArg("-debug", "0");
// Turn SPV mode on
SoftSetArg("-fullsync", "0");
SoftSetArg("-spv", "1");
#ifdef DJINNI_NODEJS
#ifdef SPV_MULTI_ACCOUNT
SoftSetArg("-accountpool", "3");
SoftSetArg("-accountpoolmobi", "1");
SoftSetArg("-accountpoolwitness", "1");
SoftSetArg("-accountpoolmining", "1");
#else
SoftSetArg("-accountpool", "0");
SoftSetArg("-accountpoolmobi", "0");
SoftSetArg("-accountpoolwitness", "0");
SoftSetArg("-accountpoolmining", "0");
#endif
SoftSetArg("-keypool", "10");
#else
// Minimise lookahead size for performance reasons
SoftSetArg("-accountpool", "1");
// Minimise background threads and memory consumption
SoftSetArg("-par", "-100");
SoftSetArg("-maxsigcachesize", "0");
SoftSetArg("-dbcache", "4");
SoftSetArg("-maxmempool", "5");
SoftSetArg("-maxconnections", "8");
//fixme: (FUT) (UNITY) Reverse headers
// Temporarily disable reverse headers for mobile until memory requirements can be reduced.
SoftSetArg("-reverseheaders", "false");
#endif
}
SoftSetArg("-spvstaticfilterfile", staticFilterPath_);
SoftSetArg("-spvstaticfilterfileoffset", i64tostr(staticFilterOffset_));
SoftSetArg("-spvstaticfilterfilelength", i64tostr(staticFilterLength_));
// Change client name
#if defined(__APPLE__) && TARGET_OS_IPHONE == 1
SoftSetArg("-clientname", GLOBAL_APPNAME" ios");
#elif defined(__ANDROID__)
SoftSetArg("-clientname", GLOBAL_APPNAME" android");
#else
SoftSetArg("-clientname", GLOBAL_APPNAME" desktop");
#endif
// Testnet
if (testnet_)
{
SoftSetArg("-testnet", "S1595347850:60");
SoftSetArg("-addnode", "178.62.195.19");
}
else
{
SoftSetArg("-addnode", "178.62.195.19");
SoftSetArg("-addnode", "149.210.165.218");
}
if (!extraArgs_.empty()) {
std::vector<const char*> args;
auto splitted = boost::program_options::split_unix(extraArgs_);
for(const auto& part: splitted)
args.push_back(part.c_str());
gArgs.ParseExtraParameters(int(args.size()), args.data());
}
}
void ILibraryController::InitUnityLibThreaded(const std::string& dataDir, const std::string& staticFilterPath, int64_t staticFilterOffset, int64_t staticFilterLength, bool testnet, bool spvMode, const std::shared_ptr<ILibraryListener>& signalHandler_, const std::string& extraArgs)
{
std::thread([=]
{
InitUnityLib(dataDir, staticFilterPath, staticFilterOffset, staticFilterLength, testnet, spvMode, signalHandler_, extraArgs);
}).detach();
}
void ILibraryController::TerminateUnityLib()
{
// Terminate in thread so we don't block interprocess communication
std::thread([=]
{
work.reset();
ioctx.stop();
AppLifecycleManager::gApp->shutdown();
AppLifecycleManager::gApp->waitForShutDown();
run_thread.join();
}).detach();
}
QrCodeRecord ILibraryController::QRImageFromString(const std::string& qr_string, int32_t width_hint)
{
QRcode* code = QRcode_encodeString(qr_string.c_str(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
if (!code)
{
return QrCodeRecord(0, std::vector<uint8_t>());
}
else
{
const int32_t generatedWidth = code->width;
const int32_t finalWidth = (width_hint / generatedWidth) * generatedWidth;
const int32_t scaleMultiplier = finalWidth / generatedWidth;
std::vector<uint8_t> dataVector;
dataVector.reserve(finalWidth*finalWidth);
int nIndex=0;
for (int nRow=0; nRow<generatedWidth; ++nRow)
{
for (int nCol=0; nCol<generatedWidth; ++nCol)
{
dataVector.insert(dataVector.end(), scaleMultiplier, (code->data[nIndex++] & 1) * 255);
}
for (int i=1; i<scaleMultiplier; ++i)
{
dataVector.insert(dataVector.end(), dataVector.end()-finalWidth, dataVector.end());
}
}
QRcode_free(code);
return QrCodeRecord(finalWidth, dataVector);
}
}
std::string ILibraryController::GetReceiveAddress()
{
LOCK2(cs_main, pactiveWallet->cs_wallet);
if (!pactiveWallet || !pactiveWallet->activeAccount)
return "";
CReserveKeyOrScript* receiveAddress = new CReserveKeyOrScript(pactiveWallet, pactiveWallet->activeAccount, KEYCHAIN_EXTERNAL);
CPubKey pubKey;
if (receiveAddress->GetReservedKey(pubKey))
{
CKeyID keyID = pubKey.GetID();
receiveAddress->ReturnKey();
delete receiveAddress;
return CNativeAddress(keyID).ToString();
}
else
{
return "";
}
}
//fixme: (UNITY) - find a way to use char[] here as well as on the java side.
MnemonicRecord ILibraryController::GetRecoveryPhrase()
{
if (pactiveWallet && pactiveWallet->activeAccount)
{
LOCK2(cs_main, pactiveWallet->cs_wallet);
//WalletModel::UnlockContext ctx(walletModel->requestUnlock());
//if (ctx.isValid())
{
int64_t birthTime = pactiveWallet->birthTime();
std::set<SecureString> allPhrases;
for (const auto& seedIter : pactiveWallet->mapSeeds)
{
SecureString phrase = seedIter.second->getMnemonic();
return ComposeRecoveryPhrase(phrase.c_str(), birthTime);
}
}
}
return MnemonicRecord("", "", 0);
}
bool ILibraryController::IsMnemonicWallet()
{
if (!pactiveWallet || !pactiveWallet->activeAccount)
throw std::runtime_error(_("No active internal wallet."));
LOCK2(cs_main, pactiveWallet->cs_wallet);
return pactiveWallet->activeSeed != nullptr;
}
bool ILibraryController::IsMnemonicCorrect(const std::string & phrase)
{
if (!pactiveWallet || !pactiveWallet->activeAccount)
throw std::runtime_error(_("No active internal wallet."));
SecureString mnemonicPhrase;
int birthNumber;
AppLifecycleManager::splitRecoveryPhraseAndBirth(SecureString(phrase), mnemonicPhrase, birthNumber);
LOCK2(cs_main, pactiveWallet->cs_wallet);
for (const auto& seedIter : pactiveWallet->mapSeeds)
{
if (mnemonicPhrase == seedIter.second->getMnemonic())
return true;
}
return false;
}
std::vector<std::string> ILibraryController::GetMnemonicDictionary()
{
return getMnemonicDictionary();
}
//fixme: (UNITY) HIGH - take a timeout value and always lock again after timeout
bool ILibraryController::UnlockWallet(const std::string& password)
{
if (!pactiveWallet)
{
LogPrintf("UnlockWallet: No active wallet");
return false;
}
if (!dynamic_cast<CExtWallet*>(pactiveWallet)->IsCrypted())
{
LogPrintf("UnlockWallet: Wallet not encrypted");
return false;
}
return pactiveWallet->Unlock(password.c_str());
}
bool ILibraryController::LockWallet()
{
if (!pactiveWallet)
{
LogPrintf("LockWallet: No active wallet");
return false;
}
if (dynamic_cast<CExtWallet*>(pactiveWallet)->IsLocked())
return true;
return dynamic_cast<CExtWallet*>(pactiveWallet)->Lock();
}
bool ILibraryController::ChangePassword(const std::string& oldPassword, const std::string& newPassword)
{
if (!pactiveWallet)
{
LogPrintf("ChangePassword: No active wallet");
return false;
}
if (newPassword.length() == 0)
{
LogPrintf("ChangePassword: Refusing invalid password of length 0");
return false;
}
return pactiveWallet->ChangeWalletPassphrase(oldPassword.c_str(), newPassword.c_str());
}
bool ILibraryController::HaveUnconfirmedFunds()
{
if (!pactiveWallet)
return true;
WalletBalances balances;
pactiveWallet->GetBalances(balances, pactiveWallet->activeAccount, true);
if (balances.unconfirmedIncludingLocked > 0 || balances.immatureIncludingLocked > 0)
{
return true;
}
return false;
}
int64_t ILibraryController::GetBalance()
{
if (!pactiveWallet)
return 0;
WalletBalances balances;
pactiveWallet->GetBalances(balances, pactiveWallet->activeAccount, true);
return balances.availableIncludingLocked + balances.unconfirmedIncludingLocked + balances.immatureIncludingLocked;
}
void ILibraryController::DoRescan()
{
if (!pactiveWallet)
return;
// Allocate some extra keys
//fixme: Persist this across runs in some way
static int32_t extraKeys=0;
extraKeys += 5;
int nKeyPoolTargetDepth = GetArg("-keypool", DEFAULT_ACCOUNT_KEYPOOL_SIZE)+extraKeys;
pactiveWallet->TopUpKeyPool(nKeyPoolTargetDepth, 0, nullptr, 1);
// Do the rescan
DoRescanInternal();
}
UriRecipient ILibraryController::IsValidRecipient(const UriRecord & request)
{
// return if URI is not valid or is no Gulden: URI
std::string lowerCaseScheme = boost::algorithm::to_lower_copy(request.scheme);
if (lowerCaseScheme != "gulden")
return UriRecipient(false, "", "", "", 0);
if (!CNativeAddress(request.path).IsValid())
return UriRecipient(false, "", "", "", 0);
std::string address = request.path;
std::string label = "";
std::string description = "";
CAmount amount = 0;
if (request.items.find("amount") != request.items.end())
{
ParseMoney(request.items.find("amount")->second, amount);
}
if (pactiveWallet)
{
LOCK2(cs_main, pactiveWallet->cs_wallet);
if (pactiveWallet->mapAddressBook.find(address) != pactiveWallet->mapAddressBook.end())
{
const auto& data = pactiveWallet->mapAddressBook[address];
label = data.name;
description = data.description;
}
}
return UriRecipient(true, address, label, description, amount);
}
bool ILibraryController::IsValidNativeAddress(const std::string& address)
{
CNativeAddress addr(address);
return addr.IsValid();
}
bool ILibraryController::IsValidBitcoinAddress(const std::string& address)
{
CNativeAddress addr(address);
return addr.IsValidBitcoin();
}
int64_t ILibraryController::feeForRecipient(const UriRecipient & request)
{
if (!pactiveWallet)
throw std::runtime_error(_("No active internal wallet."));
LOCK2(cs_main, pactiveWallet->cs_wallet);
CNativeAddress address(request.address);
if (!address.IsValid())
{
LogPrintf("feeForRecipient: invalid address %s", request.address.c_str());
throw std::runtime_error(_("Invalid address"));
}
CRecipient recipient = GetRecipientForDestination(address.Get(), std::min(GetBalance(), request.amount), true, GetPoW2Phase(chainTip()));
std::vector<CRecipient> vecSend;
vecSend.push_back(recipient);
CWalletTx wtx;
CAmount nFeeRequired;
int nChangePosRet = -1;
std::string strError;
CReserveKeyOrScript reservekey(pactiveWallet, pactiveWallet->activeAccount, KEYCHAIN_CHANGE);
std::vector<CKeyStore*> accountsToTry;
for ( const auto& accountPair : pactiveWallet->mapAccounts )
{
if(accountPair.second->getParentUUID() == pactiveWallet->activeAccount->getUUID())
{
accountsToTry.push_back(accountPair.second);
}
accountsToTry.push_back(pactiveWallet->activeAccount);
}
if (!pactiveWallet->CreateTransaction(accountsToTry, vecSend, wtx, reservekey, nFeeRequired, nChangePosRet, strError, NULL, false))
{
LogPrintf("feeForRecipient: failed to create transaction %s",strError.c_str());
throw std::runtime_error(strprintf(_("Failed to calculate fee\n%s"), strError));
}
return nFeeRequired;
}
PaymentResultStatus ILibraryController::performPaymentToRecipient(const UriRecipient & request, bool substract_fee)
{
if (!pactiveWallet)
throw std::runtime_error(_("No active internal wallet."));
LOCK2(cs_main, pactiveWallet->cs_wallet);
CNativeAddress address(request.address);
if (!address.IsValid())
{
LogPrintf("performPaymentToRecipient: invalid address %s", request.address.c_str());
throw std::runtime_error(_("Invalid address"));
}
CRecipient recipient = GetRecipientForDestination(address.Get(), request.amount, substract_fee, GetPoW2Phase(chainTip()));
std::vector<CRecipient> vecSend;
vecSend.push_back(recipient);
CWalletTx wtx;
CAmount nFeeRequired;
int nChangePosRet = -1;
std::string strError;
CReserveKeyOrScript reservekey(pactiveWallet, pactiveWallet->activeAccount, KEYCHAIN_CHANGE);
std::vector<CKeyStore*> accountsToTry;
for ( const auto& accountPair : pactiveWallet->mapAccounts )
{
if(accountPair.second->getParentUUID() == pactiveWallet->activeAccount->getUUID())
{
accountsToTry.push_back(accountPair.second);
}
accountsToTry.push_back(pactiveWallet->activeAccount);
}
if (!pactiveWallet->CreateTransaction(accountsToTry, vecSend, wtx, reservekey, nFeeRequired, nChangePosRet, strError))
{
if (!substract_fee && request.amount + nFeeRequired > GetBalance()) {
return PaymentResultStatus::INSUFFICIENT_FUNDS;
}
LogPrintf("performPaymentToRecipient: failed to create transaction %s",strError.c_str());
throw std::runtime_error(strprintf(_("Failed to create transaction\n%s"), strError));
}
CValidationState state;
if (!pactiveWallet->CommitTransaction(wtx, reservekey, g_connman.get(), state))
{
strError = strprintf("Error: The transaction was rejected! Reason given: %s", state.GetRejectReason());
LogPrintf("performPaymentToRecipient: failed to commit transaction %s",strError.c_str());
throw std::runtime_error(strprintf(_("Transaction rejected, reason: %s"), state.GetRejectReason()));
}
// Prevent accidental double spends
for (const auto &txin : wtx.tx->vin)
{
pactiveWallet->LockCoin(txin.GetPrevOut());
}
return PaymentResultStatus::SUCCESS;
}
std::vector<TransactionRecord> getTransactionHistoryForAccount(CAccount* forAccount)
{
std::vector<TransactionRecord> ret;
LOCK2(cs_main, pactiveWallet->cs_wallet);
std::vector<CAccount*> forAccounts = GetAccountsForAccount(forAccount);
for (const auto& [hash, wtx] : pactiveWallet->mapWallet)
{
bool anyInputsOrOutputsAreMine = false;
TransactionRecord tx = calculateTransactionRecordForWalletTransaction(wtx, forAccounts, anyInputsOrOutputsAreMine);
if (anyInputsOrOutputsAreMine)
{
ret.push_back(tx);
}
}
std::sort(ret.begin(), ret.end(), [&](TransactionRecord& x, TransactionRecord& y){ return (x.timeStamp > y.timeStamp); });
return ret;
}
std::vector<TransactionRecord> ILibraryController::getTransactionHistory()
{
if (!pactiveWallet)
return std::vector<TransactionRecord>();
return getTransactionHistoryForAccount(pactiveWallet->activeAccount);
}
TransactionRecord ILibraryController::getTransaction(const std::string& txHash)
{
if (!pactiveWallet)
throw std::runtime_error(strprintf("No active wallet to query tx hash [%s]", txHash));
uint256 hash = uint256S(txHash);
LOCK2(cs_main, pactiveWallet->cs_wallet);
if (pactiveWallet->mapWallet.find(hash) == pactiveWallet->mapWallet.end())
throw std::runtime_error(strprintf("No transaction found for hash [%s]", txHash));
std::vector<CAccount*> forAccounts = GetAccountsForAccount(pactiveWallet->activeAccount);
const CWalletTx& wtx = pactiveWallet->mapWallet[hash];
bool anyInputsOrOutputsAreMine = false;
return calculateTransactionRecordForWalletTransaction(wtx, forAccounts, anyInputsOrOutputsAreMine);
}
std::string ILibraryController::resendTransaction(const std::string& txHash)
{
if (!pactiveWallet)
throw std::runtime_error(strprintf("No active wallet to query tx hash [%s]", txHash));
uint256 hash = uint256S(txHash);
LOCK2(cs_main, pactiveWallet->cs_wallet);
if (pactiveWallet->mapWallet.find(hash) == pactiveWallet->mapWallet.end())
return "";
const CWalletTx& wtx = pactiveWallet->mapWallet[hash];
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << *wtx.tx;
std::string strHex = HexStr(ssTx.begin(), ssTx.end());
if(!g_connman)
return "";
const uint256& hashTx = wtx.tx->GetHash();
CInv inv(MSG_TX, hashTx);
g_connman->ForEachNode([&inv](CNode* pnode)
{
pnode->PushInventory(inv);
});
return strHex;
}
std::vector<MutationRecord> getMutationHistoryForAccount(CAccount* forAccount)
{
std::vector<MutationRecord> ret;
LOCK2(cs_main, pactiveWallet->cs_wallet);
// wallet transactions in reverse chronological ordering
std::vector<const CWalletTx*> vWtx;
for (const auto& [hash, wtx] : pactiveWallet->mapWallet)
{
vWtx.push_back(&wtx);
}
std::sort(vWtx.begin(), vWtx.end(), [&](const CWalletTx* x, const CWalletTx* y){ return (x->nTimeSmart > y->nTimeSmart); });
// build mutation list based on transactions
for (const CWalletTx* wtx : vWtx)
{
addMutationsForTransaction(wtx, ret, forAccount);
}
return ret;
}
std::vector<MutationRecord> ILibraryController::getMutationHistory()
{
if (!pactiveWallet)
return std::vector<MutationRecord>();
return getMutationHistoryForAccount(pactiveWallet->activeAccount);
}
std::vector<AddressRecord> ILibraryController::getAddressBookRecords()
{
std::vector<AddressRecord> ret;
if (pactiveWallet)
{
LOCK2(cs_main, pactiveWallet->cs_wallet);
for(const auto& [address, addressData] : pactiveWallet->mapAddressBook)
{
ret.emplace_back(AddressRecord(address, addressData.name, addressData.description, addressData.purpose));
}
}
return ret;
}
void ILibraryController::addAddressBookRecord(const AddressRecord& address)
{
if (pactiveWallet)
{
pactiveWallet->SetAddressBook(address.address, address.name, address.desc, address.purpose);
}
}
void ILibraryController::deleteAddressBookRecord(const AddressRecord& address)
{
if (pactiveWallet)
{
pactiveWallet->DelAddressBook(address.address);
}
}
void ILibraryController::PersistAndPruneForSPV()
{
PersistAndPruneForPartialSync();
}
void ILibraryController::ResetUnifiedProgress()
{
CWallet::ResetUnifiedSPVProgressNotification();
}
float ILibraryController::getUnifiedProgress()
{
if (!GetBoolArg("-spv", DEFAULT_SPV))
{
return lastProgress;
}
else
{
return CSPVScanner::lastProgressReported;
}
}
std::vector<BlockInfoRecord> ILibraryController::getLastSPVBlockInfos()
{
std::vector<BlockInfoRecord> ret;
LOCK(cs_main);
int height = partialChain.Height();
while (ret.size() < 32 && height > partialChain.HeightOffset()) {
const CBlockIndex* pindex = partialChain[height];
ret.push_back(BlockInfoRecord(pindex->nHeight, pindex->GetBlockTime(), pindex->GetBlockHashPoW2().ToString()));
height--;
}
return ret;
}
MonitorRecord ILibraryController::getMonitoringStats()
{
LOCK(cs_main);
int32_t partialHeight_ = partialChain.Height();
int32_t partialOffset_ = partialChain.HeightOffset();
int32_t prunedHeight_ = nPartialPruneHeightDone;
int32_t processedSPVHeight_ = CSPVScanner::getProcessedHeight();
int32_t probableHeight_ = GetProbableHeight();
return MonitorRecord(partialHeight_,
partialOffset_,
prunedHeight_,
processedSPVHeight_,
probableHeight_);
}
void ILibraryController::RegisterMonitorListener(const std::shared_ptr<MonitorListener> & listener)
{
LOCK(cs_monitoringListeners);
monitoringListeners.insert(listener);
}
void ILibraryController::UnregisterMonitorListener(const std::shared_ptr<MonitorListener> & listener)
{
LOCK(cs_monitoringListeners);
monitoringListeners.erase(listener);
}
std::unordered_map<std::string, std::string> ILibraryController::getClientInfo()
{
std::unordered_map<std::string, std::string> ret;
ret.insert(std::pair("client_version", FormatFullVersion()));
ret.insert(std::pair("user_agent", strSubVersion));
ret.insert(std::pair("datadir_path", GetDataDir().string()));
std::string logfilePath = (GetDataDir() / "debug.log").string();
ret.insert(std::pair("logfile_path", logfilePath));
ret.insert(std::pair("startup_timestamp", i64tostr(nClientStartupTime)));
if (!g_connman->GetNetworkActive())
{
ret.insert(std::pair("network_status", "disabled"));
ret.insert(std::pair("num_connections_in", "0"));
ret.insert(std::pair("num_connections_out", "0"));
}
else
{
ret.insert(std::pair("network_status", "enabled"));
std::string connectionsIn = i64tostr(g_connman->GetNodeCount(CConnman::NumConnections::CONNECTIONS_IN));
std::string connectionsOut = i64tostr(g_connman->GetNodeCount(CConnman::NumConnections::CONNECTIONS_OUT));
ret.insert(std::pair("num_connections_in", connectionsIn));
ret.insert(std::pair("num_connections_out", connectionsOut));
}
if (fSPV)
{
if (partialChain.Tip())
{
ret.insert(std::pair("chain_tip_height", i64tostr(partialChain.Height())));
ret.insert(std::pair("chain_tip_time", i64tostr(partialChain.Tip()->GetBlockTime())));
ret.insert(std::pair("chain_tip_hash", partialChain.Tip()->GetBlockHashPoW2().ToString()));
ret.insert(std::pair("chain_offset", i64tostr(partialChain.HeightOffset())));
ret.insert(std::pair("chain_pruned_height", i64tostr(nPartialPruneHeightDone)));
ret.insert(std::pair("chain_processed_height", i64tostr(CSPVScanner::getProcessedHeight())));
ret.insert(std::pair("chain_probable_height", i64tostr(GetProbableHeight())));
}
}
else if (chainActive.Tip())
{
ret.insert(std::pair("chain_tip_height", i64tostr(chainActive.Tip()->nHeight)));
ret.insert(std::pair("chain_tip_time", i64tostr(chainActive.Tip()->GetBlockTime())));
ret.insert(std::pair("chain_tip_hash", chainActive.Tip()->GetBlockHashPoW2().ToString()));
}
ret.insert(std::pair("mempool_transaction_count", i64tostr(mempool.size())));
ret.insert(std::pair("mempool_memory_size", i64tostr(mempool.GetTotalTxSize())));
return ret;
}
| nlgcoin/guldencoin-official | src/unity/unity_impl.cpp | C++ | mit | 56,495 |
class CreateActiveAdminComments < ActiveRecord::Migration[5.1]
def self.up
create_table :active_admin_comments do |t|
t.string :namespace
t.text :body
t.string :resource_id, null: false
t.string :resource_type, null: false
t.references :author, polymorphic: true
t.timestamps
end
add_index :active_admin_comments, [:namespace]
add_index :active_admin_comments, [:resource_type, :resource_id]
end
def self.down
drop_table :active_admin_comments
end
end
| Seybo/michaelatwork | db/migrate/20160518090723_create_active_admin_comments.rb | Ruby | mit | 521 |
namespace _03BarracksFactory.Data
{
using System;
using Contracts;
using System.Collections.Generic;
using System.Text;
class UnitRepository : IRepository
{
private IDictionary<string, int> amountOfUnits;
public UnitRepository()
{
this.amountOfUnits = new SortedDictionary<string, int>();
}
public string Statistics
{
get
{
StringBuilder statBuilder = new StringBuilder();
foreach (var entry in amountOfUnits)
{
string formatedEntry =
string.Format("{0} -> {1}", entry.Key, entry.Value);
statBuilder.AppendLine(formatedEntry);
}
return statBuilder.ToString().Trim();
}
}
public void AddUnit(IUnit unit)
{
string unitType = unit.GetType().Name;
if (!this.amountOfUnits.ContainsKey(unitType))
{
this.amountOfUnits.Add(unitType, 0);
}
this.amountOfUnits[unitType]++;
}
public void RemoveUnit(string unitType)
{
if (this.amountOfUnits[unitType] > 0)
{
this.amountOfUnits[unitType]--;
}
else
{
throw new ArgumentException("Not enought units.");
}
}
}
}
| MrPIvanov/SoftUni | 06-Csharp OOP Advanced/10-EXERCISE REFLECTION AND ATTRIBUTES/ReflectionExercises/05-BarracksWarsReturnOfTheDependencies/Data/UnitRepository.cs | C# | mit | 1,466 |
/// @copyright
/// Copyright (C) 2020 Assured Information Security, Inc.
///
/// @copyright
/// 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:
///
/// @copyright
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// @copyright
/// 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.
#ifndef TLS_T_HPP
#define TLS_T_HPP
#include <state_save_t.hpp>
#include <bsl/array.hpp>
#include <bsl/convert.hpp>
#include <bsl/cstdint.hpp>
#include <bsl/errc_type.hpp>
#include <bsl/safe_integral.hpp>
#pragma pack(push, 1)
namespace mk
{
/// @brief defines the size of the reserved1 field in the tls_t
constexpr auto TLS_T_RESERVED1_SIZE{0x020_umx};
/// @brief defines the size of the reserved2 field in the tls_t
constexpr auto TLS_T_RESERVED2_SIZE{0x008_umx};
/// @brief defines the size of the reserved3 field in the tls_t
constexpr auto TLS_T_RESERVED3_SIZE{0x007_umx};
/// @brief defines the size of the reserved4 field in the tls_t
constexpr auto TLS_T_RESERVED4_SIZE{0x040_umx};
/// IMPORTANT:
/// - If the size of the TLS is changed, the mk_main_entry will need to
/// be updated to reflect the new size. It might make sense to have a
/// header file that defines a constant that both this code and the
/// assembly logic can share
///
/// @brief defines the the total size of the TLS block
constexpr auto TLS_T_SIZE{0x400_umx};
/// <!-- description -->
/// @brief Defines the layout of the microkernel's TLS block. This
/// should not be confused with the TLS blocks given to an extension,
/// for which there are two, the TLS block for thread_local and the
/// TLS block provided by the microkernel's ABI.
///
struct tls_t final
{
/// --------------------------------------------------------------------
/// Microkernel State
/// --------------------------------------------------------------------
/// @brief stores the value of x18 for the microkernel (0x000)
bsl::uintmx mk_x18;
/// @brief stores the value of x19 for the microkernel (0x008)
bsl::uintmx mk_x19;
/// @brief stores the value of x20 for the microkernel (0x010)
bsl::uintmx mk_x20;
/// @brief stores the value of x21 for the microkernel (0x018)
bsl::uintmx mk_x21;
/// @brief stores the value of x22 for the microkernel (0x020)
bsl::uintmx mk_x22;
/// @brief stores the value of x23 for the microkernel (0x028)
bsl::uintmx mk_x23;
/// @brief stores the value of x24 for the microkernel (0x030)
bsl::uintmx mk_x24;
/// @brief stores the value of x25 for the microkernel (0x038)
bsl::uintmx mk_x25;
/// @brief stores the value of x26 for the microkernel (0x040)
bsl::uintmx mk_x26;
/// @brief stores the value of x27 for the microkernel (0x048)
bsl::uintmx mk_x27;
/// @brief stores the value of x28 for the microkernel (0x050)
bsl::uintmx mk_x28;
/// @brief stores the value of x29 for the microkernel (0x058)
bsl::uintmx mk_x29;
/// @brief stores the value of x30 for the microkernel (0x060)
bsl::uintmx mk_x30;
/// --------------------------------------------------------------------
/// Extension State
/// --------------------------------------------------------------------
/// @brief x0, stores the extension's syscall (0x068)
bsl::uintmx ext_syscall;
/// @brief x1, stores the value of REG1 for the extension (0x070)
bsl::uintmx ext_reg0;
/// @brief x2, stores the value of REG1 for the extension (0x078)
bsl::uintmx ext_reg1;
/// @brief x3, stores the value of REG1 for the extension (0x080)
bsl::uintmx ext_reg2;
/// @brief x4, stores the value of REG1 for the extension (0x088)
bsl::uintmx ext_reg3;
/// @brief x5, stores the value of REG1 for the extension (0x090)
bsl::uintmx ext_reg4;
/// @brief x6, stores the value of REG1 for the extension (0x098)
bsl::uintmx ext_reg5;
/// @brief x7, stores the value of REG1 for the extension (0x0A0)
bsl::uintmx reserved_reg7;
/// @brief x8, stores the value of REG1 for the extension (0x0A8)
bsl::uintmx reserved_reg8;
/// @brief x9, stores the value of REG1 for the extension (0x0B0)
bsl::uintmx reserved_reg9;
/// @brief x10, stores the value of REG1 for the extension (0x0B8)
bsl::uintmx reserved_reg10;
/// @brief x11, stores the value of REG1 for the extension (0x0C0)
bsl::uintmx reserved_reg11;
/// @brief x12, stores the value of REG1 for the extension (0x0C8)
bsl::uintmx reserved_reg12;
/// @brief x13, stores the value of REG1 for the extension (0x0D0)
bsl::uintmx reserved_reg13;
/// @brief x14, stores the value of REG1 for the extension (0x0D8)
bsl::uintmx reserved_reg14;
/// @brief x15, stores the value of REG1 for the extension (0x0E0)
bsl::uintmx reserved_reg15;
/// @brief x16, stores the value of REG1 for the extension (0x0E8)
bsl::uintmx reserved_reg16;
/// @brief x17, stores the value of REG1 for the extension (0x0F0)
bsl::uintmx reserved_reg17;
/// @brief x18, stores the value of REG1 for the extension (0x0F8)
bsl::uintmx reserved_reg18;
/// @brief x19, stores the value of REG1 for the extension (0x100)
bsl::uintmx reserved_reg19;
/// @brief x20, stores the value of REG1 for the extension (0x108)
bsl::uintmx reserved_reg20;
/// @brief x21, stores the value of REG1 for the extension (0x110)
bsl::uintmx reserved_reg21;
/// @brief x22, stores the value of REG1 for the extension (0x118)
bsl::uintmx reserved_reg22;
/// @brief x23, stores the value of REG1 for the extension (0x120)
bsl::uintmx reserved_reg23;
/// @brief x24, stores the value of REG1 for the extension (0x128)
bsl::uintmx reserved_reg24;
/// @brief x25, stores the value of REG1 for the extension (0x130)
bsl::uintmx reserved_reg25;
/// @brief x26, stores the value of REG1 for the extension (0x138)
bsl::uintmx reserved_reg26;
/// @brief x27, stores the value of REG1 for the extension (0x140)
bsl::uintmx reserved_reg27;
/// @brief x28, stores the value of REG1 for the extension (0x148)
bsl::uintmx reserved_reg28;
/// @brief x29, stores the value of REG1 for the extension (0x150)
bsl::uintmx reserved_reg29;
/// @brief x30, stores the value of REG1 for the extension (0x158)
bsl::uintmx reserved_reg30;
/// --------------------------------------------------------------------
/// ESR State
/// --------------------------------------------------------------------
/// @brief stores the value of x0 for the ESR (0x160)
bsl::uintmx esr_x0;
/// @brief stores the value of x1 for the ESR (0x168)
bsl::uintmx esr_x1;
/// @brief stores the value of x2 for the ESR (0x170)
bsl::uintmx esr_x2;
/// @brief stores the value of x3 for the ESR (0x178)
bsl::uintmx esr_x3;
/// @brief stores the value of x4 for the ESR (0x180)
bsl::uintmx esr_x4;
/// @brief stores the value of x5 for the ESR (0x188)
bsl::uintmx esr_x5;
/// @brief stores the value of x6 for the ESR (0x190)
bsl::uintmx esr_x6;
/// @brief stores the value of x7 for the ESR (0x198)
bsl::uintmx esr_x7;
/// @brief stores the value of x8 for the ESR (0x1A0)
bsl::uintmx esr_x8;
/// @brief stores the value of x9 for the ESR (0x1A8)
bsl::uintmx esr_x9;
/// @brief stores the value of x10 for the ESR (0x1B0)
bsl::uintmx esr_x10;
/// @brief stores the value of x11 for the ESR (0x1B8)
bsl::uintmx esr_x11;
/// @brief stores the value of x12 for the ESR (0x1C0)
bsl::uintmx esr_x12;
/// @brief stores the value of x13 for the ESR (0x1C8)
bsl::uintmx esr_x13;
/// @brief stores the value of x14 for the ESR (0x1D0)
bsl::uintmx esr_x14;
/// @brief stores the value of x15 for the ESR (0x1D8)
bsl::uintmx esr_x15;
/// @brief stores the value of x16 for the ESR (0x1E0)
bsl::uintmx esr_x16;
/// @brief stores the value of x17 for the ESR (0x1E8)
bsl::uintmx esr_x17;
/// @brief stores the value of x18 for the ESR (0x1F0)
bsl::uintmx esr_x18;
/// @brief stores the value of x19 for the ESR (0x1F8)
bsl::uintmx esr_x19;
/// @brief stores the value of x20 for the ESR (0x200)
bsl::uintmx esr_x20;
/// @brief stores the value of x21 for the ESR (0x208)
bsl::uintmx esr_x21;
/// @brief stores the value of x22 for the ESR (0x210)
bsl::uintmx esr_x22;
/// @brief stores the value of x23 for the ESR (0x218)
bsl::uintmx esr_x23;
/// @brief stores the value of x24 for the ESR (0x220)
bsl::uintmx esr_x24;
/// @brief stores the value of x25 for the ESR (0x228)
bsl::uintmx esr_x25;
/// @brief stores the value of x26 for the ESR (0x230)
bsl::uintmx esr_x26;
/// @brief stores the value of x27 for the ESR (0x238)
bsl::uintmx esr_x27;
/// @brief stores the value of x28 for the ESR (0x240)
bsl::uintmx esr_x28;
/// @brief stores the value of x29 for the ESR (0x248)
bsl::uintmx esr_x29;
/// @brief stores the value of x30 for the ESR (0x250)
bsl::uintmx esr_x30;
/// @brief stores the value of sp for the ESR (0x258)
bsl::uintmx esr_sp;
/// @brief stores the value of ip for the ESR (0x260)
bsl::uintmx esr_ip;
/// @brief stores the value of the ESR vector (0x268)
bsl::uintmx esr_vector;
/// @brief stores the value of the ESR error code (0x270)
bsl::uintmx esr_error_code;
/// @brief stores the value of far for the ESR (0x278)
bsl::uintmx esr_pf_addr;
/// @brief stores the value of esr for the ESR (0x280)
bsl::uintmx esr_esr;
/// @brief stores the value of SPSR for the ESR (0x288)
bsl::uintmx esr_spsr;
/// --------------------------------------------------------------------
/// Fast Fail Information
/// --------------------------------------------------------------------
/// @brief stores the current fast fail address (0x290)
bsl::uintmx current_fast_fail_ip;
/// @brief stores the current fast fail stack (0x298)
bsl::uintmx current_fast_fail_sp;
/// @brief stores the mk_main fast fail address (0x2A0)
bsl::uintmx mk_main_fast_fail_ip;
/// @brief stores the mk_main fast fail stack (0x2A8)
bsl::uintmx mk_main_fast_fail_sp;
/// @brief stores the call_ext fast fail address (0x2B0)
bsl::uintmx call_ext_fast_fail_ip;
/// @brief stores the call_ext fast fail stack (0x2B8)
bsl::uintmx call_ext_fast_fail_sp;
/// @brief stores the dispatch_syscall fast fail address (0x2C0)
bsl::uintmx dispatch_syscall_fast_fail_ip;
/// @brief stores the dispatch_syscall fast fail stack (0x2C8)
bsl::uintmx dispatch_syscall_fast_fail_sp;
/// @brief stores the vmexit loop address (0x2D0)
bsl::uintmx vmexit_loop_ip;
/// @brief stores the vmexit loop stack (0x2D8)
bsl::uintmx vmexit_loop_sp;
/// @brief reserve the rest of the TLS block for later use.
bsl::array<bsl::uint8, TLS_T_RESERVED1_SIZE.get()> reserved1;
/// --------------------------------------------------------------------
/// Context Information
/// --------------------------------------------------------------------
/// @brief stores the virtual address of this TLS block (0x300)
tls_t *self;
/// @brief stores the currently active VMID (0x308)
bsl::uint16 ppid;
/// @brief stores the total number of online PPs (0x30A)
bsl::uint16 online_pps;
/// @brief reserved (0x30C)
bsl::uint16 reserved_padding0;
/// @brief reserved (0x30E)
bsl::uint16 reserved_padding1;
/// @brief stores the currently active extension (0x310)
void *ext;
/// @brief stores the extension registered for VMExits (0x318)
void *ext_vmexit;
/// @brief stores the extension registered for fast fail events (0x320)
void *ext_fail;
/// @brief stores the loader provided state for the microkernel (0x328)
loader::state_save_t *mk_state;
/// @brief stores the loader provided state for the root VP (0x330)
loader::state_save_t *root_vp_state;
/// @brief stores the currently active extension ID (0x338)
bsl::uint16 active_extid;
/// @brief stores the currently active VMID (0x33A)
bsl::uint16 active_vmid;
/// @brief stores the currently active VPID (0x33C)
bsl::uint16 active_vpid;
/// @brief stores the currently active VSID (0x33E)
bsl::uint16 active_vsid;
/// @brief stores the sp used by extensions for callbacks (0x340)
bsl::uintmx sp;
/// @brief stores the tps used by extensions for callbacks (0x348)
bsl::uintmx tp;
/// @brief used to store a return address for unsafe ops (0x350)
bsl::uintmx unsafe_rip;
/// @brief reserved (0x358)
bsl::uintmx reserved_padding2;
/// @brief reserved (0x360)
bsl::uintmx reserved_padding3;
/// @brief stores whether or not the first launch succeeded (0x368)
bsl::uintmx first_launch_succeeded;
/// @brief stores the currently active root page table (0x370)
void *active_rpt;
/// @brief reserve the rest of the TLS block for later use.
bsl::array<bsl::uint8, TLS_T_RESERVED2_SIZE.get()> reserved2;
};
/// @brief make sure the tls_t is the size of a page
static_assert(sizeof(tls_t) == TLS_T_SIZE);
}
#pragma pack(pop)
#endif
| rianquinn/hypervisor | kernel/include/arm/aarch64/tls_t.hpp | C++ | mit | 15,304 |
package com.github.bachelorpraktikum.visualisierbar.model;
import com.github.bachelorpraktikum.visualisierbar.model.Element.State;
import com.github.bachelorpraktikum.visualisierbar.model.Element.Type;
public class ElementShapeableTest extends ShapeableImplementationTest {
@Override
protected Shapeable<?> getShapeable() {
Context context = new Context();
Node node = Node.in(context).create("node", new Coordinates(0, 0));
return Element.in(context).create("element", Type.HauptSignal, node, State.FAHRT);
}
}
| Bachelorpraktikum/VisualisierbaR | src/test/java/com/github/bachelorpraktikum/visualisierbar/model/ElementShapeableTest.java | Java | mit | 551 |
/**
* @license Angular v4.0.3
* (c) 2010-2017 Google, Inc. https://angular.io/
* License: MIT
*/
import { Compiler, ComponentFactoryResolver, Directive, ElementRef, EventEmitter, Inject, Injector, NgModule, NgZone, ReflectiveInjector, SimpleChange, Testability, Version } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @module
* @description
* Entry point for all public APIs of the common package.
*/
/**
* \@stable
*/
const VERSION = new Version('4.0.3');
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @return {?}
*/
function noNg() {
throw new Error('AngularJS v1.x is not loaded!');
}
let angular = ({
bootstrap: noNg,
module: noNg,
element: noNg,
version: noNg,
resumeBootstrap: noNg,
getTestability: noNg
});
try {
if (window.hasOwnProperty('angular')) {
angular = ((window)).angular;
}
}
catch (e) {
}
/**
* Resets the AngularJS library.
*
* Used when angularjs is loaded lazily, and not available on `window`.
*
* \@stable
* @param {?} ng
* @return {?}
*/
/**
* Returns the current version of the AngularJS library.
*
* \@stable
* @return {?}
*/
const bootstrap = (e, modules, config) => angular.bootstrap(e, modules, config);
const module$1 = (prefix, dependencies) => angular.module(prefix, dependencies);
const element = (e) => angular.element(e);
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const $COMPILE = '$compile';
const $CONTROLLER = '$controller';
const $HTTP_BACKEND = '$httpBackend';
const $INJECTOR = '$injector';
const $PARSE = '$parse';
const $ROOT_SCOPE = '$rootScope';
const $SCOPE = '$scope';
const $TEMPLATE_CACHE = '$templateCache';
const $$TESTABILITY = '$$testability';
const COMPILER_KEY = '$$angularCompiler';
const INJECTOR_KEY = '$$angularInjector';
const NG_ZONE_KEY = '$$angularNgZone';
const REQUIRE_INJECTOR = '?^^' + INJECTOR_KEY;
const REQUIRE_NG_MODEL = '?ngModel';
/**
* A `PropertyBinding` represents a mapping between a property name
* and an attribute name. It is parsed from a string of the form
* `"prop: attr"`; or simply `"propAndAttr" where the property
* and attribute have the same identifier.
*/
class PropertyBinding {
/**
* @param {?} prop
* @param {?} attr
*/
constructor(prop, attr) {
this.prop = prop;
this.attr = attr;
this.parseBinding();
}
/**
* @return {?}
*/
parseBinding() {
this.bracketAttr = `[${this.attr}]`;
this.parenAttr = `(${this.attr})`;
this.bracketParenAttr = `[(${this.attr})]`;
const /** @type {?} */ capitalAttr = this.attr.charAt(0).toUpperCase() + this.attr.substr(1);
this.onAttr = `on${capitalAttr}`;
this.bindAttr = `bind${capitalAttr}`;
this.bindonAttr = `bindon${capitalAttr}`;
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @param {?} e
* @return {?}
*/
function onError(e) {
// TODO: (misko): We seem to not have a stack trace here!
if (console.error) {
console.error(e, e.stack);
}
else {
// tslint:disable-next-line:no-console
console.log(e, e.stack);
}
throw e;
}
/**
* @param {?} name
* @return {?}
*/
function controllerKey(name) {
return '$' + name + 'Controller';
}
/**
* @param {?} node
* @return {?}
*/
/**
* @param {?} component
* @return {?}
*/
function getComponentName(component) {
// Return the name of the component or the first line of its stringified version.
return ((component)).overriddenName || component.name || component.toString().split('\n')[0];
}
class Deferred {
constructor() {
this.promise = new Promise((res, rej) => {
this.resolve = res;
this.reject = rej;
});
}
}
/**
* @param {?} component
* @return {?} Whether the passed-in component implements the subset of the
* `ControlValueAccessor` interface needed for AngularJS `ng-model`
* compatibility.
*/
function supportsNgModel(component) {
return typeof component.writeValue === 'function' &&
typeof component.registerOnChange === 'function';
}
/**
* Glue the AngularJS `NgModelController` (if it exists) to the component
* (if it implements the needed subset of the `ControlValueAccessor` interface).
* @param {?} ngModel
* @param {?} component
* @return {?}
*/
function hookupNgModel(ngModel, component) {
if (ngModel && supportsNgModel(component)) {
ngModel.$render = () => { component.writeValue(ngModel.$viewValue); };
component.registerOnChange(ngModel.$setViewValue.bind(ngModel));
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const INITIAL_VALUE = {
__UNINITIALIZED__: true
};
class DowngradeComponentAdapter {
/**
* @param {?} id
* @param {?} element
* @param {?} attrs
* @param {?} scope
* @param {?} ngModel
* @param {?} parentInjector
* @param {?} $injector
* @param {?} $compile
* @param {?} $parse
* @param {?} componentFactory
*/
constructor(id, element, attrs, scope, ngModel, parentInjector, $injector, $compile, $parse, componentFactory) {
this.id = id;
this.element = element;
this.attrs = attrs;
this.scope = scope;
this.ngModel = ngModel;
this.parentInjector = parentInjector;
this.$injector = $injector;
this.$compile = $compile;
this.$parse = $parse;
this.componentFactory = componentFactory;
this.inputChangeCount = 0;
this.inputChanges = null;
this.componentRef = null;
this.component = null;
this.changeDetector = null;
this.element[0].id = id;
this.componentScope = scope.$new();
}
/**
* @return {?}
*/
compileContents() {
const /** @type {?} */ compiledProjectableNodes = [];
const /** @type {?} */ projectableNodes = this.groupProjectableNodes();
const /** @type {?} */ linkFns = projectableNodes.map(nodes => this.$compile(nodes));
this.element.empty();
linkFns.forEach(linkFn => {
linkFn(this.scope, (clone) => {
compiledProjectableNodes.push(clone);
this.element.append(clone);
});
});
return compiledProjectableNodes;
}
/**
* @param {?} projectableNodes
* @return {?}
*/
createComponent(projectableNodes) {
const /** @type {?} */ childInjector = ReflectiveInjector.resolveAndCreate([{ provide: $SCOPE, useValue: this.componentScope }], this.parentInjector);
this.componentRef =
this.componentFactory.create(childInjector, projectableNodes, this.element[0]);
this.changeDetector = this.componentRef.changeDetectorRef;
this.component = this.componentRef.instance;
hookupNgModel(this.ngModel, this.component);
}
/**
* @return {?}
*/
setupInputs() {
const /** @type {?} */ attrs = this.attrs;
const /** @type {?} */ inputs = this.componentFactory.inputs || [];
for (let /** @type {?} */ i = 0; i < inputs.length; i++) {
const /** @type {?} */ input = new PropertyBinding(inputs[i].propName, inputs[i].templateName);
let /** @type {?} */ expr = null;
if (attrs.hasOwnProperty(input.attr)) {
const /** @type {?} */ observeFn = (prop => {
let /** @type {?} */ prevValue = INITIAL_VALUE;
return (currValue) => {
if (prevValue === INITIAL_VALUE) {
prevValue = currValue;
}
this.updateInput(prop, prevValue, currValue);
prevValue = currValue;
};
})(input.prop);
attrs.$observe(input.attr, observeFn);
}
else if (attrs.hasOwnProperty(input.bindAttr)) {
expr = ((attrs) /** TODO #9100 */)[input.bindAttr];
}
else if (attrs.hasOwnProperty(input.bracketAttr)) {
expr = ((attrs) /** TODO #9100 */)[input.bracketAttr];
}
else if (attrs.hasOwnProperty(input.bindonAttr)) {
expr = ((attrs) /** TODO #9100 */)[input.bindonAttr];
}
else if (attrs.hasOwnProperty(input.bracketParenAttr)) {
expr = ((attrs) /** TODO #9100 */)[input.bracketParenAttr];
}
if (expr != null) {
const /** @type {?} */ watchFn = (prop => (currValue, prevValue) => this.updateInput(prop, prevValue, currValue))(input.prop);
this.componentScope.$watch(expr, watchFn);
}
}
const /** @type {?} */ prototype = this.componentFactory.componentType.prototype;
if (prototype && ((prototype)).ngOnChanges) {
// Detect: OnChanges interface
this.inputChanges = {};
this.componentScope.$watch(() => this.inputChangeCount, () => {
const /** @type {?} */ inputChanges = this.inputChanges;
this.inputChanges = {};
((this.component)).ngOnChanges(inputChanges);
});
}
this.componentScope.$watch(() => this.changeDetector && this.changeDetector.detectChanges());
}
/**
* @return {?}
*/
setupOutputs() {
const /** @type {?} */ attrs = this.attrs;
const /** @type {?} */ outputs = this.componentFactory.outputs || [];
for (let /** @type {?} */ j = 0; j < outputs.length; j++) {
const /** @type {?} */ output = new PropertyBinding(outputs[j].propName, outputs[j].templateName);
let /** @type {?} */ expr = null;
let /** @type {?} */ assignExpr = false;
const /** @type {?} */ bindonAttr = output.bindonAttr ? output.bindonAttr.substring(0, output.bindonAttr.length - 6) : null;
const /** @type {?} */ bracketParenAttr = output.bracketParenAttr ?
`[(${output.bracketParenAttr.substring(2, output.bracketParenAttr.length - 8)})]` :
null;
if (attrs.hasOwnProperty(output.onAttr)) {
expr = ((attrs) /** TODO #9100 */)[output.onAttr];
}
else if (attrs.hasOwnProperty(output.parenAttr)) {
expr = ((attrs) /** TODO #9100 */)[output.parenAttr];
}
else if (attrs.hasOwnProperty(bindonAttr)) {
expr = ((attrs) /** TODO #9100 */)[bindonAttr];
assignExpr = true;
}
else if (attrs.hasOwnProperty(bracketParenAttr)) {
expr = ((attrs) /** TODO #9100 */)[bracketParenAttr];
assignExpr = true;
}
if (expr != null && assignExpr != null) {
const /** @type {?} */ getter = this.$parse(expr);
const /** @type {?} */ setter = getter.assign;
if (assignExpr && !setter) {
throw new Error(`Expression '${expr}' is not assignable!`);
}
const /** @type {?} */ emitter = (this.component[output.prop]);
if (emitter) {
emitter.subscribe({
next: assignExpr ?
((setter) => (v /** TODO #9100 */) => setter(this.scope, v))(setter) :
((getter) => (v /** TODO #9100 */) => getter(this.scope, { $event: v }))(getter)
});
}
else {
throw new Error(`Missing emitter '${output.prop}' on component '${getComponentName(this.componentFactory.componentType)}'!`);
}
}
}
}
/**
* @return {?}
*/
registerCleanup() {
this.element.bind('$destroy', () => {
this.componentScope.$destroy();
this.componentRef.destroy();
});
}
/**
* @return {?}
*/
getInjector() { return this.componentRef && this.componentRef.injector; }
/**
* @param {?} prop
* @param {?} prevValue
* @param {?} currValue
* @return {?}
*/
updateInput(prop, prevValue, currValue) {
if (this.inputChanges) {
this.inputChangeCount++;
this.inputChanges[prop] = new SimpleChange(prevValue, currValue, prevValue === currValue);
}
this.component[prop] = currValue;
}
/**
* @return {?}
*/
groupProjectableNodes() {
let /** @type {?} */ ngContentSelectors = this.componentFactory.ngContentSelectors;
return groupNodesBySelector(ngContentSelectors, this.element.contents());
}
}
/**
* Group a set of DOM nodes into `ngContent` groups, based on the given content selectors.
* @param {?} ngContentSelectors
* @param {?} nodes
* @return {?}
*/
function groupNodesBySelector(ngContentSelectors, nodes) {
const /** @type {?} */ projectableNodes = [];
let /** @type {?} */ wildcardNgContentIndex;
for (let /** @type {?} */ i = 0, /** @type {?} */ ii = ngContentSelectors.length; i < ii; ++i) {
projectableNodes[i] = [];
}
for (let /** @type {?} */ j = 0, /** @type {?} */ jj = nodes.length; j < jj; ++j) {
const /** @type {?} */ node = nodes[j];
const /** @type {?} */ ngContentIndex = findMatchingNgContentIndex(node, ngContentSelectors);
if (ngContentIndex != null) {
projectableNodes[ngContentIndex].push(node);
}
}
return projectableNodes;
}
/**
* @param {?} element
* @param {?} ngContentSelectors
* @return {?}
*/
function findMatchingNgContentIndex(element, ngContentSelectors) {
const /** @type {?} */ ngContentIndices = [];
let /** @type {?} */ wildcardNgContentIndex;
for (let /** @type {?} */ i = 0; i < ngContentSelectors.length; i++) {
const /** @type {?} */ selector = ngContentSelectors[i];
if (selector === '*') {
wildcardNgContentIndex = i;
}
else {
if (matchesSelector(element, selector)) {
ngContentIndices.push(i);
}
}
}
ngContentIndices.sort();
if (wildcardNgContentIndex !== undefined) {
ngContentIndices.push(wildcardNgContentIndex);
}
return ngContentIndices.length ? ngContentIndices[0] : null;
}
let _matches;
/**
* @param {?} el
* @param {?} selector
* @return {?}
*/
function matchesSelector(el, selector) {
if (!_matches) {
const /** @type {?} */ elProto = (Element.prototype);
_matches = elProto.matches || elProto.matchesSelector || elProto.mozMatchesSelector ||
elProto.msMatchesSelector || elProto.oMatchesSelector || elProto.webkitMatchesSelector;
}
return el.nodeType === Node.ELEMENT_NODE ? _matches.call(el, selector) : false;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
let downgradeCount = 0;
/**
* \@whatItDoes
*
* *Part of the [upgrade/static](/docs/ts/latest/api/#!?query=upgrade%2Fstatic)
* library for hybrid upgrade apps that support AoT compilation*
*
* Allows an Angular component to be used from AngularJS.
*
* \@howToUse
*
* Let's assume that you have an Angular component called `ng2Heroes` that needs
* to be made available in AngularJS templates.
*
* {\@example upgrade/static/ts/module.ts region="ng2-heroes"}
*
* We must create an AngularJS [directive](https://docs.angularjs.org/guide/directive)
* that will make this Angular component available inside AngularJS templates.
* The `downgradeComponent()` function returns a factory function that we
* can use to define the AngularJS directive that wraps the "downgraded" component.
*
* {\@example upgrade/static/ts/module.ts region="ng2-heroes-wrapper"}
*
* \@description
*
* A helper function that returns a factory function to be used for registering an
* AngularJS wrapper directive for "downgrading" an Angular component.
*
* The parameter contains information about the Component that is being downgraded:
*
* * `component: Type<any>`: The type of the Component that will be downgraded
*
* \@experimental
* @param {?} info
* @return {?}
*/
function downgradeComponent(info) {
const /** @type {?} */ idPrefix = `NG2_UPGRADE_${downgradeCount++}_`;
let /** @type {?} */ idCount = 0;
const /** @type {?} */ directiveFactory = function ($compile, $injector, $parse) {
return {
restrict: 'E',
terminal: true,
require: [REQUIRE_INJECTOR, REQUIRE_NG_MODEL],
link: (scope, element, attrs, required) => {
// We might have to compile the contents asynchronously, because this might have been
// triggered by `UpgradeNg1ComponentAdapterBuilder`, before the Angular templates have
// been compiled.
const /** @type {?} */ parentInjector = required[0] || $injector.get(INJECTOR_KEY);
const /** @type {?} */ ngModel = required[1];
const /** @type {?} */ downgradeFn = (injector) => {
const /** @type {?} */ componentFactoryResolver = injector.get(ComponentFactoryResolver);
const /** @type {?} */ componentFactory = componentFactoryResolver.resolveComponentFactory(info.component);
if (!componentFactory) {
throw new Error('Expecting ComponentFactory for: ' + getComponentName(info.component));
}
const /** @type {?} */ id = idPrefix + (idCount++);
const /** @type {?} */ injectorPromise = new ParentInjectorPromise$1(element);
const /** @type {?} */ facade = new DowngradeComponentAdapter(id, element, attrs, scope, ngModel, injector, $injector, $compile, $parse, componentFactory);
const /** @type {?} */ projectableNodes = facade.compileContents();
facade.createComponent(projectableNodes);
facade.setupInputs();
facade.setupOutputs();
facade.registerCleanup();
injectorPromise.resolve(facade.getInjector());
};
if (parentInjector instanceof ParentInjectorPromise$1) {
parentInjector.then(downgradeFn);
}
else {
downgradeFn(parentInjector);
}
}
};
};
// bracket-notation because of closure - see #14441
directiveFactory['$inject'] = [$COMPILE, $INJECTOR, $PARSE];
return directiveFactory;
}
/**
* Synchronous promise-like object to wrap parent injectors,
* to preserve the synchronous nature of Angular 1's $compile.
*/
class ParentInjectorPromise$1 {
/**
* @param {?} element
*/
constructor(element) {
this.element = element;
this.injectorKey = controllerKey(INJECTOR_KEY);
this.callbacks = [];
// Store the promise on the element.
element.data(this.injectorKey, this);
}
/**
* @param {?} callback
* @return {?}
*/
then(callback) {
if (this.injector) {
callback(this.injector);
}
else {
this.callbacks.push(callback);
}
}
/**
* @param {?} injector
* @return {?}
*/
resolve(injector) {
this.injector = injector;
// Store the real injector on the element.
this.element.data(this.injectorKey, injector);
// Release the element to prevent memory leaks.
this.element = null;
// Run the queued callbacks.
this.callbacks.forEach(callback => callback(injector));
this.callbacks.length = 0;
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* \@whatItDoes
*
* *Part of the [upgrade/static](/docs/ts/latest/api/#!?query=upgrade%2Fstatic)
* library for hybrid upgrade apps that support AoT compilation*
*
* Allow an Angular service to be accessible from AngularJS.
*
* \@howToUse
*
* First ensure that the service to be downgraded is provided in an {\@link NgModule}
* that will be part of the upgrade application. For example, let's assume we have
* defined `HeroesService`
*
* {\@example upgrade/static/ts/module.ts region="ng2-heroes-service"}
*
* and that we have included this in our upgrade app {\@link NgModule}
*
* {\@example upgrade/static/ts/module.ts region="ng2-module"}
*
* Now we can register the `downgradeInjectable` factory function for the service
* on an AngularJS module.
*
* {\@example upgrade/static/ts/module.ts region="downgrade-ng2-heroes-service"}
*
* Inside an AngularJS component's controller we can get hold of the
* downgraded service via the name we gave when downgrading.
*
* {\@example upgrade/static/ts/module.ts region="example-app"}
*
* \@description
*
* Takes a `token` that identifies a service provided from Angular.
*
* Returns a [factory function](https://docs.angularjs.org/guide/di) that can be
* used to register the service on an AngularJS module.
*
* The factory function provides access to the Angular service that
* is identified by the `token` parameter.
*
* \@experimental
* @param {?} token
* @return {?}
*/
function downgradeInjectable(token) {
const /** @type {?} */ factory = function (i) { return i.get(token); };
((factory)).$inject = [INJECTOR_KEY];
return factory;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const CAMEL_CASE = /([A-Z])/g;
const INITIAL_VALUE$1 = {
__UNINITIALIZED__: true
};
const NOT_SUPPORTED = 'NOT_SUPPORTED';
class UpgradeNg1ComponentAdapterBuilder {
/**
* @param {?} name
*/
constructor(name) {
this.name = name;
this.inputs = [];
this.inputsRename = [];
this.outputs = [];
this.outputsRename = [];
this.propertyOutputs = [];
this.checkProperties = [];
this.propertyMap = {};
this.linkFn = null;
this.directive = null;
this.$controller = null;
const selector = name.replace(CAMEL_CASE, (all /** TODO #9100 */, next) => '-' + next.toLowerCase());
const self = this;
this.type =
Directive({ selector: selector, inputs: this.inputsRename, outputs: this.outputsRename })
.Class({
constructor: [
new Inject($SCOPE), ElementRef,
function (scope, elementRef) {
return new UpgradeNg1ComponentAdapter(self.linkFn, scope, self.directive, elementRef, self.$controller, self.inputs, self.outputs, self.propertyOutputs, self.checkProperties, self.propertyMap);
}
],
ngOnInit: function () { },
ngOnChanges: function () { },
ngDoCheck: function () { },
ngOnDestroy: function () { },
});
}
/**
* @param {?} injector
* @return {?}
*/
extractDirective(injector) {
const /** @type {?} */ directives = injector.get(this.name + 'Directive');
if (directives.length > 1) {
throw new Error('Only support single directive definition for: ' + this.name);
}
const /** @type {?} */ directive = directives[0];
if (directive.replace)
this.notSupported('replace');
if (directive.terminal)
this.notSupported('terminal');
const /** @type {?} */ link = directive.link;
if (typeof link == 'object') {
if (((link)).post)
this.notSupported('link.post');
}
return directive;
}
/**
* @param {?} feature
* @return {?}
*/
notSupported(feature) {
throw new Error(`Upgraded directive '${this.name}' does not support '${feature}'.`);
}
/**
* @return {?}
*/
extractBindings() {
const /** @type {?} */ btcIsObject = typeof this.directive.bindToController === 'object';
if (btcIsObject && Object.keys(this.directive.scope).length) {
throw new Error(`Binding definitions on scope and controller at the same time are not supported.`);
}
const /** @type {?} */ context = (btcIsObject) ? this.directive.bindToController : this.directive.scope;
if (typeof context == 'object') {
for (const /** @type {?} */ name in context) {
if (((context)).hasOwnProperty(name)) {
let /** @type {?} */ localName = context[name];
const /** @type {?} */ type = localName.charAt(0);
const /** @type {?} */ typeOptions = localName.charAt(1);
localName = typeOptions === '?' ? localName.substr(2) : localName.substr(1);
localName = localName || name;
const /** @type {?} */ outputName = 'output_' + name;
const /** @type {?} */ outputNameRename = outputName + ': ' + name;
const /** @type {?} */ outputNameRenameChange = outputName + ': ' + name + 'Change';
const /** @type {?} */ inputName = 'input_' + name;
const /** @type {?} */ inputNameRename = inputName + ': ' + name;
switch (type) {
case '=':
this.propertyOutputs.push(outputName);
this.checkProperties.push(localName);
this.outputs.push(outputName);
this.outputsRename.push(outputNameRenameChange);
this.propertyMap[outputName] = localName;
this.inputs.push(inputName);
this.inputsRename.push(inputNameRename);
this.propertyMap[inputName] = localName;
break;
case '@':
// handle the '<' binding of angular 1.5 components
case '<':
this.inputs.push(inputName);
this.inputsRename.push(inputNameRename);
this.propertyMap[inputName] = localName;
break;
case '&':
this.outputs.push(outputName);
this.outputsRename.push(outputNameRename);
this.propertyMap[outputName] = localName;
break;
default:
let /** @type {?} */ json = JSON.stringify(context);
throw new Error(`Unexpected mapping '${type}' in '${json}' in '${this.name}' directive.`);
}
}
}
}
}
/**
* @param {?} compile
* @param {?} templateCache
* @param {?} httpBackend
* @return {?}
*/
compileTemplate(compile, templateCache, httpBackend) {
if (this.directive.template !== undefined) {
this.linkFn = compileHtml(isFunction(this.directive.template) ? this.directive.template() :
this.directive.template);
}
else if (this.directive.templateUrl) {
const /** @type {?} */ url = isFunction(this.directive.templateUrl) ? this.directive.templateUrl() :
this.directive.templateUrl;
const /** @type {?} */ html = templateCache.get(url);
if (html !== undefined) {
this.linkFn = compileHtml(html);
}
else {
return new Promise((resolve, err) => {
httpBackend('GET', url, null, (status /** TODO #9100 */, response /** TODO #9100 */) => {
if (status == 200) {
resolve(this.linkFn = compileHtml(templateCache.put(url, response)));
}
else {
err(`GET ${url} returned ${status}: ${response}`);
}
});
});
}
}
else {
throw new Error(`Directive '${this.name}' is not a component, it is missing template.`);
}
return null;
/**
* @param {?} html
* @return {?}
*/
function compileHtml(html /** TODO #9100 */) {
const /** @type {?} */ div = document.createElement('div');
div.innerHTML = html;
return compile(div.childNodes);
}
}
/**
* Upgrade ng1 components into Angular.
* @param {?} exportedComponents
* @param {?} injector
* @return {?}
*/
static resolve(exportedComponents, injector) {
const /** @type {?} */ promises = [];
const /** @type {?} */ compile = injector.get($COMPILE);
const /** @type {?} */ templateCache = injector.get($TEMPLATE_CACHE);
const /** @type {?} */ httpBackend = injector.get($HTTP_BACKEND);
const /** @type {?} */ $controller = injector.get($CONTROLLER);
for (const /** @type {?} */ name in exportedComponents) {
if (((exportedComponents)).hasOwnProperty(name)) {
const /** @type {?} */ exportedComponent = exportedComponents[name];
exportedComponent.directive = exportedComponent.extractDirective(injector);
exportedComponent.$controller = $controller;
exportedComponent.extractBindings();
const /** @type {?} */ promise = exportedComponent.compileTemplate(compile, templateCache, httpBackend);
if (promise)
promises.push(promise);
}
}
return Promise.all(promises);
}
}
class UpgradeNg1ComponentAdapter {
/**
* @param {?} linkFn
* @param {?} scope
* @param {?} directive
* @param {?} elementRef
* @param {?} $controller
* @param {?} inputs
* @param {?} outputs
* @param {?} propOuts
* @param {?} checkProperties
* @param {?} propertyMap
*/
constructor(linkFn, scope, directive, elementRef, $controller, inputs, outputs, propOuts, checkProperties, propertyMap) {
this.linkFn = linkFn;
this.directive = directive;
this.$controller = $controller;
this.inputs = inputs;
this.outputs = outputs;
this.propOuts = propOuts;
this.checkProperties = checkProperties;
this.propertyMap = propertyMap;
this.controllerInstance = null;
this.destinationObj = null;
this.checkLastValues = [];
this.$element = null;
this.element = elementRef.nativeElement;
this.componentScope = scope.$new(!!directive.scope);
this.$element = element(this.element);
const controllerType = directive.controller;
if (directive.bindToController && controllerType) {
this.controllerInstance = this.buildController(controllerType);
this.destinationObj = this.controllerInstance;
}
else {
this.destinationObj = this.componentScope;
}
for (let i = 0; i < inputs.length; i++) {
this /** TODO #9100 */[inputs[i]] = null;
}
for (let j = 0; j < outputs.length; j++) {
const emitter = this /** TODO #9100 */[outputs[j]] = new EventEmitter();
this.setComponentProperty(outputs[j], ((emitter /** TODO #9100 */) => (value /** TODO #9100 */) => emitter.emit(value))(emitter));
}
for (let k = 0; k < propOuts.length; k++) {
this /** TODO #9100 */[propOuts[k]] = new EventEmitter();
this.checkLastValues.push(INITIAL_VALUE$1);
}
}
/**
* @return {?}
*/
ngOnInit() {
if (!this.directive.bindToController && this.directive.controller) {
this.controllerInstance = this.buildController(this.directive.controller);
}
if (this.controllerInstance && isFunction(this.controllerInstance.$onInit)) {
this.controllerInstance.$onInit();
}
let /** @type {?} */ link = this.directive.link;
if (typeof link == 'object')
link = ((link)).pre;
if (link) {
const /** @type {?} */ attrs = NOT_SUPPORTED;
const /** @type {?} */ transcludeFn = NOT_SUPPORTED;
const /** @type {?} */ linkController = this.resolveRequired(this.$element, this.directive.require);
((this.directive.link))(this.componentScope, this.$element, attrs, linkController, transcludeFn);
}
const /** @type {?} */ childNodes = [];
let /** @type {?} */ childNode;
while (childNode = this.element.firstChild) {
this.element.removeChild(childNode);
childNodes.push(childNode);
}
this.linkFn(this.componentScope, (clonedElement, scope) => {
for (let /** @type {?} */ i = 0, /** @type {?} */ ii = clonedElement.length; i < ii; i++) {
this.element.appendChild(clonedElement[i]);
}
}, {
parentBoundTranscludeFn: (scope /** TODO #9100 */, cloneAttach /** TODO #9100 */) => { cloneAttach(childNodes); }
});
if (this.controllerInstance && isFunction(this.controllerInstance.$postLink)) {
this.controllerInstance.$postLink();
}
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
const /** @type {?} */ ng1Changes = {};
Object.keys(changes).forEach(name => {
const /** @type {?} */ change = changes[name];
this.setComponentProperty(name, change.currentValue);
ng1Changes[this.propertyMap[name]] = change;
});
if (isFunction(this.destinationObj.$onChanges)) {
this.destinationObj.$onChanges(ng1Changes);
}
}
/**
* @return {?}
*/
ngDoCheck() {
const /** @type {?} */ destinationObj = this.destinationObj;
const /** @type {?} */ lastValues = this.checkLastValues;
const /** @type {?} */ checkProperties = this.checkProperties;
for (let /** @type {?} */ i = 0; i < checkProperties.length; i++) {
const /** @type {?} */ value = destinationObj[checkProperties[i]];
const /** @type {?} */ last = lastValues[i];
if (value !== last) {
if (typeof value == 'number' && isNaN(value) && typeof last == 'number' && isNaN(last)) {
}
else {
const /** @type {?} */ eventEmitter = ((this) /** TODO #9100 */)[this.propOuts[i]];
eventEmitter.emit(lastValues[i] = value);
}
}
}
if (this.controllerInstance && isFunction(this.controllerInstance.$doCheck)) {
this.controllerInstance.$doCheck();
}
}
/**
* @return {?}
*/
ngOnDestroy() {
if (this.controllerInstance && isFunction(this.controllerInstance.$onDestroy)) {
this.controllerInstance.$onDestroy();
}
}
/**
* @param {?} name
* @param {?} value
* @return {?}
*/
setComponentProperty(name, value) {
this.destinationObj[this.propertyMap[name]] = value;
}
/**
* @param {?} controllerType
* @return {?}
*/
buildController(controllerType /** TODO #9100 */) {
const /** @type {?} */ locals = { $scope: this.componentScope, $element: this.$element };
const /** @type {?} */ controller = this.$controller(controllerType, locals, null, this.directive.controllerAs);
this.$element.data(controllerKey(this.directive.name), controller);
return controller;
}
/**
* @param {?} $element
* @param {?} require
* @return {?}
*/
resolveRequired($element, require) {
if (!require) {
return undefined;
}
else if (typeof require == 'string') {
let /** @type {?} */ name = (require);
let /** @type {?} */ isOptional = false;
let /** @type {?} */ startParent = false;
let /** @type {?} */ searchParents = false;
if (name.charAt(0) == '?') {
isOptional = true;
name = name.substr(1);
}
if (name.charAt(0) == '^') {
searchParents = true;
name = name.substr(1);
}
if (name.charAt(0) == '^') {
startParent = true;
name = name.substr(1);
}
const /** @type {?} */ key = controllerKey(name);
if (startParent)
$element = $element.parent();
const /** @type {?} */ dep = searchParents ? $element.inheritedData(key) : $element.data(key);
if (!dep && !isOptional) {
throw new Error(`Can not locate '${require}' in '${this.directive.name}'.`);
}
return dep;
}
else if (require instanceof Array) {
const /** @type {?} */ deps = [];
for (let /** @type {?} */ i = 0; i < require.length; i++) {
deps.push(this.resolveRequired($element, require[i]));
}
return deps;
}
throw new Error(`Directive '${this.directive.name}' require syntax unrecognized: ${this.directive.require}`);
}
}
/**
* @param {?} value
* @return {?}
*/
function isFunction(value) {
return typeof value === 'function';
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
let upgradeCount = 0;
/**
* Use `UpgradeAdapter` to allow AngularJS and Angular to coexist in a single application.
*
* The `UpgradeAdapter` allows:
* 1. creation of Angular component from AngularJS component directive
* (See [UpgradeAdapter#upgradeNg1Component()])
* 2. creation of AngularJS directive from Angular component.
* (See [UpgradeAdapter#downgradeNg2Component()])
* 3. Bootstrapping of a hybrid Angular application which contains both of the frameworks
* coexisting in a single application.
*
* ## Mental Model
*
* When reasoning about how a hybrid application works it is useful to have a mental model which
* describes what is happening and explains what is happening at the lowest level.
*
* 1. There are two independent frameworks running in a single application, each framework treats
* the other as a black box.
* 2. Each DOM element on the page is owned exactly by one framework. Whichever framework
* instantiated the element is the owner. Each framework only updates/interacts with its own
* DOM elements and ignores others.
* 3. AngularJS directives always execute inside AngularJS framework codebase regardless of
* where they are instantiated.
* 4. Angular components always execute inside Angular framework codebase regardless of
* where they are instantiated.
* 5. An AngularJS component can be upgraded to an Angular component. This creates an
* Angular directive, which bootstraps the AngularJS component directive in that location.
* 6. An Angular component can be downgraded to an AngularJS component directive. This creates
* an AngularJS directive, which bootstraps the Angular component in that location.
* 7. Whenever an adapter component is instantiated the host element is owned by the framework
* doing the instantiation. The other framework then instantiates and owns the view for that
* component. This implies that component bindings will always follow the semantics of the
* instantiation framework. The syntax is always that of Angular syntax.
* 8. AngularJS is always bootstrapped first and owns the bottom most view.
* 9. The new application is running in Angular zone, and therefore it no longer needs calls to
* `$apply()`.
*
* ### Example
*
* ```
* const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module), myCompilerOptions);
* const module = angular.module('myExample', []);
* module.directive('ng2Comp', adapter.downgradeNg2Component(Ng2Component));
*
* module.directive('ng1Hello', function() {
* return {
* scope: { title: '=' },
* template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)'
* };
* });
*
*
* \@Component({
* selector: 'ng2-comp',
* inputs: ['name'],
* template: 'ng2[<ng1-hello [title]="name">transclude</ng1-hello>](<ng-content></ng-content>)',
* directives:
* })
* class Ng2Component {
* }
*
* \@NgModule({
* declarations: [Ng2Component, adapter.upgradeNg1Component('ng1Hello')],
* imports: [BrowserModule]
* })
* class MyNg2Module {}
*
*
* document.body.innerHTML = '<ng2-comp name="World">project</ng2-comp>';
*
* adapter.bootstrap(document.body, ['myExample']).ready(function() {
* expect(document.body.textContent).toEqual(
* "ng2[ng1[Hello World!](transclude)](project)");
* });
*
* ```
*
* \@stable
*/
class UpgradeAdapter {
/**
* @param {?} ng2AppModule
* @param {?=} compilerOptions
*/
constructor(ng2AppModule, compilerOptions) {
this.ng2AppModule = ng2AppModule;
this.compilerOptions = compilerOptions;
this.idPrefix = `NG2_UPGRADE_${upgradeCount++}_`;
this.downgradedComponents = [];
/**
* An internal map of ng1 components which need to up upgraded to ng2.
*
* We can't upgrade until injector is instantiated and we can retrieve the component metadata.
* For this reason we keep a list of components to upgrade until ng1 injector is bootstrapped.
*
* \@internal
*/
this.ng1ComponentsToBeUpgraded = {};
this.upgradedProviders = [];
this.moduleRef = null;
if (!ng2AppModule) {
throw new Error('UpgradeAdapter cannot be instantiated without an NgModule of the Angular app.');
}
}
/**
* Allows Angular Component to be used from AngularJS.
*
* Use `downgradeNg2Component` to create an AngularJS Directive Definition Factory from
* Angular Component. The adapter will bootstrap Angular component from within the
* AngularJS template.
*
* ## Mental Model
*
* 1. The component is instantiated by being listed in AngularJS template. This means that the
* host element is controlled by AngularJS, but the component's view will be controlled by
* Angular.
* 2. Even thought the component is instantiated in AngularJS, it will be using Angular
* syntax. This has to be done, this way because we must follow Angular components do not
* declare how the attributes should be interpreted.
* 3. `ng-model` is controlled by AngularJS and communicates with the downgraded Angular component
* by way of the `ControlValueAccessor` interface from \@angular/forms. Only components that
* implement this interface are eligible.
*
* ## Supported Features
*
* - Bindings:
* - Attribute: `<comp name="World">`
* - Interpolation: `<comp greeting="Hello {{name}}!">`
* - Expression: `<comp [name]="username">`
* - Event: `<comp (close)="doSomething()">`
* - ng-model: `<comp ng-model="name">`
* - Content projection: yes
*
* ### Example
*
* ```
* const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module));
* const module = angular.module('myExample', []);
* module.directive('greet', adapter.downgradeNg2Component(Greeter));
*
* \@Component({
* selector: 'greet',
* template: '{{salutation}} {{name}}! - <ng-content></ng-content>'
* })
* class Greeter {
* \@Input() salutation: string;
* \@Input() name: string;
* }
*
* \@NgModule({
* declarations: [Greeter],
* imports: [BrowserModule]
* })
* class MyNg2Module {}
*
* document.body.innerHTML =
* 'ng1 template: <greet salutation="Hello" [name]="world">text</greet>';
*
* adapter.bootstrap(document.body, ['myExample']).ready(function() {
* expect(document.body.textContent).toEqual("ng1 template: Hello world! - text");
* });
* ```
* @param {?} component
* @return {?}
*/
downgradeNg2Component(component) {
this.downgradedComponents.push(component);
return downgradeComponent({ component });
}
/**
* Allows AngularJS Component to be used from Angular.
*
* Use `upgradeNg1Component` to create an Angular component from AngularJS Component
* directive. The adapter will bootstrap AngularJS component from within the Angular
* template.
*
* ## Mental Model
*
* 1. The component is instantiated by being listed in Angular template. This means that the
* host element is controlled by Angular, but the component's view will be controlled by
* AngularJS.
*
* ## Supported Features
*
* - Bindings:
* - Attribute: `<comp name="World">`
* - Interpolation: `<comp greeting="Hello {{name}}!">`
* - Expression: `<comp [name]="username">`
* - Event: `<comp (close)="doSomething()">`
* - Transclusion: yes
* - Only some of the features of
* [Directive Definition Object](https://docs.angularjs.org/api/ng/service/$compile) are
* supported:
* - `compile`: not supported because the host element is owned by Angular, which does
* not allow modifying DOM structure during compilation.
* - `controller`: supported. (NOTE: injection of `$attrs` and `$transclude` is not supported.)
* - `controllerAs`: supported.
* - `bindToController`: supported.
* - `link`: supported. (NOTE: only pre-link function is supported.)
* - `name`: supported.
* - `priority`: ignored.
* - `replace`: not supported.
* - `require`: supported.
* - `restrict`: must be set to 'E'.
* - `scope`: supported.
* - `template`: supported.
* - `templateUrl`: supported.
* - `terminal`: ignored.
* - `transclude`: supported.
*
*
* ### Example
*
* ```
* const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module));
* const module = angular.module('myExample', []);
*
* module.directive('greet', function() {
* return {
* scope: {salutation: '=', name: '=' },
* template: '{{salutation}} {{name}}! - <span ng-transclude></span>'
* };
* });
*
* module.directive('ng2', adapter.downgradeNg2Component(Ng2Component));
*
* \@Component({
* selector: 'ng2',
* template: 'ng2 template: <greet salutation="Hello" [name]="world">text</greet>'
* })
* class Ng2Component {
* }
*
* \@NgModule({
* declarations: [Ng2Component, adapter.upgradeNg1Component('greet')],
* imports: [BrowserModule]
* })
* class MyNg2Module {}
*
* document.body.innerHTML = '<ng2></ng2>';
*
* adapter.bootstrap(document.body, ['myExample']).ready(function() {
* expect(document.body.textContent).toEqual("ng2 template: Hello world! - text");
* });
* ```
* @param {?} name
* @return {?}
*/
upgradeNg1Component(name) {
if (((this.ng1ComponentsToBeUpgraded)).hasOwnProperty(name)) {
return this.ng1ComponentsToBeUpgraded[name].type;
}
else {
return (this.ng1ComponentsToBeUpgraded[name] = new UpgradeNg1ComponentAdapterBuilder(name))
.type;
}
}
/**
* Registers the adapter's AngularJS upgrade module for unit testing in AngularJS.
* Use this instead of `angular.mock.module()` to load the upgrade module into
* the AngularJS testing injector.
*
* ### Example
*
* ```
* const upgradeAdapter = new UpgradeAdapter(MyNg2Module);
*
* // configure the adapter with upgrade/downgrade components and services
* upgradeAdapter.downgradeNg2Component(MyComponent);
*
* let upgradeAdapterRef: UpgradeAdapterRef;
* let $compile, $rootScope;
*
* // We must register the adapter before any calls to `inject()`
* beforeEach(() => {
* upgradeAdapterRef = upgradeAdapter.registerForNg1Tests(['heroApp']);
* });
*
* beforeEach(inject((_$compile_, _$rootScope_) => {
* $compile = _$compile_;
* $rootScope = _$rootScope_;
* }));
*
* it("says hello", (done) => {
* upgradeAdapterRef.ready(() => {
* const element = $compile("<my-component></my-component>")($rootScope);
* $rootScope.$apply();
* expect(element.html()).toContain("Hello World");
* done();
* })
* });
*
* ```
*
* @param {?=} modules any AngularJS modules that the upgrade module should depend upon
* @return {?} an {\@link UpgradeAdapterRef}, which lets you register a `ready()` callback to
* run assertions once the Angular components are ready to test through AngularJS.
*/
registerForNg1Tests(modules) {
const /** @type {?} */ windowNgMock = ((window))['angular'].mock;
if (!windowNgMock || !windowNgMock.module) {
throw new Error('Failed to find \'angular.mock.module\'.');
}
this.declareNg1Module(modules);
windowNgMock.module(this.ng1Module.name);
const /** @type {?} */ upgrade = new UpgradeAdapterRef();
this.ng2BootstrapDeferred.promise.then((ng1Injector) => { ((upgrade))._bootstrapDone(this.moduleRef, ng1Injector); }, onError);
return upgrade;
}
/**
* Bootstrap a hybrid AngularJS / Angular application.
*
* This `bootstrap` method is a direct replacement (takes same arguments) for AngularJS
* [`bootstrap`](https://docs.angularjs.org/api/ng/function/angular.bootstrap) method. Unlike
* AngularJS, this bootstrap is asynchronous.
*
* ### Example
*
* ```
* const adapter = new UpgradeAdapter(MyNg2Module);
* const module = angular.module('myExample', []);
* module.directive('ng2', adapter.downgradeNg2Component(Ng2));
*
* module.directive('ng1', function() {
* return {
* scope: { title: '=' },
* template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)'
* };
* });
*
*
* \@Component({
* selector: 'ng2',
* inputs: ['name'],
* template: 'ng2[<ng1 [title]="name">transclude</ng1>](<ng-content></ng-content>)'
* })
* class Ng2 {
* }
*
* \@NgModule({
* declarations: [Ng2, adapter.upgradeNg1Component('ng1')],
* imports: [BrowserModule]
* })
* class MyNg2Module {}
*
* document.body.innerHTML = '<ng2 name="World">project</ng2>';
*
* adapter.bootstrap(document.body, ['myExample']).ready(function() {
* expect(document.body.textContent).toEqual(
* "ng2[ng1[Hello World!](transclude)](project)");
* });
* ```
* @param {?} element
* @param {?=} modules
* @param {?=} config
* @return {?}
*/
bootstrap(element$$1, modules, config) {
this.declareNg1Module(modules);
const /** @type {?} */ upgrade = new UpgradeAdapterRef();
// Make sure resumeBootstrap() only exists if the current bootstrap is deferred
const /** @type {?} */ windowAngular = ((window) /** TODO #???? */)['angular'];
windowAngular.resumeBootstrap = undefined;
this.ngZone.run(() => { bootstrap(element$$1, [this.ng1Module.name], config); });
const /** @type {?} */ ng1BootstrapPromise = new Promise((resolve) => {
if (windowAngular.resumeBootstrap) {
const /** @type {?} */ originalResumeBootstrap = windowAngular.resumeBootstrap;
windowAngular.resumeBootstrap = function () {
windowAngular.resumeBootstrap = originalResumeBootstrap;
windowAngular.resumeBootstrap.apply(this, arguments);
resolve();
};
}
else {
resolve();
}
});
Promise.all([this.ng2BootstrapDeferred.promise, ng1BootstrapPromise]).then(([ng1Injector]) => {
element(element$$1).data(controllerKey(INJECTOR_KEY), this.moduleRef.injector);
this.moduleRef.injector.get(NgZone).run(() => { ((upgrade))._bootstrapDone(this.moduleRef, ng1Injector); });
}, onError);
return upgrade;
}
/**
* Allows AngularJS service to be accessible from Angular.
*
*
* ### Example
*
* ```
* class Login { ... }
* class Server { ... }
*
* \@Injectable()
* class Example {
* constructor(\@Inject('server') server, login: Login) {
* ...
* }
* }
*
* const module = angular.module('myExample', []);
* module.service('server', Server);
* module.service('login', Login);
*
* const adapter = new UpgradeAdapter(MyNg2Module);
* adapter.upgradeNg1Provider('server');
* adapter.upgradeNg1Provider('login', {asToken: Login});
*
* adapter.bootstrap(document.body, ['myExample']).ready((ref) => {
* const example: Example = ref.ng2Injector.get(Example);
* });
*
* ```
* @param {?} name
* @param {?=} options
* @return {?}
*/
upgradeNg1Provider(name, options) {
const /** @type {?} */ token = options && options.asToken || name;
this.upgradedProviders.push({
provide: token,
useFactory: ($injector) => $injector.get(name),
deps: [$INJECTOR]
});
}
/**
* Allows Angular service to be accessible from AngularJS.
*
*
* ### Example
*
* ```
* class Example {
* }
*
* const adapter = new UpgradeAdapter(MyNg2Module);
*
* const module = angular.module('myExample', []);
* module.factory('example', adapter.downgradeNg2Provider(Example));
*
* adapter.bootstrap(document.body, ['myExample']).ready((ref) => {
* const example: Example = ref.ng1Injector.get('example');
* });
*
* ```
* @param {?} token
* @return {?}
*/
downgradeNg2Provider(token) { return downgradeInjectable(token); }
/**
* Declare the AngularJS upgrade module for this adapter without bootstrapping the whole
* hybrid application.
*
* This method is automatically called by `bootstrap()` and `registerForNg1Tests()`.
*
* @param {?=} modules The AngularJS modules that this upgrade module should depend upon.
* @return {?} The AngularJS upgrade module that is declared by this method
*
* ### Example
*
* ```
* const upgradeAdapter = new UpgradeAdapter(MyNg2Module);
* upgradeAdapter.declareNg1Module(['heroApp']);
* ```
*/
declareNg1Module(modules = []) {
const /** @type {?} */ delayApplyExps = [];
let /** @type {?} */ original$applyFn;
let /** @type {?} */ rootScopePrototype;
let /** @type {?} */ rootScope;
const /** @type {?} */ upgradeAdapter = this;
const /** @type {?} */ ng1Module = this.ng1Module = module$1(this.idPrefix, modules);
const /** @type {?} */ platformRef = platformBrowserDynamic();
this.ngZone = new NgZone({ enableLongStackTrace: Zone.hasOwnProperty('longStackTraceZoneSpec') });
this.ng2BootstrapDeferred = new Deferred();
ng1Module.factory(INJECTOR_KEY, () => this.moduleRef.injector.get(Injector))
.constant(NG_ZONE_KEY, this.ngZone)
.factory(COMPILER_KEY, () => this.moduleRef.injector.get(Compiler))
.config([
'$provide', '$injector',
(provide, ng1Injector) => {
provide.decorator($ROOT_SCOPE, [
'$delegate',
function (rootScopeDelegate) {
// Capture the root apply so that we can delay first call to $apply until we
// bootstrap Angular and then we replay and restore the $apply.
rootScopePrototype = rootScopeDelegate.constructor.prototype;
if (rootScopePrototype.hasOwnProperty('$apply')) {
original$applyFn = rootScopePrototype.$apply;
rootScopePrototype.$apply = (exp) => delayApplyExps.push(exp);
}
else {
throw new Error('Failed to find \'$apply\' on \'$rootScope\'!');
}
return rootScope = rootScopeDelegate;
}
]);
if (ng1Injector.has($$TESTABILITY)) {
provide.decorator($$TESTABILITY, [
'$delegate',
function (testabilityDelegate) {
const /** @type {?} */ originalWhenStable = testabilityDelegate.whenStable;
// Cannot use arrow function below because we need the context
const /** @type {?} */ newWhenStable = function (callback) {
originalWhenStable.call(this, function () {
const /** @type {?} */ ng2Testability = upgradeAdapter.moduleRef.injector.get(Testability);
if (ng2Testability.isStable()) {
callback.apply(this, arguments);
}
else {
ng2Testability.whenStable(newWhenStable.bind(this, callback));
}
});
};
testabilityDelegate.whenStable = newWhenStable;
return testabilityDelegate;
}
]);
}
}
]);
ng1Module.run([
'$injector', '$rootScope',
(ng1Injector, rootScope) => {
UpgradeNg1ComponentAdapterBuilder.resolve(this.ng1ComponentsToBeUpgraded, ng1Injector)
.then(() => {
// At this point we have ng1 injector and we have lifted ng1 components into ng2, we
// now can bootstrap ng2.
const /** @type {?} */ DynamicNgUpgradeModule = NgModule({
providers: [
{ provide: $INJECTOR, useFactory: () => ng1Injector },
{ provide: $COMPILE, useFactory: () => ng1Injector.get($COMPILE) },
this.upgradedProviders
],
imports: [this.ng2AppModule],
entryComponents: this.downgradedComponents
}).Class({
constructor: function DynamicNgUpgradeModule() { },
ngDoBootstrap: function () { }
});
((platformRef))
._bootstrapModuleWithZone(DynamicNgUpgradeModule, this.compilerOptions, this.ngZone)
.then((ref) => {
this.moduleRef = ref;
this.ngZone.run(() => {
if (rootScopePrototype) {
rootScopePrototype.$apply = original$applyFn; // restore original $apply
while (delayApplyExps.length) {
rootScope.$apply(delayApplyExps.shift());
}
rootScopePrototype = null;
}
});
})
.then(() => this.ng2BootstrapDeferred.resolve(ng1Injector), onError)
.then(() => {
let /** @type {?} */ subscription = this.ngZone.onMicrotaskEmpty.subscribe({ next: () => rootScope.$digest() });
rootScope.$on('$destroy', () => { subscription.unsubscribe(); });
});
})
.catch((e) => this.ng2BootstrapDeferred.reject(e));
}
]);
return ng1Module;
}
}
/**
* Use `UpgradeAdapterRef` to control a hybrid AngularJS / Angular application.
*
* \@stable
*/
class UpgradeAdapterRef {
constructor() {
this._readyFn = null;
this.ng1RootScope = null;
this.ng1Injector = null;
this.ng2ModuleRef = null;
this.ng2Injector = null;
}
/**
* @param {?} ngModuleRef
* @param {?} ng1Injector
* @return {?}
*/
_bootstrapDone(ngModuleRef, ng1Injector) {
this.ng2ModuleRef = ngModuleRef;
this.ng2Injector = ngModuleRef.injector;
this.ng1Injector = ng1Injector;
this.ng1RootScope = ng1Injector.get($ROOT_SCOPE);
this._readyFn && this._readyFn(this);
}
/**
* Register a callback function which is notified upon successful hybrid AngularJS / Angular
* application has been bootstrapped.
*
* The `ready` callback function is invoked inside the Angular zone, therefore it does not
* require a call to `$apply()`.
* @param {?} fn
* @return {?}
*/
ready(fn) { this._readyFn = fn; }
/**
* Dispose of running hybrid AngularJS / Angular application.
* @return {?}
*/
dispose() {
this.ng1Injector.get($ROOT_SCOPE).$destroy();
this.ng2ModuleRef.destroy();
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @module
* @description
* Entry point for all public APIs of the upgrade/dynamic package, allowing
* Angular 1 and Angular 2+ to run side by side in the same application.
*/
// This file only re-exports content of the `src` folder. Keep it that way.
/**
* Generated bundle index. Do not edit.
*/
export { VERSION, UpgradeAdapter, UpgradeAdapterRef };
//# sourceMappingURL=upgrade.js.map
| snkrishnan1/PivotGridSample | node_modules/@angular/upgrade/@angular/upgrade.js | JavaScript | mit | 64,081 |
<?php
/**
* @Created By ECMall PhpCacheServer
* @Time:2015-01-23 06:18:10
*/
if(filemtime(__FILE__) + 1800 < time())return false;
return array (
'id' => 5553,
'goods' =>
array (
'goods_id' => '5553',
'store_id' => '132',
'type' => 'material',
'goods_name' => '百枣纲目夹心枣核桃100g',
'description' => '<p style="text-align: center;"><img src="http://wap.bqmart.cn/data/files/store_132/goods_42/201501191027226980.jpg" alt="6956459400622_01.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_43/201501191027236092.jpg" alt="6956459400622_02.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_43/201501191027234428.jpg" alt="6956459400622_03.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_43/201501191027239736.jpg" alt="6956459400622_04.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_43/201501191027232880.jpg" alt="6956459400622_05.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_47/201501191027276363.jpg" alt="6956459400622_06.jpg" /><img src="http://wap.bqmart.cn/data/files/store_132/goods_47/201501191027278226.jpg" alt="6956459400622_07.jpg" /></p>',
'cate_id' => '816',
'cate_name' => '地方特产 山东特产',
'brand' => '百枣纲目',
'spec_qty' => '0',
'spec_name_1' => '',
'spec_name_2' => '',
'if_show' => '1',
'if_seckill' => '0',
'closed' => '0',
'close_reason' => NULL,
'add_time' => '1421605662',
'last_update' => '1421605662',
'default_spec' => '5557',
'default_image' => 'data/files/store_132/goods_20/small_201501191027007132.jpg',
'recommended' => '0',
'cate_id_1' => '815',
'cate_id_2' => '816',
'cate_id_3' => '0',
'cate_id_4' => '0',
'price' => '19.80',
'tags' =>
array (
0 => '百枣纲目 夹心枣核桃',
),
'cuxiao_ids' => NULL,
'from_goods_id' => '0',
'quanzhong' => NULL,
'state' => '1',
'_specs' =>
array (
0 =>
array (
'spec_id' => '5557',
'goods_id' => '5553',
'spec_1' => '',
'spec_2' => '',
'color_rgb' => '',
'price' => '19.80',
'stock' => '1000',
'sku' => '6956459400622',
),
),
'_images' =>
array (
0 =>
array (
'image_id' => '5204',
'goods_id' => '5553',
'image_url' => 'data/files/store_132/goods_20/201501191027007132.jpg',
'thumbnail' => 'data/files/store_132/goods_20/small_201501191027007132.jpg',
'sort_order' => '1',
'file_id' => '21028',
),
1 =>
array (
'image_id' => '5205',
'goods_id' => '5553',
'image_url' => 'data/files/store_132/goods_24/201501191027045479.jpg',
'thumbnail' => 'data/files/store_132/goods_24/small_201501191027045479.jpg',
'sort_order' => '255',
'file_id' => '21027',
),
2 =>
array (
'image_id' => '5206',
'goods_id' => '5553',
'image_url' => 'data/files/store_132/goods_33/201501191027133651.jpg',
'thumbnail' => 'data/files/store_132/goods_33/small_201501191027133651.jpg',
'sort_order' => '255',
'file_id' => '21030',
),
),
'_scates' =>
array (
),
'views' => '1',
'collects' => '0',
'carts' => '0',
'orders' => '0',
'sales' => '0',
'comments' => '0',
'related_info' =>
array (
),
),
'store_data' =>
array (
'store_id' => '132',
'store_name' => '大地锐城店',
'owner_name' => '倍全',
'owner_card' => '370832200104057894',
'region_id' => '2213',
'region_name' => '中国 山东 济南 历下区',
'address' => '',
'zipcode' => '',
'tel' => '15666660007',
'sgrade' => '系统默认',
'apply_remark' => '',
'credit_value' => '0',
'praise_rate' => '0.00',
'domain' => '',
'state' => '1',
'close_reason' => '',
'add_time' => '1418929047',
'end_time' => '0',
'certification' => 'autonym,material',
'sort_order' => '65535',
'recommended' => '0',
'theme' => '',
'store_banner' => NULL,
'store_logo' => 'data/files/store_132/other/store_logo.jpg',
'description' => '',
'image_1' => '',
'image_2' => '',
'image_3' => '',
'im_qq' => '',
'im_ww' => '',
'im_msn' => '',
'hot_search' => '',
'business_scope' => '',
'online_service' =>
array (
),
'hotline' => '',
'pic_slides' => '',
'pic_slides_wap' => '{"1":{"url":"data/files/store_132/pic_slides_wap/pic_slides_wap_1.jpg","link":"http://wap.bqmart.cn/index.php?app=zhuanti&id=7"},"2":{"url":"data/files/store_132/pic_slides_wap/pic_slides_wap_2.jpg","link":"http://wap.bqmart.cn/index.php?keyword= %E6%B4%97%E8%A1%A3%E5%B9%B2%E6%B4%97&app=store&act=search&id=132"},"3":{"url":"data/files/store_132/pic_slides_wap/pic_slides_wap_3.jpg","link":"http://wap.bqmart.cn/index.php?app=search&cate_id=691&id=132"}}',
'enable_groupbuy' => '0',
'enable_radar' => '1',
'waptheme' => '',
'is_open_pay' => '0',
'area_peisong' => NULL,
'power_coupon' => '0',
's_long' => '117.096102',
's_lat' => '36.68974',
'user_name' => 'bq516',
'email' => '111111111@qq.com',
'certifications' =>
array (
0 => 'autonym',
1 => 'material',
),
'credit_image' => 'http://wap.bqmart.cn/themes/store/default/styles/default/images/heart_1.gif',
'store_owner' =>
array (
'user_id' => '132',
'user_name' => 'bq516',
'email' => '111111111@qq.com',
'password' => '9cbf8a4dcb8e30682b927f352d6559a0',
'real_name' => '新生活家园',
'gender' => '0',
'birthday' => '',
'phone_tel' => NULL,
'phone_mob' => NULL,
'im_qq' => '',
'im_msn' => '',
'im_skype' => NULL,
'im_yahoo' => NULL,
'im_aliww' => NULL,
'reg_time' => '1418928900',
'last_login' => '1421874055',
'last_ip' => '123.233.201.48',
'logins' => '136',
'ugrade' => '0',
'portrait' => NULL,
'outer_id' => '0',
'activation' => NULL,
'feed_config' => NULL,
'uin' => '0',
'parentid' => '0',
'user_level' => '0',
'from_weixin' => '0',
'wx_openid' => NULL,
'wx_nickname' => NULL,
'wx_city' => NULL,
'wx_country' => NULL,
'wx_province' => NULL,
'wx_language' => NULL,
'wx_headimgurl' => NULL,
'wx_subscribe_time' => '0',
'wx_id' => '0',
'from_public' => '0',
'm_storeid' => '0',
),
'store_navs' =>
array (
),
'kmenus' => false,
'kmenusinfo' =>
array (
),
'radio_new' => 1,
'radio_recommend' => 1,
'radio_hot' => 1,
'goods_count' => '1106',
'store_gcates' =>
array (
),
'functions' =>
array (
'editor_multimedia' => 'editor_multimedia',
'coupon' => 'coupon',
'groupbuy' => 'groupbuy',
'enable_radar' => 'enable_radar',
'seckill' => 'seckill',
),
'hot_saleslist' =>
array (
3043 =>
array (
'goods_id' => '3043',
'goods_name' => '黑牛高钙豆奶粉480g',
'default_image' => 'data/files/store_132/goods_19/small_201412171103393194.gif',
'price' => '15.80',
'sales' => '7',
),
3459 =>
array (
'goods_id' => '3459',
'goods_name' => '七度空间纯棉表层透气夜用超薄卫生巾10片状',
'default_image' => 'data/files/store_132/goods_110/small_201412180915101043.jpg',
'price' => '9.60',
'sales' => '7',
),
3650 =>
array (
'goods_id' => '3650',
'goods_name' => '美汁源果粒橙450ml果汁',
'default_image' => 'data/files/store_132/goods_5/small_201412181056459752.jpg',
'price' => '3.00',
'sales' => '5',
),
3457 =>
array (
'goods_id' => '3457',
'goods_name' => '心相印红卷纸单包装120g卫生纸',
'default_image' => 'data/files/store_132/goods_71/small_201412180914313610.jpg',
'price' => '2.50',
'sales' => '4',
),
3666 =>
array (
'goods_id' => '3666',
'goods_name' => '乐百氏脉动水蜜桃600ml',
'default_image' => 'data/files/store_132/goods_101/small_201412181105019926.jpg',
'price' => '4.00',
'sales' => '3',
),
3660 =>
array (
'goods_id' => '3660',
'goods_name' => '雪碧清爽柠檬味汽水330ml',
'default_image' => 'data/files/store_132/goods_150/small_201412181102308979.jpg',
'price' => '2.00',
'sales' => '1',
),
3230 =>
array (
'goods_id' => '3230',
'goods_name' => '圣牧全程有机奶1X12X250ml',
'default_image' => 'data/files/store_132/goods_69/small_201412171617496624.jpg',
'price' => '98.00',
'sales' => '1',
),
3708 =>
array (
'goods_id' => '3708',
'goods_name' => '怡泉+c500ml功能饮料',
'default_image' => 'data/files/store_132/goods_115/small_201412181125154319.jpg',
'price' => '4.00',
'sales' => '1',
),
4012 =>
array (
'goods_id' => '4012',
'goods_name' => '【39元区】羊毛外套 羊绒大衣',
'default_image' => 'data/files/store_132/goods_186/small_201501041619467368.jpg',
'price' => '39.00',
'sales' => '1',
),
3464 =>
array (
'goods_id' => '3464',
'goods_name' => '大白兔奶糖114g牛奶糖',
'default_image' => 'data/files/store_132/goods_79/small_201412180917594452.jpg',
'price' => '7.50',
'sales' => '0',
),
),
'collect_goodslist' =>
array (
5494 =>
array (
'goods_id' => '5494',
'goods_name' => '青岛啤酒奥古特500ml',
'default_image' => 'data/files/store_42/goods_0/small_201412181433205122.jpg',
'price' => '9.80',
'collects' => '1',
),
3570 =>
array (
'goods_id' => '3570',
'goods_name' => '康师傅蜂蜜绿茶490ml',
'default_image' => 'data/files/store_132/goods_10/small_201412181016503047.jpg',
'price' => '3.00',
'collects' => '1',
),
3777 =>
array (
'goods_id' => '3777',
'goods_name' => '海天苹果醋450ml',
'default_image' => 'data/files/store_132/goods_47/small_201412181157271271.jpg',
'price' => '6.50',
'collects' => '1',
),
3871 =>
array (
'goods_id' => '3871',
'goods_name' => '品食客手抓饼葱香味400g速冻食品',
'default_image' => 'data/files/store_132/goods_103/small_201412181421434694.jpg',
'price' => '11.80',
'collects' => '1',
),
3457 =>
array (
'goods_id' => '3457',
'goods_name' => '心相印红卷纸单包装120g卫生纸',
'default_image' => 'data/files/store_132/goods_71/small_201412180914313610.jpg',
'price' => '2.50',
'collects' => '1',
),
3043 =>
array (
'goods_id' => '3043',
'goods_name' => '黑牛高钙豆奶粉480g',
'default_image' => 'data/files/store_132/goods_19/small_201412171103393194.gif',
'price' => '15.80',
'collects' => '1',
),
3800 =>
array (
'goods_id' => '3800',
'goods_name' => '蒙牛冠益乳草莓味风味发酵乳450g',
'default_image' => 'data/files/store_132/goods_12/small_201412181310121305.jpg',
'price' => '13.50',
'collects' => '1',
),
3459 =>
array (
'goods_id' => '3459',
'goods_name' => '七度空间纯棉表层透气夜用超薄卫生巾10片状',
'default_image' => 'data/files/store_132/goods_110/small_201412180915101043.jpg',
'price' => '9.60',
'collects' => '1',
),
3130 =>
array (
'goods_id' => '3130',
'goods_name' => '迪士尼巧克力味心宠杯25g',
'default_image' => 'data/files/store_132/goods_110/small_201412171515106856.jpg',
'price' => '2.50',
'collects' => '1',
),
3464 =>
array (
'goods_id' => '3464',
'goods_name' => '大白兔奶糖114g牛奶糖',
'default_image' => 'data/files/store_132/goods_79/small_201412180917594452.jpg',
'price' => '7.50',
'collects' => '0',
),
),
'left_rec_goods' =>
array (
3043 =>
array (
'goods_name' => '黑牛高钙豆奶粉480g',
'default_image' => 'data/files/store_132/goods_19/small_201412171103393194.gif',
'price' => '15.80',
'sales' => '7',
'goods_id' => '3043',
),
3457 =>
array (
'goods_name' => '心相印红卷纸单包装120g卫生纸',
'default_image' => 'data/files/store_132/goods_71/small_201412180914313610.jpg',
'price' => '2.50',
'sales' => '4',
'goods_id' => '3457',
),
3459 =>
array (
'goods_name' => '七度空间纯棉表层透气夜用超薄卫生巾10片状',
'default_image' => 'data/files/store_132/goods_110/small_201412180915101043.jpg',
'price' => '9.60',
'sales' => '7',
'goods_id' => '3459',
),
3570 =>
array (
'goods_name' => '康师傅蜂蜜绿茶490ml',
'default_image' => 'data/files/store_132/goods_10/small_201412181016503047.jpg',
'price' => '3.00',
'sales' => '0',
'goods_id' => '3570',
),
5494 =>
array (
'goods_name' => '青岛啤酒奥古特500ml',
'default_image' => 'data/files/store_42/goods_0/small_201412181433205122.jpg',
'price' => '9.80',
'sales' => '0',
'goods_id' => '5494',
),
),
),
'cur_local' =>
array (
0 =>
array (
'text' => '所有分类',
'url' => 'index.php?app=category',
),
1 =>
array (
'text' => '地方特产',
'url' => 'index.php?app=search&cate_id=815',
),
2 =>
array (
'text' => '山东特产',
'url' => 'index.php?app=search&cate_id=816',
),
3 =>
array (
'text' => '商品详情',
),
),
'share' =>
array (
4 =>
array (
'title' => '开心网',
'link' => 'http://www.kaixin001.com/repaste/share.php?rtitle=%E7%99%BE%E6%9E%A3%E7%BA%B2%E7%9B%AE%E5%A4%B9%E5%BF%83%E6%9E%A3%E6%A0%B8%E6%A1%83100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E&rurl=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D5553',
'type' => 'share',
'sort_order' => 255,
'logo' => 'data/system/kaixin001.gif',
),
3 =>
array (
'title' => 'QQ书签',
'link' => 'http://shuqian.qq.com/post?from=3&title=%E7%99%BE%E6%9E%A3%E7%BA%B2%E7%9B%AE%E5%A4%B9%E5%BF%83%E6%9E%A3%E6%A0%B8%E6%A1%83100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E++++++&uri=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D5553&jumpback=2&noui=1',
'type' => 'collect',
'sort_order' => 255,
'logo' => 'data/system/qqshuqian.gif',
),
2 =>
array (
'title' => '人人网',
'link' => 'http://share.renren.com/share/buttonshare.do?link=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D5553&title=%E7%99%BE%E6%9E%A3%E7%BA%B2%E7%9B%AE%E5%A4%B9%E5%BF%83%E6%9E%A3%E6%A0%B8%E6%A1%83100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E',
'type' => 'share',
'sort_order' => 255,
'logo' => 'data/system/renren.gif',
),
1 =>
array (
'title' => '百度收藏',
'link' => 'http://cang.baidu.com/do/add?it=%E7%99%BE%E6%9E%A3%E7%BA%B2%E7%9B%AE%E5%A4%B9%E5%BF%83%E6%9E%A3%E6%A0%B8%E6%A1%83100g-%E5%BE%AE%E4%BF%A1%E5%95%86%E5%9F%8E++++++&iu=http%3A%2F%2Fwap.bqmart.cn%2Findex.php%3Fapp%3Dgoods%26id%3D5553&fr=ien#nw=1',
'type' => 'collect',
'sort_order' => 255,
'logo' => 'data/system/baidushoucang.gif',
),
),
);
?> | guotao2000/ecmall | temp/caches/0496/d282033c16c05294e665c011f6ecac6d.cache.php | PHP | mit | 16,153 |
__all__ = []
import pkgutil
import inspect
# http://stackoverflow.com/questions/22209564/python-qualified-import-all-in-package
for loader, name, is_pkg in pkgutil.walk_packages(__path__):
module = loader.find_module(name).load_module(name)
for name, value in inspect.getmembers(module):
if name.startswith('__'):
continue
globals()[name] = value
__all__.append(name)
| pawl/CalendarAdmin | application/views/__init__.py | Python | mit | 416 |
/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015-2018 Baldur Karlsson
* Copyright (c) 2014 Crytek
*
* 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.
******************************************************************************/
#include "../gl_driver.h"
#include "3rdparty/tinyfiledialogs/tinyfiledialogs.h"
#include "common/common.h"
#include "strings/string_utils.h"
enum GLbufferbitfield
{
};
DECLARE_REFLECTION_ENUM(GLbufferbitfield);
template <>
std::string DoStringise(const GLbufferbitfield &el)
{
RDCCOMPILE_ASSERT(sizeof(GLbufferbitfield) == sizeof(GLbitfield) &&
sizeof(GLbufferbitfield) == sizeof(uint32_t),
"Fake bitfield enum must be uint32_t sized");
BEGIN_BITFIELD_STRINGISE(GLbufferbitfield);
{
STRINGISE_BITFIELD_BIT(GL_DYNAMIC_STORAGE_BIT);
STRINGISE_BITFIELD_BIT(GL_MAP_READ_BIT);
STRINGISE_BITFIELD_BIT(GL_MAP_WRITE_BIT);
STRINGISE_BITFIELD_BIT(GL_MAP_PERSISTENT_BIT);
STRINGISE_BITFIELD_BIT(GL_MAP_COHERENT_BIT);
STRINGISE_BITFIELD_BIT(GL_CLIENT_STORAGE_BIT);
}
END_BITFIELD_STRINGISE();
}
#pragma region Buffers
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glGenBuffers(SerialiserType &ser, GLsizei n, GLuint *buffers)
{
SERIALISE_ELEMENT(n);
SERIALISE_ELEMENT_LOCAL(buffer, GetResourceManager()->GetID(BufferRes(GetCtx(), *buffers)))
.TypedAs("GLResource");
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
GLuint real = 0;
m_Real.glGenBuffers(1, &real);
GLResource res = BufferRes(GetCtx(), real);
ResourceId live = m_ResourceManager->RegisterResource(res);
GetResourceManager()->AddLiveResource(buffer, res);
AddResource(buffer, ResourceType::Buffer, "Buffer");
m_Buffers[live].resource = res;
m_Buffers[live].curType = eGL_NONE;
m_Buffers[live].creationFlags = BufferCategory::NoFlags;
}
return true;
}
void WrappedOpenGL::glGenBuffers(GLsizei n, GLuint *buffers)
{
SERIALISE_TIME_CALL(m_Real.glGenBuffers(n, buffers));
for(GLsizei i = 0; i < n; i++)
{
GLResource res = BufferRes(GetCtx(), buffers[i]);
ResourceId id = GetResourceManager()->RegisterResource(res);
if(IsCaptureMode(m_State))
{
Chunk *chunk = NULL;
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glGenBuffers(ser, 1, buffers + i);
chunk = scope.Get();
}
GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
RDCASSERT(record);
record->AddChunk(chunk);
}
else
{
GetResourceManager()->AddLiveResource(id, res);
m_Buffers[id].resource = res;
m_Buffers[id].curType = eGL_NONE;
m_Buffers[id].creationFlags = BufferCategory::NoFlags;
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glCreateBuffers(SerialiserType &ser, GLsizei n, GLuint *buffers)
{
SERIALISE_ELEMENT(n);
SERIALISE_ELEMENT_LOCAL(buffer, GetResourceManager()->GetID(BufferRes(GetCtx(), *buffers)))
.TypedAs("GLResource");
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
GLuint real = 0;
m_Real.glCreateBuffers(1, &real);
GLResource res = BufferRes(GetCtx(), real);
ResourceId live = m_ResourceManager->RegisterResource(res);
GetResourceManager()->AddLiveResource(buffer, res);
AddResource(buffer, ResourceType::Buffer, "Buffer");
m_Buffers[live].resource = res;
m_Buffers[live].curType = eGL_NONE;
m_Buffers[live].creationFlags = BufferCategory::NoFlags;
}
return true;
}
void WrappedOpenGL::glCreateBuffers(GLsizei n, GLuint *buffers)
{
SERIALISE_TIME_CALL(m_Real.glCreateBuffers(n, buffers));
for(GLsizei i = 0; i < n; i++)
{
GLResource res = BufferRes(GetCtx(), buffers[i]);
ResourceId id = GetResourceManager()->RegisterResource(res);
if(IsCaptureMode(m_State))
{
Chunk *chunk = NULL;
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glCreateBuffers(ser, 1, buffers + i);
chunk = scope.Get();
}
GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
RDCASSERT(record);
record->AddChunk(chunk);
}
else
{
GetResourceManager()->AddLiveResource(id, res);
m_Buffers[id].resource = res;
m_Buffers[id].curType = eGL_NONE;
m_Buffers[id].creationFlags = BufferCategory::NoFlags;
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glBindBuffer(SerialiserType &ser, GLenum target, GLuint bufferHandle)
{
SERIALISE_ELEMENT(target);
SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle));
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
if(target == eGL_NONE)
{
// ...
}
else if(buffer.name == 0)
{
m_Real.glBindBuffer(target, 0);
}
else
{
// if we're just loading, make sure not to trample state (e.g. element array buffer
// binding in a VAO), since this is just a bind-to-create chunk.
GLuint prevbuf = 0;
if(IsLoading(m_State) && m_CurEventID == 0 && target != eGL_NONE)
m_Real.glGetIntegerv(BufferBinding(target), (GLint *)&prevbuf);
m_Real.glBindBuffer(target, buffer.name);
m_Buffers[GetResourceManager()->GetID(buffer)].curType = target;
m_Buffers[GetResourceManager()->GetID(buffer)].creationFlags |= MakeBufferCategory(target);
if(IsLoading(m_State) && m_CurEventID == 0 && target != eGL_NONE)
m_Real.glBindBuffer(target, prevbuf);
}
AddResourceInitChunk(buffer);
}
return true;
}
void WrappedOpenGL::glBindBuffer(GLenum target, GLuint buffer)
{
SERIALISE_TIME_CALL(m_Real.glBindBuffer(target, buffer));
ContextData &cd = GetCtxData();
size_t idx = BufferIdx(target);
if(IsActiveCapturing(m_State))
{
Chunk *chunk = NULL;
if(buffer == 0)
cd.m_BufferRecord[idx] = NULL;
else
cd.m_BufferRecord[idx] = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer));
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glBindBuffer(ser, target, buffer);
if(cd.m_BufferRecord[idx])
cd.m_BufferRecord[idx]->datatype = target;
chunk = scope.Get();
}
if(buffer)
{
FrameRefType refType = eFrameRef_Read;
// these targets write to the buffer
if(target == eGL_ATOMIC_COUNTER_BUFFER || target == eGL_COPY_WRITE_BUFFER ||
target == eGL_PIXEL_PACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER ||
target == eGL_TRANSFORM_FEEDBACK_BUFFER)
refType = eFrameRef_ReadBeforeWrite;
GetResourceManager()->MarkResourceFrameReferenced(cd.m_BufferRecord[idx]->GetResourceID(),
refType);
}
m_ContextRecord->AddChunk(chunk);
}
if(buffer == 0)
{
cd.m_BufferRecord[idx] = NULL;
return;
}
if(IsCaptureMode(m_State))
{
GLResourceRecord *r = cd.m_BufferRecord[idx] =
GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer));
if(!r)
{
RDCERR("Invalid/unrecognised buffer passed: glBindBuffer(%s, %u)", ToStr(target).c_str(),
buffer);
return;
}
// it's legal to re-type buffers, generate another BindBuffer chunk to rename
if(r->datatype != target)
{
Chunk *chunk = NULL;
r->LockChunks();
for(;;)
{
Chunk *end = r->GetLastChunk();
if(end->GetChunkType<GLChunk>() == GLChunk::glBindBuffer ||
end->GetChunkType<GLChunk>() == GLChunk::glBindBufferARB)
{
SAFE_DELETE(end);
r->PopChunk();
continue;
}
break;
}
r->UnlockChunks();
r->datatype = target;
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glBindBuffer(ser, target, buffer);
chunk = scope.Get();
}
r->AddChunk(chunk);
}
// element array buffer binding is vertex array record state, record there (if we've not just
// stopped)
if(IsBackgroundCapturing(m_State) && target == eGL_ELEMENT_ARRAY_BUFFER &&
RecordUpdateCheck(cd.m_VertexArrayRecord))
{
GLuint vao = cd.m_VertexArrayRecord->Resource.name;
// use glVertexArrayElementBuffer to ensure the vertex array is bound when we bind the
// element buffer
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(GLChunk::glVertexArrayElementBuffer);
Serialise_glVertexArrayElementBuffer(ser, vao, buffer);
cd.m_VertexArrayRecord->AddChunk(scope.Get());
}
// store as transform feedback record state
if(IsBackgroundCapturing(m_State) && target == eGL_TRANSFORM_FEEDBACK_BUFFER &&
RecordUpdateCheck(cd.m_FeedbackRecord))
{
GLuint feedback = cd.m_FeedbackRecord->Resource.name;
// use glTransformFeedbackBufferBase to ensure the feedback object is bound when we bind the
// buffer
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(GLChunk::glTransformFeedbackBufferBase);
Serialise_glTransformFeedbackBufferBase(ser, feedback, 0, buffer);
cd.m_FeedbackRecord->AddChunk(scope.Get());
}
// immediately consider buffers bound to transform feedbacks/SSBOs/atomic counters as dirty
if(target == eGL_TRANSFORM_FEEDBACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER ||
target == eGL_ATOMIC_COUNTER_BUFFER)
{
if(IsBackgroundCapturing(m_State))
GetResourceManager()->MarkDirtyResource(r->GetResourceID());
else
m_MissingTracks.insert(r->GetResourceID());
}
}
else
{
m_Buffers[GetResourceManager()->GetID(BufferRes(GetCtx(), buffer))].curType = target;
m_Buffers[GetResourceManager()->GetID(BufferRes(GetCtx(), buffer))].creationFlags |=
MakeBufferCategory(target);
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glNamedBufferStorageEXT(SerialiserType &ser, GLuint bufferHandle,
GLsizeiptr size, const void *data,
GLbitfield flags)
{
SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle));
SERIALISE_ELEMENT_LOCAL(bytesize, (uint64_t)size);
SERIALISE_ELEMENT_ARRAY(data, bytesize);
if(ser.IsWriting())
{
uint64_t offs = ser.GetWriter()->GetOffset() - bytesize;
RDCASSERT((offs % 64) == 0);
GLResourceRecord *record = GetResourceManager()->GetResourceRecord(buffer);
RDCASSERT(record);
record->SetDataOffset(offs);
}
SERIALISE_ELEMENT_TYPED(GLbufferbitfield, flags);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
// remove persistent flag - we will never persistently map so this is a nice
// hint. It helps especially when self-hosting, as we don't want tons of
// overhead added when we won't use it.
flags &= ~GL_MAP_PERSISTENT_BIT;
// can't have coherent without persistent, so remove as well
flags &= ~GL_MAP_COHERENT_BIT;
m_Real.glNamedBufferStorageEXT(buffer.name, (GLsizeiptr)bytesize, data, flags);
m_Buffers[GetResourceManager()->GetID(buffer)].size = bytesize;
AddResourceInitChunk(buffer);
}
return true;
}
void WrappedOpenGL::Common_glNamedBufferStorageEXT(ResourceId id, GLsizeiptr size, const void *data,
GLbitfield flags)
{
if(IsCaptureMode(m_State))
{
GLResourceRecord *record = GetResourceManager()->GetResourceRecord(id);
RDCASSERTMSG("Couldn't identify object used in function. Unbound or bad GLuint?", record);
if(record == NULL)
return;
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glNamedBufferStorageEXT(ser, record->Resource.name, size, data, flags);
Chunk *chunk = scope.Get();
{
record->AddChunk(chunk);
record->SetDataPtr(chunk->GetData());
record->Length = (int32_t)size;
record->DataInSerialiser = true;
}
// We immediately map the whole range with appropriate flags, to be copied into whenever we
// need to propogate changes. Note: Coherent buffers are not mapped coherent, but this is
// because the user code isn't writing into them anyway and we're inserting invisible sync
// points - so there's no need for it to be coherently mapped (and there's no requirement
// that a buffer declared as coherent must ALWAYS be mapped as coherent).
if(flags & GL_MAP_PERSISTENT_BIT)
{
record->Map.persistentPtr = (byte *)m_Real.glMapNamedBufferRangeEXT(
record->Resource.name, 0, size,
GL_MAP_WRITE_BIT | GL_MAP_FLUSH_EXPLICIT_BIT | GL_MAP_PERSISTENT_BIT);
RDCASSERT(record->Map.persistentPtr);
// persistent maps always need both sets of shadow storage, so allocate up front.
record->AllocShadowStorage(size);
// ensure shadow pointers have up to date data for diffing
memcpy(record->GetShadowPtr(0), data, size);
memcpy(record->GetShadowPtr(1), data, size);
}
}
else
{
m_Buffers[id].size = size;
}
}
void WrappedOpenGL::glNamedBufferStorageEXT(GLuint buffer, GLsizeiptr size, const void *data,
GLbitfield flags)
{
byte *dummy = NULL;
if(IsCaptureMode(m_State) && data == NULL)
{
dummy = new byte[size];
memset(dummy, 0xdd, size);
data = dummy;
}
SERIALISE_TIME_CALL(m_Real.glNamedBufferStorageEXT(buffer, size, data, flags));
Common_glNamedBufferStorageEXT(GetResourceManager()->GetID(BufferRes(GetCtx(), buffer)), size,
data, flags);
SAFE_DELETE_ARRAY(dummy);
}
void WrappedOpenGL::glNamedBufferStorage(GLuint buffer, GLsizeiptr size, const void *data,
GLbitfield flags)
{
// only difference to EXT function is size parameter, so just upcast
glNamedBufferStorageEXT(buffer, size, data, flags);
}
void WrappedOpenGL::glBufferStorage(GLenum target, GLsizeiptr size, const void *data, GLbitfield flags)
{
byte *dummy = NULL;
if(IsCaptureMode(m_State) && data == NULL)
{
dummy = new byte[size];
memset(dummy, 0xdd, size);
data = dummy;
}
SERIALISE_TIME_CALL(m_Real.glBufferStorage(target, size, data, flags));
if(IsCaptureMode(m_State))
Common_glNamedBufferStorageEXT(GetCtxData().m_BufferRecord[BufferIdx(target)]->GetResourceID(),
size, data, flags);
else
RDCERR("Internal buffers should be allocated via dsa interfaces");
SAFE_DELETE_ARRAY(dummy);
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glNamedBufferDataEXT(SerialiserType &ser, GLuint bufferHandle,
GLsizeiptr size, const void *data, GLenum usage)
{
SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle));
SERIALISE_ELEMENT_LOCAL(bytesize, (uint64_t)size);
SERIALISE_ELEMENT_ARRAY(data, bytesize);
if(ser.IsWriting())
{
uint64_t offs = ser.GetWriter()->GetOffset() - bytesize;
RDCASSERT((offs % 64) == 0);
GLResourceRecord *record = GetResourceManager()->GetResourceRecord(buffer);
RDCASSERT(record);
record->SetDataOffset(offs);
}
SERIALISE_ELEMENT(usage);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
m_Real.glNamedBufferDataEXT(buffer.name, (GLsizeiptr)bytesize, data, usage);
m_Buffers[GetResourceManager()->GetID(buffer)].size = bytesize;
AddResourceInitChunk(buffer);
}
return true;
}
void WrappedOpenGL::glNamedBufferDataEXT(GLuint buffer, GLsizeiptr size, const void *data,
GLenum usage)
{
byte *dummy = NULL;
if(IsCaptureMode(m_State) && data == NULL)
{
dummy = new byte[size];
memset(dummy, 0xdd, size);
data = dummy;
}
SERIALISE_TIME_CALL(m_Real.glNamedBufferDataEXT(buffer, size, data, usage));
if(IsCaptureMode(m_State))
{
GLResourceRecord *record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer));
RDCASSERTMSG("Couldn't identify object passed to function. Mismatched or bad GLuint?", record,
buffer);
if(record == NULL)
{
SAFE_DELETE_ARRAY(dummy);
return;
}
// detect buffer orphaning and just update backing store
if(IsBackgroundCapturing(m_State) && record->HasDataPtr() &&
size == (GLsizeiptr)record->Length && usage == record->usage)
{
if(data)
memcpy(record->GetDataPtr(), data, (size_t)size);
else
memset(record->GetDataPtr(), 0xbe, (size_t)size);
SAFE_DELETE_ARRAY(dummy);
return;
}
// if we're recreating the buffer, clear the record and add new chunks. Normally
// we would just mark this record as dirty and pick it up on the capture frame as initial
// data, but we don't support (if it's even possible) querying out size etc.
// we need to add only the chunks required - glGenBuffers, glBindBuffer to current target,
// and this buffer storage. All other chunks have no effect
if(IsBackgroundCapturing(m_State) &&
(record->HasDataPtr() || (record->Length > 0 && size != (GLsizeiptr)record->Length)))
{
// we need to maintain chunk ordering, so fetch the first two chunk IDs.
// We should have at least two by this point - glGenBuffers and whatever gave the record
// a size before.
RDCASSERT(record->NumChunks() >= 2);
// remove all but the first two chunks
while(record->NumChunks() > 2)
{
Chunk *c = record->GetLastChunk();
SAFE_DELETE(c);
record->PopChunk();
}
int32_t id2 = record->GetLastChunkID();
{
Chunk *c = record->GetLastChunk();
SAFE_DELETE(c);
record->PopChunk();
}
int32_t id1 = record->GetLastChunkID();
{
Chunk *c = record->GetLastChunk();
SAFE_DELETE(c);
record->PopChunk();
}
RDCASSERT(!record->HasChunks());
// add glGenBuffers chunk
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(GLChunk::glGenBuffers);
Serialise_glGenBuffers(ser, 1, &buffer);
record->AddChunk(scope.Get(), id1);
}
// add glBindBuffer chunk
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(GLChunk::glBindBuffer);
Serialise_glBindBuffer(ser, record->datatype, buffer);
record->AddChunk(scope.Get(), id2);
}
// we're about to add the buffer data chunk
}
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glNamedBufferDataEXT(ser, buffer, size, data, usage);
Chunk *chunk = scope.Get();
// if we've already created this is a renaming/data updating call. It should go in
// the frame record so we can 'update' the buffer as it goes in the frame.
// if we haven't created the buffer at all, it could be a mid-frame create and we
// should place it in the resource record, to happen before the frame.
if(IsActiveCapturing(m_State) && record->HasDataPtr())
{
// we could perhaps substitute this for a 'fake' glBufferSubData chunk?
m_ContextRecord->AddChunk(chunk);
GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_Write);
}
else
{
record->AddChunk(chunk);
record->SetDataPtr(chunk->GetData());
record->Length = (int32_t)size;
record->usage = usage;
record->DataInSerialiser = true;
}
}
else
{
m_Buffers[GetResourceManager()->GetID(BufferRes(GetCtx(), buffer))].size = size;
}
SAFE_DELETE_ARRAY(dummy);
}
void WrappedOpenGL::glNamedBufferData(GLuint buffer, GLsizeiptr size, const void *data, GLenum usage)
{
// only difference to EXT function is size parameter, so just upcast
glNamedBufferDataEXT(buffer, size, data, usage);
}
void WrappedOpenGL::glBufferData(GLenum target, GLsizeiptr size, const void *data, GLenum usage)
{
byte *dummy = NULL;
if(IsCaptureMode(m_State) && data == NULL)
{
dummy = new byte[size];
memset(dummy, 0xdd, size);
data = dummy;
}
SERIALISE_TIME_CALL(m_Real.glBufferData(target, size, data, usage));
size_t idx = BufferIdx(target);
if(IsCaptureMode(m_State))
{
GLResourceRecord *record = GetCtxData().m_BufferRecord[idx];
RDCASSERTMSG("Couldn't identify implicit object at binding. Mismatched or bad GLuint?", record,
target);
if(record == NULL)
{
SAFE_DELETE_ARRAY(dummy);
return;
}
// detect buffer orphaning and just update backing store
if(IsBackgroundCapturing(m_State) && record->HasDataPtr() &&
size == (GLsizeiptr)record->Length && usage == record->usage)
{
if(data)
memcpy(record->GetDataPtr(), data, (size_t)size);
else
memset(record->GetDataPtr(), 0xbe, (size_t)size);
SAFE_DELETE_ARRAY(dummy);
return;
}
GLuint buffer = record->Resource.name;
// if we're recreating the buffer, clear the record and add new chunks. Normally
// we would just mark this record as dirty and pick it up on the capture frame as initial
// data, but we don't support (if it's even possible) querying out size etc.
// we need to add only the chunks required - glGenBuffers, glBindBuffer to current target,
// and this buffer storage. All other chunks have no effect
if(IsBackgroundCapturing(m_State) &&
(record->HasDataPtr() || (record->Length > 0 && size != (GLsizeiptr)record->Length)))
{
// we need to maintain chunk ordering, so fetch the first two chunk IDs.
// We should have at least two by this point - glGenBuffers and whatever gave the record
// a size before.
RDCASSERT(record->NumChunks() >= 2);
// remove all but the first two chunks
while(record->NumChunks() > 2)
{
Chunk *c = record->GetLastChunk();
SAFE_DELETE(c);
record->PopChunk();
}
int32_t id2 = record->GetLastChunkID();
{
Chunk *c = record->GetLastChunk();
SAFE_DELETE(c);
record->PopChunk();
}
int32_t id1 = record->GetLastChunkID();
{
Chunk *c = record->GetLastChunk();
SAFE_DELETE(c);
record->PopChunk();
}
RDCASSERT(!record->HasChunks());
// add glGenBuffers chunk
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(GLChunk::glGenBuffers);
Serialise_glGenBuffers(ser, 1, &buffer);
record->AddChunk(scope.Get(), id1);
}
// add glBindBuffer chunk
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(GLChunk::glBindBuffer);
Serialise_glBindBuffer(ser, record->datatype, buffer);
record->AddChunk(scope.Get(), id2);
}
// we're about to add the buffer data chunk
}
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glNamedBufferDataEXT(ser, buffer, size, data, usage);
Chunk *chunk = scope.Get();
// if we've already created this is a renaming/data updating call. It should go in
// the frame record so we can 'update' the buffer as it goes in the frame.
// if we haven't created the buffer at all, it could be a mid-frame create and we
// should place it in the resource record, to happen before the frame.
if(IsActiveCapturing(m_State) && record->HasDataPtr())
{
// we could perhaps substitute this for a 'fake' glBufferSubData chunk?
m_ContextRecord->AddChunk(chunk);
GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_Write);
}
else
{
record->AddChunk(chunk);
record->SetDataPtr(chunk->GetData());
record->Length = size;
record->usage = usage;
record->DataInSerialiser = true;
}
}
else
{
RDCERR("Internal buffers should be allocated via dsa interfaces");
}
SAFE_DELETE_ARRAY(dummy);
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glNamedBufferSubDataEXT(SerialiserType &ser, GLuint bufferHandle,
GLintptr offsetPtr, GLsizeiptr size,
const void *data)
{
SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle));
SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr);
SERIALISE_ELEMENT_LOCAL(bytesize, (uint64_t)size);
SERIALISE_ELEMENT_ARRAY(data, bytesize);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
m_Real.glNamedBufferSubDataEXT(buffer.name, (GLintptr)offset, (GLsizeiptr)bytesize, data);
}
return true;
}
void WrappedOpenGL::glNamedBufferSubDataEXT(GLuint buffer, GLintptr offset, GLsizeiptr size,
const void *data)
{
SERIALISE_TIME_CALL(m_Real.glNamedBufferSubDataEXT(buffer, offset, size, data));
if(IsCaptureMode(m_State))
{
GLResourceRecord *record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer));
RDCASSERTMSG("Couldn't identify object passed to function. Mismatched or bad GLuint?", record);
if(record == NULL)
return;
if(m_HighTrafficResources.find(record->GetResourceID()) != m_HighTrafficResources.end() &&
IsBackgroundCapturing(m_State))
return;
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glNamedBufferSubDataEXT(ser, buffer, offset, size, data);
Chunk *chunk = scope.Get();
if(IsActiveCapturing(m_State))
{
m_ContextRecord->AddChunk(chunk);
m_MissingTracks.insert(record->GetResourceID());
GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(),
eFrameRef_ReadBeforeWrite);
}
else
{
record->AddChunk(chunk);
record->UpdateCount++;
if(record->UpdateCount > 10)
{
m_HighTrafficResources.insert(record->GetResourceID());
GetResourceManager()->MarkDirtyResource(record->GetResourceID());
}
}
}
}
void WrappedOpenGL::glNamedBufferSubData(GLuint buffer, GLintptr offset, GLsizeiptr size,
const void *data)
{
// only difference to EXT function is size parameter, so just upcast
glNamedBufferSubDataEXT(buffer, offset, size, data);
}
void WrappedOpenGL::glBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const void *data)
{
SERIALISE_TIME_CALL(m_Real.glBufferSubData(target, offset, size, data));
if(IsCaptureMode(m_State))
{
GLResourceRecord *record = GetCtxData().m_BufferRecord[BufferIdx(target)];
RDCASSERTMSG("Couldn't identify implicit object at binding. Mismatched or bad GLuint?", record,
target);
if(record == NULL)
return;
GLResource res = record->Resource;
if(m_HighTrafficResources.find(record->GetResourceID()) != m_HighTrafficResources.end() &&
IsBackgroundCapturing(m_State))
return;
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glNamedBufferSubDataEXT(ser, res.name, offset, size, data);
Chunk *chunk = scope.Get();
if(IsActiveCapturing(m_State))
{
m_ContextRecord->AddChunk(chunk);
m_MissingTracks.insert(record->GetResourceID());
GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(),
eFrameRef_ReadBeforeWrite);
}
else
{
record->AddChunk(chunk);
record->UpdateCount++;
if(record->UpdateCount > 10)
{
m_HighTrafficResources.insert(record->GetResourceID());
GetResourceManager()->MarkDirtyResource(record->GetResourceID());
}
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glNamedCopyBufferSubDataEXT(SerialiserType &ser,
GLuint readBufferHandle,
GLuint writeBufferHandle,
GLintptr readOffsetPtr,
GLintptr writeOffsetPtr, GLsizeiptr sizePtr)
{
SERIALISE_ELEMENT_LOCAL(readBuffer, BufferRes(GetCtx(), readBufferHandle));
SERIALISE_ELEMENT_LOCAL(writeBuffer, BufferRes(GetCtx(), writeBufferHandle));
SERIALISE_ELEMENT_LOCAL(readOffset, (uint64_t)readOffsetPtr);
SERIALISE_ELEMENT_LOCAL(writeOffset, (uint64_t)writeOffsetPtr);
SERIALISE_ELEMENT_LOCAL(size, (uint64_t)sizePtr);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
m_Real.glNamedCopyBufferSubDataEXT(readBuffer.name, writeBuffer.name, (GLintptr)readOffset,
(GLintptr)writeOffset, (GLsizeiptr)size);
}
return true;
}
void WrappedOpenGL::glNamedCopyBufferSubDataEXT(GLuint readBuffer, GLuint writeBuffer,
GLintptr readOffset, GLintptr writeOffset,
GLsizeiptr size)
{
CoherentMapImplicitBarrier();
SERIALISE_TIME_CALL(
m_Real.glNamedCopyBufferSubDataEXT(readBuffer, writeBuffer, readOffset, writeOffset, size));
if(IsCaptureMode(m_State))
{
GLResourceRecord *readrecord =
GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), readBuffer));
GLResourceRecord *writerecord =
GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), writeBuffer));
RDCASSERT(readrecord && writerecord);
if(m_HighTrafficResources.find(writerecord->GetResourceID()) != m_HighTrafficResources.end() &&
IsBackgroundCapturing(m_State))
return;
if(GetResourceManager()->IsResourceDirty(readrecord->GetResourceID()) &&
IsBackgroundCapturing(m_State))
{
m_HighTrafficResources.insert(writerecord->GetResourceID());
GetResourceManager()->MarkDirtyResource(writerecord->GetResourceID());
return;
}
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glNamedCopyBufferSubDataEXT(ser, readBuffer, writeBuffer, readOffset, writeOffset,
size);
Chunk *chunk = scope.Get();
if(IsActiveCapturing(m_State))
{
m_ContextRecord->AddChunk(chunk);
m_MissingTracks.insert(writerecord->GetResourceID());
GetResourceManager()->MarkResourceFrameReferenced(writerecord->GetResourceID(),
eFrameRef_ReadBeforeWrite);
}
else
{
writerecord->AddChunk(chunk);
writerecord->AddParent(readrecord);
writerecord->UpdateCount++;
if(writerecord->UpdateCount > 60)
{
m_HighTrafficResources.insert(writerecord->GetResourceID());
GetResourceManager()->MarkDirtyResource(writerecord->GetResourceID());
}
}
}
}
void WrappedOpenGL::glCopyNamedBufferSubData(GLuint readBuffer, GLuint writeBuffer,
GLintptr readOffset, GLintptr writeOffset,
GLsizeiptr size)
{
glNamedCopyBufferSubDataEXT(readBuffer, writeBuffer, readOffset, writeOffset, size);
}
void WrappedOpenGL::glCopyBufferSubData(GLenum readTarget, GLenum writeTarget, GLintptr readOffset,
GLintptr writeOffset, GLsizeiptr size)
{
CoherentMapImplicitBarrier();
SERIALISE_TIME_CALL(
m_Real.glCopyBufferSubData(readTarget, writeTarget, readOffset, writeOffset, size));
if(IsCaptureMode(m_State))
{
GLResourceRecord *readrecord = GetCtxData().m_BufferRecord[BufferIdx(readTarget)];
GLResourceRecord *writerecord = GetCtxData().m_BufferRecord[BufferIdx(writeTarget)];
RDCASSERT(readrecord && writerecord);
if(m_HighTrafficResources.find(writerecord->GetResourceID()) != m_HighTrafficResources.end() &&
IsBackgroundCapturing(m_State))
return;
if(GetResourceManager()->IsResourceDirty(readrecord->GetResourceID()) &&
IsBackgroundCapturing(m_State))
{
m_HighTrafficResources.insert(writerecord->GetResourceID());
GetResourceManager()->MarkDirtyResource(writerecord->GetResourceID());
return;
}
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glNamedCopyBufferSubDataEXT(
ser, readrecord->Resource.name, writerecord->Resource.name, readOffset, writeOffset, size);
Chunk *chunk = scope.Get();
if(IsActiveCapturing(m_State))
{
m_ContextRecord->AddChunk(chunk);
m_MissingTracks.insert(writerecord->GetResourceID());
GetResourceManager()->MarkResourceFrameReferenced(writerecord->GetResourceID(),
eFrameRef_ReadBeforeWrite);
}
else
{
writerecord->AddChunk(chunk);
writerecord->AddParent(readrecord);
writerecord->UpdateCount++;
if(writerecord->UpdateCount > 60)
{
m_HighTrafficResources.insert(writerecord->GetResourceID());
GetResourceManager()->MarkDirtyResource(writerecord->GetResourceID());
}
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glBindBufferBase(SerialiserType &ser, GLenum target, GLuint index,
GLuint bufferHandle)
{
SERIALISE_ELEMENT(target);
SERIALISE_ELEMENT(index);
SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle));
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
m_Real.glBindBufferBase(target, index, buffer.name);
AddResourceInitChunk(buffer);
}
return true;
}
void WrappedOpenGL::glBindBufferBase(GLenum target, GLuint index, GLuint buffer)
{
ContextData &cd = GetCtxData();
SERIALISE_TIME_CALL(m_Real.glBindBufferBase(target, index, buffer));
if(IsCaptureMode(m_State))
{
size_t idx = BufferIdx(target);
GLResourceRecord *r = NULL;
if(buffer == 0)
r = cd.m_BufferRecord[idx] = NULL;
else
r = cd.m_BufferRecord[idx] =
GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer));
if(buffer && IsActiveCapturing(m_State))
{
FrameRefType refType = eFrameRef_Read;
// these targets write to the buffer
if(target == eGL_ATOMIC_COUNTER_BUFFER || target == eGL_COPY_WRITE_BUFFER ||
target == eGL_PIXEL_PACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER ||
target == eGL_TRANSFORM_FEEDBACK_BUFFER)
refType = eFrameRef_ReadBeforeWrite;
GetResourceManager()->MarkResourceFrameReferenced(cd.m_BufferRecord[idx]->GetResourceID(),
refType);
}
// it's legal to re-type buffers, generate another BindBuffer chunk to rename
if(r && r->datatype != target)
{
Chunk *chunk = NULL;
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(GLChunk::glBindBuffer);
Serialise_glBindBuffer(ser, target, buffer);
chunk = scope.Get();
}
r->datatype = target;
r->AddChunk(chunk);
}
// store as transform feedback record state
if(IsBackgroundCapturing(m_State) && target == eGL_TRANSFORM_FEEDBACK_BUFFER &&
RecordUpdateCheck(cd.m_FeedbackRecord))
{
GLuint feedback = cd.m_FeedbackRecord->Resource.name;
// use glTransformFeedbackBufferBase to ensure the feedback object is bound when we bind the
// buffer
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(GLChunk::glTransformFeedbackBufferBase);
Serialise_glTransformFeedbackBufferBase(ser, feedback, index, buffer);
cd.m_FeedbackRecord->AddChunk(scope.Get());
}
// immediately consider buffers bound to transform feedbacks/SSBOs/atomic counters as dirty
if(r && (target == eGL_TRANSFORM_FEEDBACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER ||
target == eGL_ATOMIC_COUNTER_BUFFER))
{
if(IsActiveCapturing(m_State))
m_MissingTracks.insert(r->GetResourceID());
else
GetResourceManager()->MarkDirtyResource(BufferRes(GetCtx(), buffer));
}
if(IsActiveCapturing(m_State))
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glBindBufferBase(ser, target, index, buffer);
m_ContextRecord->AddChunk(scope.Get());
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glBindBufferRange(SerialiserType &ser, GLenum target, GLuint index,
GLuint bufferHandle, GLintptr offsetPtr,
GLsizeiptr sizePtr)
{
SERIALISE_ELEMENT(target);
SERIALISE_ELEMENT(index);
SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle));
SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr);
SERIALISE_ELEMENT_LOCAL(size, (uint64_t)sizePtr);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
m_Real.glBindBufferRange(target, index, buffer.name, (GLintptr)offset, (GLsizeiptr)size);
AddResourceInitChunk(buffer);
}
return true;
}
void WrappedOpenGL::glBindBufferRange(GLenum target, GLuint index, GLuint buffer, GLintptr offset,
GLsizeiptr size)
{
ContextData &cd = GetCtxData();
SERIALISE_TIME_CALL(m_Real.glBindBufferRange(target, index, buffer, offset, size));
if(IsCaptureMode(m_State))
{
size_t idx = BufferIdx(target);
GLResourceRecord *r = NULL;
if(buffer == 0)
r = cd.m_BufferRecord[idx] = NULL;
else
r = cd.m_BufferRecord[idx] =
GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer));
if(buffer && IsActiveCapturing(m_State))
{
FrameRefType refType = eFrameRef_Read;
// these targets write to the buffer
if(target == eGL_ATOMIC_COUNTER_BUFFER || target == eGL_COPY_WRITE_BUFFER ||
target == eGL_PIXEL_PACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER ||
target == eGL_TRANSFORM_FEEDBACK_BUFFER)
refType = eFrameRef_ReadBeforeWrite;
GetResourceManager()->MarkResourceFrameReferenced(cd.m_BufferRecord[idx]->GetResourceID(),
refType);
}
// it's legal to re-type buffers, generate another BindBuffer chunk to rename
if(r && r->datatype != target)
{
Chunk *chunk = NULL;
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(GLChunk::glBindBuffer);
Serialise_glBindBuffer(ser, target, buffer);
chunk = scope.Get();
}
r->datatype = target;
r->AddChunk(chunk);
}
// store as transform feedback record state
if(IsBackgroundCapturing(m_State) && target == eGL_TRANSFORM_FEEDBACK_BUFFER &&
RecordUpdateCheck(cd.m_FeedbackRecord))
{
GLuint feedback = cd.m_FeedbackRecord->Resource.name;
// use glTransformFeedbackBufferRange to ensure the feedback object is bound when we bind the
// buffer
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(GLChunk::glTransformFeedbackBufferRange);
Serialise_glTransformFeedbackBufferRange(ser, feedback, index, buffer, offset, (GLsizei)size);
cd.m_FeedbackRecord->AddChunk(scope.Get());
}
// immediately consider buffers bound to transform feedbacks/SSBOs/atomic counters as dirty
if(r && (target == eGL_TRANSFORM_FEEDBACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER ||
target == eGL_ATOMIC_COUNTER_BUFFER))
{
if(IsActiveCapturing(m_State))
m_MissingTracks.insert(r->GetResourceID());
else
GetResourceManager()->MarkDirtyResource(BufferRes(GetCtx(), buffer));
}
if(IsActiveCapturing(m_State))
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glBindBufferRange(ser, target, index, buffer, offset, size);
m_ContextRecord->AddChunk(scope.Get());
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glBindBuffersBase(SerialiserType &ser, GLenum target, GLuint first,
GLsizei count, const GLuint *bufferHandles)
{
SERIALISE_ELEMENT(target);
SERIALISE_ELEMENT(first);
SERIALISE_ELEMENT(count);
// can't serialise arrays of GL handles since they're not wrapped or typed :(.
std::vector<GLResource> buffers;
if(ser.IsWriting())
{
buffers.reserve(count);
for(GLsizei i = 0; i < count; i++)
buffers.push_back(BufferRes(GetCtx(), bufferHandles[i]));
}
SERIALISE_ELEMENT(buffers);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
std::vector<GLuint> bufs;
bufs.reserve(count);
for(GLsizei i = 0; i < count; i++)
{
bufs.push_back(buffers[i].name);
AddResourceInitChunk(buffers[i]);
}
m_Real.glBindBuffersBase(target, first, count, bufs.data());
}
return true;
}
void WrappedOpenGL::glBindBuffersBase(GLenum target, GLuint first, GLsizei count,
const GLuint *buffers)
{
SERIALISE_TIME_CALL(m_Real.glBindBuffersBase(target, first, count, buffers));
if(IsCaptureMode(m_State) && buffers && count > 0)
{
ContextData &cd = GetCtxData();
size_t idx = BufferIdx(target);
GLResourceRecord *r = NULL;
if(buffers[0] == 0)
r = cd.m_BufferRecord[idx] = NULL;
else
r = cd.m_BufferRecord[idx] =
GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffers[0]));
if(IsActiveCapturing(m_State))
{
FrameRefType refType = eFrameRef_Read;
// these targets write to the buffer
if(target == eGL_ATOMIC_COUNTER_BUFFER || target == eGL_COPY_WRITE_BUFFER ||
target == eGL_PIXEL_PACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER ||
target == eGL_TRANSFORM_FEEDBACK_BUFFER)
refType = eFrameRef_ReadBeforeWrite;
for(GLsizei i = 0; i < count; i++)
{
if(buffers[i])
{
ResourceId id = GetResourceManager()->GetID(BufferRes(GetCtx(), buffers[i]));
GetResourceManager()->MarkResourceFrameReferenced(id, eFrameRef_ReadBeforeWrite);
m_MissingTracks.insert(id);
}
}
}
for(int i = 0; i < count; i++)
{
GLResourceRecord *bufrecord =
GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffers[i]));
// it's legal to re-type buffers, generate another BindBuffer chunk to rename
if(bufrecord->datatype != target)
{
Chunk *chunk = NULL;
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(GLChunk::glBindBuffer);
Serialise_glBindBuffer(ser, target, buffers[i]);
chunk = scope.Get();
}
bufrecord->datatype = target;
bufrecord->AddChunk(chunk);
}
}
// store as transform feedback record state
if(IsBackgroundCapturing(m_State) && target == eGL_TRANSFORM_FEEDBACK_BUFFER &&
RecordUpdateCheck(cd.m_FeedbackRecord))
{
GLuint feedback = cd.m_FeedbackRecord->Resource.name;
for(int i = 0; i < count; i++)
{
// use glTransformFeedbackBufferBase to ensure the feedback object is bound when we bind the
// buffer
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(GLChunk::glTransformFeedbackBufferBase);
Serialise_glTransformFeedbackBufferBase(ser, feedback, first + i, buffers[i]);
cd.m_FeedbackRecord->AddChunk(scope.Get());
}
}
// immediately consider buffers bound to transform feedbacks/SSBOs/atomic counters as dirty
if(r && (target == eGL_TRANSFORM_FEEDBACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER ||
target == eGL_ATOMIC_COUNTER_BUFFER))
{
if(IsBackgroundCapturing(m_State))
{
for(int i = 0; i < count; i++)
GetResourceManager()->MarkDirtyResource(BufferRes(GetCtx(), buffers[i]));
}
}
if(IsActiveCapturing(m_State))
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glBindBuffersBase(ser, target, first, count, buffers);
m_ContextRecord->AddChunk(scope.Get());
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glBindBuffersRange(SerialiserType &ser, GLenum target, GLuint first,
GLsizei count, const GLuint *bufferHandles,
const GLintptr *offsetPtrs,
const GLsizeiptr *sizePtrs)
{
// can't serialise arrays of GL handles since they're not wrapped or typed :(.
// Likewise need to upcast the offsets and sizes to 64-bit instead of serialising as-is.
std::vector<GLResource> buffers;
std::vector<uint64_t> offsets;
std::vector<uint64_t> sizes;
if(ser.IsWriting() && bufferHandles)
{
buffers.reserve(count);
for(GLsizei i = 0; i < count; i++)
buffers.push_back(BufferRes(GetCtx(), bufferHandles[i]));
}
if(ser.IsWriting() && offsetPtrs)
{
offsets.reserve(count);
for(GLsizei i = 0; i < count; i++)
offsets.push_back((uint64_t)offsetPtrs[i]);
}
if(ser.IsWriting() && sizePtrs)
{
sizes.reserve(count);
for(GLsizei i = 0; i < count; i++)
sizes.push_back((uint64_t)sizePtrs[i]);
}
SERIALISE_ELEMENT(target);
SERIALISE_ELEMENT(first);
SERIALISE_ELEMENT(count);
SERIALISE_ELEMENT(buffers);
SERIALISE_ELEMENT(offsets);
SERIALISE_ELEMENT(sizes);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
std::vector<GLuint> bufs;
std::vector<GLintptr> offs;
std::vector<GLsizeiptr> sz;
if(!buffers.empty())
{
bufs.reserve(count);
for(GLsizei i = 0; i < count; i++)
{
bufs.push_back(buffers[i].name);
AddResourceInitChunk(buffers[i]);
}
}
if(!offsets.empty())
{
offs.reserve(count);
for(GLsizei i = 0; i < count; i++)
offs.push_back((GLintptr)offsets[i]);
}
if(!sizes.empty())
{
sz.reserve(count);
for(GLsizei i = 0; i < count; i++)
sz.push_back((GLintptr)sizes[i]);
}
m_Real.glBindBuffersRange(target, first, count, bufs.empty() ? NULL : bufs.data(),
offs.empty() ? NULL : offs.data(), sz.empty() ? NULL : sz.data());
}
return true;
}
void WrappedOpenGL::glBindBuffersRange(GLenum target, GLuint first, GLsizei count,
const GLuint *buffers, const GLintptr *offsets,
const GLsizeiptr *sizes)
{
SERIALISE_TIME_CALL(m_Real.glBindBuffersRange(target, first, count, buffers, offsets, sizes));
if(IsCaptureMode(m_State) && buffers && count > 0)
{
ContextData &cd = GetCtxData();
size_t idx = BufferIdx(target);
if(buffers[0] == 0)
cd.m_BufferRecord[idx] = NULL;
else
cd.m_BufferRecord[idx] =
GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffers[0]));
if(IsActiveCapturing(m_State))
{
FrameRefType refType = eFrameRef_Read;
// these targets write to the buffer
if(target == eGL_ATOMIC_COUNTER_BUFFER || target == eGL_COPY_WRITE_BUFFER ||
target == eGL_PIXEL_PACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER ||
target == eGL_TRANSFORM_FEEDBACK_BUFFER)
refType = eFrameRef_ReadBeforeWrite;
for(GLsizei i = 0; i < count; i++)
{
if(buffers[i])
{
ResourceId id = GetResourceManager()->GetID(BufferRes(GetCtx(), buffers[i]));
GetResourceManager()->MarkResourceFrameReferenced(id, eFrameRef_ReadBeforeWrite);
m_MissingTracks.insert(id);
}
}
}
else
{
for(int i = 0; i < count; i++)
{
GLResourceRecord *r =
GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffers[i]));
// it's legal to re-type buffers, generate another BindBuffer chunk to rename
if(r->datatype != target)
{
Chunk *chunk = NULL;
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(GLChunk::glBindBuffer);
Serialise_glBindBuffer(ser, target, buffers[i]);
chunk = scope.Get();
}
r->datatype = target;
r->AddChunk(chunk);
}
}
}
// store as transform feedback record state
if(IsBackgroundCapturing(m_State) && target == eGL_TRANSFORM_FEEDBACK_BUFFER &&
RecordUpdateCheck(cd.m_FeedbackRecord))
{
GLuint feedback = cd.m_FeedbackRecord->Resource.name;
for(int i = 0; i < count; i++)
{
// use glTransformFeedbackBufferRange to ensure the feedback object is bound when we bind
// the buffer
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(GLChunk::glTransformFeedbackBufferRange);
Serialise_glTransformFeedbackBufferRange(ser, feedback, first + i, buffers[i], offsets[i],
(GLsizei)sizes[i]);
cd.m_FeedbackRecord->AddChunk(scope.Get());
}
}
// immediately consider buffers bound to transform feedbacks/SSBOs/atomic counters as dirty
if(target == eGL_TRANSFORM_FEEDBACK_BUFFER || target == eGL_SHADER_STORAGE_BUFFER ||
target == eGL_ATOMIC_COUNTER_BUFFER)
{
if(IsBackgroundCapturing(m_State))
{
for(int i = 0; i < count; i++)
GetResourceManager()->MarkDirtyResource(BufferRes(GetCtx(), buffers[i]));
}
}
if(IsActiveCapturing(m_State))
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glBindBuffersRange(ser, target, first, count, buffers, offsets, sizes);
m_ContextRecord->AddChunk(scope.Get());
}
}
}
void WrappedOpenGL::glInvalidateBufferData(GLuint buffer)
{
m_Real.glInvalidateBufferData(buffer);
if(IsBackgroundCapturing(m_State))
GetResourceManager()->MarkDirtyResource(BufferRes(GetCtx(), buffer));
else
m_MissingTracks.insert(GetResourceManager()->GetID(BufferRes(GetCtx(), buffer)));
}
void WrappedOpenGL::glInvalidateBufferSubData(GLuint buffer, GLintptr offset, GLsizeiptr length)
{
m_Real.glInvalidateBufferSubData(buffer, offset, length);
if(IsBackgroundCapturing(m_State))
GetResourceManager()->MarkDirtyResource(BufferRes(GetCtx(), buffer));
else
m_MissingTracks.insert(GetResourceManager()->GetID(BufferRes(GetCtx(), buffer)));
}
#pragma endregion
#pragma region Mapping
/************************************************************************
*
* Mapping tends to be the most complex/dense bit of the capturing process, as there are a lot of
* carefully considered use cases and edge cases to be aware of.
*
* The primary motivation is, obviously, correctness - where we have to sacrifice performance,
* clarity for correctness, we do. Second to that, we try and keep things simple/clear where the
* performance sacrifice will be minimal, and generally we try to remove overhead entirely for
* high-traffic maps, such that we only step in where necessary.
*
* We'll consider "normal" maps of buffers, and persistent maps, separately. Note that in all cases
* we can guarantee that the buffer being mapped has correctly-sized backing store available,
* created in the glBufferData or glBufferStorage call. We also only need to consider the case of
* glMapNamedBufferRangeEXT, glUnmapNamedBufferEXT and glFlushMappedNamedBufferRange - all other
* entry points are mapped to one of these in a fairly simple fashion.
*
*
* glMapNamedBufferRangeEXT:
*
* For a normal map, we decide to either record/intercept it, or to step out of the way and allow
* the application to map directly to the GL buffer. We can only map directly when idle capturing,
* when capturing a frame we must capture all maps to be correct. Generally we perform a direct map
* either if this resource is being mapped often and we want to remove overhead, or if the map
* interception would be more complex than it's worth.
*
* The first checks are to see if we've already "given up" on a buffer, in which case we map
* directly again.
*
* Next, if the map is for write and the buffer is not invalidated, we also map directly.
* [NB: Since our buffer contents should be perfect at this point, we may not need to worry about
* non-invalidating maps. Potential future improvement.]
*
* At this point, if the map is to be done directly, we pass the parameters onto GL and return
* the result, marking the map with status GLResourceRecord::Mapped_Ignore_Real. Note that this
* means we have no idea what happens with the map, and the buffer contents after that are to us
* undefined.
*
* If not, we will be intercepting the map. If it's read-only this is relatively simple to satisfy,
* as we just need to fetch the current buffer contents and return the appropriately offsetted
* pointer. [NB: Again our buffer contents should still be perfect here, this fetch may be
* redundant.] The map status is recorded as GLResourceRecord::Mapped_Read
*
* At this point we are intercepting a map for write, and it depends on whether or not we are
* capturing a frame or just idle.
*
* If idle the handling is relatively simple, we just offset the pointer and return, marking the
* map as GLResourceRecord::Mapped_Write. Note that here we also increment a counter, and if this
* counter reaches a high enough number (arbitrary limit), we mark the buffer as high-traffic so
* that we'll stop intercepting maps and reduce overhead on this buffer.
*
* If frame capturing it is more complex. The backing store of the buffer must be preserved as it
* will contain the contents at the start of the frame. Instead we allocate two shadow storage
* copies on first use. Shadow storage [1] contains the 'current' contents of the buffer -
* when first allocated, if the map is non-invalidating, it will be filled with the buffer contents
* at that point. If the map is invalidating, it will be reset to 0xcc to help find bugs caused by
* leaving valid data behind in invalidated buffer memory.
*
* Shadow buffer [0] is the buffer that is returned to the user code. Every time it is updated
* with the contents of [1]. This way both buffers are always identical and contain the latest
* buffer contents. These buffers are used later in unmap, but Map() will return the appropriately
* offsetted pointer, and mark the map as GLResourceRecord::Mapped_Write.
*
*
* glUnmapNamedBufferEXT:
*
* The unmap becomes an actual chunk for serialisation when necessary, so we'll discuss the handling
* of the unmap call, and then how it is serialised.
*
* Unmap's handling varies depending on the status of the map, as set above in
* glMapNamedBufferRangeEXT.
*
* GLResourceRecord::Unmapped is an error case, indicating we haven't had a corresponding Map()
* call.
*
* GLResourceRecord::Mapped_Read is a no-op as we can just discard it, the pointer we returned from
* Map() was into our backing store.
*
* GLResourceRecord::Mapped_Ignore_Real is likewise a no-op as the GL pointer was updated directly
* by user code, we weren't involved. However if we are now capturing a frame, it indicates a Map()
* was made before this frame began, so this frame cannot be captured - we will need to try again
* next frame, where a map will not be allowed to go into GLResourceRecord::Mapped_Ignore_Real.
*
* GLResourceRecord::Mapped_Write is the only case that will generate a serialised unmap chunk. If
* we are idle, then all we need to do is map the 'real' GL buffer, copy across our backing store,
* and unmap. We only map the range that was modified. Then everything is complete as the user code
* updated our backing store. If we are capturing a frame, then we go into the serialise function
* and serialise out a chunk.
*
* Finally we set the map status back to GLResourceRecord::Unmapped.
*
* When serialising out a map, we serialise the details of the map (which buffer, offset, length)
* and then for non-invalidating maps of >512 byte buffers we perform a difference compare between
* the two shadow storage buffers that were set up in glMapNamedBufferRangeEXT. We then serialise
* out a buffer of the difference segment, and on replay we map and update this segment of the
* buffer.
*
* The reason for finding the actual difference segment is that many maps will be of a large region
* or even the whole buffer, but only update a small section, perhaps once per drawcall. So
* serialising the entirety of a large buffer many many times can rapidly inflate the size of the
* log. The savings from this can be many GBs as if a 4MB buffer is updated 1000 times, each time
* only updating 1KB, this is a difference between 1MB and 4000MB in written data, most of which is
* redundant in the last case.
*
*
* glFlushMappedNamedBufferRangeEXT:
*
* Now consider the specialisation of the above, for maps that have GL_MAP_FLUSH_EXPLICIT_BIT
* enabled.
*
* For the most part, these maps can be treated very similarly to normal maps, however in the case
* of unmapping we will skip creating an unmap chunk and instead just allow the unmap to be
* discarded. Instead we will serialise out a chunk for each glFlushMappedNamedBufferRangeEXT call.
* We will also include flush explicit maps along with the others that we choose to map directly
* when possible - so if we're capturing idle a flush explicit map will go straight to GL and be
* handled as with GLResourceRecord::Mapped_Ignore_Real above.
*
* For this reason, if a map status is GLResourceRecord::Mapped_Ignore_Real then we simply pass the
* flush range along to real GL. Again if we are capturing a frame now, this map has been 'missed'
* and we must try again next frame to capture. Likewise as with Unmap GLResourceRecord::Unmapped is
* an error, and for flushing we do not need to consider GLResourceRecord::Mapped_Read (it doesn't
* make sense for this case).
*
* So we only serialise out a flush chunk if we are capturing a frame, and the map is correctly
* GLResourceRecord::Mapped_Write. We clamp the flushed range to the size of the map (in case the
* user code didn't do this). Unlike map we do not perform any difference compares, but rely on the
* user to only flush the minimal range, and serialise the entire range out as a buffer. We also
* update the shadow storage buffers so that if the buffer is subsequently mapped without flush
* explicit, we have the 'current' contents to perform accurate compares with.
*
*
*
*
*
* Persistant maps:
*
* The above process handles "normal" maps that happen between other GL commands that use the buffer
* contents. Maps that are persistent need to be handled carefully since there are other knock-ons
* for correctness and proper tracking. They come in two major forms - coherent and non-coherent.
*
* Non-coherent maps are the 'easy' case, and in all cases should be recommended whenever users do
* persistent mapping. Indeed because of the implementation details, coherent maps may come at a
* performance penalty even when RenderDoc is not used and it is simply the user code using GL
* directly.
*
* The important thing is that persistent maps *must always* be intercepted regardless of
* circumstance, as in theory they may never be mapped again. We get hints to help us with these
* maps, as the buffers must have been created with glBufferStorage and must have the matching
* persistent and optionally coherent bits set in the flags bitfield.
*
* Note also that non-coherent maps tend to go hand in hand with flush explicit maps (although this
* is not guaranteed, it is highly likely).
*
* Non-coherent mappable buffers are GL-mapped on creation, and remain GL-mapped until their
* destruction regardless of what user code does. We keep this 'real' GL-mapped buffer around
* permanently but it is never returned to user code. Instead we handle maps otherwise as above
* (taking care to always intercept), and return the user a pointer to our backing store. Then every
* time a map flush happens instead of temporarily mapping and unmapping the GL buffer, we copy into
* the appropriate place in our persistent map pointer. If an unmap happens and the map wasn't
* flush-explicit, we copy the mapped region then. In this way we maintain correctness - the copies
* are "delayed" by the time between user code writing into our memory, and us copying into the real
* memory. However this is valid as it happens synchronously with a flush, unmap or other event and
* by definition non-coherent maps aren't visible to the GPU until after those operations.
*
* There is also the function glMemoryBarrier with bit GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT. This has
* the effect of acting as if all currently persistent-mapped regions were simultaneously flushed.
* This is exactly how we implement it - we store a list of all current user persistent maps and any
* time this bit is passed to glMemoryBarrier, we manually call into
* glFlushMappedNamedBufferRangeEXT() with the appropriate parameters and handling is otherwise
* identical.
*
* The final piece of the puzzle is coherent mapped buffers. Since we must break the coherency
* carefully (see below), we map coherent buffers as non-coherent at creation time, the same as
* above.
*
* To satisfy the demands of being coherent, we need to transparently propogate any changes between
* the user written data and the 'real' memory, without any call to intercept - there would be no
* need to call glMemoryBarrier or glFlushMappedNamedBufferRangeEXT. To do this, we have shadow
* storage allocated as in the "normal" mapping path all the time, and we insert a manual call to
* essentially the same code as glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT) in every
* intercepted function call that could depend on the results of the buffer. We then check if any
* write/change has happened by comparing to the shadow storage, and if so we perform a manual flush
* of that changed region and update the shadow storage for next time.
*
* This "fake coherency" is the reason we can map the buffer as non-coherent, since we will be
* performing copies and flushes manually to emulate the coherency to allow our interception in the
* middle.
*
* By definition, there will be *many* of these places where the buffer results could be used, not
* least any buffer copy, any texture copy (since a texture buffer could be created), any draw or
* dispatch, etc. At each of these points there will be a cost for each coherent map of checking for
* changes and it will scale with the size of the buffers. This is a large performance penalty but
* one that can't be easily avoided. This is another reason why coherent maps should be avoided.
*
* Note that this also involves a behaviour change that affects correctness - a user write to memory
* is not visible as soon as the write happens, but only on the next api point where the write could
* have an effect. In correct code this should not be a problem as relying on any other behaviour
* would be impossible - if you wrote into memory expecting commands in flight to be affected you
* could not ensure correct ordering. However, obvious from that description, this is precisely a
* race condition bug if user code did do that - which means race condition bugs will be hidden by
* the nature of this tracing. This is unavoidable without the extreme performance hit of making all
* coherent maps read-write, and performing a read-back at every sync point to find every change.
* Which by itself may also hide race conditions anyway.
*
*
* Implementation notes:
*
* The record->Map.ptr is the *offsetted* pointer, ie. a pointer to the beginning of the mapped
* region, at record->Map.offset bytes from the start of the buffer.
*
* record->Map.persistentPtr points to the *base* of the buffer, not offsetted by any current map.
*
* Likewise the shadow storage pointers point to the base of a buffer-sized allocation each.
*
************************************************************************/
void *WrappedOpenGL::glMapNamedBufferRangeEXT(GLuint buffer, GLintptr offset, GLsizeiptr length,
GLbitfield access)
{
// see above for high-level explanation of how mapping is handled
if(IsCaptureMode(m_State))
{
GLResourceRecord *record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer));
bool directMap = false;
// first check if we've already given up on these buffers
if(IsBackgroundCapturing(m_State) &&
m_HighTrafficResources.find(record->GetResourceID()) != m_HighTrafficResources.end())
directMap = true;
if(!directMap && IsBackgroundCapturing(m_State) &&
GetResourceManager()->IsResourceDirty(record->GetResourceID()))
directMap = true;
bool invalidateMap = (access & (GL_MAP_INVALIDATE_BUFFER_BIT | GL_MAP_INVALIDATE_RANGE_BIT)) != 0;
bool flushExplicitMap = (access & GL_MAP_FLUSH_EXPLICIT_BIT) != 0;
// if this map is writing and doesn't invalidate, or is flush explicit, map directly
if(!directMap && (!invalidateMap || flushExplicitMap) && (access & GL_MAP_WRITE_BIT) &&
IsBackgroundCapturing(m_State))
directMap = true;
// persistent maps must ALWAYS be intercepted
if((access & GL_MAP_PERSISTENT_BIT) || record->Map.persistentPtr)
directMap = false;
bool verifyWrite = (RenderDoc::Inst().GetCaptureOptions().verifyMapWrites != 0);
// must also intercept to verify writes
if(verifyWrite)
directMap = false;
if(directMap)
{
m_HighTrafficResources.insert(record->GetResourceID());
GetResourceManager()->MarkDirtyResource(record->GetResourceID());
}
record->Map.offset = offset;
record->Map.length = length;
record->Map.access = access;
record->Map.invalidate = invalidateMap;
record->Map.verifyWrite = verifyWrite;
// store a list of all persistent maps, and subset of all coherent maps
if(access & GL_MAP_PERSISTENT_BIT)
{
Atomic::Inc64(&record->Map.persistentMaps);
m_PersistentMaps.insert(record);
if(record->Map.access & GL_MAP_COHERENT_BIT)
m_CoherentMaps.insert(record);
}
// if we're doing a direct map, pass onto GL and return
if(directMap)
{
record->Map.ptr = (byte *)m_Real.glMapNamedBufferRangeEXT(buffer, offset, length, access);
record->Map.status = GLResourceRecord::Mapped_Ignore_Real;
return record->Map.ptr;
}
// only squirrel away read-only maps, read-write can just be treated as write-only
if((access & (GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)) == GL_MAP_READ_BIT)
{
byte *ptr = record->GetDataPtr();
if(record->Map.persistentPtr)
ptr = record->GetShadowPtr(0);
RDCASSERT(ptr);
ptr += offset;
m_Real.glGetNamedBufferSubDataEXT(buffer, offset, length, ptr);
record->Map.ptr = ptr;
record->Map.status = GLResourceRecord::Mapped_Read;
return ptr;
}
// below here, handle write maps to the backing store
byte *ptr = record->GetDataPtr();
RDCASSERT(ptr);
{
// persistent maps get particular handling
if(access & GL_MAP_PERSISTENT_BIT)
{
// persistent pointers are always into the shadow storage, this way we can use the backing
// store for 'initial' buffer contents as with any other buffer. We also need to keep a
// comparison & modified buffer in case the application calls glMemoryBarrier(..) at any
// time.
// if we're invalidating, mark the whole range as 0xcc
if(invalidateMap)
{
memset(record->GetShadowPtr(0) + offset, 0xcc, length);
memset(record->GetShadowPtr(1) + offset, 0xcc, length);
}
record->Map.ptr = ptr = record->GetShadowPtr(0) + offset;
record->Map.status = GLResourceRecord::Mapped_Write;
}
else if(IsActiveCapturing(m_State))
{
byte *shadow = (byte *)record->GetShadowPtr(0);
// if we don't have a shadow pointer, need to allocate & initialise
if(shadow == NULL)
{
GLint buflength;
m_Real.glGetNamedBufferParameterivEXT(buffer, eGL_BUFFER_SIZE, &buflength);
// allocate our shadow storage
record->AllocShadowStorage(buflength);
shadow = (byte *)record->GetShadowPtr(0);
// if we're not invalidating, we need the existing contents
if(!invalidateMap)
{
// need to fetch the whole buffer's contents, not just the mapped range,
// as next time we won't re-fetch and might need the rest of the contents
if(GetResourceManager()->IsResourceDirty(record->GetResourceID()))
{
// Perhaps we could get these contents from the frame initial state buffer?
m_Real.glGetNamedBufferSubDataEXT(buffer, 0, buflength, shadow);
}
else
{
memcpy(shadow, record->GetDataPtr(), buflength);
}
}
// copy into second shadow buffer ready for comparison later
memcpy(record->GetShadowPtr(1), shadow, buflength);
}
// if we're invalidating, mark the whole range as 0xcc
if(invalidateMap)
{
memset(shadow + offset, 0xcc, length);
memset(record->GetShadowPtr(1) + offset, 0xcc, length);
}
record->Map.ptr = ptr = shadow + offset;
record->Map.status = GLResourceRecord::Mapped_Write;
}
else if(IsBackgroundCapturing(m_State))
{
if(verifyWrite)
{
byte *shadow = record->GetShadowPtr(0);
GLint buflength;
m_Real.glGetNamedBufferParameterivEXT(buffer, eGL_BUFFER_SIZE, &buflength);
// if we don't have a shadow pointer, need to allocate & initialise
if(shadow == NULL)
{
// allocate our shadow storage
record->AllocShadowStorage(buflength);
shadow = (byte *)record->GetShadowPtr(0);
}
// if we're not invalidating, we need the existing contents
if(!invalidateMap)
memcpy(shadow, record->GetDataPtr(), buflength);
else
memset(shadow + offset, 0xcc, length);
ptr = shadow;
}
// return buffer backing store pointer, offsetted
ptr += offset;
record->Map.ptr = ptr;
record->Map.status = GLResourceRecord::Mapped_Write;
record->UpdateCount++;
// mark as high-traffic if we update it often enough
if(record->UpdateCount > 60)
{
m_HighTrafficResources.insert(record->GetResourceID());
GetResourceManager()->MarkDirtyResource(record->GetResourceID());
}
}
}
return ptr;
}
return m_Real.glMapNamedBufferRangeEXT(buffer, offset, length, access);
}
void *WrappedOpenGL::glMapNamedBufferRange(GLuint buffer, GLintptr offset, GLsizeiptr length,
GLbitfield access)
{
// only difference to EXT function is size parameter, so just upcast
return glMapNamedBufferRangeEXT(buffer, offset, length, access);
}
void *WrappedOpenGL::glMapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length,
GLbitfield access)
{
// see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled
if(IsCaptureMode(m_State))
{
GLResourceRecord *record = GetCtxData().m_BufferRecord[BufferIdx(target)];
RDCASSERTMSG("Couldn't identify implicit object at binding. Mismatched or bad GLuint?", record,
target);
if(record)
return glMapNamedBufferRangeEXT(record->Resource.name, offset, length, access);
RDCERR("glMapBufferRange: Couldn't get resource record for target %x - no buffer bound?", target);
}
return m_Real.glMapBufferRange(target, offset, length, access);
}
// the glMapBuffer functions are equivalent to glMapBufferRange - so we just pass through
void *WrappedOpenGL::glMapNamedBufferEXT(GLuint buffer, GLenum access)
{
if(IsCaptureMode(m_State))
{
GLResourceRecord *record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer));
RDCASSERTMSG("Couldn't identify object passed to function. Mismatched or bad GLuint?", record,
buffer);
if(record)
{
GLbitfield accessBits = 0;
if(access == eGL_READ_ONLY)
accessBits = eGL_MAP_READ_BIT;
else if(access == eGL_WRITE_ONLY)
accessBits = eGL_MAP_WRITE_BIT;
else if(access == eGL_READ_WRITE)
accessBits = eGL_MAP_READ_BIT | eGL_MAP_WRITE_BIT;
return glMapNamedBufferRangeEXT(record->Resource.name, 0, (GLsizeiptr)record->Length,
accessBits);
}
RDCERR("glMapNamedBufferEXT: Couldn't get resource record for buffer %x!", buffer);
}
return m_Real.glMapNamedBufferEXT(buffer, access);
}
void *WrappedOpenGL::glMapBuffer(GLenum target, GLenum access)
{
// see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled
if(IsCaptureMode(m_State))
{
GLResourceRecord *record = GetCtxData().m_BufferRecord[BufferIdx(target)];
if(record)
{
GLbitfield accessBits = 0;
if(access == eGL_READ_ONLY)
accessBits = eGL_MAP_READ_BIT;
else if(access == eGL_WRITE_ONLY)
accessBits = eGL_MAP_WRITE_BIT;
else if(access == eGL_READ_WRITE)
accessBits = eGL_MAP_READ_BIT | eGL_MAP_WRITE_BIT;
return glMapNamedBufferRangeEXT(record->Resource.name, 0, (GLsizeiptr)record->Length,
accessBits);
}
RDCERR("glMapBuffer: Couldn't get resource record for target %s - no buffer bound?",
ToStr(target).c_str());
}
return m_Real.glMapBuffer(target, access);
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glUnmapNamedBufferEXT(SerialiserType &ser, GLuint bufferHandle)
{
// see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled
GLResourceRecord *record = NULL;
if(ser.IsWriting())
record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), bufferHandle));
SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle));
SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)record->Map.offset);
SERIALISE_ELEMENT_LOCAL(length, (uint64_t)record->Map.length);
uint64_t diffStart = 0;
uint64_t diffEnd = (size_t)length;
byte *MapWrittenData = NULL;
if(ser.IsWriting())
{
MapWrittenData = record->Map.ptr;
if(IsActiveCapturing(m_State) &&
// don't bother checking diff range for tiny buffers
length > 512 &&
// if the map has a sub-range specified, trust the user to have specified
// a minimal range, similar to glFlushMappedBufferRange, so don't find diff
// range.
record->Map.offset == 0 && length == record->Length &&
// similarly for invalidate maps, we want to update the whole buffer
!record->Map.invalidate)
{
size_t s = (size_t)diffStart;
size_t e = (size_t)diffEnd;
bool found =
FindDiffRange(record->Map.ptr, record->GetShadowPtr(1) + offset, (size_t)length, s, e);
diffStart = (uint64_t)s;
diffEnd = (uint64_t)e;
if(found)
{
#if ENABLED(RDOC_DEVEL)
static uint64_t saved = 0;
saved += length - (diffEnd - diffStart);
RDCDEBUG(
"Mapped resource size %llu, difference: %llu -> %llu. Total bytes saved so far: %llu",
length, diffStart, diffEnd, saved);
#endif
length = diffEnd - diffStart;
}
else
{
diffStart = 0;
diffEnd = 0;
length = 1;
}
// update the data pointer to be rebased to the start of the diff data.
MapWrittenData += diffStart;
}
// update shadow stores for future diff'ing
if(IsActiveCapturing(m_State) && record->GetShadowPtr(1))
{
memcpy(record->GetShadowPtr(1) + (size_t)offset + (size_t)diffStart, MapWrittenData,
size_t(diffEnd - diffStart));
}
}
SERIALISE_ELEMENT(diffStart);
SERIALISE_ELEMENT(diffEnd);
SERIALISE_ELEMENT_ARRAY(MapWrittenData, length);
SERIALISE_CHECK_READ_ERRORS();
if(!IsStructuredExporting(m_State) && diffEnd > diffStart)
{
if(record && record->Map.persistentPtr)
{
// if we have a persistent mapped pointer, copy the range into the 'real' memory and
// do a flush. Note the persistent pointer is always to the base of the buffer so we
// need to account for the offset
memcpy(record->Map.persistentPtr + (size_t)offset + (size_t)diffStart,
record->Map.ptr + (size_t)diffStart, size_t(diffEnd - diffStart));
m_Real.glFlushMappedNamedBufferRangeEXT(buffer.name, GLintptr(offset + diffStart),
GLsizeiptr(diffEnd - diffStart));
}
else if(MapWrittenData && length > 0)
{
void *ptr = m_Real.glMapNamedBufferRangeEXT(buffer.name, (GLintptr)(offset + diffStart),
GLsizeiptr(diffEnd - diffStart), GL_MAP_WRITE_BIT);
memcpy(ptr, MapWrittenData, size_t(diffEnd - diffStart));
m_Real.glUnmapNamedBufferEXT(buffer.name);
}
}
return true;
}
GLboolean WrappedOpenGL::glUnmapNamedBufferEXT(GLuint buffer)
{
// see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled
if(IsCaptureMode(m_State))
{
GLResourceRecord *record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer));
auto status = record->Map.status;
if(IsActiveCapturing(m_State))
{
m_MissingTracks.insert(record->GetResourceID());
GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(),
eFrameRef_ReadBeforeWrite);
}
GLboolean ret = GL_TRUE;
switch(status)
{
case GLResourceRecord::Unmapped:
RDCERR("Unmapped buffer being passed to glUnmapBuffer");
break;
case GLResourceRecord::Mapped_Read:
// can ignore
break;
case GLResourceRecord::Mapped_Ignore_Real:
if(IsActiveCapturing(m_State))
{
RDCERR(
"Failed to cap frame - we saw an Unmap() that we didn't capture the corresponding "
"Map() for");
m_SuccessfulCapture = false;
m_FailureReason = CaptureFailed_UncappedUnmap;
}
// need to do the real unmap
ret = m_Real.glUnmapNamedBufferEXT(buffer);
break;
case GLResourceRecord::Mapped_Write:
{
if(record->Map.verifyWrite)
{
if(!record->VerifyShadowStorage())
{
string msg = StringFormat::Fmt(
"Overwrite of %llu byte Map()'d buffer detected\n"
"Breakpoint now to see callstack,\nor click 'Yes' to debugbreak.",
record->Length);
int res =
tinyfd_messageBox("Map() overwrite detected!", msg.c_str(), "yesno", "error", 1);
if(res == 1)
{
OS_DEBUG_BREAK();
}
}
// copy from shadow to backing store, so we're consistent
memcpy(record->GetDataPtr() + record->Map.offset, record->Map.ptr, record->Map.length);
}
if(record->Map.access & GL_MAP_FLUSH_EXPLICIT_BIT)
{
// do nothing, any flushes that happened were handled,
// and we won't do any other updates here or make a chunk.
}
else if(IsActiveCapturing(m_State))
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glUnmapNamedBufferEXT(ser, buffer);
m_ContextRecord->AddChunk(scope.Get());
}
else if(IsBackgroundCapturing(m_State))
{
if(record->Map.persistentPtr)
{
// if we have a persistent mapped pointer, copy the range into the 'real' memory and
// do a flush. Note the persistent pointer is always to the base of the buffer so we
// need to account for the offset
memcpy(record->Map.persistentPtr + record->Map.offset, record->Map.ptr,
record->Map.length);
m_Real.glFlushMappedNamedBufferRangeEXT(buffer, record->Map.offset, record->Map.length);
// update shadow storage
memcpy(record->GetShadowPtr(1) + record->Map.offset, record->Map.ptr, record->Map.length);
GetResourceManager()->MarkDirtyResource(record->GetResourceID());
}
else
{
// if we are here for background capturing, the app wrote directly into our backing
// store memory. Just need to copy the data across to GL, no other work needed
void *ptr =
m_Real.glMapNamedBufferRangeEXT(buffer, (GLintptr)record->Map.offset,
GLsizeiptr(record->Map.length), GL_MAP_WRITE_BIT);
memcpy(ptr, record->Map.ptr, record->Map.length);
m_Real.glUnmapNamedBufferEXT(buffer);
}
}
break;
}
}
// keep list of persistent & coherent maps up to date if we've
// made the last unmap to a buffer
if(record->Map.access & GL_MAP_PERSISTENT_BIT)
{
int64_t ref = Atomic::Dec64(&record->Map.persistentMaps);
if(ref == 0)
{
m_PersistentMaps.erase(record);
if(record->Map.access & GL_MAP_COHERENT_BIT)
m_CoherentMaps.erase(record);
}
}
record->Map.status = GLResourceRecord::Unmapped;
return ret;
}
return m_Real.glUnmapNamedBufferEXT(buffer);
}
GLboolean WrappedOpenGL::glUnmapBuffer(GLenum target)
{
// see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled
if(IsCaptureMode(m_State))
{
GLResourceRecord *record = GetCtxData().m_BufferRecord[BufferIdx(target)];
if(record)
return glUnmapNamedBufferEXT(record->Resource.name);
RDCERR("glUnmapBuffer: Couldn't get resource record for target %s - no buffer bound?",
ToStr(target).c_str());
}
return m_Real.glUnmapBuffer(target);
}
// offsetPtr here is from the start of the buffer, not the mapped region
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glFlushMappedNamedBufferRangeEXT(SerialiserType &ser,
GLuint bufferHandle,
GLintptr offsetPtr,
GLsizeiptr lengthPtr)
{
// see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled
SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle));
SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr);
SERIALISE_ELEMENT_LOCAL(length, (uint64_t)lengthPtr);
GLResourceRecord *record = NULL;
byte *FlushedData = NULL;
if(ser.IsWriting())
{
record = GetResourceManager()->GetResourceRecord(buffer);
FlushedData = record->Map.ptr + offset - record->Map.offset;
// update the comparison buffer in case this buffer is subsequently mapped and we want to find
// the difference region
if(IsActiveCapturing(m_State) && record->GetShadowPtr(1))
{
memcpy(record->GetShadowPtr(1) + (size_t)offset, FlushedData, (size_t)length);
}
}
SERIALISE_ELEMENT_ARRAY(FlushedData, length);
SERIALISE_CHECK_READ_ERRORS();
if(record && record->Map.persistentPtr)
{
// if we have a persistent mapped pointer, copy the range into the 'real' memory and
// do a flush. Note the persistent pointer is always to the base of the buffer so we
// need to account for the offset
memcpy(record->Map.persistentPtr + (size_t)offset,
record->Map.ptr + (size_t)(offset - record->Map.offset), (size_t)length);
m_Real.glFlushMappedNamedBufferRangeEXT(buffer.name, (GLintptr)offset, (GLsizeiptr)length);
}
else if(buffer.name && FlushedData && length > 0)
{
// perform a map of the range and copy the data, to emulate the modified region being flushed
void *ptr = m_Real.glMapNamedBufferRangeEXT(buffer.name, (GLintptr)offset, (GLsizeiptr)length,
GL_MAP_WRITE_BIT);
memcpy(ptr, FlushedData, (size_t)length);
m_Real.glUnmapNamedBufferEXT(buffer.name);
}
return true;
}
void WrappedOpenGL::glFlushMappedNamedBufferRangeEXT(GLuint buffer, GLintptr offset, GLsizeiptr length)
{
// see above glMapNamedBufferRangeEXT for high-level explanation of how mapping is handled
GLResourceRecord *record = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer));
RDCASSERTMSG("Couldn't identify object passed to function. Mismatched or bad GLuint?", record,
buffer);
// only need to pay attention to flushes when in capframe. Otherwise (see above) we
// treat the map as a normal map, and let ALL modified regions go through, flushed or not,
// as this is legal - modified but unflushed regions are 'undefined' so we can just say
// that modifications applying is our undefined behaviour.
// note that we only want to flush the range with GL if we've actually
// mapped it. Otherwise the map is 'virtual' and just pointing to our backing store data
if(record && record->Map.status == GLResourceRecord::Mapped_Ignore_Real)
{
m_Real.glFlushMappedNamedBufferRangeEXT(buffer, offset, length);
}
if(IsActiveCapturing(m_State))
{
if(record)
{
m_MissingTracks.insert(record->GetResourceID());
GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(),
eFrameRef_ReadBeforeWrite);
if(record->Map.status == GLResourceRecord::Unmapped)
{
RDCWARN("Unmapped buffer being flushed, ignoring");
}
else if(record->Map.status == GLResourceRecord::Mapped_Ignore_Real)
{
RDCERR(
"Failed to cap frame - we saw an FlushMappedBuffer() that we didn't capture the "
"corresponding Map() for");
m_SuccessfulCapture = false;
m_FailureReason = CaptureFailed_UncappedUnmap;
}
else if(record->Map.status == GLResourceRecord::Mapped_Write)
{
if(offset < 0 || offset + length > record->Map.length)
{
RDCWARN("Flushed buffer range is outside of mapped range, clamping");
// maintain the length/end boundary of the flushed range if the flushed offset
// is below the mapped range
if(offset < 0)
{
offset = 0;
length += offset;
}
// clamp the length if it's beyond the mapped range.
if(offset + length > record->Map.length)
{
length = (record->Map.length - offset);
}
}
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glFlushMappedNamedBufferRangeEXT(ser, buffer, record->Map.offset + offset, length);
m_ContextRecord->AddChunk(scope.Get());
}
// other statuses is GLResourceRecord::Mapped_Read
}
}
else if(IsBackgroundCapturing(m_State))
{
// if this is a flush of a persistent map, we need to copy through to
// the real pointer and perform a real flush.
if(record && record->Map.persistentPtr)
{
memcpy(record->Map.persistentPtr + record->Map.offset + offset, record->Map.ptr + offset,
length);
m_Real.glFlushMappedNamedBufferRangeEXT(buffer, offset, length);
GetResourceManager()->MarkDirtyResource(record->GetResourceID());
}
}
}
void WrappedOpenGL::glFlushMappedNamedBufferRange(GLuint buffer, GLintptr offset, GLsizeiptr length)
{
// only difference to EXT function is size parameter, so just upcast
glFlushMappedNamedBufferRangeEXT(buffer, offset, length);
}
void WrappedOpenGL::glFlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length)
{
if(IsCaptureMode(m_State))
{
GLResourceRecord *record = GetCtxData().m_BufferRecord[BufferIdx(target)];
RDCASSERTMSG("Couldn't identify implicit object at binding. Mismatched or bad GLuint?", record,
target);
if(record)
return glFlushMappedNamedBufferRangeEXT(record->Resource.name, offset, length);
RDCERR(
"glFlushMappedBufferRange: Couldn't get resource record for target %x - no buffer bound?",
target);
}
return m_Real.glFlushMappedBufferRange(target, offset, length);
}
void WrappedOpenGL::PersistentMapMemoryBarrier(const set<GLResourceRecord *> &maps)
{
PUSH_CURRENT_CHUNK;
// this function iterates over all the maps, checking for any changes between
// the shadow pointers, and propogates that to 'real' GL
for(set<GLResourceRecord *>::const_iterator it = maps.begin(); it != maps.end(); ++it)
{
GLResourceRecord *record = *it;
RDCASSERT(record && record->Map.persistentPtr);
size_t diffStart = 0, diffEnd = 0;
bool found = FindDiffRange(record->GetShadowPtr(0), record->GetShadowPtr(1),
(size_t)record->Length, diffStart, diffEnd);
if(found)
{
// update the modified region in the 'comparison' shadow buffer for next check
memcpy(record->GetShadowPtr(1) + diffStart, record->GetShadowPtr(0) + diffStart,
diffEnd - diffStart);
// we use our own flush function so it will serialise chunks when necessary, and it
// also handles copying into the persistent mapped pointer and flushing the real GL
// buffer
gl_CurChunk = GLChunk::glFlushMappedNamedBufferRangeEXT;
glFlushMappedNamedBufferRangeEXT(record->Resource.name, GLintptr(diffStart),
GLsizeiptr(diffEnd - diffStart));
}
}
}
#pragma endregion
#pragma region Transform Feedback
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glGenTransformFeedbacks(SerialiserType &ser, GLsizei n, GLuint *ids)
{
SERIALISE_ELEMENT(n);
SERIALISE_ELEMENT_LOCAL(feedback, GetResourceManager()->GetID(FeedbackRes(GetCtx(), *ids)))
.TypedAs("GLResource");
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
GLuint real = 0;
m_Real.glGenTransformFeedbacks(1, &real);
m_Real.glBindTransformFeedback(eGL_TRANSFORM_FEEDBACK, real);
m_Real.glBindTransformFeedback(eGL_TRANSFORM_FEEDBACK, 0);
GLResource res = FeedbackRes(GetCtx(), real);
m_ResourceManager->RegisterResource(res);
GetResourceManager()->AddLiveResource(feedback, res);
AddResource(feedback, ResourceType::StateObject, "Transform Feedback");
}
return true;
}
void WrappedOpenGL::glGenTransformFeedbacks(GLsizei n, GLuint *ids)
{
SERIALISE_TIME_CALL(m_Real.glGenTransformFeedbacks(n, ids));
for(GLsizei i = 0; i < n; i++)
{
GLResource res = FeedbackRes(GetCtx(), ids[i]);
ResourceId id = GetResourceManager()->RegisterResource(res);
if(IsCaptureMode(m_State))
{
Chunk *chunk = NULL;
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glGenTransformFeedbacks(ser, 1, ids + i);
chunk = scope.Get();
}
GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
RDCASSERT(record);
record->AddChunk(chunk);
}
else
{
GetResourceManager()->AddLiveResource(id, res);
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glCreateTransformFeedbacks(SerialiserType &ser, GLsizei n, GLuint *ids)
{
SERIALISE_ELEMENT(n);
SERIALISE_ELEMENT_LOCAL(feedback, GetResourceManager()->GetID(FeedbackRes(GetCtx(), *ids)))
.TypedAs("GLResource");
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
GLuint real = 0;
m_Real.glCreateTransformFeedbacks(1, &real);
GLResource res = FeedbackRes(GetCtx(), real);
m_ResourceManager->RegisterResource(res);
GetResourceManager()->AddLiveResource(feedback, res);
AddResource(feedback, ResourceType::StateObject, "Transform Feedback");
}
return true;
}
void WrappedOpenGL::glCreateTransformFeedbacks(GLsizei n, GLuint *ids)
{
SERIALISE_TIME_CALL(m_Real.glCreateTransformFeedbacks(n, ids));
for(GLsizei i = 0; i < n; i++)
{
GLResource res = FeedbackRes(GetCtx(), ids[i]);
ResourceId id = GetResourceManager()->RegisterResource(res);
if(IsCaptureMode(m_State))
{
Chunk *chunk = NULL;
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glCreateTransformFeedbacks(ser, 1, ids + i);
chunk = scope.Get();
}
GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
RDCASSERT(record);
record->AddChunk(chunk);
}
else
{
GetResourceManager()->AddLiveResource(id, res);
}
}
}
void WrappedOpenGL::glDeleteTransformFeedbacks(GLsizei n, const GLuint *ids)
{
for(GLsizei i = 0; i < n; i++)
{
GLResource res = FeedbackRes(GetCtx(), ids[i]);
if(GetResourceManager()->HasCurrentResource(res))
{
GetResourceManager()->MarkCleanResource(res);
if(GetResourceManager()->HasResourceRecord(res))
GetResourceManager()->GetResourceRecord(res)->Delete(GetResourceManager());
GetResourceManager()->UnregisterResource(res);
}
}
m_Real.glDeleteTransformFeedbacks(n, ids);
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glTransformFeedbackBufferBase(SerialiserType &ser, GLuint xfbHandle,
GLuint index, GLuint bufferHandle)
{
SERIALISE_ELEMENT_LOCAL(xfb, FeedbackRes(GetCtx(), xfbHandle));
SERIALISE_ELEMENT(index);
SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle));
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
// use ARB_direct_state_access functions here as we use EXT_direct_state_access elsewhere. If
// we are running without ARB_dsa support, these functions are emulated in the trivial way. This
// is necessary since these functions can be serialised even if ARB_dsa was not used originally,
// and we need to support this case.
m_Real.glTransformFeedbackBufferBase(xfb.name, index, buffer.name);
}
return true;
}
void WrappedOpenGL::glTransformFeedbackBufferBase(GLuint xfb, GLuint index, GLuint buffer)
{
SERIALISE_TIME_CALL(m_Real.glTransformFeedbackBufferBase(xfb, index, buffer));
if(IsCaptureMode(m_State))
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glTransformFeedbackBufferBase(ser, xfb, index, buffer);
if(IsActiveCapturing(m_State))
{
m_ContextRecord->AddChunk(scope.Get());
GetResourceManager()->MarkResourceFrameReferenced(BufferRes(GetCtx(), buffer),
eFrameRef_ReadBeforeWrite);
}
else if(xfb != 0)
{
GLResourceRecord *fbrecord =
GetResourceManager()->GetResourceRecord(FeedbackRes(GetCtx(), xfb));
fbrecord->AddChunk(scope.Get());
if(buffer != 0)
fbrecord->AddParent(GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)));
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glTransformFeedbackBufferRange(SerialiserType &ser, GLuint xfbHandle,
GLuint index, GLuint bufferHandle,
GLintptr offsetPtr, GLsizeiptr sizePtr)
{
SERIALISE_ELEMENT_LOCAL(xfb, FeedbackRes(GetCtx(), xfbHandle));
SERIALISE_ELEMENT(index);
SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle));
SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr);
SERIALISE_ELEMENT_LOCAL(size, (uint64_t)sizePtr);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
// use ARB_direct_state_access functions here as we use EXT_direct_state_access elsewhere. If
// we are running without ARB_dsa support, these functions are emulated in the obvious way. This
// is necessary since these functions can be serialised even if ARB_dsa was not used originally,
// and we need to support this case.
m_Real.glTransformFeedbackBufferRange(xfb.name, index, buffer.name, (GLintptr)offset,
(GLsizei)size);
}
return true;
}
void WrappedOpenGL::glTransformFeedbackBufferRange(GLuint xfb, GLuint index, GLuint buffer,
GLintptr offset, GLsizeiptr size)
{
SERIALISE_TIME_CALL(m_Real.glTransformFeedbackBufferRange(xfb, index, buffer, offset, size));
if(IsCaptureMode(m_State))
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glTransformFeedbackBufferRange(ser, xfb, index, buffer, offset, size);
if(IsActiveCapturing(m_State))
{
m_ContextRecord->AddChunk(scope.Get());
GetResourceManager()->MarkResourceFrameReferenced(BufferRes(GetCtx(), buffer),
eFrameRef_ReadBeforeWrite);
}
else if(xfb != 0)
{
GLResourceRecord *fbrecord =
GetResourceManager()->GetResourceRecord(FeedbackRes(GetCtx(), xfb));
fbrecord->AddChunk(scope.Get());
if(buffer != 0)
fbrecord->AddParent(GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)));
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glBindTransformFeedback(SerialiserType &ser, GLenum target,
GLuint xfbHandle)
{
SERIALISE_ELEMENT(target);
SERIALISE_ELEMENT_LOCAL(xfb, FeedbackRes(GetCtx(), xfbHandle));
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
m_Real.glBindTransformFeedback(target, xfb.name);
}
return true;
}
void WrappedOpenGL::glBindTransformFeedback(GLenum target, GLuint id)
{
SERIALISE_TIME_CALL(m_Real.glBindTransformFeedback(target, id));
GLResourceRecord *record = NULL;
if(IsCaptureMode(m_State))
{
if(id == 0)
{
GetCtxData().m_FeedbackRecord = record = NULL;
}
else
{
GetCtxData().m_FeedbackRecord = record =
GetResourceManager()->GetResourceRecord(FeedbackRes(GetCtx(), id));
}
}
if(IsActiveCapturing(m_State))
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glBindTransformFeedback(ser, target, id);
m_ContextRecord->AddChunk(scope.Get());
if(record)
GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_Read);
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glBeginTransformFeedback(SerialiserType &ser, GLenum primitiveMode)
{
SERIALISE_ELEMENT(primitiveMode);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
m_Real.glBeginTransformFeedback(primitiveMode);
m_ActiveFeedback = true;
}
return true;
}
void WrappedOpenGL::glBeginTransformFeedback(GLenum primitiveMode)
{
SERIALISE_TIME_CALL(m_Real.glBeginTransformFeedback(primitiveMode));
m_ActiveFeedback = true;
if(IsActiveCapturing(m_State))
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glBeginTransformFeedback(ser, primitiveMode);
m_ContextRecord->AddChunk(scope.Get());
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glPauseTransformFeedback(SerialiserType &ser)
{
if(IsReplayingAndReading())
{
m_Real.glPauseTransformFeedback();
}
return true;
}
void WrappedOpenGL::glPauseTransformFeedback()
{
SERIALISE_TIME_CALL(m_Real.glPauseTransformFeedback());
if(IsActiveCapturing(m_State))
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glPauseTransformFeedback(ser);
m_ContextRecord->AddChunk(scope.Get());
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glResumeTransformFeedback(SerialiserType &ser)
{
if(IsReplayingAndReading())
{
m_Real.glResumeTransformFeedback();
}
return true;
}
void WrappedOpenGL::glResumeTransformFeedback()
{
SERIALISE_TIME_CALL(m_Real.glResumeTransformFeedback());
if(IsActiveCapturing(m_State))
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glResumeTransformFeedback(ser);
m_ContextRecord->AddChunk(scope.Get());
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glEndTransformFeedback(SerialiserType &ser)
{
if(IsReplayingAndReading())
{
m_Real.glEndTransformFeedback();
m_ActiveFeedback = false;
}
return true;
}
void WrappedOpenGL::glEndTransformFeedback()
{
SERIALISE_TIME_CALL(m_Real.glEndTransformFeedback());
m_ActiveFeedback = false;
if(IsActiveCapturing(m_State))
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glEndTransformFeedback(ser);
m_ContextRecord->AddChunk(scope.Get());
}
}
#pragma endregion
#pragma region Vertex Arrays
// NOTE: In each of the vertex array object functions below, we might not have the live buffer
// resource if it's is a pre-capture chunk, and the buffer was never referenced at all in the actual
// frame.
// The reason for this is that the VAO record doesn't add a parent of the buffer record - because
// that parent tracking quickly becomes stale with high traffic VAOs ignoring updates etc, so we
// don't rely on the parent connection and manually reference the buffer wherever it is actually
// used.
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribOffsetEXT(
SerialiserType &ser, GLuint vaobjHandle, GLuint bufferHandle, GLuint index, GLint size,
GLenum type, GLboolean normalized, GLsizei stride, GLintptr offsetPtr)
{
SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle));
SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle));
SERIALISE_ELEMENT(index);
SERIALISE_ELEMENT(size);
SERIALISE_ELEMENT(type);
SERIALISE_ELEMENT_TYPED(bool, normalized);
SERIALISE_ELEMENT(stride);
SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
if(vaobj.name == 0)
vaobj.name = m_FakeVAO;
// some intel drivers don't properly update query states (like GL_VERTEX_ATTRIB_ARRAY_SIZE)
// unless the VAO is also bound when performing EXT_dsa functions :(
GLuint prevVAO = 0;
m_Real.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, (GLint *)&prevVAO);
m_Real.glBindVertexArray(vaobj.name);
// seems buggy when mixed and matched with new style vertex attrib binding, which we use for VAO
// initial states. Since the spec defines how this function should work in terms of new style
// bindings, just do that ourselves.
// m_Real.glVertexArrayVertexAttribOffsetEXT(vaobj.name, buffer.name, index, size, type,
// normalized, stride, (GLintptr)offset);
m_Real.glVertexArrayVertexAttribFormatEXT(vaobj.name, index, size, type, normalized, 0);
m_Real.glVertexArrayVertexAttribBindingEXT(vaobj.name, index, index);
if(stride == 0)
{
GLenum SizeEnum = size == 1 ? eGL_RED : size == 2 ? eGL_RG : size == 3 ? eGL_RGB : eGL_RGBA;
stride = (uint32_t)GetByteSize(1, 1, 1, SizeEnum, type);
}
if(buffer.name == 0)
{
// ES allows client-memory pointers, which we override with temp buffers during capture.
// For replay, discard these pointers to prevent driver complaining about "negative offsets".
offset = 0;
}
m_Real.glVertexArrayBindVertexBufferEXT(vaobj.name, index, buffer.name, (GLintptr)offset, stride);
m_Real.glBindVertexArray(prevVAO);
}
return true;
}
void WrappedOpenGL::glVertexArrayVertexAttribOffsetEXT(GLuint vaobj, GLuint buffer, GLuint index,
GLint size, GLenum type, GLboolean normalized,
GLsizei stride, GLintptr offset)
{
SERIALISE_TIME_CALL(m_Real.glVertexArrayVertexAttribOffsetEXT(vaobj, buffer, index, size, type,
normalized, stride, offset));
if(IsCaptureMode(m_State))
{
GLResourceRecord *bufrecord =
GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer));
GLResourceRecord *varecord =
GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj));
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
if(IsActiveCapturing(m_State) && bufrecord)
GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexAttribOffsetEXT(ser, vaobj, buffer, index, size, type,
normalized, stride, offset);
r->AddChunk(scope.Get());
}
}
}
}
void WrappedOpenGL::glVertexAttribPointer(GLuint index, GLint size, GLenum type,
GLboolean normalized, GLsizei stride, const void *pointer)
{
SERIALISE_TIME_CALL(m_Real.glVertexAttribPointer(index, size, type, normalized, stride, pointer));
if(IsCaptureMode(m_State))
{
ContextData &cd = GetCtxData();
GLResourceRecord *bufrecord = cd.m_BufferRecord[BufferIdx(eGL_ARRAY_BUFFER)];
GLResourceRecord *varecord = cd.m_VertexArrayRecord;
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
if(IsActiveCapturing(m_State) && bufrecord)
GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexAttribOffsetEXT(
ser, varecord ? varecord->Resource.name : 0, bufrecord ? bufrecord->Resource.name : 0,
index, size, type, normalized, stride, (GLintptr)pointer);
r->AddChunk(scope.Get());
}
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribIOffsetEXT(SerialiserType &ser,
GLuint vaobjHandle,
GLuint bufferHandle, GLuint index,
GLint size, GLenum type,
GLsizei stride, GLintptr offsetPtr)
{
SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle));
SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle));
SERIALISE_ELEMENT(index);
SERIALISE_ELEMENT(size);
SERIALISE_ELEMENT(type);
SERIALISE_ELEMENT(stride);
SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
if(vaobj.name == 0)
vaobj.name = m_FakeVAO;
// some intel drivers don't properly update query states (like GL_VERTEX_ATTRIB_ARRAY_SIZE)
// unless the VAO is also bound when performing EXT_dsa functions :(
GLuint prevVAO = 0;
m_Real.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, (GLint *)&prevVAO);
m_Real.glBindVertexArray(vaobj.name);
// seems buggy when mixed and matched with new style vertex attrib binding, which we use for VAO
// initial states. Since the spec defines how this function should work in terms of new style
// bindings, just do that ourselves.
// m_Real.glVertexArrayVertexAttribIOffsetEXT(vaobj.name, buffer.name, index, size, type,
// stride, (GLintptr)offset);
m_Real.glVertexArrayVertexAttribIFormatEXT(vaobj.name, index, size, type, 0);
m_Real.glVertexArrayVertexAttribBindingEXT(vaobj.name, index, index);
if(stride == 0)
{
GLenum SizeEnum = size == 1 ? eGL_RED : size == 2 ? eGL_RG : size == 3 ? eGL_RGB : eGL_RGBA;
stride = (uint32_t)GetByteSize(1, 1, 1, SizeEnum, type);
}
if(buffer.name == 0)
{
// ES allows client-memory pointers, which we override with temp buffers during capture.
// For replay, discard these pointers to prevent driver complaining about "negative offsets".
offset = 0;
}
m_Real.glVertexArrayBindVertexBufferEXT(vaobj.name, index, buffer.name, (GLintptr)offset, stride);
m_Real.glBindVertexArray(prevVAO);
}
return true;
}
void WrappedOpenGL::glVertexArrayVertexAttribIOffsetEXT(GLuint vaobj, GLuint buffer, GLuint index,
GLint size, GLenum type, GLsizei stride,
GLintptr offset)
{
SERIALISE_TIME_CALL(
m_Real.glVertexArrayVertexAttribIOffsetEXT(vaobj, buffer, index, size, type, stride, offset));
if(IsCaptureMode(m_State))
{
GLResourceRecord *bufrecord =
GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer));
GLResourceRecord *varecord =
GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj));
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
if(IsActiveCapturing(m_State) && bufrecord)
GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexAttribIOffsetEXT(ser, vaobj, buffer, index, size, type, stride,
offset);
r->AddChunk(scope.Get());
}
}
}
}
void WrappedOpenGL::glVertexAttribIPointer(GLuint index, GLint size, GLenum type, GLsizei stride,
const void *pointer)
{
SERIALISE_TIME_CALL(m_Real.glVertexAttribIPointer(index, size, type, stride, pointer));
if(IsCaptureMode(m_State))
{
ContextData &cd = GetCtxData();
GLResourceRecord *bufrecord = cd.m_BufferRecord[BufferIdx(eGL_ARRAY_BUFFER)];
GLResourceRecord *varecord = cd.m_VertexArrayRecord;
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
if(IsActiveCapturing(m_State) && bufrecord)
GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexAttribIOffsetEXT(ser, varecord ? varecord->Resource.name : 0,
bufrecord ? bufrecord->Resource.name : 0,
index, size, type, stride, (GLintptr)pointer);
r->AddChunk(scope.Get());
}
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribLOffsetEXT(SerialiserType &ser,
GLuint vaobjHandle,
GLuint bufferHandle, GLuint index,
GLint size, GLenum type,
GLsizei stride, GLintptr offsetPtr)
{
SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle));
SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle));
SERIALISE_ELEMENT(index);
SERIALISE_ELEMENT(size);
SERIALISE_ELEMENT(type);
SERIALISE_ELEMENT(stride);
SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
if(vaobj.name == 0)
vaobj.name = m_FakeVAO;
// some intel drivers don't properly update query states (like GL_VERTEX_ATTRIB_ARRAY_SIZE)
// unless the VAO is also bound when performing EXT_dsa functions :(
GLuint prevVAO = 0;
m_Real.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, (GLint *)&prevVAO);
m_Real.glBindVertexArray(vaobj.name);
// seems buggy when mixed and matched with new style vertex attrib binding, which we use for VAO
// initial states. Since the spec defines how this function should work in terms of new style
// bindings, just do that ourselves.
// m_Real.glVertexArrayVertexAttribIOffsetEXT(vaobj.name, buffer.name, index, size, type,
// stride, (GLintptr)offset);
m_Real.glVertexArrayVertexAttribLFormatEXT(vaobj.name, index, size, type, 0);
m_Real.glVertexArrayVertexAttribBindingEXT(vaobj.name, index, index);
if(stride == 0)
{
GLenum SizeEnum = size == 1 ? eGL_RED : size == 2 ? eGL_RG : size == 3 ? eGL_RGB : eGL_RGBA;
stride = (uint32_t)GetByteSize(1, 1, 1, SizeEnum, type);
}
if(buffer.name == 0)
{
// ES allows client-memory pointers, which we override with temp buffers during capture.
// For replay, discard these pointers to prevent driver complaining about "negative offsets".
offset = 0;
}
m_Real.glVertexArrayBindVertexBufferEXT(vaobj.name, index, buffer.name, (GLintptr)offset, stride);
m_Real.glBindVertexArray(prevVAO);
}
return true;
}
void WrappedOpenGL::glVertexArrayVertexAttribLOffsetEXT(GLuint vaobj, GLuint buffer, GLuint index,
GLint size, GLenum type, GLsizei stride,
GLintptr offset)
{
SERIALISE_TIME_CALL(
m_Real.glVertexArrayVertexAttribLOffsetEXT(vaobj, buffer, index, size, type, stride, offset));
if(IsCaptureMode(m_State))
{
GLResourceRecord *bufrecord =
GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer));
GLResourceRecord *varecord =
GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj));
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
if(IsActiveCapturing(m_State) && bufrecord)
GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexAttribLOffsetEXT(ser, vaobj, buffer, index, size, type, stride,
offset);
r->AddChunk(scope.Get());
}
}
}
}
void WrappedOpenGL::glVertexAttribLPointer(GLuint index, GLint size, GLenum type, GLsizei stride,
const void *pointer)
{
SERIALISE_TIME_CALL(m_Real.glVertexAttribLPointer(index, size, type, stride, pointer));
if(IsCaptureMode(m_State))
{
ContextData &cd = GetCtxData();
GLResourceRecord *bufrecord = cd.m_BufferRecord[BufferIdx(eGL_ARRAY_BUFFER)];
GLResourceRecord *varecord = cd.m_VertexArrayRecord;
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
if(IsActiveCapturing(m_State) && bufrecord)
GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexAttribLOffsetEXT(ser, varecord ? varecord->Resource.name : 0,
bufrecord ? bufrecord->Resource.name : 0,
index, size, type, stride, (GLintptr)pointer);
r->AddChunk(scope.Get());
}
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribBindingEXT(SerialiserType &ser,
GLuint vaobjHandle,
GLuint attribindex,
GLuint bindingindex)
{
SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle));
SERIALISE_ELEMENT(attribindex);
SERIALISE_ELEMENT(bindingindex);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
if(vaobj.name == 0)
vaobj.name = m_FakeVAO;
m_Real.glVertexArrayVertexAttribBindingEXT(vaobj.name, attribindex, bindingindex);
}
return true;
}
void WrappedOpenGL::glVertexArrayVertexAttribBindingEXT(GLuint vaobj, GLuint attribindex,
GLuint bindingindex)
{
SERIALISE_TIME_CALL(m_Real.glVertexArrayVertexAttribBindingEXT(vaobj, attribindex, bindingindex));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord =
GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj));
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexAttribBindingEXT(ser, vaobj, attribindex, bindingindex);
r->AddChunk(scope.Get());
}
}
}
}
void WrappedOpenGL::glVertexAttribBinding(GLuint attribindex, GLuint bindingindex)
{
SERIALISE_TIME_CALL(m_Real.glVertexAttribBinding(attribindex, bindingindex));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord;
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexAttribBindingEXT(ser, varecord ? varecord->Resource.name : 0,
attribindex, bindingindex);
r->AddChunk(scope.Get());
}
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribFormatEXT(SerialiserType &ser,
GLuint vaobjHandle,
GLuint attribindex, GLint size,
GLenum type, GLboolean normalized,
GLuint relativeoffset)
{
SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle));
SERIALISE_ELEMENT(attribindex);
SERIALISE_ELEMENT(size);
SERIALISE_ELEMENT(type);
SERIALISE_ELEMENT_TYPED(bool, normalized);
SERIALISE_ELEMENT(relativeoffset);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
if(vaobj.name == 0)
vaobj.name = m_FakeVAO;
m_Real.glVertexArrayVertexAttribFormatEXT(vaobj.name, attribindex, size, type, normalized,
relativeoffset);
}
return true;
}
void WrappedOpenGL::glVertexArrayVertexAttribFormatEXT(GLuint vaobj, GLuint attribindex, GLint size,
GLenum type, GLboolean normalized,
GLuint relativeoffset)
{
SERIALISE_TIME_CALL(m_Real.glVertexArrayVertexAttribFormatEXT(vaobj, attribindex, size, type,
normalized, relativeoffset));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord =
GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj));
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexAttribFormatEXT(ser, vaobj, attribindex, size, type,
normalized, relativeoffset);
r->AddChunk(scope.Get());
}
}
}
}
void WrappedOpenGL::glVertexAttribFormat(GLuint attribindex, GLint size, GLenum type,
GLboolean normalized, GLuint relativeoffset)
{
SERIALISE_TIME_CALL(
m_Real.glVertexAttribFormat(attribindex, size, type, normalized, relativeoffset));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord;
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexAttribFormatEXT(ser, varecord ? varecord->Resource.name : 0,
attribindex, size, type, normalized,
relativeoffset);
r->AddChunk(scope.Get());
}
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribIFormatEXT(SerialiserType &ser,
GLuint vaobjHandle,
GLuint attribindex, GLint size,
GLenum type, GLuint relativeoffset)
{
SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle));
SERIALISE_ELEMENT(attribindex);
SERIALISE_ELEMENT(size);
SERIALISE_ELEMENT(type);
SERIALISE_ELEMENT(relativeoffset);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
if(vaobj.name == 0)
vaobj.name = m_FakeVAO;
m_Real.glVertexArrayVertexAttribIFormatEXT(vaobj.name, attribindex, size, type, relativeoffset);
}
return true;
}
void WrappedOpenGL::glVertexArrayVertexAttribIFormatEXT(GLuint vaobj, GLuint attribindex, GLint size,
GLenum type, GLuint relativeoffset)
{
SERIALISE_TIME_CALL(
m_Real.glVertexArrayVertexAttribIFormatEXT(vaobj, attribindex, size, type, relativeoffset));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord =
GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj));
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexAttribIFormatEXT(ser, vaobj, attribindex, size, type,
relativeoffset);
r->AddChunk(scope.Get());
}
}
}
}
void WrappedOpenGL::glVertexAttribIFormat(GLuint attribindex, GLint size, GLenum type,
GLuint relativeoffset)
{
SERIALISE_TIME_CALL(m_Real.glVertexAttribIFormat(attribindex, size, type, relativeoffset));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord;
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexAttribIFormatEXT(ser, varecord ? varecord->Resource.name : 0,
attribindex, size, type, relativeoffset);
r->AddChunk(scope.Get());
}
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribLFormatEXT(SerialiserType &ser,
GLuint vaobjHandle,
GLuint attribindex, GLint size,
GLenum type, GLuint relativeoffset)
{
SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle));
SERIALISE_ELEMENT(attribindex);
SERIALISE_ELEMENT(size);
SERIALISE_ELEMENT(type);
SERIALISE_ELEMENT(relativeoffset);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
if(vaobj.name == 0)
vaobj.name = m_FakeVAO;
m_Real.glVertexArrayVertexAttribLFormatEXT(vaobj.name, attribindex, size, type, relativeoffset);
}
return true;
}
void WrappedOpenGL::glVertexArrayVertexAttribLFormatEXT(GLuint vaobj, GLuint attribindex, GLint size,
GLenum type, GLuint relativeoffset)
{
SERIALISE_TIME_CALL(
m_Real.glVertexArrayVertexAttribLFormatEXT(vaobj, attribindex, size, type, relativeoffset));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord =
GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj));
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexAttribLFormatEXT(ser, vaobj, attribindex, size, type,
relativeoffset);
r->AddChunk(scope.Get());
}
}
}
}
void WrappedOpenGL::glVertexAttribLFormat(GLuint attribindex, GLint size, GLenum type,
GLuint relativeoffset)
{
SERIALISE_TIME_CALL(m_Real.glVertexAttribLFormat(attribindex, size, type, relativeoffset));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord;
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexAttribLFormatEXT(ser, varecord ? varecord->Resource.name : 0,
attribindex, size, type, relativeoffset);
r->AddChunk(scope.Get());
}
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glVertexArrayVertexAttribDivisorEXT(SerialiserType &ser,
GLuint vaobjHandle, GLuint index,
GLuint divisor)
{
SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle));
SERIALISE_ELEMENT(index);
SERIALISE_ELEMENT(divisor);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
if(vaobj.name == 0)
vaobj.name = m_FakeVAO;
// at the time of writing, AMD driver seems to not have this entry point
if(m_Real.glVertexArrayVertexAttribDivisorEXT)
{
m_Real.glVertexArrayVertexAttribDivisorEXT(vaobj.name, index, divisor);
}
else
{
GLuint VAO = 0;
m_Real.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, (GLint *)&VAO);
m_Real.glBindVertexArray(vaobj.name);
m_Real.glVertexAttribDivisor(index, divisor);
m_Real.glBindVertexArray(VAO);
}
}
return true;
}
void WrappedOpenGL::glVertexArrayVertexAttribDivisorEXT(GLuint vaobj, GLuint index, GLuint divisor)
{
SERIALISE_TIME_CALL(m_Real.glVertexArrayVertexAttribDivisorEXT(vaobj, index, divisor));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord =
GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj));
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexAttribDivisorEXT(ser, vaobj, index, divisor);
r->AddChunk(scope.Get());
}
}
}
}
void WrappedOpenGL::glVertexAttribDivisor(GLuint index, GLuint divisor)
{
SERIALISE_TIME_CALL(m_Real.glVertexAttribDivisor(index, divisor));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord;
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexAttribDivisorEXT(ser, varecord ? varecord->Resource.name : 0,
index, divisor);
r->AddChunk(scope.Get());
}
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glEnableVertexArrayAttribEXT(SerialiserType &ser, GLuint vaobjHandle,
GLuint index)
{
SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle));
SERIALISE_ELEMENT(index);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
if(vaobj.name == 0)
vaobj.name = m_FakeVAO;
GLint prevVAO = 0;
m_Real.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, &prevVAO);
m_Real.glEnableVertexArrayAttribEXT(vaobj.name, index);
// nvidia bug seems to sometimes change VAO binding in glEnableVertexArrayAttribEXT, although it
// seems like it only happens if GL_DEBUG_OUTPUT_SYNCHRONOUS is NOT enabled.
m_Real.glBindVertexArray(prevVAO);
}
return true;
}
void WrappedOpenGL::glEnableVertexArrayAttribEXT(GLuint vaobj, GLuint index)
{
SERIALISE_TIME_CALL(m_Real.glEnableVertexArrayAttribEXT(vaobj, index));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord =
GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj));
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glEnableVertexArrayAttribEXT(ser, vaobj, index);
r->AddChunk(scope.Get());
}
}
}
}
void WrappedOpenGL::glEnableVertexAttribArray(GLuint index)
{
SERIALISE_TIME_CALL(m_Real.glEnableVertexAttribArray(index));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord;
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glEnableVertexArrayAttribEXT(ser, varecord ? varecord->Resource.name : 0, index);
r->AddChunk(scope.Get());
}
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glDisableVertexArrayAttribEXT(SerialiserType &ser, GLuint vaobjHandle,
GLuint index)
{
SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle));
SERIALISE_ELEMENT(index);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
if(vaobj.name == 0)
vaobj.name = m_FakeVAO;
GLint prevVAO = 0;
m_Real.glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, &prevVAO);
m_Real.glDisableVertexArrayAttribEXT(vaobj.name, index);
// nvidia bug seems to sometimes change VAO binding in glEnableVertexArrayAttribEXT, although it
// seems like it only happens if GL_DEBUG_OUTPUT_SYNCHRONOUS is NOT enabled.
m_Real.glBindVertexArray(prevVAO);
}
return true;
}
void WrappedOpenGL::glDisableVertexArrayAttribEXT(GLuint vaobj, GLuint index)
{
SERIALISE_TIME_CALL(m_Real.glDisableVertexArrayAttribEXT(vaobj, index));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord =
GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj));
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glDisableVertexArrayAttribEXT(ser, vaobj, index);
r->AddChunk(scope.Get());
}
}
}
}
void WrappedOpenGL::glDisableVertexAttribArray(GLuint index)
{
SERIALISE_TIME_CALL(m_Real.glDisableVertexAttribArray(index));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord;
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glDisableVertexArrayAttribEXT(ser, varecord ? varecord->Resource.name : 0, index);
r->AddChunk(scope.Get());
}
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glGenVertexArrays(SerialiserType &ser, GLsizei n, GLuint *arrays)
{
SERIALISE_ELEMENT(n);
SERIALISE_ELEMENT_LOCAL(array, GetResourceManager()->GetID(VertexArrayRes(GetCtx(), *arrays)))
.TypedAs("GLResource");
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
GLuint real = 0;
m_Real.glGenVertexArrays(1, &real);
m_Real.glBindVertexArray(real);
m_Real.glBindVertexArray(0);
GLResource res = VertexArrayRes(GetCtx(), real);
m_ResourceManager->RegisterResource(res);
GetResourceManager()->AddLiveResource(array, res);
AddResource(array, ResourceType::StateObject, "Vertex Array");
}
return true;
}
void WrappedOpenGL::glGenVertexArrays(GLsizei n, GLuint *arrays)
{
SERIALISE_TIME_CALL(m_Real.glGenVertexArrays(n, arrays));
for(GLsizei i = 0; i < n; i++)
{
GLResource res = VertexArrayRes(GetCtx(), arrays[i]);
ResourceId id = GetResourceManager()->RegisterResource(res);
if(IsCaptureMode(m_State))
{
Chunk *chunk = NULL;
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glGenVertexArrays(ser, 1, arrays + i);
chunk = scope.Get();
}
GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
RDCASSERT(record);
record->AddChunk(chunk);
}
else
{
GetResourceManager()->AddLiveResource(id, res);
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glCreateVertexArrays(SerialiserType &ser, GLsizei n, GLuint *arrays)
{
SERIALISE_ELEMENT(n);
SERIALISE_ELEMENT_LOCAL(array, GetResourceManager()->GetID(VertexArrayRes(GetCtx(), *arrays)))
.TypedAs("GLResource");
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
GLuint real = 0;
m_Real.glCreateVertexArrays(1, &real);
GLResource res = VertexArrayRes(GetCtx(), real);
m_ResourceManager->RegisterResource(res);
GetResourceManager()->AddLiveResource(array, res);
AddResource(array, ResourceType::StateObject, "Vertex Array");
}
return true;
}
void WrappedOpenGL::glCreateVertexArrays(GLsizei n, GLuint *arrays)
{
SERIALISE_TIME_CALL(m_Real.glCreateVertexArrays(n, arrays));
for(GLsizei i = 0; i < n; i++)
{
GLResource res = VertexArrayRes(GetCtx(), arrays[i]);
ResourceId id = GetResourceManager()->RegisterResource(res);
if(IsCaptureMode(m_State))
{
Chunk *chunk = NULL;
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glCreateVertexArrays(ser, 1, arrays + i);
chunk = scope.Get();
}
GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id);
RDCASSERT(record);
record->AddChunk(chunk);
}
else
{
GetResourceManager()->AddLiveResource(id, res);
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glBindVertexArray(SerialiserType &ser, GLuint vaobjHandle)
{
SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle));
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
if(vaobj.name == 0)
vaobj.name = m_FakeVAO;
m_Real.glBindVertexArray(vaobj.name);
}
return true;
}
void WrappedOpenGL::glBindVertexArray(GLuint array)
{
SERIALISE_TIME_CALL(m_Real.glBindVertexArray(array));
GLResourceRecord *record = NULL;
if(IsCaptureMode(m_State))
{
if(array == 0)
{
GetCtxData().m_VertexArrayRecord = record = NULL;
}
else
{
GetCtxData().m_VertexArrayRecord = record =
GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), array));
}
}
if(IsActiveCapturing(m_State))
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glBindVertexArray(ser, array);
m_ContextRecord->AddChunk(scope.Get());
if(record)
GetResourceManager()->MarkVAOReferenced(record->Resource, eFrameRef_ReadBeforeWrite);
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glVertexArrayElementBuffer(SerialiserType &ser, GLuint vaobjHandle,
GLuint bufferHandle)
{
SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle));
SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle));
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
if(vaobj.name == 0)
vaobj.name = m_FakeVAO;
// might not have the live resource if this is a pre-capture chunk, and the buffer was never
// referenced at all in the actual frame
if(buffer.name)
{
m_Buffers[GetResourceManager()->GetID(buffer)].curType = eGL_ELEMENT_ARRAY_BUFFER;
m_Buffers[GetResourceManager()->GetID(buffer)].creationFlags |= BufferCategory::Index;
}
// use ARB_direct_state_access functions here as we use EXT_direct_state_access elsewhere. If
// we are running without ARB_dsa support, these functions are emulated in the obvious way. This
// is necessary since these functions can be serialised even if ARB_dsa was not used originally,
// and we need to support this case.
m_Real.glVertexArrayElementBuffer(vaobj.name, buffer.name);
}
return true;
}
void WrappedOpenGL::glVertexArrayElementBuffer(GLuint vaobj, GLuint buffer)
{
SERIALISE_TIME_CALL(m_Real.glVertexArrayElementBuffer(vaobj, buffer));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord =
GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj));
GLResourceRecord *bufrecord =
GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer));
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
if(IsActiveCapturing(m_State) && bufrecord)
GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayElementBuffer(ser, vaobj, buffer);
r->AddChunk(scope.Get());
}
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glVertexArrayBindVertexBufferEXT(SerialiserType &ser,
GLuint vaobjHandle,
GLuint bindingindex,
GLuint bufferHandle,
GLintptr offsetPtr, GLsizei stride)
{
SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle));
SERIALISE_ELEMENT(bindingindex);
SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle));
SERIALISE_ELEMENT_LOCAL(offset, (uint64_t)offsetPtr);
SERIALISE_ELEMENT(stride);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
if(vaobj.name == 0)
vaobj.name = m_FakeVAO;
if(buffer.name)
{
m_Buffers[GetResourceManager()->GetID(buffer)].curType = eGL_ARRAY_BUFFER;
m_Buffers[GetResourceManager()->GetID(buffer)].creationFlags |= BufferCategory::Vertex;
}
m_Real.glVertexArrayBindVertexBufferEXT(vaobj.name, bindingindex, buffer.name, (GLintptr)offset,
(GLsizei)stride);
}
return true;
}
void WrappedOpenGL::glVertexArrayBindVertexBufferEXT(GLuint vaobj, GLuint bindingindex,
GLuint buffer, GLintptr offset, GLsizei stride)
{
SERIALISE_TIME_CALL(
m_Real.glVertexArrayBindVertexBufferEXT(vaobj, bindingindex, buffer, offset, stride));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord =
GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj));
GLResourceRecord *bufrecord =
GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer));
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
if(IsActiveCapturing(m_State) && bufrecord)
GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayBindVertexBufferEXT(ser, vaobj, bindingindex, buffer, offset, stride);
r->AddChunk(scope.Get());
}
}
}
}
void WrappedOpenGL::glBindVertexBuffer(GLuint bindingindex, GLuint buffer, GLintptr offset,
GLsizei stride)
{
SERIALISE_TIME_CALL(m_Real.glBindVertexBuffer(bindingindex, buffer, offset, stride));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord;
GLResourceRecord *bufrecord =
GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer));
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
if(IsActiveCapturing(m_State) && bufrecord)
GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(), eFrameRef_Read);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayBindVertexBufferEXT(ser, varecord ? varecord->Resource.name : 0,
bindingindex, buffer, offset, stride);
r->AddChunk(scope.Get());
}
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glVertexArrayVertexBuffers(SerialiserType &ser, GLuint vaobjHandle,
GLuint first, GLsizei count,
const GLuint *bufferHandles,
const GLintptr *offsetPtrs,
const GLsizei *strides)
{
// can't serialise arrays of GL handles since they're not wrapped or typed :(.
// Likewise need to upcast the offsets to 64-bit instead of serialising as-is.
std::vector<GLResource> buffers;
std::vector<uint64_t> offsets;
if(ser.IsWriting() && bufferHandles)
{
buffers.reserve(count);
for(GLsizei i = 0; i < count; i++)
buffers.push_back(BufferRes(GetCtx(), bufferHandles[i]));
}
if(ser.IsWriting() && offsetPtrs)
{
offsets.reserve(count);
for(GLsizei i = 0; i < count; i++)
offsets.push_back((uint64_t)offsetPtrs[i]);
}
SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle));
SERIALISE_ELEMENT(first);
SERIALISE_ELEMENT(count);
SERIALISE_ELEMENT(buffers);
SERIALISE_ELEMENT(offsets);
SERIALISE_ELEMENT_ARRAY(strides, count);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
std::vector<GLuint> bufs;
std::vector<GLintptr> offs;
if(!buffers.empty())
{
bufs.reserve(count);
for(GLsizei i = 0; i < count; i++)
bufs.push_back(buffers[i].name);
}
if(!offsets.empty())
{
offs.reserve(count);
for(GLsizei i = 0; i < count; i++)
offs.push_back((GLintptr)offsets[i]);
}
if(vaobj.name == 0)
vaobj.name = m_FakeVAO;
// use ARB_direct_state_access functions here as we use EXT_direct_state_access elsewhere. If
// we are running without ARB_dsa support, these functions are emulated in the obvious way. This
// is necessary since these functions can be serialised even if ARB_dsa was not used originally,
// and we need to support this case.
m_Real.glVertexArrayVertexBuffers(vaobj.name, first, count, bufs.empty() ? NULL : bufs.data(),
offs.empty() ? NULL : offs.data(), strides);
if(IsLoading(m_State))
{
for(GLsizei i = 0; i < count; i++)
{
m_Buffers[GetResourceManager()->GetID(buffers[i])].curType = eGL_ARRAY_BUFFER;
m_Buffers[GetResourceManager()->GetID(buffers[i])].creationFlags |= BufferCategory::Vertex;
}
}
}
return true;
}
void WrappedOpenGL::glVertexArrayVertexBuffers(GLuint vaobj, GLuint first, GLsizei count,
const GLuint *buffers, const GLintptr *offsets,
const GLsizei *strides)
{
SERIALISE_TIME_CALL(
m_Real.glVertexArrayVertexBuffers(vaobj, first, count, buffers, offsets, strides));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord =
GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj));
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexBuffers(ser, vaobj, first, count, buffers, offsets, strides);
r->AddChunk(scope.Get());
}
if(IsActiveCapturing(m_State))
{
for(GLsizei i = 0; i < count; i++)
{
if(buffers != NULL && buffers[i] != 0)
{
GLResourceRecord *bufrecord =
GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffers[i]));
if(bufrecord)
GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(),
eFrameRef_Read);
}
}
}
}
}
}
void WrappedOpenGL::glBindVertexBuffers(GLuint first, GLsizei count, const GLuint *buffers,
const GLintptr *offsets, const GLsizei *strides)
{
SERIALISE_TIME_CALL(m_Real.glBindVertexBuffers(first, count, buffers, offsets, strides));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord;
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexBuffers(ser, varecord ? varecord->Resource.name : 0, first,
count, buffers, offsets, strides);
r->AddChunk(scope.Get());
}
if(IsActiveCapturing(m_State))
{
for(GLsizei i = 0; i < count; i++)
{
if(buffers != NULL && buffers[i] != 0)
{
GLResourceRecord *bufrecord =
GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffers[i]));
if(bufrecord)
GetResourceManager()->MarkResourceFrameReferenced(bufrecord->GetResourceID(),
eFrameRef_Read);
}
}
}
}
}
}
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glVertexArrayVertexBindingDivisorEXT(SerialiserType &ser,
GLuint vaobjHandle,
GLuint bindingindex,
GLuint divisor)
{
SERIALISE_ELEMENT_LOCAL(vaobj, VertexArrayRes(GetCtx(), vaobjHandle));
SERIALISE_ELEMENT(bindingindex);
SERIALISE_ELEMENT(divisor);
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
if(vaobj.name == 0)
vaobj.name = m_FakeVAO;
m_Real.glVertexArrayVertexBindingDivisorEXT(vaobj.name, bindingindex, divisor);
}
return true;
}
void WrappedOpenGL::glVertexArrayVertexBindingDivisorEXT(GLuint vaobj, GLuint bindingindex,
GLuint divisor)
{
SERIALISE_TIME_CALL(m_Real.glVertexArrayVertexBindingDivisorEXT(vaobj, bindingindex, divisor));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord =
GetResourceManager()->GetResourceRecord(VertexArrayRes(GetCtx(), vaobj));
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexBindingDivisorEXT(ser, vaobj, bindingindex, divisor);
r->AddChunk(scope.Get());
}
}
}
}
void WrappedOpenGL::glVertexBindingDivisor(GLuint bindingindex, GLuint divisor)
{
SERIALISE_TIME_CALL(m_Real.glVertexBindingDivisor(bindingindex, divisor));
if(IsCaptureMode(m_State))
{
GLResourceRecord *varecord = GetCtxData().m_VertexArrayRecord;
GLResourceRecord *r = IsActiveCapturing(m_State) ? m_ContextRecord : varecord;
if(r)
{
if(IsBackgroundCapturing(m_State) && !RecordUpdateCheck(varecord))
return;
if(IsActiveCapturing(m_State) && varecord)
GetResourceManager()->MarkVAOReferenced(varecord->Resource, eFrameRef_ReadBeforeWrite);
{
USE_SCRATCH_SERIALISER();
SCOPED_SERIALISE_CHUNK(gl_CurChunk);
Serialise_glVertexArrayVertexBindingDivisorEXT(ser, varecord ? varecord->Resource.name : 0,
bindingindex, divisor);
r->AddChunk(scope.Get());
}
}
}
}
void WrappedOpenGL::glDeleteBuffers(GLsizei n, const GLuint *buffers)
{
for(GLsizei i = 0; i < n; i++)
{
GLResource res = BufferRes(GetCtx(), buffers[i]);
if(GetResourceManager()->HasCurrentResource(res))
{
GLResourceRecord *record = GetResourceManager()->GetResourceRecord(res);
if(record)
{
// if we have a persistent pointer, make sure to unmap it
if(record->Map.persistentPtr)
{
m_PersistentMaps.erase(record);
if(record->Map.access & GL_MAP_COHERENT_BIT)
m_CoherentMaps.erase(record);
m_Real.glUnmapNamedBufferEXT(res.name);
}
// free any shadow storage
record->FreeShadowStorage();
}
GetResourceManager()->MarkCleanResource(res);
if(GetResourceManager()->HasResourceRecord(res))
GetResourceManager()->GetResourceRecord(res)->Delete(GetResourceManager());
GetResourceManager()->UnregisterResource(res);
}
}
m_Real.glDeleteBuffers(n, buffers);
}
void WrappedOpenGL::glDeleteVertexArrays(GLsizei n, const GLuint *arrays)
{
for(GLsizei i = 0; i < n; i++)
{
GLResource res = VertexArrayRes(GetCtx(), arrays[i]);
if(GetResourceManager()->HasCurrentResource(res))
{
GetResourceManager()->MarkCleanResource(res);
if(GetResourceManager()->HasResourceRecord(res))
GetResourceManager()->GetResourceRecord(res)->Delete(GetResourceManager());
GetResourceManager()->UnregisterResource(res);
}
}
m_Real.glDeleteVertexArrays(n, arrays);
}
#pragma endregion
#pragma region Horrible glVertexAttrib variants
template <typename SerialiserType>
bool WrappedOpenGL::Serialise_glVertexAttrib(SerialiserType &ser, GLuint index, int count,
GLenum type, GLboolean normalized, const void *value,
AttribType attribtype)
{
// this is used to share serialisation code amongst the brazillion variations
SERIALISE_ELEMENT(attribtype).Hidden();
AttribType attr = AttribType(attribtype & Attrib_typemask);
// this is the number of components in the attribute (1,2,3,4). We hide it because it's part of
// the function signature
SERIALISE_ELEMENT(count).Hidden();
SERIALISE_ELEMENT(index);
// only serialise the type and normalized flags for packed commands
if(attr == Attrib_packed)
{
SERIALISE_ELEMENT(type);
SERIALISE_ELEMENT_TYPED(bool, normalized);
}
// create a union of all the value types - since we can only have up to 4, we can just make it
// fixed size
union
{
double d[4];
float f[4];
int32_t i32[4];
uint32_t u32[4];
int16_t i16[4];
uint16_t u16[4];
int8_t i8[4];
uint8_t u8[4];
} v;
if(ser.IsWriting())
{
uint32_t byteCount = count;
if(attr == Attrib_GLbyte)
byteCount *= sizeof(char);
else if(attr == Attrib_GLshort)
byteCount *= sizeof(int16_t);
else if(attr == Attrib_GLint)
byteCount *= sizeof(int32_t);
else if(attr == Attrib_GLubyte)
byteCount *= sizeof(unsigned char);
else if(attr == Attrib_GLushort)
byteCount *= sizeof(uint16_t);
else if(attr == Attrib_GLuint || attr == Attrib_packed)
byteCount *= sizeof(uint32_t);
RDCEraseEl(v);
memcpy(v.f, value, byteCount);
}
// Serialise the array with the right type. We don't want to allocate new storage
switch(attr)
{
case Attrib_GLdouble: ser.Serialise("values", v.d, SerialiserFlags::NoFlags); break;
case Attrib_GLfloat: ser.Serialise("values", v.f, SerialiserFlags::NoFlags); break;
case Attrib_GLint: ser.Serialise("values", v.i32, SerialiserFlags::NoFlags); break;
case Attrib_packed:
case Attrib_GLuint: ser.Serialise("values", v.u32, SerialiserFlags::NoFlags); break;
case Attrib_GLshort: ser.Serialise("values", v.i16, SerialiserFlags::NoFlags); break;
case Attrib_GLushort: ser.Serialise("values", v.u16, SerialiserFlags::NoFlags); break;
case Attrib_GLbyte: ser.Serialise("values", v.i8, SerialiserFlags::NoFlags); break;
default:
case Attrib_GLubyte: ser.Serialise("values", v.u8, SerialiserFlags::NoFlags); break;
}
SERIALISE_CHECK_READ_ERRORS();
if(IsReplayingAndReading())
{
if(attr == Attrib_packed)
{
if(count == 1)
m_Real.glVertexAttribP1uiv(index, type, normalized, v.u32);
else if(count == 2)
m_Real.glVertexAttribP2uiv(index, type, normalized, v.u32);
else if(count == 3)
m_Real.glVertexAttribP3uiv(index, type, normalized, v.u32);
else if(count == 4)
m_Real.glVertexAttribP4uiv(index, type, normalized, v.u32);
}
else if(attribtype & Attrib_I)
{
if(count == 1)
{
if(attr == Attrib_GLint)
m_Real.glVertexAttribI1iv(index, v.i32);
else if(attr == Attrib_GLuint)
m_Real.glVertexAttribI1uiv(index, v.u32);
}
else if(count == 2)
{
if(attr == Attrib_GLint)
m_Real.glVertexAttribI2iv(index, v.i32);
else if(attr == Attrib_GLuint)
m_Real.glVertexAttribI2uiv(index, v.u32);
}
else if(count == 3)
{
if(attr == Attrib_GLint)
m_Real.glVertexAttribI3iv(index, v.i32);
else if(attr == Attrib_GLuint)
m_Real.glVertexAttribI3uiv(index, v.u32);
}
else
{
if(attr == Attrib_GLbyte)
m_Real.glVertexAttribI4bv(index, v.i8);
else if(attr == Attrib_GLshort)
m_Real.glVertexAttribI4sv(index, v.i16);
else if(attr == Attrib_GLint)
m_Real.glVertexAttribI4iv(index, v.i32);
else if(attr == Attrib_GLubyte)
m_Real.glVertexAttribI4ubv(index, v.u8);
else if(attr == Attrib_GLushort)
m_Real.glVertexAttribI4usv(index, v.u16);
else if(attr == Attrib_GLuint)
m_Real.glVertexAttribI4uiv(index, v.u32);
}
}
else if(attribtype & Attrib_L)
{
if(count == 1)
m_Real.glVertexAttribL1dv(index, v.d);
else if(count == 2)
m_Real.glVertexAttribL2dv(index, v.d);
else if(count == 3)
m_Real.glVertexAttribL3dv(index, v.d);
else if(count == 4)
m_Real.glVertexAttribL4dv(index, v.d);
}
else if(attribtype & Attrib_N)
{
if(attr == Attrib_GLbyte)
m_Real.glVertexAttrib4Nbv(index, v.i8);
else if(attr == Attrib_GLshort)
m_Real.glVertexAttrib4Nsv(index, v.i16);
else if(attr == Attrib_GLint)
m_Real.glVertexAttrib4Niv(index, v.i32);
else if(attr == Attrib_GLubyte)
m_Real.glVertexAttrib4Nubv(index, v.u8);
else if(attr == Attrib_GLushort)
m_Real.glVertexAttrib4Nusv(index, v.u16);
else if(attr == Attrib_GLuint)
m_Real.glVertexAttrib4Nuiv(index, v.u32);
}
else
{
if(count == 1)
{
if(attr == Attrib_GLdouble)
m_Real.glVertexAttrib1dv(index, v.d);
else if(attr == Attrib_GLfloat)
m_Real.glVertexAttrib1fv(index, v.f);
else if(attr == Attrib_GLshort)
m_Real.glVertexAttrib1sv(index, v.i16);
}
else if(count == 2)
{
if(attr == Attrib_GLdouble)
m_Real.glVertexAttrib2dv(index, v.d);
else if(attr == Attrib_GLfloat)
m_Real.glVertexAttrib2fv(index, v.f);
else if(attr == Attrib_GLshort)
m_Real.glVertexAttrib2sv(index, v.i16);
}
else if(count == 3)
{
if(attr == Attrib_GLdouble)
m_Real.glVertexAttrib3dv(index, v.d);
else if(attr == Attrib_GLfloat)
m_Real.glVertexAttrib3fv(index, v.f);
else if(attr == Attrib_GLshort)
m_Real.glVertexAttrib3sv(index, v.i16);
}
else
{
if(attr == Attrib_GLdouble)
m_Real.glVertexAttrib4dv(index, v.d);
else if(attr == Attrib_GLfloat)
m_Real.glVertexAttrib4fv(index, v.f);
else if(attr == Attrib_GLbyte)
m_Real.glVertexAttrib4bv(index, v.i8);
else if(attr == Attrib_GLshort)
m_Real.glVertexAttrib4sv(index, v.i16);
else if(attr == Attrib_GLint)
m_Real.glVertexAttrib4iv(index, v.i32);
else if(attr == Attrib_GLubyte)
m_Real.glVertexAttrib4ubv(index, v.u8);
else if(attr == Attrib_GLushort)
m_Real.glVertexAttrib4usv(index, v.u16);
else if(attr == Attrib_GLuint)
m_Real.glVertexAttrib4uiv(index, v.u32);
}
}
}
return true;
}
#define ATTRIB_FUNC(count, suffix, TypeOr, paramtype, ...) \
\
void WrappedOpenGL::CONCAT(glVertexAttrib, suffix)(GLuint index, __VA_ARGS__) \
\
{ \
SERIALISE_TIME_CALL(m_Real.CONCAT(glVertexAttrib, suffix)(index, ARRAYLIST)); \
\
if(IsActiveCapturing(m_State)) \
{ \
USE_SCRATCH_SERIALISER(); \
SCOPED_SERIALISE_CHUNK(gl_CurChunk); \
const paramtype vals[] = {ARRAYLIST}; \
Serialise_glVertexAttrib(ser, index, count, eGL_NONE, GL_FALSE, vals, \
AttribType(TypeOr | CONCAT(Attrib_, paramtype))); \
\
m_ContextRecord->AddChunk(scope.Get()); \
} \
}
#define ARRAYLIST x
ATTRIB_FUNC(1, 1f, 0, GLfloat, GLfloat x)
ATTRIB_FUNC(1, 1s, 0, GLshort, GLshort x)
ATTRIB_FUNC(1, 1d, 0, GLdouble, GLdouble x)
ATTRIB_FUNC(1, L1d, Attrib_L, GLdouble, GLdouble x)
ATTRIB_FUNC(1, I1i, Attrib_I, GLint, GLint x)
ATTRIB_FUNC(1, I1ui, Attrib_I, GLuint, GLuint x)
#undef ARRAYLIST
#define ARRAYLIST x, y
ATTRIB_FUNC(2, 2f, 0, GLfloat, GLfloat x, GLfloat y)
ATTRIB_FUNC(2, 2s, 0, GLshort, GLshort x, GLshort y)
ATTRIB_FUNC(2, 2d, 0, GLdouble, GLdouble x, GLdouble y)
ATTRIB_FUNC(2, L2d, Attrib_L, GLdouble, GLdouble x, GLdouble y)
ATTRIB_FUNC(2, I2i, Attrib_I, GLint, GLint x, GLint y)
ATTRIB_FUNC(2, I2ui, Attrib_I, GLuint, GLuint x, GLuint y)
#undef ARRAYLIST
#define ARRAYLIST x, y, z
ATTRIB_FUNC(3, 3f, 0, GLfloat, GLfloat x, GLfloat y, GLfloat z)
ATTRIB_FUNC(3, 3s, 0, GLshort, GLshort x, GLshort y, GLshort z)
ATTRIB_FUNC(3, 3d, 0, GLdouble, GLdouble x, GLdouble y, GLdouble z)
ATTRIB_FUNC(3, L3d, Attrib_L, GLdouble, GLdouble x, GLdouble y, GLdouble z)
ATTRIB_FUNC(3, I3i, Attrib_I, GLint, GLint x, GLint y, GLint z)
ATTRIB_FUNC(3, I3ui, Attrib_I, GLuint, GLuint x, GLuint y, GLuint z)
#undef ARRAYLIST
#define ARRAYLIST x, y, z, w
ATTRIB_FUNC(4, 4f, 0, GLfloat, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
ATTRIB_FUNC(4, 4s, 0, GLshort, GLshort x, GLshort y, GLshort z, GLshort w)
ATTRIB_FUNC(4, 4d, 0, GLdouble, GLdouble x, GLdouble y, GLdouble z, GLdouble w)
ATTRIB_FUNC(4, L4d, Attrib_L, GLdouble, GLdouble x, GLdouble y, GLdouble z, GLdouble w)
ATTRIB_FUNC(4, I4i, Attrib_I, GLint, GLint x, GLint y, GLint z, GLint w)
ATTRIB_FUNC(4, I4ui, Attrib_I, GLuint, GLuint x, GLuint y, GLuint z, GLuint w)
ATTRIB_FUNC(4, 4Nub, Attrib_N, GLubyte, GLubyte x, GLubyte y, GLubyte z, GLubyte w)
#undef ATTRIB_FUNC
#define ATTRIB_FUNC(count, suffix, TypeOr, paramtype) \
\
void WrappedOpenGL::CONCAT(glVertexAttrib, suffix)(GLuint index, const paramtype *value) \
\
{ \
m_Real.CONCAT(glVertexAttrib, suffix)(index, value); \
\
if(IsActiveCapturing(m_State)) \
{ \
USE_SCRATCH_SERIALISER(); \
SCOPED_SERIALISE_CHUNK(gl_CurChunk); \
Serialise_glVertexAttrib(ser, index, count, eGL_NONE, GL_FALSE, value, \
AttribType(TypeOr | CONCAT(Attrib_, paramtype))); \
\
m_ContextRecord->AddChunk(scope.Get()); \
} \
}
ATTRIB_FUNC(1, 1dv, 0, GLdouble)
ATTRIB_FUNC(2, 2dv, 0, GLdouble)
ATTRIB_FUNC(3, 3dv, 0, GLdouble)
ATTRIB_FUNC(4, 4dv, 0, GLdouble)
ATTRIB_FUNC(1, 1sv, 0, GLshort)
ATTRIB_FUNC(2, 2sv, 0, GLshort)
ATTRIB_FUNC(3, 3sv, 0, GLshort)
ATTRIB_FUNC(4, 4sv, 0, GLshort)
ATTRIB_FUNC(1, 1fv, 0, GLfloat)
ATTRIB_FUNC(2, 2fv, 0, GLfloat)
ATTRIB_FUNC(3, 3fv, 0, GLfloat)
ATTRIB_FUNC(4, 4fv, 0, GLfloat)
ATTRIB_FUNC(4, 4bv, 0, GLbyte)
ATTRIB_FUNC(4, 4iv, 0, GLint)
ATTRIB_FUNC(4, 4uiv, 0, GLuint)
ATTRIB_FUNC(4, 4usv, 0, GLushort)
ATTRIB_FUNC(4, 4ubv, 0, GLubyte)
ATTRIB_FUNC(1, L1dv, Attrib_L, GLdouble)
ATTRIB_FUNC(2, L2dv, Attrib_L, GLdouble)
ATTRIB_FUNC(3, L3dv, Attrib_L, GLdouble)
ATTRIB_FUNC(4, L4dv, Attrib_L, GLdouble)
ATTRIB_FUNC(1, I1iv, Attrib_I, GLint)
ATTRIB_FUNC(1, I1uiv, Attrib_I, GLuint)
ATTRIB_FUNC(2, I2iv, Attrib_I, GLint)
ATTRIB_FUNC(2, I2uiv, Attrib_I, GLuint)
ATTRIB_FUNC(3, I3iv, Attrib_I, GLint)
ATTRIB_FUNC(3, I3uiv, Attrib_I, GLuint)
ATTRIB_FUNC(4, I4bv, Attrib_I, GLbyte)
ATTRIB_FUNC(4, I4iv, Attrib_I, GLint)
ATTRIB_FUNC(4, I4sv, Attrib_I, GLshort)
ATTRIB_FUNC(4, I4ubv, Attrib_I, GLubyte)
ATTRIB_FUNC(4, I4uiv, Attrib_I, GLuint)
ATTRIB_FUNC(4, I4usv, Attrib_I, GLushort)
ATTRIB_FUNC(4, 4Nbv, Attrib_N, GLbyte)
ATTRIB_FUNC(4, 4Niv, Attrib_N, GLint)
ATTRIB_FUNC(4, 4Nsv, Attrib_N, GLshort)
ATTRIB_FUNC(4, 4Nubv, Attrib_N, GLubyte)
ATTRIB_FUNC(4, 4Nuiv, Attrib_N, GLuint)
ATTRIB_FUNC(4, 4Nusv, Attrib_N, GLushort)
#undef ATTRIB_FUNC
#define ATTRIB_FUNC(count, suffix, funcparam, passparam) \
\
void WrappedOpenGL::CONCAT(CONCAT(glVertexAttribP, count), suffix)( \
GLuint index, GLenum type, GLboolean normalized, funcparam) \
\
{ \
m_Real.CONCAT(CONCAT(glVertexAttribP, count), suffix)(index, type, normalized, value); \
\
if(IsActiveCapturing(m_State)) \
{ \
USE_SCRATCH_SERIALISER(); \
SCOPED_SERIALISE_CHUNK(gl_CurChunk); \
Serialise_glVertexAttrib(ser, index, count, type, normalized, passparam, Attrib_packed); \
\
m_ContextRecord->AddChunk(scope.Get()); \
} \
}
ATTRIB_FUNC(1, ui, GLuint value, &value)
ATTRIB_FUNC(2, ui, GLuint value, &value)
ATTRIB_FUNC(3, ui, GLuint value, &value)
ATTRIB_FUNC(4, ui, GLuint value, &value)
ATTRIB_FUNC(1, uiv, const GLuint *value, value)
ATTRIB_FUNC(2, uiv, const GLuint *value, value)
ATTRIB_FUNC(3, uiv, const GLuint *value, value)
ATTRIB_FUNC(4, uiv, const GLuint *value, value)
#pragma endregion
INSTANTIATE_FUNCTION_SERIALISED(void, glGenBuffers, GLsizei n, GLuint *buffers);
INSTANTIATE_FUNCTION_SERIALISED(void, glCreateBuffers, GLsizei n, GLuint *buffers);
INSTANTIATE_FUNCTION_SERIALISED(void, glBindBuffer, GLenum target, GLuint bufferHandle);
INSTANTIATE_FUNCTION_SERIALISED(void, glNamedBufferStorageEXT, GLuint buffer, GLsizeiptr size,
const void *data, GLbitfield flags);
INSTANTIATE_FUNCTION_SERIALISED(void, glNamedBufferDataEXT, GLuint buffer, GLsizeiptr size,
const void *data, GLenum usage);
INSTANTIATE_FUNCTION_SERIALISED(void, glNamedBufferSubDataEXT, GLuint buffer, GLintptr offsetPtr,
GLsizeiptr size, const void *data);
INSTANTIATE_FUNCTION_SERIALISED(void, glNamedCopyBufferSubDataEXT, GLuint readBufferHandle,
GLuint writeBufferHandle, GLintptr readOffsetPtr,
GLintptr writeOffsetPtr, GLsizeiptr sizePtr);
INSTANTIATE_FUNCTION_SERIALISED(void, glBindBufferBase, GLenum target, GLuint index, GLuint buffer);
INSTANTIATE_FUNCTION_SERIALISED(void, glBindBufferRange, GLenum target, GLuint index,
GLuint bufferHandle, GLintptr offsetPtr, GLsizeiptr sizePtr);
INSTANTIATE_FUNCTION_SERIALISED(void, glBindBuffersBase, GLenum target, GLuint first, GLsizei count,
const GLuint *bufferHandles);
INSTANTIATE_FUNCTION_SERIALISED(void, glBindBuffersRange, GLenum target, GLuint first,
GLsizei count, const GLuint *bufferHandles, const GLintptr *offsets,
const GLsizeiptr *sizes);
INSTANTIATE_FUNCTION_SERIALISED(void, glUnmapNamedBufferEXT, GLuint buffer);
INSTANTIATE_FUNCTION_SERIALISED(void, glFlushMappedNamedBufferRangeEXT, GLuint buffer,
GLintptr offset, GLsizeiptr length);
INSTANTIATE_FUNCTION_SERIALISED(void, glGenTransformFeedbacks, GLsizei n, GLuint *ids);
INSTANTIATE_FUNCTION_SERIALISED(void, glCreateTransformFeedbacks, GLsizei n, GLuint *ids);
INSTANTIATE_FUNCTION_SERIALISED(void, glTransformFeedbackBufferBase, GLuint xfbHandle, GLuint index,
GLuint bufferHandle);
INSTANTIATE_FUNCTION_SERIALISED(void, glTransformFeedbackBufferRange, GLuint xfbHandle,
GLuint index, GLuint bufferHandle, GLintptr offset, GLsizeiptr size);
INSTANTIATE_FUNCTION_SERIALISED(void, glBindTransformFeedback, GLenum target, GLuint xfbHandle);
INSTANTIATE_FUNCTION_SERIALISED(void, glBeginTransformFeedback, GLenum primitiveMode);
INSTANTIATE_FUNCTION_SERIALISED(void, glPauseTransformFeedback);
INSTANTIATE_FUNCTION_SERIALISED(void, glResumeTransformFeedback);
INSTANTIATE_FUNCTION_SERIALISED(void, glEndTransformFeedback);
INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribOffsetEXT, GLuint vaobj,
GLuint buffer, GLuint index, GLint size, GLenum type,
GLboolean normalized, GLsizei stride, GLintptr offset);
INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribIOffsetEXT, GLuint vaobj,
GLuint buffer, GLuint index, GLint size, GLenum type,
GLsizei stride, GLintptr offset);
INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribLOffsetEXT, GLuint vaobj,
GLuint buffer, GLuint index, GLint size, GLenum type,
GLsizei stride, GLintptr pointer);
INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribBindingEXT, GLuint vaobj,
GLuint attribindex, GLuint bindingindex);
INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribFormatEXT, GLuint vaobj,
GLuint attribindex, GLint size, GLenum type, GLboolean normalized,
GLuint relativeoffset);
INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribIFormatEXT, GLuint vaobj,
GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);
INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribLFormatEXT, GLuint vaobj,
GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset);
INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexAttribDivisorEXT, GLuint vaobj,
GLuint index, GLuint divisor);
INSTANTIATE_FUNCTION_SERIALISED(void, glEnableVertexArrayAttribEXT, GLuint vaobj, GLuint index);
INSTANTIATE_FUNCTION_SERIALISED(void, glDisableVertexArrayAttribEXT, GLuint vaobj, GLuint index);
INSTANTIATE_FUNCTION_SERIALISED(void, glGenVertexArrays, GLsizei n, GLuint *arrays);
INSTANTIATE_FUNCTION_SERIALISED(void, glCreateVertexArrays, GLsizei n, GLuint *arrays);
INSTANTIATE_FUNCTION_SERIALISED(void, glBindVertexArray, GLuint arrayHandle);
INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayElementBuffer, GLuint vaobjHandle,
GLuint bufferHandle);
INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayBindVertexBufferEXT, GLuint vaobj,
GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride);
INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexBuffers, GLuint vaobjHandle, GLuint first,
GLsizei count, const GLuint *buffers, const GLintptr *offsets,
const GLsizei *strides);
INSTANTIATE_FUNCTION_SERIALISED(void, glVertexArrayVertexBindingDivisorEXT, GLuint vaobj,
GLuint bindingindex, GLuint divisor);
INSTANTIATE_FUNCTION_SERIALISED(void, glVertexAttrib, GLuint index, int count, GLenum type,
GLboolean normalized, const void *value, AttribType attribtype);
| etnlGD/renderdoc | renderdoc/driver/gl/wrappers/gl_buffer_funcs.cpp | C++ | mit | 180,105 |
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
namespace PInvoke
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using static Kernel32;
/// <content>
/// Methods and nested types that are not strictly P/Invokes but provide
/// a slightly higher level of functionality to ease calling into native code.
/// </content>
[SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Functions are named like their native counterparts")]
public static partial class Hid
{
public static Guid HidD_GetHidGuid()
{
Guid guid;
HidD_GetHidGuid(out guid);
return guid;
}
public static HiddAttributes HidD_GetAttributes(SafeObjectHandle hFile)
{
var result = HiddAttributes.Create();
if (!HidD_GetAttributes(hFile, ref result))
{
throw new Win32Exception();
}
return result;
}
public static SafePreparsedDataHandle HidD_GetPreparsedData(SafeObjectHandle hDevice)
{
SafePreparsedDataHandle preparsedDataHandle;
if (!HidD_GetPreparsedData(hDevice, out preparsedDataHandle))
{
throw new Win32Exception();
}
return preparsedDataHandle;
}
public static HidpCaps HidP_GetCaps(SafePreparsedDataHandle preparsedData)
{
var hidCaps = default(HidpCaps);
var result = HidP_GetCaps(preparsedData, ref hidCaps);
switch (result.Value)
{
case NTSTATUS.Code.HIDP_STATUS_SUCCESS:
return hidCaps;
case NTSTATUS.Code.HIDP_STATUS_INVALID_PREPARSED_DATA:
throw new ArgumentException("The specified preparsed data is invalid.", nameof(preparsedData));
default:
result.ThrowOnError();
throw new InvalidOperationException("HidP_GetCaps returned an unexpected success value");
}
}
public static bool HidD_GetManufacturerString(SafeObjectHandle hidDeviceObject, out string result)
{
return GrowStringBuffer(sb => HidD_GetManufacturerString(hidDeviceObject, sb, sb.Capacity), out result);
}
public static bool HidD_GetProductString(SafeObjectHandle hidDeviceObject, out string result)
{
return GrowStringBuffer(sb => HidD_GetProductString(hidDeviceObject, sb, sb.Capacity), out result);
}
public static bool HidD_GetSerialNumberString(SafeObjectHandle hidDeviceObject, out string result)
{
return GrowStringBuffer(sb => HidD_GetSerialNumberString(hidDeviceObject, sb, sb.Capacity), out result);
}
public static string HidD_GetManufacturerString(SafeObjectHandle hidDeviceObject)
{
string result;
if (!HidD_GetManufacturerString(hidDeviceObject, out result))
{
throw new Win32Exception();
}
return result;
}
public static string HidD_GetProductString(SafeObjectHandle hidDeviceObject)
{
string result;
if (!HidD_GetProductString(hidDeviceObject, out result))
{
throw new Win32Exception();
}
return result;
}
public static string HidD_GetSerialNumberString(SafeObjectHandle hidDeviceObject)
{
string result;
if (!HidD_GetSerialNumberString(hidDeviceObject, out result))
{
throw new Win32Exception();
}
return result;
}
private static bool GrowStringBuffer(Func<StringBuilder, bool> nativeMethod, out string result)
{
// USB Hid maximum size is 126 wide chars + '\0' = 254 bytes, allocating 256 bytes we should never grow
// until another HID standard decide otherwise.
var stringBuilder = new StringBuilder(256);
// If we ever resize over this value something got really wrong
const int maximumRealisticSize = 1 * 1024 * 2014;
while (stringBuilder.Capacity < maximumRealisticSize)
{
if (nativeMethod(stringBuilder))
{
result = stringBuilder.ToString();
return true;
}
if (GetLastError() != Win32ErrorCode.ERROR_INVALID_USER_BUFFER)
{
result = null;
return false;
}
stringBuilder.Capacity = stringBuilder.Capacity * 2;
}
result = null;
return false;
}
}
}
| vbfox/pinvoke | src/Hid/Hid.Helpers.cs | C# | mit | 5,014 |
var searchData=
[
['player',['player',['../classplayer.html#a4c43d838817775e2a2b0241d30de4abc',1,'player']]]
];
| gawag/Spooky-Urho-Sample | doxygen/html/search/functions_6.js | JavaScript | mit | 114 |
//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
using System;
namespace nanoFramework.Tools.Debugger.Usb
{
// This class is kept here for reference only.
// It was to provide backwards compatibility with NETMF WinUSB devices of v4.4
// In the current nanoFramework implementation USB connection with devices is carried using USB CDC
public class STM_Discovery4
{
public const UInt16 DeviceVid = 0x0483;
public const UInt16 DevicePid = 0xA08F;
/// <summary>
/// USB device interface class GUID. For NETMF debug capable devices this must be {D32D1D64-963D-463E-874A-8EC8C8082CBF}.
/// </summary>
public static Guid DeviceInterfaceClass = new Guid("{D32D1D64-963D-463E-874A-8EC8C8082CBF}");
/// <summary>
/// ID string for the device
/// </summary>
public static String IDString
{
get { return String.Format("VID_{0:X4}&PID_{1:X4}", DeviceVid, DevicePid); }
}
public static new string ToString()
{
return "ST Discovery4";
}
}
}
| nanoframework/nf-debugger | nanoFramework.Tools.DebugLibrary.Shared/SupportedUSBDevices/STM_Discovery4.cs | C# | mit | 1,181 |
/* dtpicker javascript jQuery */
(function($) {
// 严格模式
'use strict';
// 控件类名
var pluginName = 'dtpicker';
var PluginClass=T.UI.Controls.DTPicker;
var pluginRef = 't-plugin-ref';
// 胶水代码
$.fn[pluginName] = function(options) {
if(typeof options === 'string'){
// 2. 调用API
var plugin = this.data(pluginRef);
if(!plugin || !plugin[options]){
throw '方法 ' + options + ' 不存在';
}
var result = plugin[options].apply(plugin, Array.prototype.slice.call(arguments, 1));
if(options === 'destroy'){
jqElement.removeData(pluginRef);
}
return result;
}
this.each(function () {
var jqElement=$(this);
var plugin = jqElement.data(pluginRef);
if(plugin === undefined){
// 1. 创建新对象
plugin=new PluginClass(this, $.extend(true, {}, options));
jqElement.data(pluginRef, plugin);
}
else{
// 3. 更新选项
plugin.updateOptions || plugin.updateOptions(options);
}
});
return this;
};
})(jQuery);
// (function($) {
// // 'use strict';
// var dateTimePicker = function (element, options) {
// /********************************************************************************
// *
// * Public API functions
// * =====================
// *
// * Important: Do not expose direct references to private objects or the options
// * object to the outer world. Always return a clone when returning values or make
// * a clone when setting a private variable.
// *
// ********************************************************************************/
// picker.toggle = toggle;
// picker.show = show;
// picker.hide = hide;
// picker.ignoreReadonly = function (ignoreReadonly) {
// if (arguments.length === 0) {
// return options.ignoreReadonly;
// }
// if (typeof ignoreReadonly !== 'boolean') {
// throw new TypeError('ignoreReadonly () expects a boolean parameter');
// }
// options.ignoreReadonly = ignoreReadonly;
// return picker;
// };
// picker.options = function (newOptions) {
// if (arguments.length === 0) {
// return $.extend(true, {}, options);
// }
// if (!(newOptions instanceof Object)) {
// throw new TypeError('options() options parameter should be an object');
// }
// $.extend(true, options, newOptions);
// $.each(options, function (key, value) {
// if (picker[key] !== undefined) {
// picker[key](value);
// } else {
// throw new TypeError('option ' + key + ' is not recognized!');
// }
// });
// return picker;
// };
// picker.date = function (newDate) {
// ///<signature helpKeyword="$.fn.datetimepicker.date">
// ///<summary>Returns the component's model current date, a moment object or null if not set.</summary>
// ///<returns type="Moment">date.clone()</returns>
// ///</signature>
// ///<signature>
// ///<summary>Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.</summary>
// ///<param name="newDate" locid="$.fn.datetimepicker.date_p:newDate">Takes string, Date, moment, null parameter.</param>
// ///</signature>
// if (arguments.length === 0) {
// if (unset) {
// return null;
// }
// return date.clone();
// }
// if (newDate !== null && typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) {
// throw new TypeError('date() parameter must be one of [null, string, moment or Date]');
// }
// setValue(newDate === null ? null : parseInputDate(newDate));
// return picker;
// };
// picker.format = function (newFormat) {
// ///<summary>test su</summary>
// ///<param name="newFormat">info about para</param>
// ///<returns type="string|boolean">returns foo</returns>
// if (arguments.length === 0) {
// return options.format;
// }
// if ((typeof newFormat !== 'string') && ((typeof newFormat !== 'boolean') || (newFormat !== false))) {
// throw new TypeError('format() expects a sting or boolean:false parameter ' + newFormat);
// }
// options.format = newFormat;
// if (actualFormat) {
// initFormatting(); // reinit formatting
// }
// return picker;
// };
// picker.timeZone = function (newZone) {
// if (arguments.length === 0) {
// return options.timeZone;
// }
// options.timeZone = newZone;
// return picker;
// };
// picker.dayViewHeaderFormat = function (newFormat) {
// if (arguments.length === 0) {
// return options.dayViewHeaderFormat;
// }
// if (typeof newFormat !== 'string') {
// throw new TypeError('dayViewHeaderFormat() expects a string parameter');
// }
// options.dayViewHeaderFormat = newFormat;
// return picker;
// };
// picker.extraFormats = function (formats) {
// if (arguments.length === 0) {
// return options.extraFormats;
// }
// if (formats !== false && !(formats instanceof Array)) {
// throw new TypeError('extraFormats() expects an array or false parameter');
// }
// options.extraFormats = formats;
// if (parseFormats) {
// initFormatting(); // reinit formatting
// }
// return picker;
// };
// picker.disabledDates = function (dates) {
// ///<signature helpKeyword="$.fn.datetimepicker.disabledDates">
// ///<summary>Returns an array with the currently set disabled dates on the component.</summary>
// ///<returns type="array">options.disabledDates</returns>
// ///</signature>
// ///<signature>
// ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of
// ///options.enabledDates if such exist.</summary>
// ///<param name="dates" locid="$.fn.datetimepicker.disabledDates_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param>
// ///</signature>
// if (arguments.length === 0) {
// return (options.disabledDates ? $.extend({}, options.disabledDates) : options.disabledDates);
// }
// if (!dates) {
// options.disabledDates = false;
// update();
// return picker;
// }
// if (!(dates instanceof Array)) {
// throw new TypeError('disabledDates() expects an array parameter');
// }
// options.disabledDates = indexGivenDates(dates);
// options.enabledDates = false;
// update();
// return picker;
// };
// picker.enabledDates = function (dates) {
// ///<signature helpKeyword="$.fn.datetimepicker.enabledDates">
// ///<summary>Returns an array with the currently set enabled dates on the component.</summary>
// ///<returns type="array">options.enabledDates</returns>
// ///</signature>
// ///<signature>
// ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledDates if such exist.</summary>
// ///<param name="dates" locid="$.fn.datetimepicker.enabledDates_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param>
// ///</signature>
// if (arguments.length === 0) {
// return (options.enabledDates ? $.extend({}, options.enabledDates) : options.enabledDates);
// }
// if (!dates) {
// options.enabledDates = false;
// update();
// return picker;
// }
// if (!(dates instanceof Array)) {
// throw new TypeError('enabledDates() expects an array parameter');
// }
// options.enabledDates = indexGivenDates(dates);
// options.disabledDates = false;
// update();
// return picker;
// };
// picker.daysOfWeekDisabled = function (daysOfWeekDisabled) {
// if (arguments.length === 0) {
// return options.daysOfWeekDisabled.splice(0);
// }
// if ((typeof daysOfWeekDisabled === 'boolean') && !daysOfWeekDisabled) {
// options.daysOfWeekDisabled = false;
// update();
// return picker;
// }
// if (!(daysOfWeekDisabled instanceof Array)) {
// throw new TypeError('daysOfWeekDisabled() expects an array parameter');
// }
// options.daysOfWeekDisabled = daysOfWeekDisabled.reduce(function (previousValue, currentValue) {
// currentValue = parseInt(currentValue, 10);
// if (currentValue > 6 || currentValue < 0 || isNaN(currentValue)) {
// return previousValue;
// }
// if (previousValue.indexOf(currentValue) === -1) {
// previousValue.push(currentValue);
// }
// return previousValue;
// }, []).sort();
// if (options.useCurrent && !options.keepInvalid) {
// var tries = 0;
// while (!isValid(date, 'd')) {
// date.add(1, 'd');
// if (tries === 7) {
// throw 'Tried 7 times to find a valid date';
// }
// tries++;
// }
// setValue(date);
// }
// update();
// return picker;
// };
// picker.maxDate = function (maxDate) {
// if (arguments.length === 0) {
// return options.maxDate ? options.maxDate.clone() : options.maxDate;
// }
// if ((typeof maxDate === 'boolean') && maxDate === false) {
// options.maxDate = false;
// update();
// return picker;
// }
// if (typeof maxDate === 'string') {
// if (maxDate === 'now' || maxDate === 'moment') {
// maxDate = getMoment();
// }
// }
// var parsedDate = parseInputDate(maxDate);
// if (!parsedDate.isValid()) {
// throw new TypeError('maxDate() Could not parse date parameter: ' + maxDate);
// }
// if (options.minDate && parsedDate.isBefore(options.minDate)) {
// throw new TypeError('maxDate() date parameter is before options.minDate: ' + parsedDate.format(actualFormat));
// }
// options.maxDate = parsedDate;
// if (options.useCurrent && !options.keepInvalid && date.isAfter(maxDate)) {
// setValue(options.maxDate);
// }
// if (viewDate.isAfter(parsedDate)) {
// viewDate = parsedDate.clone().subtract(options.stepping, 'm');
// }
// update();
// return picker;
// };
// picker.minDate = function (minDate) {
// if (arguments.length === 0) {
// return options.minDate ? options.minDate.clone() : options.minDate;
// }
// if ((typeof minDate === 'boolean') && minDate === false) {
// options.minDate = false;
// update();
// return picker;
// }
// if (typeof minDate === 'string') {
// if (minDate === 'now' || minDate === 'moment') {
// minDate = getMoment();
// }
// }
// var parsedDate = parseInputDate(minDate);
// if (!parsedDate.isValid()) {
// throw new TypeError('minDate() Could not parse date parameter: ' + minDate);
// }
// if (options.maxDate && parsedDate.isAfter(options.maxDate)) {
// throw new TypeError('minDate() date parameter is after options.maxDate: ' + parsedDate.format(actualFormat));
// }
// options.minDate = parsedDate;
// if (options.useCurrent && !options.keepInvalid && date.isBefore(minDate)) {
// setValue(options.minDate);
// }
// if (viewDate.isBefore(parsedDate)) {
// viewDate = parsedDate.clone().add(options.stepping, 'm');
// }
// update();
// return picker;
// };
// picker.defaultDate = function (defaultDate) {
// ///<signature helpKeyword="$.fn.datetimepicker.defaultDate">
// ///<summary>Returns a moment with the options.defaultDate option configuration or false if not set</summary>
// ///<returns type="Moment">date.clone()</returns>
// ///</signature>
// ///<signature>
// ///<summary>Will set the picker's inital date. If a boolean:false value is passed the options.defaultDate parameter is cleared.</summary>
// ///<param name="defaultDate" locid="$.fn.datetimepicker.defaultDate_p:defaultDate">Takes a string, Date, moment, boolean:false</param>
// ///</signature>
// if (arguments.length === 0) {
// return options.defaultDate ? options.defaultDate.clone() : options.defaultDate;
// }
// if (!defaultDate) {
// options.defaultDate = false;
// return picker;
// }
// if (typeof defaultDate === 'string') {
// if (defaultDate === 'now' || defaultDate === 'moment') {
// defaultDate = getMoment();
// }
// }
// var parsedDate = parseInputDate(defaultDate);
// if (!parsedDate.isValid()) {
// throw new TypeError('defaultDate() Could not parse date parameter: ' + defaultDate);
// }
// if (!isValid(parsedDate)) {
// throw new TypeError('defaultDate() date passed is invalid according to component setup validations');
// }
// options.defaultDate = parsedDate;
// if ((options.defaultDate && options.inline) || input.val().trim() === '') {
// setValue(options.defaultDate);
// }
// return picker;
// };
// picker.locale = function (locale) {
// if (arguments.length === 0) {
// return options.locale;
// }
// if (!moment.localeData(locale)) {
// throw new TypeError('locale() locale ' + locale + ' is not loaded from moment locales!');
// }
// options.locale = locale;
// date.locale(options.locale);
// viewDate.locale(options.locale);
// if (actualFormat) {
// initFormatting(); // reinit formatting
// }
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.stepping = function (stepping) {
// if (arguments.length === 0) {
// return options.stepping;
// }
// stepping = parseInt(stepping, 10);
// if (isNaN(stepping) || stepping < 1) {
// stepping = 1;
// }
// options.stepping = stepping;
// return picker;
// };
// picker.useCurrent = function (useCurrent) {
// var useCurrentOptions = ['year', 'month', 'day', 'hour', 'minute'];
// if (arguments.length === 0) {
// return options.useCurrent;
// }
// if ((typeof useCurrent !== 'boolean') && (typeof useCurrent !== 'string')) {
// throw new TypeError('useCurrent() expects a boolean or string parameter');
// }
// if (typeof useCurrent === 'string' && useCurrentOptions.indexOf(useCurrent.toLowerCase()) === -1) {
// throw new TypeError('useCurrent() expects a string parameter of ' + useCurrentOptions.join(', '));
// }
// options.useCurrent = useCurrent;
// return picker;
// };
// picker.collapse = function (collapse) {
// if (arguments.length === 0) {
// return options.collapse;
// }
// if (typeof collapse !== 'boolean') {
// throw new TypeError('collapse() expects a boolean parameter');
// }
// if (options.collapse === collapse) {
// return picker;
// }
// options.collapse = collapse;
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.icons = function (icons) {
// if (arguments.length === 0) {
// return $.extend({}, options.icons);
// }
// if (!(icons instanceof Object)) {
// throw new TypeError('icons() expects parameter to be an Object');
// }
// $.extend(options.icons, icons);
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.tooltips = function (tooltips) {
// if (arguments.length === 0) {
// return $.extend({}, options.tooltips);
// }
// if (!(tooltips instanceof Object)) {
// throw new TypeError('tooltips() expects parameter to be an Object');
// }
// $.extend(options.tooltips, tooltips);
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.useStrict = function (useStrict) {
// if (arguments.length === 0) {
// return options.useStrict;
// }
// if (typeof useStrict !== 'boolean') {
// throw new TypeError('useStrict() expects a boolean parameter');
// }
// options.useStrict = useStrict;
// return picker;
// };
// picker.sideBySide = function (sideBySide) {
// if (arguments.length === 0) {
// return options.sideBySide;
// }
// if (typeof sideBySide !== 'boolean') {
// throw new TypeError('sideBySide() expects a boolean parameter');
// }
// options.sideBySide = sideBySide;
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.viewMode = function (viewMode) {
// if (arguments.length === 0) {
// return options.viewMode;
// }
// if (typeof viewMode !== 'string') {
// throw new TypeError('viewMode() expects a string parameter');
// }
// if (viewModes.indexOf(viewMode) === -1) {
// throw new TypeError('viewMode() parameter must be one of (' + viewModes.join(', ') + ') value');
// }
// options.viewMode = viewMode;
// currentViewMode = Math.max(viewModes.indexOf(viewMode), minViewModeNumber);
// showMode();
// return picker;
// };
// picker.toolbarPlacement = function (toolbarPlacement) {
// if (arguments.length === 0) {
// return options.toolbarPlacement;
// }
// if (typeof toolbarPlacement !== 'string') {
// throw new TypeError('toolbarPlacement() expects a string parameter');
// }
// if (toolbarPlacements.indexOf(toolbarPlacement) === -1) {
// throw new TypeError('toolbarPlacement() parameter must be one of (' + toolbarPlacements.join(', ') + ') value');
// }
// options.toolbarPlacement = toolbarPlacement;
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.widgetPositioning = function (widgetPositioning) {
// if (arguments.length === 0) {
// return $.extend({}, options.widgetPositioning);
// }
// if (({}).toString.call(widgetPositioning) !== '[object Object]') {
// throw new TypeError('widgetPositioning() expects an object variable');
// }
// if (widgetPositioning.horizontal) {
// if (typeof widgetPositioning.horizontal !== 'string') {
// throw new TypeError('widgetPositioning() horizontal variable must be a string');
// }
// widgetPositioning.horizontal = widgetPositioning.horizontal.toLowerCase();
// if (horizontalModes.indexOf(widgetPositioning.horizontal) === -1) {
// throw new TypeError('widgetPositioning() expects horizontal parameter to be one of (' + horizontalModes.join(', ') + ')');
// }
// options.widgetPositioning.horizontal = widgetPositioning.horizontal;
// }
// if (widgetPositioning.vertical) {
// if (typeof widgetPositioning.vertical !== 'string') {
// throw new TypeError('widgetPositioning() vertical variable must be a string');
// }
// widgetPositioning.vertical = widgetPositioning.vertical.toLowerCase();
// if (verticalModes.indexOf(widgetPositioning.vertical) === -1) {
// throw new TypeError('widgetPositioning() expects vertical parameter to be one of (' + verticalModes.join(', ') + ')');
// }
// options.widgetPositioning.vertical = widgetPositioning.vertical;
// }
// update();
// return picker;
// };
// picker.calendarWeeks = function (calendarWeeks) {
// if (arguments.length === 0) {
// return options.calendarWeeks;
// }
// if (typeof calendarWeeks !== 'boolean') {
// throw new TypeError('calendarWeeks() expects parameter to be a boolean value');
// }
// options.calendarWeeks = calendarWeeks;
// update();
// return picker;
// };
// picker.showTodayButton = function (showTodayButton) {
// if (arguments.length === 0) {
// return options.showTodayButton;
// }
// if (typeof showTodayButton !== 'boolean') {
// throw new TypeError('showTodayButton() expects a boolean parameter');
// }
// options.showTodayButton = showTodayButton;
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.showClear = function (showClear) {
// if (arguments.length === 0) {
// return options.showClear;
// }
// if (typeof showClear !== 'boolean') {
// throw new TypeError('showClear() expects a boolean parameter');
// }
// options.showClear = showClear;
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.widgetParent = function (widgetParent) {
// if (arguments.length === 0) {
// return options.widgetParent;
// }
// if (typeof widgetParent === 'string') {
// widgetParent = $(widgetParent);
// }
// if (widgetParent !== null && (typeof widgetParent !== 'string' && !(widgetParent instanceof $))) {
// throw new TypeError('widgetParent() expects a string or a jQuery object parameter');
// }
// options.widgetParent = widgetParent;
// if (widget) {
// hide();
// show();
// }
// return picker;
// };
// picker.keepOpen = function (keepOpen) {
// if (arguments.length === 0) {
// return options.keepOpen;
// }
// if (typeof keepOpen !== 'boolean') {
// throw new TypeError('keepOpen() expects a boolean parameter');
// }
// options.keepOpen = keepOpen;
// return picker;
// };
// picker.focusOnShow = function (focusOnShow) {
// if (arguments.length === 0) {
// return options.focusOnShow;
// }
// if (typeof focusOnShow !== 'boolean') {
// throw new TypeError('focusOnShow() expects a boolean parameter');
// }
// options.focusOnShow = focusOnShow;
// return picker;
// };
// picker.inline = function (inline) {
// if (arguments.length === 0) {
// return options.inline;
// }
// if (typeof inline !== 'boolean') {
// throw new TypeError('inline() expects a boolean parameter');
// }
// options.inline = inline;
// return picker;
// };
// picker.clear = function () {
// clear();
// return picker;
// };
// picker.keyBinds = function (keyBinds) {
// options.keyBinds = keyBinds;
// return picker;
// };
// picker.getMoment = function (d) {
// return this.getMoment(d);
// };
// picker.debug = function (debug) {
// if (typeof debug !== 'boolean') {
// throw new TypeError('debug() expects a boolean parameter');
// }
// options.debug = debug;
// return picker;
// };
// picker.allowInputToggle = function (allowInputToggle) {
// if (arguments.length === 0) {
// return options.allowInputToggle;
// }
// if (typeof allowInputToggle !== 'boolean') {
// throw new TypeError('allowInputToggle() expects a boolean parameter');
// }
// options.allowInputToggle = allowInputToggle;
// return picker;
// };
// picker.showClose = function (showClose) {
// if (arguments.length === 0) {
// return options.showClose;
// }
// if (typeof showClose !== 'boolean') {
// throw new TypeError('showClose() expects a boolean parameter');
// }
// options.showClose = showClose;
// return picker;
// };
// picker.keepInvalid = function (keepInvalid) {
// if (arguments.length === 0) {
// return options.keepInvalid;
// }
// if (typeof keepInvalid !== 'boolean') {
// throw new TypeError('keepInvalid() expects a boolean parameter');
// }
// options.keepInvalid = keepInvalid;
// return picker;
// };
// picker.datepickerInput = function (datepickerInput) {
// if (arguments.length === 0) {
// return options.datepickerInput;
// }
// if (typeof datepickerInput !== 'string') {
// throw new TypeError('datepickerInput() expects a string parameter');
// }
// options.datepickerInput = datepickerInput;
// return picker;
// };
// picker.parseInputDate = function (parseInputDate) {
// if (arguments.length === 0) {
// return options.parseInputDate;
// }
// if (typeof parseInputDate !== 'function') {
// throw new TypeError('parseInputDate() sholud be as function');
// }
// options.parseInputDate = parseInputDate;
// return picker;
// };
// picker.disabledTimeIntervals = function (disabledTimeIntervals) {
// ///<signature helpKeyword="$.fn.datetimepicker.disabledTimeIntervals">
// ///<summary>Returns an array with the currently set disabled dates on the component.</summary>
// ///<returns type="array">options.disabledTimeIntervals</returns>
// ///</signature>
// ///<signature>
// ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of
// ///options.enabledDates if such exist.</summary>
// ///<param name="dates" locid="$.fn.datetimepicker.disabledTimeIntervals_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param>
// ///</signature>
// if (arguments.length === 0) {
// return (options.disabledTimeIntervals ? $.extend({}, options.disabledTimeIntervals) : options.disabledTimeIntervals);
// }
// if (!disabledTimeIntervals) {
// options.disabledTimeIntervals = false;
// update();
// return picker;
// }
// if (!(disabledTimeIntervals instanceof Array)) {
// throw new TypeError('disabledTimeIntervals() expects an array parameter');
// }
// options.disabledTimeIntervals = disabledTimeIntervals;
// update();
// return picker;
// };
// picker.disabledHours = function (hours) {
// ///<signature helpKeyword="$.fn.datetimepicker.disabledHours">
// ///<summary>Returns an array with the currently set disabled hours on the component.</summary>
// ///<returns type="array">options.disabledHours</returns>
// ///</signature>
// ///<signature>
// ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of
// ///options.enabledHours if such exist.</summary>
// ///<param name="hours" locid="$.fn.datetimepicker.disabledHours_p:hours">Takes an [ int ] of values and disallows the user to select only from those hours.</param>
// ///</signature>
// if (arguments.length === 0) {
// return (options.disabledHours ? $.extend({}, options.disabledHours) : options.disabledHours);
// }
// if (!hours) {
// options.disabledHours = false;
// update();
// return picker;
// }
// if (!(hours instanceof Array)) {
// throw new TypeError('disabledHours() expects an array parameter');
// }
// options.disabledHours = indexGivenHours(hours);
// options.enabledHours = false;
// if (options.useCurrent && !options.keepInvalid) {
// var tries = 0;
// while (!isValid(date, 'h')) {
// date.add(1, 'h');
// if (tries === 24) {
// throw 'Tried 24 times to find a valid date';
// }
// tries++;
// }
// setValue(date);
// }
// update();
// return picker;
// };
// picker.enabledHours = function (hours) {
// ///<signature helpKeyword="$.fn.datetimepicker.enabledHours">
// ///<summary>Returns an array with the currently set enabled hours on the component.</summary>
// ///<returns type="array">options.enabledHours</returns>
// ///</signature>
// ///<signature>
// ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledHours if such exist.</summary>
// ///<param name="hours" locid="$.fn.datetimepicker.enabledHours_p:hours">Takes an [ int ] of values and allows the user to select only from those hours.</param>
// ///</signature>
// if (arguments.length === 0) {
// return (options.enabledHours ? $.extend({}, options.enabledHours) : options.enabledHours);
// }
// if (!hours) {
// options.enabledHours = false;
// update();
// return picker;
// }
// if (!(hours instanceof Array)) {
// throw new TypeError('enabledHours() expects an array parameter');
// }
// options.enabledHours = indexGivenHours(hours);
// options.disabledHours = false;
// if (options.useCurrent && !options.keepInvalid) {
// var tries = 0;
// while (!isValid(date, 'h')) {
// date.add(1, 'h');
// if (tries === 24) {
// throw 'Tried 24 times to find a valid date';
// }
// tries++;
// }
// setValue(date);
// }
// update();
// return picker;
// };
// picker.viewDate = function (newDate) {
// ///<signature helpKeyword="$.fn.datetimepicker.viewDate">
// ///<summary>Returns the component's model current viewDate, a moment object or null if not set.</summary>
// ///<returns type="Moment">viewDate.clone()</returns>
// ///</signature>
// ///<signature>
// ///<summary>Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.</summary>
// ///<param name="newDate" locid="$.fn.datetimepicker.date_p:newDate">Takes string, viewDate, moment, null parameter.</param>
// ///</signature>
// if (arguments.length === 0) {
// return viewDate.clone();
// }
// if (!newDate) {
// viewDate = date.clone();
// return picker;
// }
// if (typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) {
// throw new TypeError('viewDate() parameter must be one of [string, moment or Date]');
// }
// viewDate = parseInputDate(newDate);
// viewUpdate();
// return picker;
// };
// };
// })(jQuery); | staticmatrix/Triangle | src/framework/controls/dtpicker/dtpicker-jq.js | JavaScript | mit | 36,843 |
using RippleCommonUtilities;
using RippleDictionary;
using RippleScreenApp.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace RippleScreenApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class ScreenWindow : Window
{
internal static RippleDictionary.Ripple rippleData;
private static TextBlock tbElement = new TextBlock();
private static TextBlock fullScreenTbElement = new TextBlock();
private static Image imgElement = new Image();
private static Image fullScreenImgElement = new Image();
private static String currentVideoURI = String.Empty;
private static RippleDictionary.ContentType currentScreenContent = ContentType.Nothing;
private static bool loopVideo = false;
private BackgroundWorker myBackgroundWorker;
private BackgroundWorker pptWorker;
Utilities.ScriptingHelper helper;
public System.Windows.Forms.Integration.WindowsFormsHost host;
public System.Windows.Forms.WebBrowser browserElement;
internal static String personName;
private long prevRow;
private Tile currentTile = null;
private bool StartVideoPlayed = false;
public static String sessionGuid = String.Empty;
public ScreenWindow()
{
try
{
InitializeComponent();
LoadData();
SetObjectProperties();
//Start receiving messages
Utilities.MessageReceiver.StartReceivingMessages(this);
}
catch (Exception ex)
{
//Exit and do nothing
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Screen {0}", ex.Message);
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
try
{
this.WindowState = System.Windows.WindowState.Maximized;
ResetUI();
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Window Loaded {0}", ex.Message);
}
}
private void SetObjectProperties()
{
//Initialize video properties
this.IntroVideoControl.Source = new Uri(Helper.GetAssetURI(rippleData.Screen.ScreenContents["IntroVideo"].Content));
this.IntroVideoControl.ScrubbingEnabled = true;
//Set image elements properties
imgElement.Stretch = Stretch.Fill;
fullScreenImgElement.Stretch = Stretch.Fill;
//Set text block properties
tbElement.FontSize = 50;
tbElement.Margin = new Thickness(120, 120, 120, 0);
tbElement.TextWrapping = TextWrapping.Wrap;
fullScreenTbElement.FontSize = 50;
fullScreenTbElement.Margin = new Thickness(120, 120, 120, 0);
fullScreenTbElement.TextWrapping = TextWrapping.Wrap;
}
/// <summary>
/// Method that loads the configured data for the Screen, right now the Source is XML
/// </summary>
private void LoadData()
{
try
{
//Loads the local dictionary data from the configuration XML
rippleData = RippleDictionary.Dictionary.GetRipple(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location));
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Load Data for Screen {0}", ex.Message);
throw;
}
}
/// <summary>
/// Resets the UI to System locked mode.
/// </summary>
private void ResetUI()
{
try
{
Globals.ResetGlobals();
currentVideoURI = String.Empty;
currentScreenContent = ContentType.Nothing;
loopVideo = false;
StartVideoPlayed = false;
sessionGuid = String.Empty;
//Pick up content based on the "LockScreen" ID
ProjectContent(rippleData.Screen.ScreenContents["LockScreen"]);
//Commit the telemetry data
Utilities.TelemetryWriter.CommitTelemetryAsync();
}
catch (Exception ex)
{
//Do nothing
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Reset UI for Screen {0}", ex.Message);
}
}
/// <summary>
/// Code will receive messages from the floor
/// Invoke appropriate content projection based on the tile ID passed
/// </summary>
/// <param name="val"></param>
public void OnMessageReceived(string val)
{
try
{
//Check for reset
if (val.Equals("Reset"))
{
//Update the previous entry
Utilities.TelemetryWriter.UpdatePreviousEntry();
//Reset the system
ResetUI();
}
//Check for System start
//Check for System start
else if (val.StartsWith("System Start"))
{
//Load the telemetry Data
Utilities.TelemetryWriter.RetrieveTelemetryData();
//The floor has asked the screen to start the system
//Get the User Name
Globals.UserName = val.Split(':')[1];
//Get the person identity for the session
personName = String.IsNullOrEmpty(Globals.UserName) ? Convert.ToString(Guid.NewGuid()) : Globals.UserName;
Utilities.TelemetryWriter.AddTelemetryRow(rippleData.Floor.SetupID, personName, "Unlock", val, "Unlock");
//Set the system state
Globals.currentAppState = RippleSystemStates.UserDetected;
//Play the Intro Content
ProjectIntroContent(rippleData.Screen.ScreenContents["IntroVideo"]);
}
//Check for gestures
else if (val.StartsWith("Gesture"))
{
OnGestureInput(val.Split(':')[1]);
}
//Check for HTMl messages
else if (val.StartsWith("HTML"))
{
OnHTMLMessagesReceived(val.Split(':')[1]);
}
//Check for options- TODO need to figure out
else if (val.StartsWith("Option"))
{
//Do nothing
}
//Check if a content - tile mapping or in general content tag exists
else
{
if (rippleData.Screen.ScreenContents.ContainsKey(val) && rippleData.Screen.ScreenContents[val].Type != ContentType.Nothing)
{
//Set the system state
Globals.currentAppState = RippleSystemStates.OptionSelected;
ProjectContent(rippleData.Screen.ScreenContents[val]);
RippleCommonUtilities.LoggingHelper.LogTrace(1, "In Message Received {0} {1}:{2}", Utilities.TelemetryWriter.telemetryData.Tables[0].Rows.Count, Utilities.TelemetryWriter.telemetryData.Tables[0].Rows[Utilities.TelemetryWriter.telemetryData.Tables[0].Rows.Count - 1].ItemArray[6], DateTime.Now);
//Update the end time for the previous
Utilities.TelemetryWriter.UpdatePreviousEntry();
//Insert the new entry
Utilities.TelemetryWriter.AddTelemetryRow(rippleData.Floor.SetupID, personName, ((currentTile = GetFloorTileForID(val))==null)?"Unknown":currentTile.Name, val, (val == "Tile0") ? "Start" : "Option");
}
else
{
//Stop any existing projections
DocumentPresentation.HelperMethods.StopPresentation();
FullScreenContentGrid.Children.Clear();
ContentGrid.Children.Clear();
//Set focus for screen window also
Utilities.Helper.ClickOnScreenToGetFocus();
//Stop any existing videos
loopVideo = false;
VideoControl.Source = null;
FullScreenVideoControl.Source = null;
//Clean the images
fullScreenImgElement.Source = null;
imgElement.Source = null;
//Clear the header text
TitleLabel.Text = "";
//Dispose the objects
if(browserElement != null)
browserElement.Dispose();
browserElement = null;
if (host != null)
host.Dispose();
host = null;
if (helper != null)
helper.PropertyChanged -= helper_PropertyChanged;
helper = null;
currentScreenContent = ContentType.Nothing;
ShowText("No content available for this option, Please try some other tile option", "No Content");
}
}
}
catch (Exception ex)
{
//Do nothing
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in On message received for Screen {0}", ex.Message);
}
}
private void OnHTMLMessagesReceived(string p)
{
try
{
if(p.StartsWith("SessionID,"))
{
sessionGuid = p;
return;
}
if (helper != null && currentScreenContent == ContentType.HTML)
{
helper.MessageReceived(p);
}
}
catch (Exception ex)
{
//Do nothing
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in OnHTMLMessagesReceived received for Screen {0}", ex.Message);
}
}
private void OnGestureInput(string inputGesture)
{
try
{
//PPT Mode - left and right swipe
if (inputGesture == GestureTypes.LeftSwipe.ToString() && currentScreenContent == ContentType.PPT)
{
//Acts as previous
DocumentPresentation.HelperMethods.GotoPrevious();
}
else if (inputGesture == GestureTypes.RightSwipe.ToString() && currentScreenContent == ContentType.PPT)
{
//Check again, Means the presentation ended on clicking next
if (!DocumentPresentation.HelperMethods.HasPresentationStarted())
{
//Change the screen
//ShowText("Your presentation has ended, Select some other option", "Select some other option");
ShowImage(@"\Assets\Images\pptend.png", "Presentation Ended");
//Set focus for screen window also
Utilities.Helper.ClickOnScreenToGetFocus();
}
//Acts as next
DocumentPresentation.HelperMethods.GotoNext();
//Check again, Means the presentation ended on clicking next
if (!DocumentPresentation.HelperMethods.HasPresentationStarted())
{
//Change the screen text
//ShowText("Your presentation has ended, Select some other option", "Select some other option");
ShowImage(@"\Assets\Images\pptend.png", "Presentation Ended");
//Set focus for screen window also
Utilities.Helper.ClickOnScreenToGetFocus();
}
}
//Browser mode
else if (currentScreenContent == ContentType.HTML)
{
OnHTMLMessagesReceived(inputGesture.ToString());
}
//Set focus for screen window also
//Utilities.Helper.ClickOnScreenToGetFocus();
}
catch (Exception ex)
{
//Do nothing
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in OnGestureInput received for Screen {0}", ex.Message);
}
}
#region Content Projection methods
/// <summary>
/// Identifies the content type and project accordingly
/// </summary>
/// <param name="screenContent"></param>
private void ProjectContent(RippleDictionary.ScreenContent screenContent)
{
try
{
if (screenContent.Type == ContentType.HTMLMessage)
{
if (helper != null && currentScreenContent == ContentType.HTML)
{
helper.MessageReceived(screenContent.Content);
return;
}
}
//Stop any existing projections
DocumentPresentation.HelperMethods.StopPresentation();
FullScreenContentGrid.Children.Clear();
ContentGrid.Children.Clear();
//Set focus for screen window also
Utilities.Helper.ClickOnScreenToGetFocus();
//Stop any existing videos
loopVideo = false;
VideoControl.Source = null;
FullScreenVideoControl.Source = null;
//Clean the images
fullScreenImgElement.Source = null;
imgElement.Source = null;
//Clear the header text
TitleLabel.Text = "";
//Dispose the objects
if (browserElement != null)
browserElement.Dispose();
browserElement = null;
if (host != null)
host.Dispose();
host = null;
if (helper != null)
helper.PropertyChanged -= helper_PropertyChanged;
helper = null;
currentScreenContent = screenContent.Type;
if (screenContent.Id == "Tile0" && StartVideoPlayed)
{
currentScreenContent = ContentType.Image;
ShowImage("\\Assets\\Images\\default_start.png", screenContent.Header);
return;
}
switch (screenContent.Type)
{
case RippleDictionary.ContentType.HTML:
ShowBrowser(screenContent.Content, screenContent.Header);
break;
case RippleDictionary.ContentType.Image:
ShowImage(screenContent.Content, screenContent.Header);
break;
case RippleDictionary.ContentType.PPT:
ShowPPT(screenContent.Content, screenContent.Header);
break;
case RippleDictionary.ContentType.Text:
ShowText(screenContent.Content, screenContent.Header);
break;
case RippleDictionary.ContentType.Video:
loopVideo = (screenContent.LoopVideo == null) ? false : Convert.ToBoolean(screenContent.LoopVideo);
if (screenContent.Id == "Tile0")
StartVideoPlayed = true;
ShowVideo(screenContent.Content, screenContent.Header);
break;
}
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in ProjectContent Method for screen {0}", ex.Message);
}
}
private void ProjectIntroContent(RippleDictionary.ScreenContent screenContent)
{
try
{
//Dispose the previous content
//Stop any existing projections
DocumentPresentation.HelperMethods.StopPresentation();
FullScreenContentGrid.Children.Clear();
ContentGrid.Children.Clear();
//Set focus for screen window also
Utilities.Helper.ClickOnScreenToGetFocus();
//Stop any existing videos
loopVideo = false;
VideoControl.Source = null;
FullScreenVideoControl.Source = null;
//Clean the images
fullScreenImgElement.Source = null;
imgElement.Source = null;
//Clear the header text
TitleLabel.Text = "";
if (browserElement != null)
browserElement.Dispose();
browserElement = null;
if (host != null)
host.Dispose();
host = null;
if (helper != null)
helper.PropertyChanged -= helper_PropertyChanged;
helper = null;
//Play the Intro video
this.TitleLabel.Text = "";
ContentGrid.Visibility = Visibility.Collapsed;
FullScreenContentGrid.Visibility = Visibility.Collapsed;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
IntroVideoControl.Visibility = Visibility.Visible;
VideoControl.Visibility = Visibility.Collapsed;
VideoGrid.Visibility = Visibility.Visible;
IntroVideoControl.Play();
this.UpdateLayout();
myBackgroundWorker = new BackgroundWorker();
myBackgroundWorker.DoWork += myBackgroundWorker_DoWork;
myBackgroundWorker.RunWorkerCompleted += myBackgroundWorker_RunWorkerCompleted;
myBackgroundWorker.RunWorkerAsync(rippleData.Floor.Start.IntroVideoWaitPeriod);
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in ProjectIntroContent Method for screen {0}", ex.Message);
}
}
private void myBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//System has been started, it just finished playing the intro video
if (Globals.currentAppState == RippleSystemStates.UserDetected)
{
this.IntroVideoControl.Stop();
//this.IntroVideoControl.Source = null;
this.IntroVideoControl.Visibility = System.Windows.Visibility.Collapsed;
ShowGotoStartContent();
}
}
private void myBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
System.Threading.Thread.Sleep(Convert.ToInt16(e.Argument) * 1000);
}
/// <summary>
/// Code to project a video
/// If the Header value is not provided, the content is projected in full screen mode
/// </summary>
/// <param name="Content"></param>
/// <param name="header"></param>
private void ShowVideo(String Content, String header)
{
try
{
//Check if header is null
//Null - Show full screen content
if (String.IsNullOrEmpty(header))
{
//Show the full screen video control
currentVideoURI = Helper.GetAssetURI(Content);
FullScreenVideoControl.Source = new Uri(currentVideoURI);
FullScreenContentGrid.Visibility = Visibility.Collapsed;
FullScreenVideoGrid.Visibility = Visibility.Visible;
FullScreenVideoControl.Play();
}
else
{
TitleLabel.Text = header;
currentVideoURI = Helper.GetAssetURI(Content);
VideoControl.Source = new Uri(currentVideoURI);
ContentGrid.Visibility = Visibility.Collapsed;
FullScreenContentGrid.Visibility = Visibility.Collapsed;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
VideoControl.Visibility = Visibility.Visible;
VideoGrid.Visibility = Visibility.Visible;
VideoControl.Play();
}
this.UpdateLayout();
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Show Video method {0}", ex.Message);
}
}
/// <summary>
/// Code to display text
/// If the Header value is not provided, the content is projected in full screen mode
/// </summary>
/// <param name="Content"></param>
/// <param name="header"></param>
private void ShowText(String Content, String header)
{
try
{
//Check if header is null
//Null - Show full screen content
if (String.IsNullOrEmpty(header))
{
//Show the full screen control with text
fullScreenTbElement.Text = Content;
FullScreenContentGrid.Children.Clear();
FullScreenContentGrid.Children.Add(fullScreenTbElement);
FullScreenContentGrid.Visibility = Visibility.Visible;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
}
else
{
TitleLabel.Text = header;
tbElement.Text = Content;
ContentGrid.Children.Clear();
ContentGrid.Children.Add(tbElement);
ContentGrid.Visibility = Visibility.Visible;
FullScreenContentGrid.Visibility = Visibility.Collapsed;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
VideoGrid.Visibility = Visibility.Collapsed;
}
this.UpdateLayout();
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Show Text method {0}", ex.Message);
}
}
/// <summary>
/// Code to project a PPT
/// If the Header value is not provided, the content is projected in full screen mode
/// </summary>
/// <param name="Content"></param>
/// <param name="header"></param>
private void ShowPPT(String Content, String header)
{
try
{
//Check if header is null
//Null - Show full screen content
if (String.IsNullOrEmpty(header))
{
//Show the full screen video control
FullScreenContentGrid.Visibility = Visibility.Visible;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
}
else
{
TitleLabel.Text = header;
ContentGrid.Visibility = Visibility.Visible;
FullScreenContentGrid.Visibility = Visibility.Collapsed;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
VideoGrid.Visibility = Visibility.Collapsed;
}
this.UpdateLayout();
DocumentPresentation.HelperMethods.StartPresentation(Helper.GetAssetURI(Content));
//ShowText("Please wait while we load your presentation", header);
//ShowImage(@"\Assets\Images\loading.png", header);
//this.UpdateLayout();
//pptWorker = new BackgroundWorker();
//pptWorker.DoWork += pptWorker_DoWork;
//pptWorker.RunWorkerAsync(Content);
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Show PPT method {0}", ex.Message);
}
}
void pptWorker_DoWork(object sender, DoWorkEventArgs e)
{
DocumentPresentation.HelperMethods.StartPresentation(Helper.GetAssetURI(e.Argument.ToString()));
}
/// <summary>
/// Code to project an image
/// If the Header value is not provided, the content is projected in full screen mode
/// </summary>
/// <param name="Content"></param>
/// <param name="header"></param>
private void ShowImage(String Content, String header)
{
try
{
//Check if header is null
//Null - Show full screen content
if (String.IsNullOrEmpty(header))
{
//Show the full screen control with text
fullScreenImgElement.Source = new BitmapImage(new Uri(Helper.GetAssetURI(Content)));
FullScreenContentGrid.Children.Clear();
FullScreenContentGrid.Children.Add(fullScreenImgElement);
FullScreenContentGrid.Visibility = Visibility.Visible;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
}
else
{
TitleLabel.Text = header;
imgElement.Source = new BitmapImage(new Uri(Helper.GetAssetURI(Content)));
ContentGrid.Children.Clear();
ContentGrid.Children.Add(imgElement);
ContentGrid.Visibility = Visibility.Visible;
FullScreenContentGrid.Visibility = Visibility.Collapsed;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
VideoGrid.Visibility = Visibility.Collapsed;
}
this.UpdateLayout();
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Show Image {0}", ex.Message);
}
}
/// <summary>
/// Code to show browser based content, applicable for URL's
/// If the Header value is not provided, the content is projected in full screen mode
/// </summary>
/// <param name="Content"></param>
/// <param name="header"></param>
private void ShowBrowser(String Content, String header)
{
try
{
//Check if header is null
//Null - Show full screen content
if (String.IsNullOrEmpty(header))
{
//Show the full screen video control
//Display HTML content
host = new System.Windows.Forms.Integration.WindowsFormsHost();
browserElement = new System.Windows.Forms.WebBrowser();
browserElement.ScriptErrorsSuppressed = true;
helper = new Utilities.ScriptingHelper(this);
browserElement.ObjectForScripting = helper;
host.Child = browserElement;
helper.PropertyChanged += helper_PropertyChanged;
FullScreenContentGrid.Children.Clear();
FullScreenContentGrid.Children.Add(host);
FullScreenContentGrid.Visibility = Visibility.Visible;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
}
else
{
TitleLabel.Text = header;
host = new System.Windows.Forms.Integration.WindowsFormsHost();
browserElement = new System.Windows.Forms.WebBrowser();
browserElement.ScriptErrorsSuppressed = true;
helper = new Utilities.ScriptingHelper(this);
host.Child = browserElement;
browserElement.ObjectForScripting = helper;
helper.PropertyChanged += helper_PropertyChanged;
ContentGrid.Children.Clear();
ContentGrid.Children.Add(host);
ContentGrid.Visibility = Visibility.Visible;
FullScreenContentGrid.Visibility = Visibility.Collapsed;
FullScreenVideoGrid.Visibility = Visibility.Collapsed;
VideoGrid.Visibility = Visibility.Collapsed;
}
String fileLocation = Helper.GetAssetURI(Content);
String pageUri = String.Empty;
//Local file
if (File.Exists(fileLocation))
{
String[] PathParts = fileLocation.Split(new char[] { ':' });
pageUri = "file://127.0.0.1/" + PathParts[0] + "$" + PathParts[1];
}
//Web hosted file
else
{
pageUri = Content;
}
browserElement.Navigate(pageUri);
this.UpdateLayout();
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Show Browser {0}", ex.Message);
}
}
#endregion
#region Helpers
private Tile GetFloorTileForID(string TileID)
{
Tile reqdTile = null;
try
{
reqdTile = rippleData.Floor.Tiles[TileID];
}
catch (Exception)
{
try
{
reqdTile = rippleData.Floor.Tiles[TileID.Substring(0, TileID.LastIndexOf("SubTile"))].SubTiles[TileID];
}
catch (Exception)
{
return null;
}
}
return reqdTile;
}
#endregion
private void VideoControl_MediaEnded(object sender, RoutedEventArgs e)
{
if (currentScreenContent == ContentType.Video && loopVideo && (!String.IsNullOrEmpty(currentVideoURI)))
{
//Replay the video
VideoControl.Source = new Uri(currentVideoURI);
VideoControl.Play();
}
}
private void FullScreenVideoControl_MediaEnded(object sender, RoutedEventArgs e)
{
if (currentScreenContent == ContentType.Video && loopVideo && (!String.IsNullOrEmpty(currentVideoURI)))
{
//Replay the video
FullScreenVideoControl.Source = new Uri(currentVideoURI);
FullScreenVideoControl.Play();
}
}
private void ShowGotoStartContent()
{
//Set the system state
Globals.currentAppState = RippleSystemStates.UserWaitToGoOnStart;
ProjectContent(rippleData.Screen.ScreenContents["GotoStart"]);
}
private void IntroVideoControl_MediaEnded(object sender, RoutedEventArgs e)
{
//System has been started, it just finished playing the intro video
//if (Globals.currentAppState == RippleSystemStates.UserDetected)
//{
// this.IntroVideoControl.Stop();
// ShowGotoStartContent();
//}
}
private void Window_Closing_1(object sender, CancelEventArgs e)
{
RippleCommonUtilities.LoggingHelper.StopLogging();
}
//Handles messages sent by HTML animations
void helper_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
try
{
var scriptingHelper = sender as Utilities.ScriptingHelper;
if (scriptingHelper != null)
{
if (e.PropertyName == "SendMessage")
{
if ((!String.IsNullOrEmpty(scriptingHelper.SendMessage)) && currentScreenContent == ContentType.HTML)
{
//Send the screen a message for HTML parameter passing
Utilities.MessageReceiver.SendMessage("HTML:" + scriptingHelper.SendMessage);
}
}
}
}
catch (Exception ex)
{
RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in helper property changed event {0}", ex.Message);
}
}
}
}
| Microsoft/kinect-ripple | Ripple/RippleScreenApp/ScreenWindow.xaml.cs | C# | mit | 33,912 |
# Note that this is not a valid measurement of tail latency. This uses the execution times we measure because they're convenient, but this does not include queueing time inside BitFunnel nor does it include head-of-line blocking queue waiting time on the queue into BitFunnel.
import csv
filename = "/tmp/QueryPipelineStatistics.csv"
times = []
with open(filename) as f:
reader = csv.reader(f)
header = next(reader)
assert header == ['query',
'rows',
'matches',
'quadwords',
'cachelines',
'parse',
'plan',
'match']
for row in reader:
total_time = float(row[-1]) + float(row[-2]) + float(row[-3])
times.append(total_time)
times.sort(reverse=True)
idx_max = len(times) - 1
idx = [round(idx_max / 2),
round(idx_max / 10),
round(idx_max / 100),
round(idx_max / 1000),
0]
tails = [times[x] for x in idx]
print(tails)
| BitFunnel/BitFunnel | src/Scripts/tail-latency.py | Python | mit | 1,033 |
const assert = require('assert');
const md5 = require('blueimp-md5');
const createApp = require('../../lib');
describe('tokenize service', () => {
it('tokenizes and stems', () => {
const app = createApp();
const text = `what's the weather in vancouver`;
const hash = md5(text);
return app.service('tokenize').create({ text }).then(data => {
assert.equal(data._id, hash, 'id is MD5 hash of the string');
assert.deepEqual(data, {
_id: '873dd3d48eed1d576a4d5b1dcacd2348',
text: 'what\'s the weather in vancouver',
tokens: [ 'what', 's', 'the', 'weather', 'in', 'vancouver' ],
stems: [ 'what', 's', 'the', 'weather', 'in', 'vancouv' ]
});
});
});
});
| solveEZ/neuroJ | test/services/tokenize.test.js | JavaScript | mit | 723 |
// AForge Kinect Video Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2005-2011
// contacts@aforgenet.com
//
namespace AForge.Video.Kinect
{
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using AForge;
using AForge.Imaging;
using AForge.Video;
/// <summary>
/// Enumeration of video camera modes for the <see cref="KinectVideoCamera"/>.
/// </summary>
public enum VideoCameraMode
{
/// <summary>
/// 24 bit per pixel RGB mode.
/// </summary>
Color,
/// <summary>
/// 8 bit per pixel Bayer mode.
/// </summary>
Bayer,
/// <summary>
/// 8 bit per pixel Infra Red mode.
/// </summary>
InfraRed
}
/// <summary>
/// Video source for Microsoft Kinect's video camera.
/// </summary>
///
/// <remarks><para>The video source captures video data from Microsoft <a href="http://en.wikipedia.org/wiki/Kinect">Kinect</a>
/// video camera, which is aimed originally as a gaming device for XBox 360 platform.</para>
///
/// <para><note>Prior to using the class, make sure you've installed Kinect's drivers
/// as described on <a href="http://openkinect.org/wiki/Getting_Started#Windows">Open Kinect</a>
/// project's page.</note></para>
///
/// <para><note>In order to run correctly the class requires <i>freenect.dll</i> library
/// to be put into solution's output folder. This can be found within the AForge.NET framework's
/// distribution in Externals folder.</note></para>
///
/// <para>Sample usage:</para>
/// <code>
/// // create video source
/// KinectVideoCamera videoSource = new KinectVideoCamera( 0 );
/// // set NewFrame event handler
/// videoSource.NewFrame += new NewFrameEventHandler( video_NewFrame );
/// // start the video source
/// videoSource.Start( );
/// // ...
///
/// private void video_NewFrame( object sender, NewFrameEventArgs eventArgs )
/// {
/// // get new frame
/// Bitmap bitmap = eventArgs.Frame;
/// // process the frame
/// }
/// </code>
/// </remarks>
///
public class KinectVideoCamera : IVideoSource
{
// Kinect's device ID
private int deviceID;
// received frames count
private int framesReceived;
// recieved byte count
private long bytesReceived;
// camera mode
private VideoCameraMode cameraMode = VideoCameraMode.Color;
// camera resolution to set
private CameraResolution resolution = CameraResolution.Medium;
// list of currently running cameras
private static List<int> runningCameras = new List<int>( );
// dummy object to lock for synchronization
private object sync = new object( );
/// <summary>
/// New frame event.
/// </summary>
///
/// <remarks><para>Notifies clients about new available frames from the video source.</para>
///
/// <para><note>Since video source may have multiple clients, each client is responsible for
/// making a copy (cloning) of the passed video frame, because the video source disposes its
/// own original copy after notifying of clients.</note></para>
/// </remarks>
///
public event NewFrameEventHandler NewFrame;
/// <summary>
/// Video source error event.
/// </summary>
///
/// <remarks>This event is used to notify clients about any type of errors occurred in
/// video source object, for example internal exceptions.</remarks>
///
public event VideoSourceErrorEventHandler VideoSourceError;
/// <summary>
/// Video playing finished event.
/// </summary>
///
/// <remarks><para>This event is used to notify clients that the video playing has finished.</para>
/// </remarks>
///
public event PlayingFinishedEventHandler PlayingFinished;
/// <summary>
/// Specifies video mode for the camera.
/// </summary>
///
/// <remarks>
/// <para><note>The property must be set before running the video source to take effect.</note></para>
///
/// <para>Default value of the property is set to <see cref="VideoCameraMode.Color"/>.</para>
/// </remarks>
///
public VideoCameraMode CameraMode
{
get { return cameraMode; }
set { cameraMode = value; }
}
/// <summary>
/// Resolution of video camera to set.
/// </summary>
///
/// <remarks><para><note>The property must be set before running the video source to take effect.</note></para>
///
/// <para>Default value of the property is set to <see cref="CameraResolution.Medium"/>.</para>
/// </remarks>
///
public CameraResolution Resolution
{
get { return resolution; }
set { resolution = value; }
}
/// <summary>
/// A string identifying the video source.
/// </summary>
///
public virtual string Source
{
get { return "Kinect:VideoCamera:" + deviceID; }
}
/// <summary>
/// State of the video source.
/// </summary>
///
/// <remarks>Current state of video source object - running or not.</remarks>
///
public bool IsRunning
{
get
{
lock ( sync )
{
return ( device != null );
}
}
}
/// <summary>
/// Received bytes count.
/// </summary>
///
/// <remarks>Number of bytes the video source provided from the moment of the last
/// access to the property.
/// </remarks>
///
public long BytesReceived
{
get
{
long bytes = bytesReceived;
bytesReceived = 0;
return bytes;
}
}
/// <summary>
/// Received frames count.
/// </summary>
///
/// <remarks>Number of frames the video source provided from the moment of the last
/// access to the property.
/// </remarks>
///
public int FramesReceived
{
get
{
int frames = framesReceived;
framesReceived = 0;
return frames;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="KinectVideoCamera"/> class.
/// </summary>
///
/// <param name="deviceID">Kinect's device ID (index) to connect to.</param>
///
public KinectVideoCamera( int deviceID )
{
this.deviceID = deviceID;
}
/// <summary>
/// Initializes a new instance of the <see cref="KinectVideoCamera"/> class.
/// </summary>
///
/// <param name="deviceID">Kinect's device ID (index) to connect to.</param>
/// <param name="resolution">Resolution of video camera to set.</param>
///
public KinectVideoCamera( int deviceID, CameraResolution resolution )
{
this.deviceID = deviceID;
this.resolution = resolution;
}
/// <summary>
/// Initializes a new instance of the <see cref="KinectVideoCamera"/> class.
/// </summary>
///
/// <param name="deviceID">Kinect's device ID (index) to connect to.</param>
/// <param name="resolution">Resolution of video camera to set.</param>
/// <param name="cameraMode">Sets video camera mode.</param>
///
public KinectVideoCamera( int deviceID, CameraResolution resolution, VideoCameraMode cameraMode )
{
this.deviceID = deviceID;
this.resolution = resolution;
this.cameraMode = cameraMode;
}
private Kinect device = null;
private IntPtr imageBuffer = IntPtr.Zero;
private KinectNative.BitmapInfoHeader videoModeInfo;
/// <summary>
/// Start video source.
/// </summary>
///
/// <remarks>Starts video source and returns execution to caller. Video camera will be started
/// and will provide new video frames through the <see cref="NewFrame"/> event.</remarks>
///
/// <exception cref="ArgumentException">The specified resolution is not supported for the selected
/// mode of the Kinect video camera.</exception>
/// <exception cref="ConnectionFailedException">Could not connect to Kinect's video camera.</exception>
/// <exception cref="DeviceBusyException">Another connection to the specified video camera is already running.</exception>
///
public void Start( )
{
lock ( sync )
{
lock ( runningCameras )
{
if ( device == null )
{
bool success = false;
try
{
if ( runningCameras.Contains( deviceID ) )
{
throw new DeviceBusyException( "Another connection to the specified video camera is already running." );
}
// get Kinect device
device = Kinect.GetDevice( deviceID );
KinectNative.VideoCameraFormat dataFormat = KinectNative.VideoCameraFormat.RGB;
if ( cameraMode == VideoCameraMode.Bayer )
{
dataFormat = KinectNative.VideoCameraFormat.Bayer;
}
else if ( cameraMode == VideoCameraMode.InfraRed )
{
dataFormat = KinectNative.VideoCameraFormat.IR8Bit;
}
// find video format parameters
videoModeInfo = KinectNative.freenect_find_video_mode( resolution, dataFormat );
if ( videoModeInfo.IsValid == 0 )
{
throw new ArgumentException( "The specified resolution is not supported for the selected mode of the Kinect video camera." );
}
// set video format
if ( KinectNative.freenect_set_video_mode( device.RawDevice, videoModeInfo ) != 0 )
{
throw new VideoException( "Could not switch to the specified video format." );
}
// allocate video buffer and provide it freenect
imageBuffer = Marshal.AllocHGlobal( (int) videoModeInfo.Bytes );
KinectNative.freenect_set_video_buffer( device.RawDevice, imageBuffer );
// set video callback
videoCallback = new KinectNative.FreenectVideoDataCallback( HandleDataReceived );
KinectNative.freenect_set_video_callback( device.RawDevice, videoCallback );
// start the camera
if ( KinectNative.freenect_start_video( device.RawDevice ) != 0 )
{
throw new ConnectionFailedException( "Could not start video stream." );
}
success = true;
runningCameras.Add( deviceID );
device.AddFailureHandler( deviceID, Stop );
}
finally
{
if ( !success )
{
if ( device != null )
{
device.Dispose( );
device = null;
}
if ( imageBuffer != IntPtr.Zero )
{
Marshal.FreeHGlobal( imageBuffer );
imageBuffer = IntPtr.Zero;
}
}
}
}
}
}
}
/// <summary>
/// Signal video source to stop its work.
/// </summary>
///
/// <remarks><para><note>Calling this method is equivalent to calling <see cref="Stop"/>
/// for Kinect video camera.</note></para></remarks>
///
public void SignalToStop( )
{
Stop( );
}
/// <summary>
/// Wait for video source has stopped.
/// </summary>
///
/// <remarks><para><note>Calling this method is equivalent to calling <see cref="Stop"/>
/// for Kinect video camera.</note></para></remarks>
///
public void WaitForStop( )
{
Stop( );
}
/// <summary>
/// Stop video source.
/// </summary>
///
/// <remarks><para>The method stops the video source, so it no longer provides new video frames
/// and does not consume any resources.</para>
/// </remarks>
///
public void Stop( )
{
lock ( sync )
{
lock ( runningCameras )
{
if ( device != null )
{
bool deviceFailed = device.IsDeviceFailed( deviceID );
if ( !deviceFailed )
{
KinectNative.freenect_stop_video( device.RawDevice );
}
device.Dispose( );
device = null;
runningCameras.Remove( deviceID );
if ( PlayingFinished != null )
{
PlayingFinished( this, ( !deviceFailed ) ?
ReasonToFinishPlaying.StoppedByUser : ReasonToFinishPlaying.DeviceLost );
}
}
if ( imageBuffer != IntPtr.Zero )
{
Marshal.FreeHGlobal( imageBuffer );
imageBuffer = IntPtr.Zero;
}
videoCallback = null;
}
}
}
// New video data event handler
private KinectNative.FreenectVideoDataCallback videoCallback = null;
private void HandleDataReceived( IntPtr device, IntPtr imageData, UInt32 timeStamp )
{
int width = videoModeInfo.Width;
int height = videoModeInfo.Height;
Bitmap image = null;
BitmapData data = null;
try
{
image = ( cameraMode == VideoCameraMode.Color ) ?
new Bitmap( width, height, PixelFormat.Format24bppRgb ) :
AForge.Imaging.Image.CreateGrayscaleImage( width, height );
data = image.LockBits( new Rectangle( 0, 0, width, height ),
ImageLockMode.ReadWrite, image.PixelFormat );
unsafe
{
byte* dst = (byte*) data.Scan0.ToPointer( );
byte* src = (byte*) imageBuffer.ToPointer( );
if ( cameraMode == VideoCameraMode.Color )
{
// color RGB 24 mode
int offset = data.Stride - width * 3;
for ( int y = 0; y < height; y++ )
{
for ( int x = 0; x < width; x++, src += 3, dst += 3 )
{
dst[0] = src[2];
dst[1] = src[1];
dst[2] = src[0];
}
dst += offset;
}
}
else
{
// infra red mode - grayscale output
int stride = data.Stride;
if ( stride != width )
{
for ( int y = 0; y < height; y++ )
{
SystemTools.CopyUnmanagedMemory( dst, src, width );
dst += stride;
src += width;
}
}
else
{
SystemTools.CopyUnmanagedMemory( dst, src, width * height );
}
}
}
image.UnlockBits( data );
framesReceived++;
bytesReceived += width * height;
}
catch ( Exception ex )
{
if ( VideoSourceError != null )
{
VideoSourceError( this, new VideoSourceErrorEventArgs( ex.Message ) );
}
if ( image != null )
{
if ( data != null )
{
image.UnlockBits( data );
}
image.Dispose( );
image = null;
}
}
if ( image != null )
{
if ( NewFrame != null )
{
NewFrame( this, new NewFrameEventArgs( image ) );
}
image.Dispose( );
}
}
}
}
| lyuboasenov/scheduler | packages/AForge.NET Framework-2.2.5/Sources/Video.Kinect/KinectVideoCamera.cs | C# | mit | 19,055 |
namespace DeviceHive.Data.EF.Migrations
{
using System.Data.Entity.Migrations;
public partial class _91 : DbMigration
{
public override void Up()
{
CreateTable(
"OAuthClient",
c => new
{
ID = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 128),
Domain = c.String(nullable: false, maxLength: 128),
Subnet = c.String(maxLength: 128),
RedirectUri = c.String(nullable: false, maxLength: 128),
OAuthID = c.String(nullable: false, maxLength: 32),
OAuthSecret = c.String(nullable: false, maxLength: 32),
})
.PrimaryKey(t => t.ID)
.Index(t => t.OAuthID, unique: true);
CreateTable(
"OAuthGrant",
c => new
{
ID = c.Int(nullable: false, identity: true),
Timestamp = c.DateTime(nullable: false, storeType: "datetime2"),
AuthCode = c.Guid(),
ClientID = c.Int(nullable: false),
UserID = c.Int(nullable: false),
AccessKeyID = c.Int(nullable: false),
Type = c.Int(nullable: false),
AccessType = c.Int(nullable: false),
RedirectUri = c.String(maxLength: 128),
Scope = c.String(nullable: false, maxLength: 256),
NetworkList = c.String(maxLength: 128),
})
.PrimaryKey(t => t.ID)
.ForeignKey("OAuthClient", t => t.ClientID, cascadeDelete: true)
.ForeignKey("User", t => t.UserID, cascadeDelete: true)
.ForeignKey("AccessKey", t => t.AccessKeyID, cascadeDelete: false)
.Index(t => t.ClientID)
.Index(t => t.UserID)
.Index(t => t.AccessKeyID);
Sql("CREATE UNIQUE NONCLUSTERED INDEX [IX_AuthCode] ON [OAuthGrant] ( [AuthCode] ASC ) WHERE [AuthCode] IS NOT NULL");
}
public override void Down()
{
DropIndex("OAuthGrant", new[] { "AccessKeyID" });
DropIndex("OAuthGrant", new[] { "UserID" });
DropIndex("OAuthGrant", new[] { "ClientID" });
DropIndex("OAuthGrant", new[] { "AuthCode" });
DropForeignKey("OAuthGrant", "AccessKeyID", "AccessKey");
DropForeignKey("OAuthGrant", "UserID", "User");
DropForeignKey("OAuthGrant", "ClientID", "OAuthClient");
DropTable("OAuthGrant");
DropIndex("OAuthClient", new[] { "OAuthID" });
DropTable("OAuthClient");
}
}
}
| deus42/devicehive-.net | src/Server/DeviceHive.Data.EF/Migrations/201310111016567_9.1.cs | C# | mit | 2,823 |
namespace MonoGame.Extended.Collisions
{
public class CollisionGridCell : ICollidable
{
private readonly CollisionGrid _parentGrid;
public CollisionGridCell(CollisionGrid parentGrid, int column, int row, int data)
{
_parentGrid = parentGrid;
Column = column;
Row = row;
Data = data;
Flag = data == 0 ? CollisionGridCellFlag.Empty : CollisionGridCellFlag.Solid;
}
public int Column { get; }
public int Row { get; }
public int Data { get; private set; }
public object Tag { get; set; }
public CollisionGridCellFlag Flag { get; set; }
public RectangleF BoundingBox => _parentGrid.GetCellRectangle(Column, Row).ToRectangleF();
}
} | cra0zy/MonoGame.Extended | Source/MonoGame.Extended.Collisions/CollisionGridCell.cs | C# | mit | 786 |
'use strict';
var getTemplatedStylesheet = require('./templatedStylesheet'),
path = require('path');
module.exports = getTemplatedStylesheet(path.join(__dirname, '/templates/stylus.tpl'));
| filippovdaniil/node-sprite-generator | lib/stylesheet/stylus.js | JavaScript | mit | 195 |
import React from 'react'
import Icon from 'react-icon-base'
const MdTonality = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m32.9 23.4c0.1-0.6 0.2-1.2 0.3-1.8h-11.6v1.8h11.3z m-2.5 5c0.4-0.6 0.9-1.2 1.2-1.8h-10v1.8h8.8z m-8.8 4.8c1.8-0.2 3.4-0.8 4.9-1.6h-4.9v1.6z m0-16.6v1.8h11.6c-0.1-0.6-0.2-1.2-0.3-1.8h-11.3z m0-5v1.8h10c-0.4-0.6-0.8-1.2-1.2-1.8h-8.8z m0-4.8v1.6h4.9c-1.5-0.8-3.1-1.4-4.9-1.6z m-3.2 26.4v-26.4c-6.6 0.8-11.8 6.4-11.8 13.2s5.2 12.4 11.8 13.2z m1.6-29.8c9.2 0 16.6 7.4 16.6 16.6s-7.4 16.6-16.6 16.6-16.6-7.4-16.6-16.6 7.4-16.6 16.6-16.6z"/></g>
</Icon>
)
export default MdTonality
| bengimbel/Solstice-React-Contacts-Project | node_modules/react-icons/md/tonality.js | JavaScript | mit | 635 |
<?php
namespace Censo\CensoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* TipoViviendas
*
* @ORM\Table(name="tipo_viviendas")
* @ORM\Entity
*/
class TipoViviendas
{
/**
* @var integer
*
* @ORM\Column(name="id", type="bigint", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
* @ORM\SequenceGenerator(sequenceName="tipo_viviendas_id_seq", allocationSize=1, initialValue=1)
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="nombre", type="string", length=255, nullable=false)
*/
private $nombre;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nombre
*
* @param string $nombre
* @return TipoViviendas
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* @return string
*/
public function getNombre()
{
return $this->nombre;
}
public function __toString() {
return $this->getNombre();
}
}
| profa1131/censo | src/Censo/CensoBundle/Entity/TipoViviendas.php | PHP | mit | 1,161 |